initial commit
Some checks failed
Build / build (push) Has been cancelled

This commit is contained in:
trunksbomb
2026-03-24 17:41:26 -04:00
commit 456913cea0
33 changed files with 2708 additions and 0 deletions

5
.gitattributes vendored Normal file
View File

@@ -0,0 +1,5 @@
# Disable autocrlf on generated files, they always generate with LF
# Add any extra files or paths here to make git stop saying they
# are changed when only line endings change.
src/generated/**/.cache/* text eol=lf
src/generated/**/*.json text eol=lf

30
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,30 @@
name: Build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 0
fetch-tags: true
- name: Setup JDK 21
uses: actions/setup-java@v4
with:
java-version: '21'
distribution: 'temurin'
- name: Setup Gradle
uses: gradle/actions/setup-gradle@v4
# This is needed to be able to run ./gradlew below
# You can run `git update-index --chmod +x gradlew` then remove this step.
- name: Make Gradle wrapper executable
run: chmod +x ./gradlew
- name: Build with Gradle
run: ./gradlew build

41
.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
### Gradle ###
.gradle
build/
!gradle/wrapper/gradle-wrapper.jar
!**/src/**/build/
### IntelliJ IDEA ###
.idea/
*.iws
*.iml
*.ipr
out/
!**/src/**/out/
.run/
### Eclipse ###
.apt_generated
.classpath
.eclipse/
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/**/bin/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
### Minecraft Modding ###
run/
!**/src/**/run/
**/src/generated/**/.cache/
repo/
!**/src/**/repo/
/.gradle-user-home/

25
README.md Normal file
View File

@@ -0,0 +1,25 @@
Installation information
=======
This template repository can be directly cloned to get you started with a new
mod. Simply create a new repository cloned from this one, by following the
instructions provided by [GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-repository-from-a-template).
Once you have your clone, simply open the repository in the IDE of your choice. The usual recommendation for an IDE is either IntelliJ IDEA or Eclipse.
If at any point you are missing libraries in your IDE, or you've run into problems you can
run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything
{this does not affect your code} and then start the process again.
Mapping Names:
============
By default, the MDK is configured to use the official mapping names from Mojang for methods and fields
in the Minecraft codebase. These names are covered by a specific license. All modders should be aware of this
license. For the latest license text, refer to the mapping file itself, or the reference copy here:
https://github.com/NeoForged/NeoForm/blob/main/Mojang.md
Additional Resources:
==========
Community Documentation: https://docs.neoforged.net/
NeoForged Discord: https://discord.neoforged.net/

24
TEMPLATE_LICENSE.txt Normal file
View File

@@ -0,0 +1,24 @@
MIT License
Copyright (c) 2023 NeoForged project
This license applies to the template files as supplied by github.com/NeoForged/MDK
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

192
build.gradle Normal file
View File

@@ -0,0 +1,192 @@
plugins {
id 'java-library'
id 'maven-publish'
id 'net.neoforged.moddev' version '2.0.140'
id 'idea'
}
tasks.named('wrapper', Wrapper).configure {
// Define wrapper values here so as to not have to always do so when updating gradlew.properties.
// Switching this to Wrapper.DistributionType.ALL will download the full gradle sources that comes with
// documentation attached on cursor hover of gradle classes and methods. However, this comes with increased
// file size for Gradle. If you do switch this to ALL, run the Gradle wrapper task twice afterwards.
// (Verify by checking gradle/wrapper/gradle-wrapper.properties to see if distributionUrl now points to `-all`)
distributionType = Wrapper.DistributionType.BIN
}
version = mod_version
group = mod_group_id
sourceSets.main.resources {
// Include resources generated by data generators.
srcDir('src/generated/resources')
// Exclude common development only resources from finalized outputs
exclude("**/*.bbmodel") // BlockBench project files
exclude("src/generated/**/.cache") // datagen cache files
}
repositories {
// Add here additional repositories if required by some of the dependencies below.
}
base {
archivesName = mod_id
}
// Mojang ships Java 21 to end users in 1.21.1, so mods should target Java 21.
java.toolchain.languageVersion = JavaLanguageVersion.of(21)
neoForge {
// Specify the version of NeoForge to use.
version = project.neo_version
parchment {
mappingsVersion = project.parchment_mappings_version
minecraftVersion = project.parchment_minecraft_version
}
// This line is optional. Access Transformers are automatically detected
// accessTransformers = project.files('src/main/resources/META-INF/accesstransformer.cfg')
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
client()
// Comma-separated list of namespaces to load gametests from. Empty = all namespaces.
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
server {
server()
programArgument '--nogui'
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
// 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 {
type = "gameTestServer"
systemProperty 'neoforge.enabledGameTestNamespaces', project.mod_id
}
data {
data()
// example of overriding the workingDirectory set in configureEach above, uncomment if you want to use it
// gameDirectory = project.file('run-data')
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
programArguments.addAll '--mod', project.mod_id, '--all', '--output', file('src/generated/resources/').getAbsolutePath(), '--existing', file('src/main/resources/').getAbsolutePath()
}
// applies to all the run configs above
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'
// 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
logLevel = org.slf4j.event.Level.DEBUG
}
}
mods {
// define mod <-> source bindings
// these are used to tell the game which sources are for which mod
// multi mod projects should define one per mod
"${mod_id}" {
sourceSet(sourceSets.main)
}
}
}
// Sets up a dependency configuration called 'localRuntime'.
// This configuration should be used instead of 'runtimeOnly' to declare
// a dependency that will be present for runtime testing but that is
// "optional", meaning it will not be pulled by dependents of this mod.
configurations {
runtimeClasspath.extendsFrom localRuntime
}
dependencies {
// Example optional mod dependency with JEI
// The JEI API is declared for compile time use, while the full JEI artifact is used at runtime
// compileOnly "mezz.jei:jei-${mc_version}-common-api:${jei_version}"
// compileOnly "mezz.jei:jei-${mc_version}-neoforge-api:${jei_version}"
// We add the full version to localRuntime, not runtimeOnly, so that we do not publish a dependency on it
// localRuntime "mezz.jei:jei-${mc_version}-neoforge:${jei_version}"
// Example mod dependency using a mod jar from ./libs with a flat dir repository
// This maps to ./libs/coolmod-${mc_version}-${coolmod_version}.jar
// The group id is ignored when searching -- in this case, it is "blank"
// implementation "blank:coolmod-${mc_version}:${coolmod_version}"
// Example mod dependency using a file as dependency
// implementation files("libs/coolmod-${mc_version}-${coolmod_version}.jar")
// Example project dependency using a sister or child project:
// implementation project(":myproject")
// For more info:
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// This block of code expands all declared replace properties in the specified resource targets.
// A missing property will result in an error. Properties are expanded using ${} Groovy notation.
var generateModMetadata = tasks.register("generateModMetadata", ProcessResources) {
var replaceProperties = [
minecraft_version : minecraft_version,
minecraft_version_range: minecraft_version_range,
neo_version : neo_version,
loader_version_range : loader_version_range,
mod_id : mod_id,
mod_name : mod_name,
mod_license : mod_license,
mod_version : mod_version,
]
inputs.properties replaceProperties
expand replaceProperties
from "src/main/templates"
into "build/generated/sources/modMetadata"
}
// Include the output of "generateModMetadata" as an input directory for the build
// this works with both building through Gradle and the IDE.
sourceSets.main.resources.srcDir generateModMetadata
// To avoid having to run "generateModMetadata" manually, make it run on every project reload
neoForge.ideSyncTask generateModMetadata
// Example configuration to allow publishing using the maven-publish plugin
publishing {
publications {
register('mavenJava', MavenPublication) {
from components.java
}
}
repositories {
maven {
url "file://${project.projectDir}/repo"
}
}
}
tasks.withType(JavaCompile).configureEach {
options.encoding = 'UTF-8' // Use the UTF-8 charset for Java compilation
}
// IDEA no longer automatically downloads sources/javadoc jars for dependencies, so we need to explicitly enable the behavior.
idea {
module {
downloadSources = true
downloadJavadoc = true
}
}

39
gradle.properties Normal file
View File

@@ -0,0 +1,39 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
org.gradle.jvmargs=-Xmx1G
org.gradle.daemon=true
org.gradle.parallel=true
org.gradle.caching=true
org.gradle.configuration-cache=true
#read more on this at https://github.com/neoforged/ModDevGradle?tab=readme-ov-file#better-minecraft-parameter-names--javadoc-parchment
# you can also find the latest versions at: https://parchmentmc.org/docs/getting-started
parchment_minecraft_version=1.21.1
parchment_mappings_version=2024.11.17
# Environment Properties
# You can find the latest versions here: https://projects.neoforged.net/neoforged/neoforge
# The Minecraft version must agree with the Neo version to get a valid artifact
minecraft_version=1.21.1
# 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
# as they do not follow standard versioning conventions.
minecraft_version_range=[1.21.1]
# The Neo version must agree with the Minecraft version to get a valid artifact
neo_version=21.1.220
# The loader version range can only use the major version of FML as bounds
loader_version_range=[1,)
## Mod Properties
# The unique mod identifier for the mod. Must be lowercase in English locale. Must fit the regex [a-z][a-z0-9_]{1,63}
# Must match the String constant located in the main mod class annotated with @Mod.
mod_id=trade
# The human-readable display name for the mod.
mod_name=Trading Screen
# The license of the mod. Review your options at https://choosealicense.com/. All Rights Reserved is the default.
mod_license=All Rights Reserved
# The mod version. See https://semver.org/
mod_version=1.0.0
# 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.
# See https://maven.apache.org/guides/mini/guide-naming-conventions.html
mod_group_id=com.trunksbomb.trade

BIN
gradle/wrapper/gradle-wrapper.jar vendored Normal file

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.2.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

251
gradlew vendored Normal file
View File

@@ -0,0 +1,251 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH="\\\"\\\""
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
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:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

9
settings.gradle Normal file
View File

@@ -0,0 +1,9 @@
pluginManagement {
repositories {
gradlePluginPortal()
}
}
plugins {
id 'org.gradle.toolchains.foojay-resolver-convention' version '1.0.0'
}

View File

@@ -0,0 +1,45 @@
package com.trunksbomb.trade.mod.client;
import com.trunksbomb.trade.mod.trade.TradeView;
import java.util.UUID;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
public final class TradeClientState {
private static Minecraft minecraft;
private TradeClientState() {}
public static void init(Minecraft minecraftInstance) {
minecraft = minecraftInstance;
}
public static Minecraft minecraft() {
return minecraft;
}
public static void showOrUpdate(Minecraft minecraftInstance, TradeView view) {
minecraft = minecraftInstance;
if (minecraft.screen instanceof TradeScreen screen && screen.sessionId().equals(view.sessionId())) {
screen.updateView(view);
return;
}
if (minecraft.player == null) {
return;
}
minecraft.setScreen(new TradeScreen(new TradeScreen.TradeMenu(0, minecraft.player.getInventory(), view), minecraft.player.getInventory(), Component.literal("Trade")));
}
public static void closeTrade(Minecraft minecraftInstance, UUID sessionId, Component reason) {
minecraft = minecraftInstance;
if (minecraft.screen instanceof TradeScreen screen && screen.sessionId().equals(sessionId)) {
minecraft.setScreen(null);
}
if (minecraft.player != null) {
minecraft.player.displayClientMessage(reason, false);
}
}
}

View File

@@ -0,0 +1,311 @@
package com.trunksbomb.trade.mod.client;
import com.trunksbomb.trade.mod.network.TradeActionPayload;
import com.trunksbomb.trade.mod.network.DebugTradeControlPayload;
import com.trunksbomb.trade.mod.trade.DebugControlAction;
import com.trunksbomb.trade.mod.trade.TradeAction;
import com.trunksbomb.trade.mod.trade.TradeStage;
import com.trunksbomb.trade.mod.trade.TradeView;
import java.util.UUID;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.screens.inventory.AbstractContainerScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.Container;
import net.minecraft.world.SimpleContainer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.ClickType;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.inventory.Slot;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.PacketDistributor;
public class TradeScreen extends AbstractContainerScreen<TradeScreen.TradeMenu> {
private static final ResourceLocation TEXTURE = ResourceLocation.fromNamespaceAndPath("trade", "textures/gui/trade.png");
private static final int LEFT_OFFER_START_X = 8;
private static final int RIGHT_OFFER_START_X = 170;
private static final int OFFER_START_Y = 18;
private static final int INVENTORY_START_X = 62;
private static final int INVENTORY_START_Y = 139;
private static final int CENTER_COLUMN_X = 115;
private static final int STATUS_LABEL_Y = 54;
private static final int ACCEPT_BUTTON_Y = 74;
private static final int CANCEL_BUTTON_Y = 98;
private static final int ACTION_BUTTON_WIDTH = 48;
private static final int ACTION_BUTTON_HEIGHT = 20;
private static final int DEBUG_PANEL_OFFSET_X = 96;
private static final int DEBUG_BUTTON_WIDTH = 86;
private static final int DEBUG_BUTTON_HEIGHT = 20;
private static final int DEBUG_BUTTON_GAP = 4;
private static final int CONFIRM_PANEL_X = 89;
private static final int CONFIRM_PANEL_Y = 77;
private static final int CONFIRM_PANEL_WIDTH = 106;
private static final int CONFIRM_PANEL_HEIGHT = 64;
public TradeScreen(TradeMenu menu, Inventory inventory, Component title) {
super(menu, inventory, title);
this.imageWidth = 284;
this.imageHeight = 221;
this.inventoryLabelX = INVENTORY_START_X;
this.inventoryLabelY = INVENTORY_START_Y - 11;
}
public UUID sessionId() {
return menu.view().sessionId();
}
public void updateView(TradeView view) {
menu.updateView(view);
}
@Override
protected void init() {
super.init();
titleLabelX = LEFT_OFFER_START_X;
titleLabelY = 6;
addRenderableWidget(Button.builder(Component.literal("Accept"), button -> sendAction(TradeAction.ACCEPT, -1, false))
.bounds(leftPos + CENTER_COLUMN_X + 3, topPos + ACCEPT_BUTTON_Y, ACTION_BUTTON_WIDTH, ACTION_BUTTON_HEIGHT)
.build());
addRenderableWidget(Button.builder(Component.literal("Cancel"), button -> sendAction(TradeAction.DECLINE, -1, false))
.bounds(leftPos + CENTER_COLUMN_X + 3, topPos + CANCEL_BUTTON_Y, ACTION_BUTTON_WIDTH, ACTION_BUTTON_HEIGHT)
.build());
if (menu.view().debugMode()) {
int debugX = leftPos - DEBUG_PANEL_OFFSET_X;
int debugY = topPos + 8;
addRenderableWidget(Button.builder(Component.literal("Debug Accept"), button -> sendDebug(DebugControlAction.ACCEPT))
.bounds(debugX, debugY, DEBUG_BUTTON_WIDTH, DEBUG_BUTTON_HEIGHT)
.build());
addRenderableWidget(Button.builder(Component.literal("Debug Cancel"), button -> sendDebug(DebugControlAction.CANCEL))
.bounds(debugX, debugY + (DEBUG_BUTTON_HEIGHT + DEBUG_BUTTON_GAP), DEBUG_BUTTON_WIDTH, DEBUG_BUTTON_HEIGHT)
.build());
addRenderableWidget(Button.builder(Component.literal("Add Random"), button -> sendDebug(DebugControlAction.APPEND_RANDOM))
.bounds(debugX, debugY + 2 * (DEBUG_BUTTON_HEIGHT + DEBUG_BUTTON_GAP), DEBUG_BUTTON_WIDTH, DEBUG_BUTTON_HEIGHT)
.build());
addRenderableWidget(Button.builder(Component.literal("Remove Item"), button -> sendDebug(DebugControlAction.REMOVE_LAST))
.bounds(debugX, debugY + 3 * (DEBUG_BUTTON_HEIGHT + DEBUG_BUTTON_GAP), DEBUG_BUTTON_WIDTH, DEBUG_BUTTON_HEIGHT)
.build());
}
}
@Override
public boolean keyPressed(int keyCode, int scanCode, int modifiers) {
if (minecraft != null && minecraft.options.keyInventory.matches(keyCode, scanCode)) {
onClose();
return true;
}
return super.keyPressed(keyCode, scanCode, modifiers);
}
@Override
public void onClose() {
sendAction(TradeAction.CLOSE, -1, false);
if (minecraft != null) {
minecraft.setScreen(null);
}
}
@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (menu.view().stage() == TradeStage.CONFIRMING) {
return super.mouseClicked(mouseX, mouseY, button);
}
if (hoveredSlot instanceof SelfOfferSlot selfOfferSlot) {
sendAction(TradeAction.REMOVE_ITEM, selfOfferSlot.offerIndex(), button == 1);
return true;
}
if (hoveredSlot instanceof OtherOfferSlot) {
return true;
}
if (hoveredSlot != null && hoveredSlot.container == menu.playerInventory()) {
sendAction(TradeAction.ADD_ITEM, hoveredSlot.getSlotIndex(), button == 1);
return true;
}
return super.mouseClicked(mouseX, mouseY, button);
}
@Override
protected void renderBg(GuiGraphics guiGraphics, float partialTick, int mouseX, int mouseY) {
guiGraphics.blit(TEXTURE, leftPos, topPos, 0, 0, imageWidth, imageHeight, imageWidth, imageHeight);
if (menu.view().stage() == TradeStage.CONFIRMING) {
renderConfirmationOverlay(guiGraphics);
}
}
@Override
protected void renderLabels(GuiGraphics guiGraphics, int mouseX, int mouseY) {
guiGraphics.drawString(font, menu.view().selfName(), titleLabelX, titleLabelY, 0x404040, false);
guiGraphics.drawString(font, menu.view().otherName(), RIGHT_OFFER_START_X, 6, 0x404040, false);
guiGraphics.drawString(font, playerInventoryTitle, inventoryLabelX, inventoryLabelY, 0x404040, false);
if (menu.view().otherAccepted()) {
drawScaledCenteredColumnText(guiGraphics, "Other player", STATUS_LABEL_Y, 0x2E7D32, 0.7F);
drawScaledCenteredColumnText(guiGraphics, "has accepted", STATUS_LABEL_Y + 7, 0x2E7D32, 0.7F);
}
if (menu.view().stage() == TradeStage.CONFIRMING) {
drawCenteredColumnText(guiGraphics, "FINAL", 16, 0x7A4F00);
drawCenteredColumnText(guiGraphics, "CONFIRM", 28, 0x7A4F00);
}
}
@Override
public void render(GuiGraphics guiGraphics, int mouseX, int mouseY, float partialTick) {
super.render(guiGraphics, mouseX, mouseY, partialTick);
renderTooltip(guiGraphics, mouseX, mouseY);
}
private void sendAction(TradeAction action, int slot, boolean secondary) {
if (minecraft == null || minecraft.getConnection() == null) {
return;
}
PacketDistributor.sendToServer(new TradeActionPayload(menu.view().sessionId(), action, slot, secondary));
}
private void sendDebug(DebugControlAction action) {
if (minecraft == null || minecraft.getConnection() == null) {
return;
}
PacketDistributor.sendToServer(new DebugTradeControlPayload(menu.view().sessionId(), action, ""));
}
private void renderConfirmationOverlay(GuiGraphics guiGraphics) {
int panelLeft = leftPos + CONFIRM_PANEL_X;
int panelTop = topPos + CONFIRM_PANEL_Y;
guiGraphics.fill(leftPos, topPos, leftPos + imageWidth, topPos + imageHeight, 0x22000000);
guiGraphics.fill(panelLeft, panelTop, panelLeft + CONFIRM_PANEL_WIDTH, panelTop + CONFIRM_PANEL_HEIGHT, 0xDDF7D48C);
guiGraphics.fill(panelLeft + 1, panelTop + 1, panelLeft + CONFIRM_PANEL_WIDTH - 1, panelTop + CONFIRM_PANEL_HEIGHT - 1, 0xAAFFF4D6);
guiGraphics.drawString(font, Component.literal("Confirm Trade"), panelLeft + 11, panelTop + 9, 0x5B3A00, false);
guiGraphics.drawString(font, Component.literal("Review items"), panelLeft + 18, panelTop + 24, 0x5B3A00, false);
guiGraphics.drawString(font, Component.literal("No more changes"), panelLeft + 9, panelTop + 36, 0x5B3A00, false);
}
private void drawCenteredColumnText(GuiGraphics guiGraphics, String text, int y, int color) {
int textX = CENTER_COLUMN_X + (ACTION_BUTTON_WIDTH / 2) - (font.width(text) / 2);
guiGraphics.drawString(font, text, textX, y, color, false);
}
private void drawScaledCenteredColumnText(GuiGraphics guiGraphics, String text, int y, int color, float scale) {
var pose = guiGraphics.pose();
pose.pushPose();
pose.scale(scale, scale, 1.0F);
float scaledCenterX = CENTER_COLUMN_X + 3 + (ACTION_BUTTON_WIDTH / 2.0F);
float drawX = (scaledCenterX - (font.width(text) * scale / 2.0F)) / scale;
float drawY = y / scale;
guiGraphics.drawString(font, text, (int) drawX, (int) drawY, color, false);
pose.popPose();
}
public static class TradeMenu extends AbstractContainerMenu {
private static final int OFFER_COLUMNS = 6;
private static final int OFFER_ROWS = 6;
private TradeView view;
private final Inventory playerInventory;
private final SimpleContainer selfOffer = new SimpleContainer(TradeView.OFFER_SLOT_COUNT);
private final SimpleContainer otherOffer = new SimpleContainer(TradeView.OFFER_SLOT_COUNT);
public TradeMenu(int containerId, Inventory inventory, TradeView view) {
super(MenuType.GENERIC_9x6, containerId);
this.playerInventory = inventory;
this.view = view;
syncOfferContainers();
for (int row = 0; row < OFFER_ROWS; row++) {
for (int col = 0; col < OFFER_COLUMNS; col++) {
int slot = col + row * OFFER_COLUMNS;
addSlot(new SelfOfferSlot(selfOffer, slot, LEFT_OFFER_START_X + col * 18, OFFER_START_Y + row * 18));
}
}
for (int row = 0; row < OFFER_ROWS; row++) {
for (int col = 0; col < OFFER_COLUMNS; col++) {
int slot = col + row * OFFER_COLUMNS;
addSlot(new OtherOfferSlot(otherOffer, slot, RIGHT_OFFER_START_X + col * 18, OFFER_START_Y + row * 18));
}
}
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 9; col++) {
int slot = col + row * 9 + 9;
addSlot(new Slot(inventory, slot, INVENTORY_START_X + col * 18, INVENTORY_START_Y + row * 18));
}
}
for (int col = 0; col < 9; col++) {
addSlot(new Slot(inventory, col, INVENTORY_START_X + col * 18, INVENTORY_START_Y + 58));
}
}
public TradeView view() {
return view;
}
public Inventory playerInventory() {
return playerInventory;
}
public void updateView(TradeView view) {
this.view = view;
syncOfferContainers();
}
private void syncOfferContainers() {
for (int i = 0; i < TradeView.OFFER_SLOT_COUNT; i++) {
selfOffer.setItem(i, view.selfOffer().get(i).copy());
otherOffer.setItem(i, view.otherOffer().get(i).copy());
}
}
@Override
public void clicked(int slotId, int button, ClickType clickType, Player player) {
// All interaction is routed through custom trade packets instead of vanilla container clicks.
}
@Override
public ItemStack quickMoveStack(Player player, int index) {
return ItemStack.EMPTY;
}
@Override
public boolean stillValid(Player player) {
return true;
}
}
private static class SelfOfferSlot extends Slot {
public SelfOfferSlot(Container container, int slot, int x, int y) {
super(container, slot, x, y);
}
public int offerIndex() {
return getSlotIndex();
}
@Override
public boolean mayPlace(ItemStack stack) {
return false;
}
}
private static class OtherOfferSlot extends Slot {
public OtherOfferSlot(Container container, int slot, int x, int y) {
super(container, slot, x, y);
}
@Override
public boolean mayPickup(Player player) {
return false;
}
@Override
public boolean mayPlace(ItemStack stack) {
return false;
}
}
}

View File

@@ -0,0 +1,160 @@
package com.trunksbomb.trade.mod.command;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.arguments.StringArgumentType;
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
import com.trunksbomb.trade.mod.trade.DebugTradeSession;
import com.trunksbomb.trade.mod.trade.TradeManager;
import java.util.concurrent.CompletableFuture;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.Commands;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
public final class TradeCommand {
private TradeCommand() {}
public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
dispatcher.register(Commands.literal("trade")
.then(Commands.literal("debug")
.then(Commands.literal("init").executes(context -> initDebug(context.getSource())))
.then(Commands.literal("offer")
.then(Commands.argument("spec", StringArgumentType.greedyString())
.executes(context -> setDebugOffer(
context.getSource(),
StringArgumentType.getString(context, "spec")))))
.then(Commands.literal("remove")
.then(Commands.argument("spec", StringArgumentType.greedyString())
.executes(context -> removeDebugOffer(
context.getSource(),
StringArgumentType.getString(context, "spec")))))
.then(Commands.literal("accept").executes(context -> acceptDebug(context.getSource())))
.then(Commands.literal("cancel").executes(context -> cancelDebug(context.getSource())))
.then(Commands.literal("close").executes(context -> closeDebug(context.getSource()))))
.then(Commands.argument("player", StringArgumentType.word())
.suggests((context, builder) -> suggestPlayers(context.getSource(), builder))
.executes(context -> startTrade(context.getSource(), StringArgumentType.getString(context, "player")))));
}
private static CompletableFuture<com.mojang.brigadier.suggestion.Suggestions> suggestPlayers(CommandSourceStack source, SuggestionsBuilder builder) {
for (ServerPlayer player : source.getServer().getPlayerList().getPlayers()) {
if (!player.getGameProfile().getName().equalsIgnoreCase(source.getTextName())) {
builder.suggest(player.getGameProfile().getName());
}
}
return builder.buildFuture();
}
private static int startTrade(CommandSourceStack source, String targetName) {
if (!(source.getEntity() instanceof ServerPlayer player)) {
source.sendFailure(Component.literal("Only players can start trades."));
return 0;
}
ServerPlayer target = source.getServer().getPlayerList().getPlayerByName(targetName);
if (target == null) {
source.sendFailure(Component.literal("That player is not online."));
return 0;
}
if (target == player) {
source.sendFailure(Component.literal("You cannot trade with yourself."));
return 0;
}
if (!TradeManager.get(source.getServer()).startTrade(player, target)) {
source.sendFailure(Component.literal("Trade could not be started. One of you is already trading."));
return 0;
}
source.sendSuccess(() -> Component.literal("Trade opened with " + target.getGameProfile().getName() + "."), false);
return 1;
}
private static int initDebug(CommandSourceStack source) {
if (!(source.getEntity() instanceof ServerPlayer player)) {
source.sendFailure(Component.literal("Only players can start debug trades."));
return 0;
}
if (!TradeManager.get(source.getServer()).initDebugTrade(player)) {
source.sendFailure(Component.literal("You are already in a trade."));
return 0;
}
source.sendSuccess(() -> Component.literal("Debug trade initialized."), false);
return 1;
}
private static int setDebugOffer(CommandSourceStack source, String spec) {
if (!(source.getEntity() instanceof ServerPlayer player)) {
source.sendFailure(Component.literal("Only players can control debug trades."));
return 0;
}
try {
if (!TradeManager.get(source.getServer()).setDebugOffer(player, DebugTradeSession.parseOfferSpec(spec))) {
source.sendFailure(Component.literal("Start a debug trade first with /trade debug init."));
return 0;
}
} catch (IllegalArgumentException exception) {
source.sendFailure(Component.literal(exception.getMessage()));
return 0;
}
source.sendSuccess(() -> Component.literal("Debug offer updated."), false);
return 1;
}
private static int acceptDebug(CommandSourceStack source) {
return runDebugAction(source, TradeManager.get(source.getServer())::acceptDebug, "Debug trader accepted.");
}
private static int removeDebugOffer(CommandSourceStack source, String spec) {
if (!(source.getEntity() instanceof ServerPlayer player)) {
source.sendFailure(Component.literal("Only players can control debug trades."));
return 0;
}
try {
int result = TradeManager.get(source.getServer()).removeDebugOffer(player, spec);
if (result < 0) {
source.sendFailure(Component.literal("Start a debug trade first with /trade debug init."));
return 0;
}
if (result == 0) {
source.sendFailure(Component.literal("That debug offer slot is already empty."));
return 0;
}
} catch (IllegalArgumentException exception) {
source.sendFailure(Component.literal(exception.getMessage()));
return 0;
}
source.sendSuccess(() -> Component.literal("Debug offer updated."), false);
return 1;
}
private static int cancelDebug(CommandSourceStack source) {
return runDebugAction(source, TradeManager.get(source.getServer())::cancelDebug, "Debug trader cancelled.");
}
private static int closeDebug(CommandSourceStack source) {
return runDebugAction(source, TradeManager.get(source.getServer())::closeDebug, "Debug trade closed.");
}
private static int runDebugAction(CommandSourceStack source, java.util.function.Predicate<ServerPlayer> action, String successMessage) {
if (!(source.getEntity() instanceof ServerPlayer player)) {
source.sendFailure(Component.literal("Only players can control debug trades."));
return 0;
}
if (!action.test(player)) {
source.sendFailure(Component.literal("Start a debug trade first with /trade debug init."));
return 0;
}
source.sendSuccess(() -> Component.literal(successMessage), false);
return 1;
}
}

View File

@@ -0,0 +1,18 @@
package com.trunksbomb.trade.mod;
import com.trunksbomb.trade.mod.client.TradeClientState;
import net.minecraft.client.Minecraft;
import net.neoforged.api.distmarker.Dist;
import net.neoforged.bus.api.SubscribeEvent;
import net.neoforged.fml.common.EventBusSubscriber;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
@Mod(value = TradeMod.MODID, dist = Dist.CLIENT)
@EventBusSubscriber(modid = TradeMod.MODID, value = Dist.CLIENT)
public class TradeClientMod {
@SubscribeEvent
static void onClientSetup(FMLClientSetupEvent event) {
event.enqueueWork(() -> TradeClientState.init(Minecraft.getInstance()));
}
}

View File

@@ -0,0 +1,46 @@
package com.trunksbomb.trade.mod;
import com.mojang.logging.LogUtils;
import com.trunksbomb.trade.mod.command.TradeCommand;
import com.trunksbomb.trade.mod.network.TradeNetworking;
import com.trunksbomb.trade.mod.trade.TradeManager;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.common.Mod;
import net.neoforged.fml.event.lifecycle.FMLCommonSetupEvent;
import net.neoforged.neoforge.common.NeoForge;
import net.neoforged.neoforge.event.RegisterCommandsEvent;
import net.neoforged.neoforge.event.entity.player.PlayerEvent;
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
import org.slf4j.Logger;
@Mod(TradeMod.MODID)
public class TradeMod {
public static final String MODID = "trade";
public static final Logger LOGGER = LogUtils.getLogger();
public TradeMod(IEventBus modEventBus) {
modEventBus.addListener(this::commonSetup);
modEventBus.addListener(this::registerPayloads);
NeoForge.EVENT_BUS.addListener(this::registerCommands);
NeoForge.EVENT_BUS.addListener(this::onPlayerLogout);
}
private void commonSetup(FMLCommonSetupEvent event) {
LOGGER.info("Initializing trading screen");
}
private void registerPayloads(RegisterPayloadHandlersEvent event) {
TradeNetworking.register(event.registrar("1"));
}
public void registerCommands(RegisterCommandsEvent event) {
LOGGER.info("Registering /trade command");
TradeCommand.register(event.getDispatcher());
}
public void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) {
if (event.getEntity() instanceof net.minecraft.server.level.ServerPlayer player) {
TradeManager.get(player.server).handleDisconnect(player);
}
}
}

View File

@@ -0,0 +1,31 @@
package com.trunksbomb.trade.mod.network;
import com.trunksbomb.trade.mod.TradeMod;
import com.trunksbomb.trade.mod.trade.DebugControlAction;
import java.util.UUID;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
public record DebugTradeControlPayload(UUID sessionId, DebugControlAction action, String spec) implements CustomPacketPayload {
public static final Type<DebugTradeControlPayload> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(TradeMod.MODID, "debug_trade_control"));
public static final StreamCodec<RegistryFriendlyByteBuf, DebugTradeControlPayload> STREAM_CODEC = new StreamCodec<>() {
@Override
public void encode(RegistryFriendlyByteBuf buf, DebugTradeControlPayload value) {
buf.writeUUID(value.sessionId());
buf.writeEnum(value.action());
buf.writeUtf(value.spec(), 256);
}
@Override
public DebugTradeControlPayload decode(RegistryFriendlyByteBuf buf) {
return new DebugTradeControlPayload(buf.readUUID(), buf.readEnum(DebugControlAction.class), buf.readUtf(256));
}
};
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,32 @@
package com.trunksbomb.trade.mod.network;
import com.trunksbomb.trade.mod.TradeMod;
import com.trunksbomb.trade.mod.trade.TradeAction;
import java.util.UUID;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
public record TradeActionPayload(UUID sessionId, TradeAction action, int slot, boolean secondary) implements CustomPacketPayload {
public static final Type<TradeActionPayload> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(TradeMod.MODID, "trade_action"));
public static final StreamCodec<RegistryFriendlyByteBuf, TradeActionPayload> STREAM_CODEC = new StreamCodec<>() {
@Override
public void encode(RegistryFriendlyByteBuf buf, TradeActionPayload value) {
buf.writeUUID(value.sessionId);
buf.writeEnum(value.action);
buf.writeVarInt(value.slot);
buf.writeBoolean(value.secondary);
}
@Override
public TradeActionPayload decode(RegistryFriendlyByteBuf buf) {
return new TradeActionPayload(buf.readUUID(), buf.readEnum(TradeAction.class), buf.readVarInt(), buf.readBoolean());
}
};
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,31 @@
package com.trunksbomb.trade.mod.network;
import com.trunksbomb.trade.mod.TradeMod;
import java.util.UUID;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.ComponentSerialization;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
public record TradeClosePayload(UUID sessionId, Component reason) implements CustomPacketPayload {
public static final Type<TradeClosePayload> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(TradeMod.MODID, "trade_close"));
public static final StreamCodec<RegistryFriendlyByteBuf, TradeClosePayload> STREAM_CODEC = new StreamCodec<>() {
@Override
public void encode(RegistryFriendlyByteBuf buf, TradeClosePayload value) {
buf.writeUUID(value.sessionId);
ComponentSerialization.STREAM_CODEC.encode(buf, value.reason);
}
@Override
public TradeClosePayload decode(RegistryFriendlyByteBuf buf) {
return new TradeClosePayload(buf.readUUID(), ComponentSerialization.STREAM_CODEC.decode(buf));
}
};
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,77 @@
package com.trunksbomb.trade.mod.network;
import com.trunksbomb.trade.mod.client.TradeScreen;
import com.trunksbomb.trade.mod.trade.TradeManager;
import net.minecraft.client.Minecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.neoforged.neoforge.network.handling.DirectionalPayloadHandler;
import net.neoforged.neoforge.network.handling.IPayloadContext;
import net.neoforged.neoforge.network.registration.PayloadRegistrar;
public final class TradeNetworking {
private TradeNetworking() {}
public static void register(PayloadRegistrar registrar) {
registrar.playBidirectional(
TradeStatePayload.TYPE,
TradeStatePayload.STREAM_CODEC,
new DirectionalPayloadHandler<>(TradeNetworking::handleTradeStateClient, TradeNetworking::ignoreTradeStateServer));
registrar.playBidirectional(
TradeClosePayload.TYPE,
TradeClosePayload.STREAM_CODEC,
new DirectionalPayloadHandler<>(TradeNetworking::handleTradeCloseClient, TradeNetworking::ignoreTradeCloseServer));
registrar.playToServer(
TradeActionPayload.TYPE,
TradeActionPayload.STREAM_CODEC,
TradeNetworking::handleTradeActionServer);
registrar.playToServer(
DebugTradeControlPayload.TYPE,
DebugTradeControlPayload.STREAM_CODEC,
TradeNetworking::handleDebugTradeControlServer);
}
private static void handleTradeStateClient(TradeStatePayload payload, IPayloadContext context) {
Minecraft minecraft = Minecraft.getInstance();
if (minecraft.player == null) {
return;
}
if (minecraft.screen instanceof TradeScreen screen && screen.sessionId().equals(payload.view().sessionId())) {
screen.updateView(payload.view());
return;
}
minecraft.setScreen(new TradeScreen(
new TradeScreen.TradeMenu(0, minecraft.player.getInventory(), payload.view()),
minecraft.player.getInventory(),
Component.literal("Trade")));
}
private static void handleTradeCloseClient(TradeClosePayload payload, IPayloadContext context) {
Minecraft minecraft = Minecraft.getInstance();
if (minecraft.screen instanceof TradeScreen screen && screen.sessionId().equals(payload.sessionId())) {
minecraft.setScreen(null);
}
if (minecraft.player != null) {
minecraft.player.displayClientMessage(payload.reason(), false);
}
}
private static void handleTradeActionServer(TradeActionPayload payload, IPayloadContext context) {
if (context.player() instanceof ServerPlayer player) {
TradeManager.get(player.server).handleAction(player, payload.sessionId(), payload.action(), payload.slot(), payload.secondary());
}
}
private static void handleDebugTradeControlServer(DebugTradeControlPayload payload, IPayloadContext context) {
if (context.player() instanceof ServerPlayer player) {
TradeManager.get(player.server).handleDebugControl(player, payload.sessionId(), payload.action(), payload.spec());
}
}
private static void ignoreTradeStateServer(TradeStatePayload payload, IPayloadContext context) {}
private static void ignoreTradeCloseServer(TradeClosePayload payload, IPayloadContext context) {}
}

View File

@@ -0,0 +1,28 @@
package com.trunksbomb.trade.mod.network;
import com.trunksbomb.trade.mod.TradeMod;
import com.trunksbomb.trade.mod.trade.TradeView;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.ResourceLocation;
public record TradeStatePayload(TradeView view) implements CustomPacketPayload {
public static final Type<TradeStatePayload> TYPE = new Type<>(ResourceLocation.fromNamespaceAndPath(TradeMod.MODID, "trade_state"));
public static final StreamCodec<RegistryFriendlyByteBuf, TradeStatePayload> STREAM_CODEC = new StreamCodec<>() {
@Override
public void encode(RegistryFriendlyByteBuf buf, TradeStatePayload value) {
TradeView.STREAM_CODEC.encode(buf, value.view);
}
@Override
public TradeStatePayload decode(RegistryFriendlyByteBuf buf) {
return new TradeStatePayload(TradeView.STREAM_CODEC.decode(buf));
}
};
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,11 @@
package com.trunksbomb.trade.mod.trade;
public enum DebugControlAction {
SET_OFFER,
APPEND_RANDOM,
REMOVE_OFFER,
REMOVE_LAST,
ACCEPT,
CANCEL,
CLOSE
}

View File

@@ -0,0 +1,405 @@
package com.trunksbomb.trade.mod.trade;
import com.trunksbomb.trade.mod.network.TradeClosePayload;
import com.trunksbomb.trade.mod.network.TradeStatePayload;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.PacketDistributor;
public class DebugTradeSession {
private static final int INVENTORY_SLOT_COUNT = TradeView.INVENTORY_SLOT_COUNT;
private static final int OFFER_SLOT_COUNT = TradeView.OFFER_SLOT_COUNT;
private static final String DEBUG_NAME = "Debug Trader";
private static final net.minecraft.util.RandomSource RANDOM = net.minecraft.util.RandomSource.create();
private final UUID id = UUID.randomUUID();
private final ServerPlayer player;
private final List<ItemStack> selfOffer = blankOffer();
private final List<ItemStack> otherOffer = blankStacks();
private boolean selfAccepted;
private boolean otherAccepted;
private TradeStage stage = TradeStage.OFFERING;
public DebugTradeSession(ServerPlayer player) {
this.player = player;
}
public UUID id() {
return id;
}
public ServerPlayer player() {
return player;
}
public void sync() {
PacketDistributor.sendToPlayer(player, new TradeStatePayload(view()));
}
public void close(Component reason) {
PacketDistributor.sendToPlayer(player, new TradeClosePayload(id, reason));
}
public boolean addFromInventory(int inventorySlot, boolean singleItem) {
if (stage != TradeStage.OFFERING || inventorySlot < 0 || inventorySlot >= INVENTORY_SLOT_COUNT) {
return false;
}
Inventory inventory = player.getInventory();
ItemStack sourceStack = inventory.getItem(inventorySlot);
if (sourceStack.isEmpty()) {
return false;
}
ItemStack moving = sourceStack.copyWithCount(singleItem ? 1 : sourceStack.getCount());
if (!insertStack(selfOffer, moving)) {
return false;
}
sourceStack.shrink(singleItem ? 1 : sourceStack.getCount());
if (sourceStack.isEmpty()) {
inventory.setItem(inventorySlot, ItemStack.EMPTY);
}
inventory.setChanged();
clearAccepts();
return true;
}
public boolean removeFromOffer(int offerSlot, boolean singleItem) {
if (stage != TradeStage.OFFERING || offerSlot < 0 || offerSlot >= OFFER_SLOT_COUNT) {
return false;
}
ItemStack offered = selfOffer.get(offerSlot);
if (offered.isEmpty()) {
return false;
}
List<ItemStack> workingInventory = inventorySnapshot();
ItemStack returned = offered.copyWithCount(singleItem ? 1 : offered.getCount());
if (!insertStack(workingInventory, returned)) {
return false;
}
Inventory inventory = player.getInventory();
for (int i = 0; i < workingInventory.size(); i++) {
inventory.setItem(i, workingInventory.get(i));
}
inventory.setChanged();
if (singleItem && offered.getCount() > 1) {
ItemStack updated = offered.copy();
updated.shrink(1);
selfOffer.set(offerSlot, updated);
} else {
selfOffer.set(offerSlot, ItemStack.EMPTY);
}
clearAccepts();
return true;
}
public void acceptSelf() {
selfAccepted = true;
}
public void acceptOther() {
otherAccepted = true;
}
public void setOtherOffer(List<ItemStack> offer) {
for (int i = 0; i < OFFER_SLOT_COUNT; i++) {
otherOffer.set(i, i < offer.size() ? offer.get(i).copy() : ItemStack.EMPTY);
}
clearAccepts();
}
public boolean appendOtherOffer(List<ItemStack> offer) {
boolean changed = false;
for (ItemStack stack : offer) {
if (stack.isEmpty()) {
continue;
}
if (!insertStack(otherOffer, stack.copy())) {
break;
}
changed = true;
}
if (changed) {
clearAccepts();
}
return changed;
}
public boolean removeOtherOffer(String spec) {
if ("all".equalsIgnoreCase(spec)) {
for (int i = 0; i < OFFER_SLOT_COUNT; i++) {
otherOffer.set(i, ItemStack.EMPTY);
}
clearAccepts();
return true;
}
int split = spec.indexOf(':');
if (split <= 0 || split >= spec.length() - 1) {
throw new IllegalArgumentException("Use all or slot:count");
}
int slot = parsePositiveInt(spec.substring(0, split), "slot") - 1;
int count = parsePositiveInt(spec.substring(split + 1), "count");
if (slot < 0 || slot >= OFFER_SLOT_COUNT) {
throw new IllegalArgumentException("Slot must be between 1 and " + OFFER_SLOT_COUNT + ".");
}
ItemStack stack = otherOffer.get(slot);
if (stack.isEmpty()) {
return false;
}
if (count >= stack.getCount()) {
otherOffer.set(slot, ItemStack.EMPTY);
} else {
ItemStack updated = stack.copy();
updated.shrink(count);
otherOffer.set(slot, updated);
}
clearAccepts();
return true;
}
public boolean removeLastOtherOffer() {
for (int i = OFFER_SLOT_COUNT - 1; i >= 0; i--) {
if (otherOffer.get(i).isEmpty()) {
continue;
}
otherOffer.set(i, ItemStack.EMPTY);
clearAccepts();
return true;
}
return false;
}
public void advanceToConfirmation() {
if (stage == TradeStage.OFFERING && selfAccepted && otherAccepted) {
stage = TradeStage.CONFIRMING;
selfAccepted = false;
otherAccepted = false;
}
}
public boolean bothAccepted() {
return selfAccepted && otherAccepted;
}
public boolean isConfirmationStage() {
return stage == TradeStage.CONFIRMING;
}
public boolean completeTrade() {
List<ItemStack> result = inventorySnapshot();
for (ItemStack stack : otherOffer) {
if (!stack.isEmpty() && !insertStack(result, stack.copy())) {
return false;
}
}
Inventory inventory = player.getInventory();
for (int i = 0; i < result.size(); i++) {
inventory.setItem(i, result.get(i));
}
inventory.setChanged();
return true;
}
public TradeView view() {
return new TradeView(
id,
player.getGameProfile().getName(),
DEBUG_NAME,
true,
stage,
selfAccepted,
otherAccepted,
inventorySnapshot(),
emptyReservedSnapshot(),
selfOfferSnapshot(),
otherOfferSnapshot());
}
public static List<ItemStack> parseOfferSpec(String spec) {
if (spec.startsWith("random:")) {
return parseRandomOffer(spec);
}
int split = spec.lastIndexOf(':');
if (split <= 0 || split >= spec.length() - 1) {
throw new IllegalArgumentException("Use item:count or random:count or random:numStacks:stackCount");
}
ResourceLocation itemId = ResourceLocation.tryParse(spec.substring(0, split));
if (itemId == null) {
throw new IllegalArgumentException("Invalid item id.");
}
Item item = BuiltInRegistries.ITEM.get(itemId);
if (item == null || item == net.minecraft.world.item.Items.AIR) {
throw new IllegalArgumentException("Unknown item: " + itemId);
}
int count = parsePositiveInt(spec.substring(split + 1), "count");
return List.of(new ItemStack(item, count));
}
private static List<ItemStack> parseRandomOffer(String spec) {
String[] parts = spec.split(":");
List<Item> items = BuiltInRegistries.ITEM.stream()
.filter(item -> item != net.minecraft.world.item.Items.AIR)
.toList();
if (parts.length == 2) {
int count = parsePositiveInt(parts[1], "count");
return List.of(new ItemStack(randomItem(items), count));
}
if (parts.length == 3) {
int numStacks = parsePositiveInt(parts[1], "numStacks");
int stackCount = parsePositiveInt(parts[2], "stackCount");
List<ItemStack> result = new ArrayList<>();
for (int i = 0; i < Math.min(numStacks, OFFER_SLOT_COUNT); i++) {
result.add(new ItemStack(randomItem(items), stackCount));
}
return result;
}
throw new IllegalArgumentException("Use random:count or random:numStacks:stackCount");
}
private static Item randomItem(List<Item> items) {
return items.get(RANDOM.nextInt(items.size()));
}
public static List<ItemStack> randomSingleStackOffer() {
List<Item> items = BuiltInRegistries.ITEM.stream()
.filter(item -> item != net.minecraft.world.item.Items.AIR)
.toList();
Item item = randomItem(items);
int maxCount = Math.max(1, Math.min(item.getDefaultMaxStackSize(), 64));
int count = 1 + RANDOM.nextInt(maxCount);
return List.of(new ItemStack(item, count));
}
private static int parsePositiveInt(String value, String label) {
try {
int parsed = Integer.parseInt(value);
if (parsed <= 0) {
throw new IllegalArgumentException(label + " must be positive.");
}
return parsed;
} catch (NumberFormatException exception) {
throw new IllegalArgumentException("Invalid " + label + ": " + value);
}
}
private static boolean insertStack(List<ItemStack> working, ItemStack incoming) {
if (incoming.isEmpty()) {
return true;
}
for (int i = 0; i < working.size(); i++) {
ItemStack existing = working.get(i);
if (existing.isEmpty() || !ItemStack.isSameItemSameComponents(existing, incoming)) {
continue;
}
int space = existing.getMaxStackSize() - existing.getCount();
if (space <= 0) {
continue;
}
int moved = Math.min(space, incoming.getCount());
ItemStack updated = existing.copy();
updated.grow(moved);
working.set(i, updated);
incoming.shrink(moved);
if (incoming.isEmpty()) {
return true;
}
}
for (int i = 0; i < working.size(); i++) {
if (!working.get(i).isEmpty()) {
continue;
}
working.set(i, incoming.copy());
incoming.setCount(0);
return true;
}
return false;
}
private static List<Integer> emptyReservedSnapshot() {
List<Integer> result = new ArrayList<>(INVENTORY_SLOT_COUNT);
for (int i = 0; i < INVENTORY_SLOT_COUNT; i++) {
result.add(0);
}
return result;
}
private void clearAccepts() {
selfAccepted = false;
otherAccepted = false;
}
private List<ItemStack> inventorySnapshot() {
List<ItemStack> result = new ArrayList<>(INVENTORY_SLOT_COUNT);
Inventory inventory = player.getInventory();
for (int i = 0; i < INVENTORY_SLOT_COUNT; i++) {
result.add(inventory.getItem(i).copy());
}
return result;
}
private List<ItemStack> selfOfferSnapshot() {
List<ItemStack> result = new ArrayList<>(OFFER_SLOT_COUNT);
for (ItemStack stack : selfOffer) {
result.add(stack.copy());
}
return result;
}
private List<ItemStack> otherOfferSnapshot() {
List<ItemStack> result = new ArrayList<>(OFFER_SLOT_COUNT);
for (ItemStack stack : otherOffer) {
result.add(stack.copy());
}
return result;
}
private static List<ItemStack> blankOffer() {
List<ItemStack> result = new ArrayList<>(OFFER_SLOT_COUNT);
for (int i = 0; i < OFFER_SLOT_COUNT; i++) {
result.add(ItemStack.EMPTY);
}
return result;
}
private static List<ItemStack> blankStacks() {
List<ItemStack> result = new ArrayList<>(OFFER_SLOT_COUNT);
for (int i = 0; i < OFFER_SLOT_COUNT; i++) {
result.add(ItemStack.EMPTY);
}
return result;
}
}

View File

@@ -0,0 +1,9 @@
package com.trunksbomb.trade.mod.trade;
public enum TradeAction {
ADD_ITEM,
REMOVE_ITEM,
ACCEPT,
DECLINE,
CLOSE
}

View File

@@ -0,0 +1,5 @@
package com.trunksbomb.trade.mod.trade;
import net.minecraft.world.item.ItemStack;
public record TradeEntry(int sourceSlot, ItemStack stack) {}

View File

@@ -0,0 +1,309 @@
package com.trunksbomb.trade.mod.trade;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import net.minecraft.network.chat.Component;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.item.ItemStack;
public class TradeManager {
private static final Map<MinecraftServer, TradeManager> INSTANCES = new WeakHashMap<>();
private final Map<UUID, TradeSession> sessionsById = new HashMap<>();
private final Map<UUID, UUID> sessionByPlayer = new HashMap<>();
private final Map<UUID, DebugTradeSession> debugSessionsById = new HashMap<>();
private final Map<UUID, UUID> debugSessionByPlayer = new HashMap<>();
public static TradeManager get(MinecraftServer server) {
return INSTANCES.computeIfAbsent(server, ignored -> new TradeManager());
}
public boolean startTrade(ServerPlayer first, ServerPlayer second) {
if (isTrading(first) || isTrading(second)) {
return false;
}
TradeSession session = new TradeSession(first, second);
sessionsById.put(session.id(), session);
sessionByPlayer.put(first.getUUID(), session.id());
sessionByPlayer.put(second.getUUID(), session.id());
session.syncToPlayers();
first.sendSystemMessage(Component.literal("Trade opened with " + second.getGameProfile().getName() + "."));
second.sendSystemMessage(Component.literal("Trade opened with " + first.getGameProfile().getName() + "."));
return true;
}
public void handleAction(ServerPlayer player, UUID sessionId, TradeAction action, int slot, boolean secondary) {
TradeSession session = sessionsById.get(sessionId);
if (session != null && session.involves(player)) {
handleRealAction(player, session, action, slot, secondary);
return;
}
DebugTradeSession debugSession = debugSessionsById.get(sessionId);
if (debugSession != null && debugSession.player() == player) {
handleDebugAction(debugSession, action, slot, secondary);
return;
}
}
private void handleRealAction(ServerPlayer player, TradeSession session, TradeAction action, int slot, boolean secondary) {
boolean changed = switch (action) {
case ADD_ITEM -> session.addFromInventory(player, slot, secondary);
case REMOVE_ITEM -> session.removeFromOffer(player, slot, secondary);
case ACCEPT -> {
session.accept(player);
yield true;
}
case DECLINE, CLOSE -> {
cancel(session, Component.literal(player.getGameProfile().getName() + " cancelled the trade."));
yield false;
}
};
if (!changed) {
return;
}
if (!session.isConfirmationStage()) {
session.advanceToConfirmation();
session.syncToPlayers();
return;
}
if (!session.bothAccepted()) {
session.syncToPlayers();
return;
}
if (session.completeTrade()) {
finish(session, Component.literal("Trade completed."));
} else {
cancel(session, Component.literal("Trade cancelled because one player could not fit all traded items."));
}
}
private void handleDebugAction(DebugTradeSession session, TradeAction action, int slot, boolean secondary) {
boolean changed = switch (action) {
case ADD_ITEM -> session.addFromInventory(slot, secondary);
case REMOVE_ITEM -> session.removeFromOffer(slot, secondary);
case ACCEPT -> {
session.acceptSelf();
yield true;
}
case DECLINE, CLOSE -> {
closeDebug(session, Component.literal("You closed the debug trade."));
yield false;
}
};
if (!changed) {
return;
}
if (!session.isConfirmationStage()) {
session.advanceToConfirmation();
session.sync();
return;
}
if (!session.bothAccepted()) {
session.sync();
return;
}
if (session.completeTrade()) {
finishDebug(session, Component.literal("Debug trade completed."));
} else {
closeDebug(session, Component.literal("Debug trade cancelled because the items would not fit."));
}
}
public void handleDisconnect(ServerPlayer player) {
TradeSession session = getSession(player);
if (session != null) {
cancel(session, Component.literal(player.getGameProfile().getName() + " left the game."));
return;
}
DebugTradeSession debugSession = getDebugSession(player);
if (debugSession != null) {
closeDebug(debugSession, Component.literal("Debug trade closed because you left the game."));
}
}
public boolean isTrading(ServerPlayer player) {
return sessionByPlayer.containsKey(player.getUUID()) || debugSessionByPlayer.containsKey(player.getUUID());
}
public boolean initDebugTrade(ServerPlayer player) {
if (isTrading(player)) {
return false;
}
DebugTradeSession session = new DebugTradeSession(player);
debugSessionsById.put(session.id(), session);
debugSessionByPlayer.put(player.getUUID(), session.id());
session.sync();
player.sendSystemMessage(Component.literal("Debug trade opened."));
return true;
}
public boolean setDebugOffer(ServerPlayer player, List<ItemStack> offer) {
DebugTradeSession session = getDebugSession(player);
if (session == null) {
return false;
}
session.setOtherOffer(offer);
session.sync();
return true;
}
public int removeDebugOffer(ServerPlayer player, String spec) {
DebugTradeSession session = getDebugSession(player);
if (session == null) {
return -1;
}
boolean changed = session.removeOtherOffer(spec);
if (changed) {
session.sync();
return 1;
}
return 0;
}
public boolean acceptDebug(ServerPlayer player) {
DebugTradeSession session = getDebugSession(player);
if (session == null) {
return false;
}
session.acceptOther();
if (!session.isConfirmationStage()) {
session.advanceToConfirmation();
session.sync();
return true;
}
if (session.bothAccepted()) {
if (session.completeTrade()) {
finishDebug(session, Component.literal("Debug trade completed."));
} else {
closeDebug(session, Component.literal("Debug trade cancelled because the items would not fit."));
}
} else {
session.sync();
}
return true;
}
public boolean cancelDebug(ServerPlayer player) {
DebugTradeSession session = getDebugSession(player);
if (session == null) {
return false;
}
closeDebug(session, Component.literal("Debug trader cancelled the trade."));
return true;
}
public boolean closeDebug(ServerPlayer player) {
DebugTradeSession session = getDebugSession(player);
if (session == null) {
return false;
}
closeDebug(session, Component.literal("Debug trade closed."));
return true;
}
public void handleDebugControl(ServerPlayer player, UUID sessionId, DebugControlAction action, String spec) {
DebugTradeSession session = debugSessionsById.get(sessionId);
if (session == null || session.player() != player) {
return;
}
try {
switch (action) {
case SET_OFFER -> {
session.setOtherOffer(DebugTradeSession.parseOfferSpec(spec));
session.sync();
}
case APPEND_RANDOM -> {
if (session.appendOtherOffer(DebugTradeSession.randomSingleStackOffer())) {
session.sync();
}
}
case REMOVE_OFFER -> {
if (session.removeOtherOffer(spec)) {
session.sync();
}
}
case REMOVE_LAST -> {
if (session.removeLastOtherOffer()) {
session.sync();
}
}
case ACCEPT -> acceptDebug(player);
case CANCEL -> cancelDebug(player);
case CLOSE -> closeDebug(player);
}
} catch (IllegalArgumentException ignored) {
player.sendSystemMessage(Component.literal(ignored.getMessage()));
}
}
private TradeSession getSession(ServerPlayer player) {
UUID sessionId = sessionByPlayer.get(player.getUUID());
return sessionId == null ? null : sessionsById.get(sessionId);
}
private DebugTradeSession getDebugSession(ServerPlayer player) {
UUID sessionId = debugSessionByPlayer.get(player.getUUID());
return sessionId == null ? null : debugSessionsById.get(sessionId);
}
private void finish(TradeSession session, Component reason) {
session.firstPlayer().sendSystemMessage(reason);
session.secondPlayer().sendSystemMessage(reason);
session.close(reason);
removeSession(session);
}
private void cancel(TradeSession session, Component reason) {
session.firstPlayer().sendSystemMessage(reason);
session.secondPlayer().sendSystemMessage(reason);
session.close(reason);
removeSession(session);
}
private void removeSession(TradeSession session) {
sessionsById.remove(session.id());
sessionByPlayer.remove(session.firstPlayer().getUUID());
sessionByPlayer.remove(session.secondPlayer().getUUID());
}
private void finishDebug(DebugTradeSession session, Component reason) {
session.player().sendSystemMessage(reason);
session.close(reason);
removeDebugSession(session);
}
private void closeDebug(DebugTradeSession session, Component reason) {
session.player().sendSystemMessage(reason);
session.close(reason);
removeDebugSession(session);
}
private void removeDebugSession(DebugTradeSession session) {
debugSessionsById.remove(session.id());
debugSessionByPlayer.remove(session.player().getUUID());
}
}

View File

@@ -0,0 +1,281 @@
package com.trunksbomb.trade.mod.trade;
import com.trunksbomb.trade.mod.network.TradeClosePayload;
import com.trunksbomb.trade.mod.network.TradeStatePayload;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.ItemStack;
import net.neoforged.neoforge.network.PacketDistributor;
public class TradeSession {
private static final int INVENTORY_SLOT_COUNT = TradeView.INVENTORY_SLOT_COUNT;
private static final int OFFER_SLOT_COUNT = TradeView.OFFER_SLOT_COUNT;
private final UUID id = UUID.randomUUID();
private final ServerPlayer first;
private final ServerPlayer second;
private final List<ItemStack> firstOffer = blankOffer();
private final List<ItemStack> secondOffer = blankOffer();
private boolean firstAccepted;
private boolean secondAccepted;
private TradeStage stage = TradeStage.OFFERING;
public TradeSession(ServerPlayer first, ServerPlayer second) {
this.first = first;
this.second = second;
}
public UUID id() {
return id;
}
public ServerPlayer firstPlayer() {
return first;
}
public ServerPlayer secondPlayer() {
return second;
}
public boolean involves(ServerPlayer player) {
return player == first || player == second;
}
public ServerPlayer other(ServerPlayer player) {
return player == first ? second : first;
}
public void syncToPlayers() {
sendState(first);
sendState(second);
}
public void close(Component reason) {
PacketDistributor.sendToPlayer(first, new TradeClosePayload(id, reason));
PacketDistributor.sendToPlayer(second, new TradeClosePayload(id, reason));
}
public boolean addFromInventory(ServerPlayer player, int inventorySlot, boolean singleItem) {
if (stage != TradeStage.OFFERING || inventorySlot < 0 || inventorySlot >= INVENTORY_SLOT_COUNT) {
return false;
}
List<ItemStack> offer = offerFor(player);
Inventory inventory = player.getInventory();
ItemStack sourceStack = inventory.getItem(inventorySlot);
if (sourceStack.isEmpty()) {
return false;
}
ItemStack moving = sourceStack.copyWithCount(singleItem ? 1 : sourceStack.getCount());
if (!insertStack(offer, moving)) {
return false;
}
sourceStack.shrink(singleItem ? 1 : sourceStack.getCount());
if (sourceStack.isEmpty()) {
inventory.setItem(inventorySlot, ItemStack.EMPTY);
}
inventory.setChanged();
clearAccepts();
return true;
}
public boolean removeFromOffer(ServerPlayer player, int offerSlot, boolean singleItem) {
if (stage != TradeStage.OFFERING || offerSlot < 0 || offerSlot >= OFFER_SLOT_COUNT) {
return false;
}
List<ItemStack> offer = offerFor(player);
ItemStack offered = offer.get(offerSlot);
if (offered.isEmpty()) {
return false;
}
Inventory inventory = player.getInventory();
List<ItemStack> workingInventory = inventorySnapshot(player);
ItemStack returned = offered.copyWithCount(singleItem ? 1 : offered.getCount());
if (!insertStack(workingInventory, returned)) {
return false;
}
applyInventory(player, workingInventory);
if (singleItem && offered.getCount() > 1) {
ItemStack updated = offered.copy();
updated.shrink(1);
offer.set(offerSlot, updated);
} else {
offer.set(offerSlot, ItemStack.EMPTY);
}
clearAccepts();
return true;
}
public void accept(ServerPlayer player) {
if (player == first) {
firstAccepted = true;
} else {
secondAccepted = true;
}
}
public void advanceToConfirmation() {
if (stage == TradeStage.OFFERING && firstAccepted && secondAccepted) {
stage = TradeStage.CONFIRMING;
firstAccepted = false;
secondAccepted = false;
}
}
public boolean bothAccepted() {
return firstAccepted && secondAccepted;
}
public boolean isConfirmationStage() {
return stage == TradeStage.CONFIRMING;
}
public boolean completeTrade() {
List<ItemStack> firstResult = simulateResult(first, secondOffer);
List<ItemStack> secondResult = simulateResult(second, firstOffer);
if (firstResult == null || secondResult == null) {
return false;
}
applyInventory(first, firstResult);
applyInventory(second, secondResult);
clearOffer(firstOffer);
clearOffer(secondOffer);
return true;
}
public TradeView viewFor(ServerPlayer player) {
boolean isFirst = player == first;
ServerPlayer other = isFirst ? second : first;
return new TradeView(
id,
player.getGameProfile().getName(),
other.getGameProfile().getName(),
false,
stage,
isFirst ? firstAccepted : secondAccepted,
isFirst ? secondAccepted : firstAccepted,
inventorySnapshot(player),
emptyReservedSnapshot(),
offerSnapshot(isFirst ? firstOffer : secondOffer),
offerSnapshot(isFirst ? secondOffer : firstOffer));
}
public void sendState(ServerPlayer player) {
PacketDistributor.sendToPlayer(player, new TradeStatePayload(viewFor(player)));
}
private List<ItemStack> simulateResult(ServerPlayer player, List<ItemStack> incoming) {
List<ItemStack> working = inventorySnapshot(player);
for (ItemStack stack : incoming) {
if (!stack.isEmpty() && !insertStack(working, stack.copy())) {
return null;
}
}
return working;
}
private static boolean insertStack(List<ItemStack> working, ItemStack incoming) {
if (incoming.isEmpty()) {
return true;
}
for (int i = 0; i < working.size(); i++) {
ItemStack existing = working.get(i);
if (existing.isEmpty() || !ItemStack.isSameItemSameComponents(existing, incoming)) {
continue;
}
int space = existing.getMaxStackSize() - existing.getCount();
if (space <= 0) {
continue;
}
int moved = Math.min(space, incoming.getCount());
ItemStack updated = existing.copy();
updated.grow(moved);
working.set(i, updated);
incoming.shrink(moved);
if (incoming.isEmpty()) {
return true;
}
}
for (int i = 0; i < working.size(); i++) {
if (!working.get(i).isEmpty()) {
continue;
}
working.set(i, incoming.copy());
incoming.setCount(0);
return true;
}
return false;
}
private static void clearOffer(List<ItemStack> offer) {
for (int i = 0; i < offer.size(); i++) {
offer.set(i, ItemStack.EMPTY);
}
}
private static void applyInventory(ServerPlayer player, List<ItemStack> result) {
Inventory inventory = player.getInventory();
for (int i = 0; i < result.size(); i++) {
inventory.setItem(i, result.get(i));
}
inventory.setChanged();
}
private static List<ItemStack> blankOffer() {
List<ItemStack> result = new ArrayList<>(OFFER_SLOT_COUNT);
for (int i = 0; i < OFFER_SLOT_COUNT; i++) {
result.add(ItemStack.EMPTY);
}
return result;
}
private void clearAccepts() {
firstAccepted = false;
secondAccepted = false;
}
private static List<Integer> emptyReservedSnapshot() {
List<Integer> result = new ArrayList<>(INVENTORY_SLOT_COUNT);
for (int i = 0; i < INVENTORY_SLOT_COUNT; i++) {
result.add(0);
}
return result;
}
private List<ItemStack> offerFor(ServerPlayer player) {
return player == first ? firstOffer : secondOffer;
}
private static List<ItemStack> inventorySnapshot(ServerPlayer player) {
List<ItemStack> result = new ArrayList<>(INVENTORY_SLOT_COUNT);
Inventory inventory = player.getInventory();
for (int i = 0; i < INVENTORY_SLOT_COUNT; i++) {
result.add(inventory.getItem(i).copy());
}
return result;
}
private static List<ItemStack> offerSnapshot(List<ItemStack> offer) {
List<ItemStack> result = new ArrayList<>(OFFER_SLOT_COUNT);
for (ItemStack stack : offer) {
result.add(stack.copy());
}
return result;
}
}

View File

@@ -0,0 +1,6 @@
package com.trunksbomb.trade.mod.trade;
public enum TradeStage {
OFFERING,
CONFIRMING
}

View File

@@ -0,0 +1,86 @@
package com.trunksbomb.trade.mod.trade;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.world.item.ItemStack;
public record TradeView(
UUID sessionId,
String selfName,
String otherName,
boolean debugMode,
TradeStage stage,
boolean selfAccepted,
boolean otherAccepted,
List<ItemStack> inventory,
List<Integer> reservedCounts,
List<ItemStack> selfOffer,
List<ItemStack> otherOffer) {
public static final int INVENTORY_SLOT_COUNT = 36;
public static final int OFFER_SLOT_COUNT = 36;
public static final StreamCodec<RegistryFriendlyByteBuf, TradeView> STREAM_CODEC = new StreamCodec<>() {
@Override
public void encode(RegistryFriendlyByteBuf buf, TradeView value) {
buf.writeUUID(value.sessionId);
buf.writeUtf(value.selfName);
buf.writeUtf(value.otherName);
buf.writeBoolean(value.debugMode);
buf.writeEnum(value.stage);
buf.writeBoolean(value.selfAccepted);
buf.writeBoolean(value.otherAccepted);
writeStacks(buf, value.inventory, INVENTORY_SLOT_COUNT);
writeInts(buf, value.reservedCounts, INVENTORY_SLOT_COUNT);
writeStacks(buf, value.selfOffer, OFFER_SLOT_COUNT);
writeStacks(buf, value.otherOffer, OFFER_SLOT_COUNT);
}
@Override
public TradeView decode(RegistryFriendlyByteBuf buf) {
return new TradeView(
buf.readUUID(),
buf.readUtf(),
buf.readUtf(),
buf.readBoolean(),
buf.readEnum(TradeStage.class),
buf.readBoolean(),
buf.readBoolean(),
readStacks(buf, INVENTORY_SLOT_COUNT),
readInts(buf, INVENTORY_SLOT_COUNT),
readStacks(buf, OFFER_SLOT_COUNT),
readStacks(buf, OFFER_SLOT_COUNT));
}
};
private static void writeStacks(RegistryFriendlyByteBuf buf, List<ItemStack> stacks, int expectedSize) {
for (int i = 0; i < expectedSize; i++) {
ItemStack.OPTIONAL_STREAM_CODEC.encode(buf, stacks.get(i));
}
}
private static List<ItemStack> readStacks(RegistryFriendlyByteBuf buf, int expectedSize) {
List<ItemStack> stacks = new ArrayList<>(expectedSize);
for (int i = 0; i < expectedSize; i++) {
stacks.add(ItemStack.OPTIONAL_STREAM_CODEC.decode(buf));
}
return stacks;
}
private static void writeInts(RegistryFriendlyByteBuf buf, List<Integer> values, int expectedSize) {
for (int i = 0; i < expectedSize; i++) {
buf.writeVarInt(values.get(i));
}
}
private static List<Integer> readInts(RegistryFriendlyByteBuf buf, int expectedSize) {
List<Integer> values = new ArrayList<>(expectedSize);
for (int i = 0; i < expectedSize; i++) {
values.add(buf.readVarInt());
}
return values;
}
}

View File

@@ -0,0 +1,5 @@
{
"trade.trade.title": "Trading Screen",
"trade.trade.offer": "Offer screen",
"trade.trade.confirm": "Confirmation screen"
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@@ -0,0 +1,95 @@
# This is an example neoforge.mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader="javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the FML version. This is currently 2.
loaderVersion="${loader_version_range}" #mandatory
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license="${mod_license}"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId="${mod_id}" #mandatory
# The version number of the mod
version="${mod_version}" #mandatory
# A display name for the mod
displayName="Trading Screen" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://docs.neoforged.net/docs/misc/updatechecker/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
#logoFile="examplemod.png" #optional
# A text field displayed in the mod UI
#credits="" #optional
# The authors of the mod, displayed in the mod UI (optional)
authors="trunksbomb"
# The description text for the mod (multi line!) (#mandatory)
description='''
RuneScape-style player trading with ghost item offers and a two-step confirmation flow.
'''
# The [[mixins]] block allows you to declare your mixin config to FML so that it gets loaded.
#[[mixins]]
#config="${mod_id}.mixins.json"
# The [[accessTransformers]] block allows you to declare where your AT file is.
# If this block is omitted, a fallback attempt will be made to load an AT from META-INF/accesstransformer.cfg
#[[accessTransformers]]
#file="META-INF/accesstransformer.cfg"
# The coremods config file path is not configurable and is always loaded from META-INF/coremods.json
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.${mod_id}]] #optional
# the modid of the dependency
modId="neoforge" #mandatory
# The type of the dependency. Can be one of "required", "optional", "incompatible" or "discouraged" (case insensitive).
# 'required' requires the mod to exist, 'optional' does not
# 'incompatible' will prevent the game from loading when the mod exists, and 'discouraged' will show a warning
type="required" #mandatory
# Optional field describing why the dependency is required or why it is incompatible
# reason="..."
# The version range of the dependency
versionRange="[${neo_version},)" #mandatory
# An ordering relationship for the dependency.
# BEFORE - This mod is loaded BEFORE the dependency
# AFTER - This mod is loaded AFTER the dependency
ordering="NONE"
# Side this dependency is applied on - BOTH, CLIENT, or SERVER
side="BOTH"
# Here's another dependency
[[dependencies.${mod_id}]]
modId="minecraft"
type="required"
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange="${minecraft_version_range}"
ordering="NONE"
side="BOTH"
# Features are specific properties of the game environment, that you may want to declare you require. This example declares
# that your mod requires GL version 3.2 or higher. Other features will be added. They are side aware so declaring this won't
# stop your mod loading on the server for example.
#[features.${mod_id}]
#openGLVersion="[3.2,)"