Satura: каркас мода, ядро, селекция, план, рендер, стратегии постановки и движок
Фазы 0-5: сборка Gradle/Loom, core (события, команды, конфиг), selection/plan/scan, рендер (перенесён из Atheryx, см. NOTICE.md), стратегии ColumnDrop/BandStack, HotbarRefill/ClickScheduler, BuildEngine и команды .build.
This commit is contained in:
commit
b26dfbbade
169 changed files with 7825 additions and 0 deletions
30
.gitignore
vendored
Normal file
30
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Gradle
|
||||
.gradle/
|
||||
build/
|
||||
run/
|
||||
remappedSrc/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.settings/
|
||||
.classpath
|
||||
.project
|
||||
bin/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
|
||||
# Чужие референсы и распаковки (343M, чужой код)
|
||||
ref/
|
||||
|
||||
# Логи и локальные данные
|
||||
*.log
|
||||
hs_err_pid*
|
||||
logs/
|
||||
todo.md
|
||||
|
||||
# Локальные заметки
|
||||
NOTICE.md
|
||||
todo.md
|
||||
76
build.gradle.kts
Normal file
76
build.gradle.kts
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
plugins {
|
||||
id("fabric-loom") version "1.18.4"
|
||||
java
|
||||
checkstyle
|
||||
pmd
|
||||
}
|
||||
|
||||
version = property("mod_version") as String
|
||||
group = property("maven_group") as String
|
||||
|
||||
base {
|
||||
archivesName.set(property("archives_base_name") as String)
|
||||
}
|
||||
|
||||
repositories {
|
||||
// nether-pathfinder — рантайм-зависимость Baritone (Aethereal) для dev-запусков
|
||||
maven("https://babbaj.github.io/maven/") {
|
||||
name = "Babbaj"
|
||||
}
|
||||
}
|
||||
|
||||
dependencies {
|
||||
minecraft("com.mojang:minecraft:${property("minecraft_version")}")
|
||||
mappings("net.fabricmc:yarn:${property("yarn_mappings")}:v2")
|
||||
modImplementation("net.fabricmc:fabric-loader:${property("loader_version")}")
|
||||
modImplementation("net.fabricmc.fabric-api:fabric-api:${property("fabric_version")}")
|
||||
|
||||
// Baritone (Aethereal): API для компиляции + сам мод в dev-рантайме
|
||||
compileOnly(files("libs/aethereal-1.21.11.jar"))
|
||||
modLocalRuntime(files("libs/aethereal-1.21.11.jar"))
|
||||
modLocalRuntime("dev.babbaj:nether-pathfinder:1.4.1")
|
||||
|
||||
testImplementation(platform("org.junit:junit-bom:5.11.4"))
|
||||
testImplementation("org.junit.jupiter:junit-jupiter")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
}
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_21
|
||||
targetCompatibility = JavaVersion.VERSION_21
|
||||
withSourcesJar()
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.encoding = "UTF-8"
|
||||
options.release.set(21)
|
||||
}
|
||||
|
||||
tasks.processResources {
|
||||
inputs.property("version", project.version)
|
||||
filesMatching("fabric.mod.json") {
|
||||
expand("version" to project.version)
|
||||
}
|
||||
}
|
||||
|
||||
// Правило проекта: файл максимум 200 строк — FileLength (severity=error валит check)
|
||||
checkstyle {
|
||||
toolVersion = "10.21.2"
|
||||
configFile = rootProject.file("config/checkstyle/checkstyle.xml")
|
||||
}
|
||||
|
||||
pmd {
|
||||
toolVersion = "7.9.0"
|
||||
isConsoleOutput = true
|
||||
ruleSetFiles = rootProject.files("config/pmd/pmd.xml")
|
||||
ruleSets = mutableListOf()
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
|
||||
// Тесты — шумные правила JUnit в PMD (assert-сообщения, число assert) не применяем
|
||||
tasks.named("pmdTest") {
|
||||
enabled = false
|
||||
}
|
||||
43
config/checkstyle/checkstyle.xml
Normal file
43
config/checkstyle/checkstyle.xml
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
<?xml version="1.0"?>
|
||||
<!DOCTYPE module PUBLIC
|
||||
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
|
||||
"https://checkstyle.org/dtds/configuration_1_3.dtd">
|
||||
|
||||
<!-- Правила проекта satura: FileLength 200 — единственный жёсткий (error) гейт,
|
||||
остальное — предупреждения. -->
|
||||
<module name="Checker">
|
||||
<property name="charset" value="UTF-8"/>
|
||||
<property name="severity" value="warning"/>
|
||||
|
||||
<module name="FileLength">
|
||||
<property name="max" value="200"/>
|
||||
<property name="severity" value="error"/>
|
||||
<property name="fileExtensions" value="java"/>
|
||||
</module>
|
||||
|
||||
<module name="FileTabCharacter">
|
||||
<property name="eachLine" value="true"/>
|
||||
</module>
|
||||
|
||||
<module name="NewlineAtEndOfFile"/>
|
||||
|
||||
<module name="LineLength">
|
||||
<property name="max" value="120"/>
|
||||
</module>
|
||||
|
||||
<module name="TreeWalker">
|
||||
<module name="UnusedImports"/>
|
||||
<module name="RedundantImport"/>
|
||||
<module name="OneTopLevelClass"/>
|
||||
<module name="OuterTypeFilename"/>
|
||||
<module name="FinalClass"/>
|
||||
<module name="HideUtilityClassConstructor"/>
|
||||
<module name="StringLiteralEquality"/>
|
||||
<module name="EmptyCatchBlock">
|
||||
<property name="exceptionVariableName" value="expected|ignore|ignored"/>
|
||||
</module>
|
||||
<module name="FallThrough"/>
|
||||
<module name="SimplifyBooleanExpression"/>
|
||||
<module name="SimplifyBooleanReturn"/>
|
||||
</module>
|
||||
</module>
|
||||
25
config/pmd/pmd.xml
Normal file
25
config/pmd/pmd.xml
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<?xml version="1.0"?>
|
||||
<ruleset name="satura"
|
||||
xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0
|
||||
https://pmd.sourceforge.io/ruleset_2_0_0.xsd">
|
||||
|
||||
<description>Satura base ruleset: errorprone + bestpractices + design (без шума)</description>
|
||||
|
||||
<rule ref="category/java/errorprone.xml"/>
|
||||
|
||||
<rule ref="category/java/bestpractices.xml">
|
||||
<exclude name="GuardLogStatements"/>
|
||||
<exclude name="AccessorMethodGeneration"/>
|
||||
<exclude name="UnusedPrivateMethod"/>
|
||||
</rule>
|
||||
|
||||
<rule ref="category/java/design.xml">
|
||||
<exclude name="TooManyMethods"/>
|
||||
<exclude name="ExcessiveImports"/>
|
||||
<exclude name="LawOfDemeter"/>
|
||||
<exclude name="LoosePackageCoupling"/>
|
||||
<exclude name="UseUtilityClass"/>
|
||||
</rule>
|
||||
</ruleset>
|
||||
15
gradle.properties
Normal file
15
gradle.properties
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
# Gradle
|
||||
org.gradle.jvmargs=-Xmx2G
|
||||
org.gradle.parallel=true
|
||||
|
||||
# Fabric / Minecraft (проверены: meta.fabricmc.net + Modrinth)
|
||||
minecraft_version=1.21.11
|
||||
yarn_mappings=1.21.11+build.6
|
||||
loader_version=0.20.1
|
||||
fabric_version=0.141.6+1.21.11
|
||||
|
||||
# Мод
|
||||
mod_version=0.1.0
|
||||
maven_group=dev.loki
|
||||
archives_base_name=satura
|
||||
org.gradle.java.home=/usr/lib/jvm/java-25-openjdk
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Normal file
Binary file not shown.
9
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
9
gradle/wrapper/gradle-wrapper.properties
vendored
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.2-bin.zip
|
||||
networkTimeout=10000
|
||||
retries=0
|
||||
retryBackOffMs=500
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
zipStorePath=wrapper/dists
|
||||
248
gradlew
vendored
Executable file
248
gradlew
vendored
Executable file
|
|
@ -0,0 +1,248 @@
|
|||
#!/bin/sh
|
||||
|
||||
#
|
||||
# Copyright © 2015 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
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
#
|
||||
# gradlew 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 gradlew
|
||||
#
|
||||
# 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/<unknown>/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
|
||||
|
||||
|
||||
|
||||
# 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" )
|
||||
|
||||
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" \
|
||||
-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" "$@"
|
||||
112
gradlew.bat
vendored
Normal file
112
gradlew.bat
vendored
Normal file
|
|
@ -0,0 +1,112 @@
|
|||
@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 gradlew startup script for Windows
|
||||
@rem
|
||||
@rem ##########################################################################
|
||||
|
||||
@rem Set local scope for the variables, and ensure extensions are enabled
|
||||
setlocal EnableExtensions
|
||||
|
||||
@rem Catch executions from older scripts and ensure they exit cleanly.
|
||||
@rem This can be removed once we can be reasonably confident that few people
|
||||
@rem will be migrating directly to this new wrapper.
|
||||
goto afterSafetyNet
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
|
||||
goto exitWithErrorLevel
|
||||
:afterSafetyNet
|
||||
|
||||
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
|
||||
|
||||
1>&2 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.
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
goto exitWithErrorLevel
|
||||
|
||||
:findJavaFromJavaHome
|
||||
set JAVA_HOME=%JAVA_HOME:"=%
|
||||
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
|
||||
|
||||
if exist "%JAVA_EXE%" goto execute
|
||||
|
||||
1>&2 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.
|
||||
|
||||
"%COMSPEC%" /c exit 1
|
||||
goto exitWithErrorLevel
|
||||
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
|
||||
|
||||
@rem Execute gradlew
|
||||
@rem endlocal doesn't take effect until after the line is parsed and variables are expanded
|
||||
@rem which allows us to clear the local environment before executing the java command
|
||||
endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel
|
||||
|
||||
@rem This label must not be changed. We rely on old scripts being able to jump to this point.
|
||||
:exitWithErrorLevel
|
||||
@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts
|
||||
"%COMSPEC%" /c exit %ERRORLEVEL%
|
||||
BIN
libs/aethereal-1.21.11.jar
Normal file
BIN
libs/aethereal-1.21.11.jar
Normal file
Binary file not shown.
11
settings.gradle.kts
Normal file
11
settings.gradle.kts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
pluginManagement {
|
||||
repositories {
|
||||
maven("https://maven.fabricmc.net/") {
|
||||
name = "Fabric"
|
||||
}
|
||||
mavenCentral()
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
|
||||
rootProject.name = "satura"
|
||||
44
src/main/java/dev/loki/satura/SaturaClient.java
Normal file
44
src/main/java/dev/loki/satura/SaturaClient.java
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
package dev.loki.satura;
|
||||
|
||||
import dev.loki.satura.core.CoreServices;
|
||||
import dev.loki.satura.core.command.CommandRegistry;
|
||||
import dev.loki.satura.core.command.builtin.HelpCommand;
|
||||
import dev.loki.satura.core.config.ConfigStore;
|
||||
import dev.loki.satura.core.event.EventBus;
|
||||
import dev.loki.satura.feature.builder.BuilderFeature;
|
||||
import dev.loki.satura.render.RenderDebug;
|
||||
import dev.loki.satura.render.Renderer;
|
||||
import dev.loki.satura.render.world.Marks;
|
||||
import dev.loki.satura.render.world.SelectionRenderer;
|
||||
import dev.loki.satura.util.ChatOut;
|
||||
import net.fabricmc.api.ClientModInitializer;
|
||||
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Точка входа клиента. Только сборка компонентов — вся логика в feature-пакетах.
|
||||
*/
|
||||
public final class SaturaClient implements ClientModInitializer {
|
||||
|
||||
public static final String MOD_ID = "satura";
|
||||
private static final boolean SELECTION_SEE_THROUGH = true;
|
||||
|
||||
public static final Logger LOG = LoggerFactory.getLogger(MOD_ID);
|
||||
|
||||
@Override
|
||||
public void onInitializeClient() {
|
||||
CommandRegistry commands = new CommandRegistry(new ChatOut());
|
||||
commands.register(new HelpCommand(commands));
|
||||
EventBus events = new EventBus();
|
||||
ConfigStore config = new ConfigStore(FabricLoader.getInstance().getConfigDir().resolve(MOD_ID));
|
||||
BuilderFeature builder = BuilderFeature.create(commands, events, config);
|
||||
CoreServices.install(new CoreServices(events, commands, config));
|
||||
ClientTickEvents.END_CLIENT_TICK.register(client -> builder.tick());
|
||||
RenderDebug.installIfEnabled(Renderer.shared());
|
||||
new SelectionRenderer(() -> new Marks(builder.selection().pos1(), builder.selection().pos2()),
|
||||
SELECTION_SEE_THROUGH).register();
|
||||
LOG.info("[satura] client init");
|
||||
}
|
||||
}
|
||||
20
src/main/java/dev/loki/satura/core/CoreServices.java
Normal file
20
src/main/java/dev/loki/satura/core/CoreServices.java
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
package dev.loki.satura.core;
|
||||
|
||||
import dev.loki.satura.core.command.CommandRegistry;
|
||||
import dev.loki.satura.core.config.ConfigStore;
|
||||
import dev.loki.satura.core.event.EventBus;
|
||||
|
||||
/** Собранное ядро; доступ для миксинов (они не могут получить зависимости через конструктор). */
|
||||
public record CoreServices(EventBus events, CommandRegistry commands, ConfigStore config) {
|
||||
|
||||
private static CoreServices current;
|
||||
|
||||
public static void install(CoreServices services) {
|
||||
current = services;
|
||||
}
|
||||
|
||||
/** Ядро или null, если мод ещё не инициализирован. */
|
||||
public static CoreServices get() {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
29
src/main/java/dev/loki/satura/core/command/Command.java
Normal file
29
src/main/java/dev/loki/satura/core/command/Command.java
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
package dev.loki.satura.core.command;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Чат-команда с префиксом {@code .}. */
|
||||
public interface Command {
|
||||
|
||||
String name();
|
||||
|
||||
String description();
|
||||
|
||||
/**
|
||||
* Выполнить команду.
|
||||
*
|
||||
* @param args токены после имени
|
||||
* @param reply куда писать ответ пользователю
|
||||
*/
|
||||
void execute(List<String> args, Consumer<String> reply);
|
||||
|
||||
/**
|
||||
* Кандидаты для последнего (редактируемого) токена.
|
||||
*
|
||||
* @param args токены после имени; последний — недописанный (может быть пустым)
|
||||
*/
|
||||
default List<String> suggest(List<String> args) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package dev.loki.satura.core.command;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/** Разбиение строки на токены по пробелам; кавычки группируют; хвостовой пробел даёт пустой токен. */
|
||||
final class CommandParser {
|
||||
|
||||
private static final char QUOTE = '"';
|
||||
private static final char SEPARATOR = ' ';
|
||||
|
||||
private CommandParser() {
|
||||
}
|
||||
|
||||
static List<String> tokenize(String line) {
|
||||
List<String> tokens = new ArrayList<>();
|
||||
StringBuilder cur = new StringBuilder();
|
||||
boolean quoted = false;
|
||||
for (char ch : line.toCharArray()) {
|
||||
if (ch == QUOTE) {
|
||||
quoted = !quoted;
|
||||
} else if (ch == SEPARATOR && !quoted) {
|
||||
flush(tokens, cur);
|
||||
} else {
|
||||
cur.append(ch);
|
||||
}
|
||||
}
|
||||
tokens.add(cur.toString());
|
||||
return tokens;
|
||||
}
|
||||
|
||||
private static void flush(List<String> tokens, StringBuilder cur) {
|
||||
if (!cur.isEmpty()) {
|
||||
tokens.add(cur.toString());
|
||||
cur.setLength(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,62 @@
|
|||
package dev.loki.satura.core.command;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Реестр команд: регистрация, выполнение строки и подсказки. */
|
||||
@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidCatchingGenericException"})
|
||||
public final class CommandRegistry {
|
||||
|
||||
private static final int COMMAND_ONLY = 1;
|
||||
|
||||
private final Map<String, Command> commands = new TreeMap<>();
|
||||
private final Consumer<String> reply;
|
||||
|
||||
public CommandRegistry(Consumer<String> reply) {
|
||||
this.reply = reply;
|
||||
}
|
||||
|
||||
public void register(Command command) {
|
||||
commands.put(command.name().toLowerCase(Locale.ROOT), command);
|
||||
}
|
||||
|
||||
public Collection<Command> all() {
|
||||
return commands.values();
|
||||
}
|
||||
|
||||
/** Выполняет строку без префикса, например {@code "help"}. */
|
||||
public void execute(String line) {
|
||||
List<String> tokens = CommandParser.tokenize(line.strip());
|
||||
Command command = commands.get(tokens.get(0).toLowerCase(Locale.ROOT));
|
||||
if (command == null) {
|
||||
reply.accept("Неизвестная команда: " + tokens.get(0) + " (.help)");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
command.execute(tokens.subList(1, tokens.size()), reply);
|
||||
} catch (RuntimeException e) {
|
||||
reply.accept("Ошибка: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** Подсказки для текста до курсора (с префиксом). */
|
||||
public List<String> suggest(String toCursor) {
|
||||
String body = toCursor.startsWith(SuggestHelper.PREFIX)
|
||||
? toCursor.substring(SuggestHelper.PREFIX.length()) : toCursor;
|
||||
List<String> tokens = CommandParser.tokenize(body);
|
||||
String current = tokens.get(tokens.size() - 1);
|
||||
if (tokens.size() == COMMAND_ONLY) {
|
||||
return SuggestHelper.filter(current, new ArrayList<>(commands.keySet()));
|
||||
}
|
||||
Command command = commands.get(tokens.get(0).toLowerCase(Locale.ROOT));
|
||||
if (command == null) {
|
||||
return List.of();
|
||||
}
|
||||
return SuggestHelper.filter(current, command.suggest(tokens.subList(1, tokens.size())));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
package dev.loki.satura.core.command;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
|
||||
/** Фильтрация подсказок по префиксу и позиция начала редактируемого токена. */
|
||||
public final class SuggestHelper {
|
||||
|
||||
public static final String PREFIX = ".";
|
||||
private static final char SEPARATOR = ' ';
|
||||
|
||||
private SuggestHelper() {
|
||||
}
|
||||
|
||||
public static boolean isCommand(String text) {
|
||||
return text.startsWith(PREFIX);
|
||||
}
|
||||
|
||||
public static int tokenStart(String toCursor) {
|
||||
int lastSpace = toCursor.lastIndexOf(SEPARATOR);
|
||||
if (lastSpace >= 0) {
|
||||
return lastSpace + 1;
|
||||
}
|
||||
return isCommand(toCursor) ? PREFIX.length() : 0;
|
||||
}
|
||||
|
||||
public static List<String> filter(String prefix, List<String> options) {
|
||||
String key = prefix.toLowerCase(Locale.ROOT);
|
||||
return options.stream()
|
||||
.filter(o -> o.toLowerCase(Locale.ROOT).startsWith(key))
|
||||
.distinct()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package dev.loki.satura.core.command.builtin;
|
||||
|
||||
import dev.loki.satura.core.command.Command;
|
||||
import dev.loki.satura.core.command.CommandRegistry;
|
||||
import dev.loki.satura.core.command.SuggestHelper;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** {@code .help} — список зарегистрированных команд. */
|
||||
public final class HelpCommand implements Command {
|
||||
|
||||
private final CommandRegistry registry;
|
||||
|
||||
public HelpCommand(CommandRegistry registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "help";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "список команд";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(List<String> args, Consumer<String> reply) {
|
||||
reply.accept("Команды Satura:");
|
||||
for (Command c : registry.all()) {
|
||||
reply.accept(SuggestHelper.PREFIX + c.name() + " — " + c.description());
|
||||
}
|
||||
}
|
||||
}
|
||||
60
src/main/java/dev/loki/satura/core/config/ConfigStore.java
Normal file
60
src/main/java/dev/loki/satura/core/config/ConfigStore.java
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package dev.loki.satura.core.config;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import java.io.IOException;
|
||||
import java.io.Reader;
|
||||
import java.io.Writer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/** Хранение профилей как json-файлов в каталоге (config/satura/). */
|
||||
public final class ConfigStore {
|
||||
|
||||
private static final String EXTENSION = ".json";
|
||||
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().create();
|
||||
|
||||
private final Path dir;
|
||||
|
||||
public ConfigStore(Path dir) {
|
||||
this.dir = dir;
|
||||
}
|
||||
|
||||
public void save(Profile profile) throws IOException {
|
||||
Files.createDirectories(dir);
|
||||
try (Writer w = Files.newBufferedWriter(file(profile.name()), StandardCharsets.UTF_8)) {
|
||||
GSON.toJson(profile, w);
|
||||
}
|
||||
}
|
||||
|
||||
public Optional<Profile> load(String name) throws IOException {
|
||||
Path file = file(name);
|
||||
if (!Files.exists(file)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try (Reader r = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
|
||||
return Optional.ofNullable(GSON.fromJson(r, Profile.class));
|
||||
}
|
||||
}
|
||||
|
||||
public List<String> list() throws IOException {
|
||||
if (!Files.isDirectory(dir)) {
|
||||
return List.of();
|
||||
}
|
||||
try (Stream<Path> files = Files.list(dir)) {
|
||||
return files.map(p -> p.getFileName().toString())
|
||||
.filter(n -> n.endsWith(EXTENSION))
|
||||
.map(n -> n.substring(0, n.length() - EXTENSION.length()))
|
||||
.sorted()
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
|
||||
private Path file(String name) {
|
||||
return dir.resolve(name + EXTENSION);
|
||||
}
|
||||
}
|
||||
34
src/main/java/dev/loki/satura/core/config/Profile.java
Normal file
34
src/main/java/dev/loki/satura/core/config/Profile.java
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
package dev.loki.satura.core.config;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Иммутабельный профиль настроек.
|
||||
*
|
||||
* @param name имя профиля (имя файла)
|
||||
* @param settings ключ → значение
|
||||
*/
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public record Profile(String name, Map<String, String> settings) {
|
||||
|
||||
public static final String DEFAULT_NAME = "default";
|
||||
|
||||
public Profile {
|
||||
settings = Map.copyOf(settings);
|
||||
}
|
||||
|
||||
public static Profile empty(String name) {
|
||||
return new Profile(name, Map.of());
|
||||
}
|
||||
|
||||
public String get(String key, String fallback) {
|
||||
return settings.getOrDefault(key, fallback);
|
||||
}
|
||||
|
||||
public Profile with(String key, String value) {
|
||||
Map<String, String> copy = new HashMap<>(settings);
|
||||
copy.put(key, value);
|
||||
return new Profile(name, copy);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package dev.loki.satura.core.event;
|
||||
|
||||
/** Событие, обработку которого можно отменить; после отмены цепочка слушателей прерывается. */
|
||||
public interface Cancellable extends Event {
|
||||
|
||||
boolean isCancelled();
|
||||
|
||||
void cancel();
|
||||
}
|
||||
5
src/main/java/dev/loki/satura/core/event/Event.java
Normal file
5
src/main/java/dev/loki/satura/core/event/Event.java
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
package dev.loki.satura.core.event;
|
||||
|
||||
/** Маркер события. Тип события = его класс. */
|
||||
public interface Event {
|
||||
}
|
||||
48
src/main/java/dev/loki/satura/core/event/EventBus.java
Normal file
48
src/main/java/dev/loki/satura/core/event/EventBus.java
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
package dev.loki.satura.core.event;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
/** Шина событий: подписка с приоритетами, отписка, остановка цепочки на отменённом событии. */
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public final class EventBus {
|
||||
|
||||
private static final Comparator<Listener<?>> BY_PRIORITY = Comparator.comparingInt(Listener::priority);
|
||||
|
||||
private final Map<Class<?>, List<Listener<?>>> registry = new ConcurrentHashMap<>();
|
||||
|
||||
public <T extends Event> Listener<T> subscribe(Listener<T> listener) {
|
||||
registry.computeIfAbsent(listener.type(), k -> new CopyOnWriteArrayList<>()).add(listener);
|
||||
registry.get(listener.type()).sort(BY_PRIORITY);
|
||||
return listener;
|
||||
}
|
||||
|
||||
public <T extends Event> Listener<T> subscribe(Class<T> type, java.util.function.Consumer<T> handler) {
|
||||
return subscribe(Listener.of(type, handler));
|
||||
}
|
||||
|
||||
public void unsubscribe(Listener<?> listener) {
|
||||
List<Listener<?>> list = registry.get(listener.type());
|
||||
if (list != null) {
|
||||
list.remove(listener);
|
||||
}
|
||||
}
|
||||
|
||||
public <T extends Event> T post(T event) {
|
||||
List<Listener<?>> list = registry.get(event.getClass());
|
||||
if (list == null) {
|
||||
return event;
|
||||
}
|
||||
for (Listener<?> listener : new ArrayList<>(list)) {
|
||||
listener.accept(event);
|
||||
if (event instanceof Cancellable c && c.isCancelled()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return event;
|
||||
}
|
||||
}
|
||||
24
src/main/java/dev/loki/satura/core/event/Listener.java
Normal file
24
src/main/java/dev/loki/satura/core/event/Listener.java
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
package dev.loki.satura.core.event;
|
||||
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Подписка на событие. Меньший priority вызывается раньше.
|
||||
*
|
||||
* @param type класс события
|
||||
* @param priority порядок вызова
|
||||
* @param handler обработчик
|
||||
* @param <T> тип события
|
||||
*/
|
||||
public record Listener<T extends Event>(Class<T> type, int priority, Consumer<T> handler) {
|
||||
|
||||
public static final int DEFAULT_PRIORITY = 0;
|
||||
|
||||
public static <T extends Event> Listener<T> of(Class<T> type, Consumer<T> handler) {
|
||||
return new Listener<>(type, DEFAULT_PRIORITY, handler);
|
||||
}
|
||||
|
||||
void accept(Event event) {
|
||||
handler.accept(type.cast(event));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package dev.loki.satura.core.event.world;
|
||||
|
||||
import dev.loki.satura.core.event.Event;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** В клиентском мире изменился блок. */
|
||||
public record BlockChangeEvent(BlockPos pos) implements Event {
|
||||
}
|
||||
151
src/main/java/dev/loki/satura/feature/builder/BuildSettings.java
Normal file
151
src/main/java/dev/loki/satura/feature/builder/BuildSettings.java
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
package dev.loki.satura.feature.builder;
|
||||
|
||||
import dev.loki.satura.core.config.Profile;
|
||||
import dev.loki.satura.feature.builder.plan.Planner;
|
||||
import dev.loki.satura.feature.builder.plan.shape.BoxShape;
|
||||
import dev.loki.satura.feature.builder.plan.shape.CheckerShape;
|
||||
import dev.loki.satura.feature.builder.plan.shape.Shape;
|
||||
import dev.loki.satura.feature.builder.plan.shape.WallsShape;
|
||||
import dev.loki.satura.interaction.place.PlaceStrategy;
|
||||
import dev.loki.satura.interaction.place.option.CommonOptions;
|
||||
import dev.loki.satura.interaction.place.option.Option;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
/** Настройки билдера; читаются из {@link Profile} и в него же сериализуются. */
|
||||
@SuppressWarnings({"PMD.LooseCoupling", "PMD.AvoidFieldNameMatchingMethodName"})
|
||||
public final class BuildSettings {
|
||||
|
||||
static final String KEY_BLOCK = "block";
|
||||
static final String KEY_SHAPE = "shape";
|
||||
static final String KEY_LAYERS = "layers";
|
||||
static final String KEY_STRATEGY = "strategy";
|
||||
private static final String OPT_PREFIX = "opt.";
|
||||
private static final String DEFAULT_BLOCK = "hand";
|
||||
private static final String DEFAULT_SHAPE = "box";
|
||||
|
||||
private final Map<String, Shape> shapes = new LinkedHashMap<>();
|
||||
private final Map<String, PlaceStrategy> strategies = new LinkedHashMap<>();
|
||||
private String block;
|
||||
private String shape;
|
||||
private String strategy;
|
||||
private int layers;
|
||||
|
||||
public BuildSettings(final Profile profile, final List<PlaceStrategy> available) {
|
||||
shapes.put("box", new BoxShape());
|
||||
shapes.put("checker", new CheckerShape());
|
||||
shapes.put("walls", new WallsShape());
|
||||
for (final PlaceStrategy s : available) {
|
||||
strategies.put(s.id(), s);
|
||||
}
|
||||
block = profile.get(KEY_BLOCK, DEFAULT_BLOCK);
|
||||
shape = shapes.containsKey(profile.get(KEY_SHAPE, "")) ? profile.get(KEY_SHAPE, "") : DEFAULT_SHAPE;
|
||||
strategy = strategies.containsKey(profile.get(KEY_STRATEGY, ""))
|
||||
? profile.get(KEY_STRATEGY, "") : available.get(0).id();
|
||||
layers = parseLayers(profile.get(KEY_LAYERS, "2"));
|
||||
strategies.values().forEach(s -> loadOptions(profile, s));
|
||||
}
|
||||
|
||||
public String block() {
|
||||
return block;
|
||||
}
|
||||
|
||||
public void setBlock(final String id) {
|
||||
block = id;
|
||||
}
|
||||
|
||||
public String shapeId() {
|
||||
return shape;
|
||||
}
|
||||
|
||||
public Shape shape() {
|
||||
return shapes.get(shape);
|
||||
}
|
||||
|
||||
public List<String> shapeIds() {
|
||||
return List.copyOf(shapes.keySet());
|
||||
}
|
||||
|
||||
public void setShape(final String id) {
|
||||
final String key = id.toLowerCase(Locale.ROOT);
|
||||
require(shapes.containsKey(key), "форма: " + shapeIds());
|
||||
shape = key;
|
||||
}
|
||||
|
||||
public PlaceStrategy strategy() {
|
||||
return strategies.get(strategy);
|
||||
}
|
||||
|
||||
public List<String> strategyIds() {
|
||||
return List.copyOf(strategies.keySet());
|
||||
}
|
||||
|
||||
public void setStrategy(final String id) {
|
||||
require(strategies.containsKey(id), "стратегия: " + strategyIds());
|
||||
strategy = id;
|
||||
}
|
||||
|
||||
/** Слоёв за проход: значение опции стратегии bandLayers, если она её объявляет. */
|
||||
public int layers() {
|
||||
final PlaceStrategy s = strategy();
|
||||
return s.options().contains(CommonOptions.BAND_LAYERS)
|
||||
? s.values().getInt(CommonOptions.BAND_LAYERS) : layers;
|
||||
}
|
||||
|
||||
public void setLayers(final int value) {
|
||||
require(value >= Planner.MIN_BAND_LAYERS && value <= Planner.MAX_BAND_LAYERS, "слои: 1-3");
|
||||
layers = value;
|
||||
strategies.values().stream().filter(s -> s.options().contains(CommonOptions.BAND_LAYERS))
|
||||
.forEach(s -> s.values().set(CommonOptions.BAND_LAYERS.key(), value));
|
||||
}
|
||||
|
||||
public List<String> optionKeys() {
|
||||
return strategy().options().stream().map(Option::key).toList();
|
||||
}
|
||||
|
||||
public void setOption(final String key, final String value) {
|
||||
final double number;
|
||||
try {
|
||||
number = Double.parseDouble(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException("не число: " + value, e);
|
||||
}
|
||||
require(strategy().values().set(key, number), "параметр: " + optionKeys());
|
||||
if (CommonOptions.BAND_LAYERS.key().equals(key)) {
|
||||
layers = strategy().values().getInt(CommonOptions.BAND_LAYERS);
|
||||
}
|
||||
}
|
||||
|
||||
public Profile toProfile(final String name) {
|
||||
Profile p = Profile.empty(name).with(KEY_BLOCK, block).with(KEY_SHAPE, shape)
|
||||
.with(KEY_STRATEGY, strategy).with(KEY_LAYERS, String.valueOf(layers));
|
||||
for (final PlaceStrategy s : strategies.values()) {
|
||||
for (final Option o : s.options()) {
|
||||
p = p.with(OPT_PREFIX + s.id() + "." + o.key(), String.valueOf(s.values().get(o)));
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
private static void loadOptions(final Profile profile, final PlaceStrategy s) {
|
||||
for (final Option o : s.options()) {
|
||||
final String raw = profile.get(OPT_PREFIX + s.id() + "." + o.key(), "");
|
||||
if (!raw.isEmpty()) {
|
||||
s.values().set(o.key(), Double.parseDouble(raw));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int parseLayers(final String raw) {
|
||||
final int v = Integer.parseInt(raw);
|
||||
return Math.max(Planner.MIN_BAND_LAYERS, Math.min(Planner.MAX_BAND_LAYERS, v));
|
||||
}
|
||||
|
||||
private static void require(final boolean ok, final String message) {
|
||||
if (!ok) {
|
||||
throw new IllegalArgumentException(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,200 @@
|
|||
package dev.loki.satura.feature.builder;
|
||||
|
||||
import dev.loki.satura.core.command.CommandRegistry;
|
||||
import dev.loki.satura.core.config.ConfigStore;
|
||||
import dev.loki.satura.core.config.Profile;
|
||||
import dev.loki.satura.core.event.EventBus;
|
||||
import dev.loki.satura.feature.builder.commands.BuildCommand;
|
||||
import dev.loki.satura.feature.builder.commands.BuildControl;
|
||||
import dev.loki.satura.feature.builder.engine.BuildEngine;
|
||||
import dev.loki.satura.feature.builder.engine.Stage;
|
||||
import dev.loki.satura.feature.builder.engine.walk.NoWalker;
|
||||
import dev.loki.satura.feature.builder.engine.walk.Walker;
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import dev.loki.satura.feature.builder.selection.PosCommand;
|
||||
import dev.loki.satura.feature.builder.selection.SelCommand;
|
||||
import dev.loki.satura.feature.builder.selection.Selection;
|
||||
import dev.loki.satura.interaction.place.PlaceStrategy;
|
||||
import dev.loki.satura.interaction.place.strategy.BandStack;
|
||||
import dev.loki.satura.interaction.place.strategy.ColumnDrop;
|
||||
import dev.loki.satura.interaction.place.support.BlockPlacer;
|
||||
import dev.loki.satura.interaction.place.support.Cooldown;
|
||||
import dev.loki.satura.interaction.place.support.SupportFinder;
|
||||
import dev.loki.satura.util.ActionBarOut;
|
||||
import dev.loki.satura.util.ChatOut;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** Фасад фичи «авто-билдер»: единственная точка входа для GUI, команд и рендера. */
|
||||
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"})
|
||||
public final class BuilderFeature implements BuildControl {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BuilderFeature.class);
|
||||
|
||||
private final Selection current = new Selection();
|
||||
private final BuildSettings settings;
|
||||
private final EngineAssembler assembler;
|
||||
private final Consumer<Profile> persist;
|
||||
private BuildEngine engine;
|
||||
|
||||
public BuilderFeature(final CommandRegistry commands, final Supplier<BlockPos> feet,
|
||||
final EngineAssembler assembler, final BuildSettings settings,
|
||||
final Consumer<Profile> persist) {
|
||||
this.assembler = assembler;
|
||||
this.settings = settings;
|
||||
this.persist = persist;
|
||||
commands.register(new PosCommand("pos1", current, feet, Selection::setPos1));
|
||||
commands.register(new PosCommand("pos2", current, feet, Selection::setPos2));
|
||||
commands.register(new SelCommand(current));
|
||||
commands.register(new BuildCommand(this));
|
||||
}
|
||||
|
||||
/** Фасад на клиенте Minecraft; ходок «нет» (мост Baritone подключается через перегрузку). */
|
||||
public static BuilderFeature create(final CommandRegistry commands, final EventBus events,
|
||||
final ConfigStore store) {
|
||||
return create(commands, events, store, new NoWalker());
|
||||
}
|
||||
|
||||
@SuppressWarnings("PMD.CloseResource")
|
||||
public static BuilderFeature create(final CommandRegistry commands, final EventBus events,
|
||||
final ConfigStore store, final Walker walker) {
|
||||
final MinecraftClient client = MinecraftClient.getInstance();
|
||||
final BlockPlacer placer = new BlockPlacer(new SupportFinder(), new Cooldown());
|
||||
final List<PlaceStrategy> strategies = List.of(new BandStack(placer), new ColumnDrop(placer));
|
||||
final Profile profile = load(store);
|
||||
return new BuilderFeature(commands, () -> client.player == null ? null : client.player.getBlockPos(),
|
||||
new EngineAssembler(client, events, walker, new ChatOut(), new ActionBarOut()),
|
||||
new BuildSettings(profile, strategies), p -> save(store, p));
|
||||
}
|
||||
|
||||
public Selection selection() {
|
||||
return current;
|
||||
}
|
||||
|
||||
/** Вызывать каждый клиентский тик. */
|
||||
public void tick() {
|
||||
if (engine != null) {
|
||||
engine.tick();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String start() {
|
||||
final Area area = current.area().orElseThrow(() -> new IllegalStateException("задай .pos1 и .pos2"));
|
||||
stop();
|
||||
engine = assembler.assemble(settings, area);
|
||||
engine.start();
|
||||
return "Старт: " + area.volume() + " блоков в области, стратегия " + settings.strategy().label();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String pause() {
|
||||
active().pause();
|
||||
return "Пауза";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String resume() {
|
||||
active().resume();
|
||||
return "Продолжаю";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String stop() {
|
||||
if (engine != null) {
|
||||
engine.stop();
|
||||
}
|
||||
return "Остановлено";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String status() {
|
||||
return engine == null ? "IDLE" : engine.snapshot().describe();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String setBlock(final String id) {
|
||||
assembler.blocks().resolve(id);
|
||||
settings.setBlock(id);
|
||||
return changed("Блок: " + id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String setStrategy(final String id) {
|
||||
settings.setStrategy(id);
|
||||
return changed("Стратегия: " + id + ", параметры: " + settings.optionKeys());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String setOption(final String key, final String value) {
|
||||
settings.setOption(key, value);
|
||||
return changed(key + " = " + value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String setShape(final String id) {
|
||||
settings.setShape(id);
|
||||
return changed("Форма: " + settings.shapeId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String setLayers(final int layers) {
|
||||
settings.setLayers(layers);
|
||||
return changed("Слоёв за проход: " + layers);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> blockIds() {
|
||||
return assembler.blocks().ids();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> strategyIds() {
|
||||
return settings.strategyIds();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> optionKeys() {
|
||||
return settings.optionKeys();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> shapeIds() {
|
||||
return settings.shapeIds();
|
||||
}
|
||||
|
||||
private BuildEngine active() {
|
||||
final Optional<BuildEngine> running = Optional.ofNullable(engine)
|
||||
.filter(e -> e.stage() == Stage.BUILD || e.stage() == Stage.PAUSED);
|
||||
return running.orElseThrow(() -> new IllegalStateException("билд не запущен"));
|
||||
}
|
||||
|
||||
private String changed(final String message) {
|
||||
persist.accept(settings.toProfile(Profile.DEFAULT_NAME));
|
||||
return message;
|
||||
}
|
||||
|
||||
private static Profile load(final ConfigStore store) {
|
||||
try {
|
||||
return store.load(Profile.DEFAULT_NAME).orElse(Profile.empty(Profile.DEFAULT_NAME));
|
||||
} catch (IOException | RuntimeException e) {
|
||||
LOG.warn("[satura] профиль не загружен: {}", e.toString());
|
||||
return Profile.empty(Profile.DEFAULT_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
private static void save(final ConfigStore store, final Profile profile) {
|
||||
try {
|
||||
store.save(profile);
|
||||
} catch (IOException e) {
|
||||
LOG.warn("[satura] профиль не сохранён: {}", e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package dev.loki.satura.feature.builder;
|
||||
|
||||
import dev.loki.satura.core.event.EventBus;
|
||||
import dev.loki.satura.feature.builder.engine.BuildEngine;
|
||||
import dev.loki.satura.feature.builder.engine.RepairTracker;
|
||||
import dev.loki.satura.feature.builder.engine.host.EngineDeps;
|
||||
import dev.loki.satura.feature.builder.engine.host.MinecraftBlocks;
|
||||
import dev.loki.satura.feature.builder.engine.host.MinecraftGameState;
|
||||
import dev.loki.satura.feature.builder.engine.walk.Walker;
|
||||
import dev.loki.satura.feature.builder.plan.Planner;
|
||||
import dev.loki.satura.feature.builder.scan.ColumnCache;
|
||||
import dev.loki.satura.feature.builder.scan.WorldBlockProbe;
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import dev.loki.satura.interaction.click.ClickConfig;
|
||||
import dev.loki.satura.interaction.click.ClickScheduler;
|
||||
import dev.loki.satura.interaction.click.Clock;
|
||||
import dev.loki.satura.interaction.inventory.HotbarRefill;
|
||||
import dev.loki.satura.interaction.inventory.MinecraftInventoryView;
|
||||
import dev.loki.satura.interaction.place.client.MinecraftPlaceContext;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.random.RandomGenerator;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
|
||||
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
|
||||
/** Тонкий сборщик движка из настроек и клиента Minecraft. */
|
||||
public final class EngineAssembler {
|
||||
|
||||
private final MinecraftClient client;
|
||||
private final EventBus events;
|
||||
private final Walker walker;
|
||||
private final Consumer<String> chat;
|
||||
private final Consumer<String> bar;
|
||||
private final MinecraftBlocks blocks;
|
||||
|
||||
public EngineAssembler(final MinecraftClient client, final EventBus events, final Walker walker,
|
||||
final Consumer<String> chat, final Consumer<String> bar) {
|
||||
this.client = client;
|
||||
this.events = events;
|
||||
this.walker = walker;
|
||||
this.chat = chat;
|
||||
this.bar = bar;
|
||||
this.blocks = new MinecraftBlocks(client);
|
||||
}
|
||||
|
||||
public MinecraftBlocks blocks() {
|
||||
return blocks;
|
||||
}
|
||||
|
||||
public BuildEngine assemble(final BuildSettings s, final Area area) {
|
||||
if (client.player == null || client.world == null) {
|
||||
throw new IllegalStateException("зайди в мир");
|
||||
}
|
||||
final Block block = blocks.resolve(s.block());
|
||||
final ColumnCache cache = new ColumnCache(area, s.shape(), new WorldBlockProbe(() -> client.world));
|
||||
final RepairTracker tracker = new RepairTracker(RepairTracker.MAX_PASSES);
|
||||
final Planner planner = new Planner(area, s.shape(), s.layers(),
|
||||
pos -> cache.isDone(pos) || tracker.skipped(pos));
|
||||
final ClickScheduler clicks = new ClickScheduler(ClickConfig.DEFAULT, Clock.SYSTEM,
|
||||
RandomGenerator.getDefault());
|
||||
final HotbarRefill refill = new HotbarRefill(new MinecraftInventoryView(client, block), clicks);
|
||||
return new BuildEngine(new EngineDeps(planner, cache, tracker, s.strategy(),
|
||||
new MinecraftPlaceContext(client), refill, clicks, new MinecraftGameState(client),
|
||||
walker, Clock.SYSTEM, events, chat, bar));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,105 @@
|
|||
package dev.loki.satura.feature.builder.baritone;
|
||||
|
||||
import java.util.function.BooleanSupplier;
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/** Мост к Baritone (Aethereal): только рефлексия, любая ошибка отключает мост одной записью в лог. */
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.AvoidCatchingGenericException", "PMD.GuardLogStatement"})
|
||||
public final class BaritoneBridge implements WalkerPort {
|
||||
|
||||
static final String MOD_ID = "baritone-meteor";
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BaritoneBridge.class);
|
||||
|
||||
private final BooleanSupplier modLoaded;
|
||||
private BaritoneLink link;
|
||||
private boolean initTried;
|
||||
private boolean failed;
|
||||
|
||||
public BaritoneBridge(BooleanSupplier modLoaded) {
|
||||
this.modLoaded = modLoaded;
|
||||
}
|
||||
|
||||
public static BaritoneBridge create() {
|
||||
return new BaritoneBridge(() -> FabricLoader.getInstance().isModLoaded(MOD_ID));
|
||||
}
|
||||
|
||||
public boolean present() {
|
||||
return link() != null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean walkTo(double x, double z) {
|
||||
BaritoneLink l = link();
|
||||
if (l == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
l.walkTo((int) Math.floor(x), (int) Math.floor(z));
|
||||
return true;
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
fail(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
BaritoneLink l = link();
|
||||
if (l == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
l.cancel();
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isActive() {
|
||||
BaritoneLink l = link();
|
||||
if (l == null) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
return l.isActive();
|
||||
} catch (ReflectiveOperationException | RuntimeException e) {
|
||||
fail(e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private BaritoneLink link() {
|
||||
if (failed) {
|
||||
return null;
|
||||
}
|
||||
if (!initTried) {
|
||||
initTried = true;
|
||||
init();
|
||||
}
|
||||
return failed ? null : link;
|
||||
}
|
||||
|
||||
private void init() {
|
||||
if (!modLoaded.getAsBoolean()) {
|
||||
failed = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
BaritoneLink created = new BaritoneLink(BaritoneBridge.class.getClassLoader());
|
||||
created.applySettings();
|
||||
link = created;
|
||||
} catch (ReflectiveOperationException | RuntimeException | LinkageError e) {
|
||||
fail(e);
|
||||
}
|
||||
}
|
||||
|
||||
private void fail(Throwable e) {
|
||||
if (!failed) {
|
||||
LOG.warn("Baritone bridge disabled: {}", e.toString());
|
||||
}
|
||||
failed = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
package dev.loki.satura.feature.builder.baritone;
|
||||
|
||||
import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
/** Кэш рефлексивных дескрипторов Baritone API; создаётся один раз. */
|
||||
final class BaritoneLink {
|
||||
|
||||
private static final String PKG = "baritone.api.";
|
||||
private static final List<String> WALK_ONLY_FALSE = List.of("allowBreak", "allowPlace", "allowInventory");
|
||||
private static final List<String> TRUE_FLAGS = List.of("freeLook", "allowSprint");
|
||||
|
||||
private final Method getProvider;
|
||||
private final Method getPrimary;
|
||||
private final Method customGoal;
|
||||
private final Method pathingBehavior;
|
||||
private final Method setGoal;
|
||||
private final Method path;
|
||||
private final Method processActive;
|
||||
private final Method cancelEverything;
|
||||
private final Constructor<?> goalXz;
|
||||
private final Object settings;
|
||||
private final Field settingValue;
|
||||
private final Class<?> settingsClass;
|
||||
|
||||
BaritoneLink(ClassLoader loader) throws ReflectiveOperationException {
|
||||
Class<?> api = Class.forName(PKG + "BaritoneAPI", true, loader);
|
||||
Class<?> baritone = Class.forName(PKG + "IBaritone", true, loader);
|
||||
Class<?> goal = Class.forName(PKG + "pathing.goals.Goal", true, loader);
|
||||
Class<?> goalProcess = Class.forName(PKG + "process.ICustomGoalProcess", true, loader);
|
||||
Class<?> process = Class.forName(PKG + "process.IBaritoneProcess", true, loader);
|
||||
Class<?> behavior = Class.forName(PKG + "behavior.IPathingBehavior", true, loader);
|
||||
settingsClass = Class.forName(PKG + "Settings", true, loader);
|
||||
getProvider = api.getMethod("getProvider");
|
||||
getPrimary = getProvider.getReturnType().getMethod("getPrimaryBaritone");
|
||||
customGoal = baritone.getMethod("getCustomGoalProcess");
|
||||
pathingBehavior = baritone.getMethod("getPathingBehavior");
|
||||
setGoal = goalProcess.getMethod("setGoal", goal);
|
||||
path = goalProcess.getMethod("path");
|
||||
processActive = process.getMethod("isActive");
|
||||
cancelEverything = behavior.getMethod("cancelEverything");
|
||||
goalXz = Class.forName(PKG + "pathing.goals.GoalXZ", true, loader).getConstructor(int.class, int.class);
|
||||
settings = api.getMethod("getSettings").invoke(null);
|
||||
settingValue = Class.forName(PKG + "Settings$Setting", true, loader).getField("value");
|
||||
}
|
||||
|
||||
void applySettings() throws ReflectiveOperationException {
|
||||
for (String name : WALK_ONLY_FALSE) {
|
||||
set(name, Boolean.FALSE);
|
||||
}
|
||||
for (String name : TRUE_FLAGS) {
|
||||
set(name, Boolean.TRUE);
|
||||
}
|
||||
}
|
||||
|
||||
void walkTo(int x, int z) throws ReflectiveOperationException {
|
||||
Object process = customGoal.invoke(primary());
|
||||
setGoal.invoke(process, goalXz.newInstance(x, z));
|
||||
path.invoke(process);
|
||||
}
|
||||
|
||||
boolean isActive() throws ReflectiveOperationException {
|
||||
return (Boolean) processActive.invoke(customGoal.invoke(primary()));
|
||||
}
|
||||
|
||||
void cancel() throws ReflectiveOperationException {
|
||||
cancelEverything.invoke(pathingBehavior.invoke(primary()));
|
||||
}
|
||||
|
||||
private Object primary() throws ReflectiveOperationException {
|
||||
return getPrimary.invoke(getProvider.invoke(null));
|
||||
}
|
||||
|
||||
private void set(String name, Object value) throws ReflectiveOperationException {
|
||||
settingValue.set(settingsClass.getField(name).get(settings), value);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
package dev.loki.satura.feature.builder.baritone;
|
||||
|
||||
/** Порт перемещения: движок видит только его, а не Baritone. */
|
||||
public interface WalkerPort {
|
||||
|
||||
/** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */
|
||||
boolean walkTo(double x, double z);
|
||||
|
||||
void cancel();
|
||||
|
||||
boolean isActive();
|
||||
}
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
package dev.loki.satura.feature.builder.commands;
|
||||
|
||||
import dev.loki.satura.core.command.Command;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** {@code .build} — диспетчер подкоманд. */
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public final class BuildCommand implements Command {
|
||||
|
||||
private static final int NAME_ONLY = 1;
|
||||
|
||||
private final Map<String, SubCommand> subs = new LinkedHashMap<>();
|
||||
|
||||
public BuildCommand(final BuildControl control) {
|
||||
for (final SubCommand sub : BuildSubs.of(control)) {
|
||||
subs.put(sub.name(), sub);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "build";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "билдер: " + String.join("|", subs.keySet());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(final List<String> args, final Consumer<String> reply) {
|
||||
final SubCommand sub = args.isEmpty() ? null : subs.get(args.get(0).toLowerCase(Locale.ROOT));
|
||||
if (sub == null) {
|
||||
reply.accept("Использование: .build " + subs.values().stream()
|
||||
.map(s -> (s.name() + " " + s.usage()).strip())
|
||||
.collect(Collectors.joining(" | ")));
|
||||
return;
|
||||
}
|
||||
reply.accept(sub.run().apply(args.subList(1, args.size())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> suggest(final List<String> args) {
|
||||
if (args.size() <= NAME_ONLY) {
|
||||
return List.copyOf(subs.keySet());
|
||||
}
|
||||
final SubCommand sub = subs.get(args.get(0).toLowerCase(Locale.ROOT));
|
||||
return sub == null ? List.of() : sub.options().apply(args.size() - 2);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package dev.loki.satura.feature.builder.commands;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Что команды {@code .build} умеют просить у фичи. Ошибки — исключения с текстом для пользователя. */
|
||||
public interface BuildControl {
|
||||
|
||||
String start();
|
||||
|
||||
String pause();
|
||||
|
||||
String resume();
|
||||
|
||||
String stop();
|
||||
|
||||
String status();
|
||||
|
||||
String setBlock(String id);
|
||||
|
||||
String setStrategy(String id);
|
||||
|
||||
String setOption(String key, String value);
|
||||
|
||||
String setShape(String id);
|
||||
|
||||
String setLayers(int layers);
|
||||
|
||||
List<String> blockIds();
|
||||
|
||||
List<String> strategyIds();
|
||||
|
||||
List<String> optionKeys();
|
||||
|
||||
List<String> shapeIds();
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
package dev.loki.satura.feature.builder.commands;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** Набор подкоманд {@code .build}, привязанных к {@link BuildControl}. */
|
||||
final class BuildSubs {
|
||||
|
||||
private static final int SET_ARGS = 2;
|
||||
private static final String LAYERS_USAGE = "слои: 1-3";
|
||||
|
||||
private BuildSubs() {
|
||||
}
|
||||
|
||||
static List<SubCommand> of(final BuildControl c) {
|
||||
return List.of(
|
||||
SubCommand.plain("start", c::start),
|
||||
SubCommand.plain("pause", c::pause),
|
||||
SubCommand.plain("resume", c::resume),
|
||||
SubCommand.plain("stop", c::stop),
|
||||
SubCommand.plain("status", c::status),
|
||||
SubCommand.value("block", () -> blockChoices(c), c::setBlock),
|
||||
SubCommand.value("strategy", c::strategyIds, c::setStrategy),
|
||||
SubCommand.value("shape", c::shapeIds, c::setShape),
|
||||
SubCommand.value("layers", () -> List.of("1", "2", "3"), v -> c.setLayers(parse(v))),
|
||||
set(c));
|
||||
}
|
||||
|
||||
private static List<String> blockChoices(final BuildControl c) {
|
||||
final List<String> ids = new java.util.ArrayList<>(c.blockIds());
|
||||
ids.add(0, "hand");
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static int parse(final String v) {
|
||||
try {
|
||||
return Integer.parseInt(v);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new IllegalArgumentException(LAYERS_USAGE, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static SubCommand set(final BuildControl c) {
|
||||
return new SubCommand("set", "<ключ> <значение>", i -> i == 0 ? c.optionKeys() : List.of(), args -> {
|
||||
if (args.size() != SET_ARGS) {
|
||||
throw new IllegalArgumentException("использование: .build set <ключ> <значение>; ключи: "
|
||||
+ c.optionKeys());
|
||||
}
|
||||
return c.setOption(args.get(0), args.get(1));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
package dev.loki.satura.feature.builder.commands;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Подкоманда {@code .build <name>}.
|
||||
*
|
||||
* @param usage справка по аргументам
|
||||
* @param options кандидаты для подсказки по токену номер index (после имени)
|
||||
* @param run выполнить с аргументами после имени, вернуть ответ
|
||||
*/
|
||||
public record SubCommand(String name, String usage, Function<Integer, List<String>> options,
|
||||
Function<List<String>, String> run) {
|
||||
|
||||
private static final int SINGLE_ARG = 1;
|
||||
|
||||
public static SubCommand plain(final String name, final Supplier<String> action) {
|
||||
return new SubCommand(name, "", i -> List.of(), args -> action.get());
|
||||
}
|
||||
|
||||
public static SubCommand value(final String name, final Supplier<List<String>> choices,
|
||||
final Function<String, String> apply) {
|
||||
return new SubCommand(name, "<значение>", i -> i == 0 ? choices.get() : List.of(), args -> {
|
||||
if (args.size() != SINGLE_ARG) {
|
||||
throw new IllegalArgumentException("нужно значение: .build " + name + " <значение>");
|
||||
}
|
||||
return apply.apply(args.get(0));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
package dev.loki.satura.feature.builder.engine;
|
||||
|
||||
import dev.loki.satura.core.event.Listener;
|
||||
import dev.loki.satura.core.event.world.BlockChangeEvent;
|
||||
import dev.loki.satura.feature.builder.engine.host.EngineDeps;
|
||||
import dev.loki.satura.feature.builder.plan.ColumnTarget;
|
||||
import dev.loki.satura.interaction.inventory.HotbarRefill;
|
||||
import dev.loki.satura.interaction.place.PlaceResult;
|
||||
import java.util.Optional;
|
||||
|
||||
@SuppressWarnings("PMD.CompareObjectsWithEquals")
|
||||
/**
|
||||
* Тик билдера: planner → стратегия → пополнение хотбара. Паузы (экран, смерть, смена мира)
|
||||
* снимаются сами, «нет блоков» — только вручную. Дыры чинятся ремонтными проходами.
|
||||
*/
|
||||
public final class BuildEngine {
|
||||
|
||||
public static final int PROGRESS_INTERVAL_TICKS = 20;
|
||||
public static final String NO_BLOCKS = "нет блоков";
|
||||
|
||||
private final EngineDeps deps;
|
||||
private final BuildSession session;
|
||||
private final Listener<BlockChangeEvent> blockListener;
|
||||
private Object world;
|
||||
private int ticks;
|
||||
|
||||
public BuildEngine(final EngineDeps deps) {
|
||||
this.deps = deps;
|
||||
this.session = new BuildSession(deps.cache());
|
||||
this.blockListener = Listener.of(BlockChangeEvent.class, e -> deps.cache().onBlockChanged(e.pos()));
|
||||
}
|
||||
|
||||
public void start() {
|
||||
deps.events().subscribe(blockListener);
|
||||
world = deps.game().worldToken();
|
||||
deps.cache().fullRescan();
|
||||
session.start();
|
||||
}
|
||||
|
||||
/** Ручная пауза: авто-резюм не сработает. */
|
||||
public void pause() {
|
||||
if (session.stage() == Stage.BUILD || session.stage() == Stage.PAUSED) {
|
||||
session.pause("пауза", false);
|
||||
halt();
|
||||
}
|
||||
}
|
||||
|
||||
public void resume() {
|
||||
if (session.stage() == Stage.PAUSED) {
|
||||
session.resume();
|
||||
}
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
halt();
|
||||
deps.events().unsubscribe(blockListener);
|
||||
session.stop();
|
||||
}
|
||||
|
||||
public Stage stage() {
|
||||
return session.stage();
|
||||
}
|
||||
|
||||
public BuildSession.Snapshot snapshot() {
|
||||
return session.snapshot(deps.tracker().holes());
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
deps.clicks().tick();
|
||||
session.advance(deps.clock().nowMillis());
|
||||
switch (session.stage()) {
|
||||
case BUILD -> build();
|
||||
case PAUSED -> tryAutoResume();
|
||||
default -> { }
|
||||
}
|
||||
ticks++;
|
||||
if (ticks % PROGRESS_INTERVAL_TICKS == 0 && session.stage() != Stage.IDLE) {
|
||||
deps.bar().accept(snapshot().describe());
|
||||
}
|
||||
}
|
||||
|
||||
private void tryAutoResume() {
|
||||
if (session.autoResume() && deps.game().blockReason().isEmpty()) {
|
||||
syncWorld();
|
||||
session.resume();
|
||||
}
|
||||
}
|
||||
|
||||
private void build() {
|
||||
final Optional<String> blocked = deps.game().blockReason();
|
||||
if (blocked.isPresent()) {
|
||||
session.pause(blocked.get(), true);
|
||||
return;
|
||||
}
|
||||
syncWorld();
|
||||
final HotbarRefill.State stock = deps.refill().tick();
|
||||
if (stock == HotbarRefill.State.EMPTY) {
|
||||
session.pause(NO_BLOCKS, false);
|
||||
deps.chat().accept("Пауза: " + NO_BLOCKS + ". Положи блоки и .build resume");
|
||||
} else if (stock == HotbarRefill.State.READY) {
|
||||
deps.planner().next().ifPresentOrElse(this::place, this::finishOrRepair);
|
||||
}
|
||||
}
|
||||
|
||||
private void syncWorld() {
|
||||
final Object token = deps.game().worldToken();
|
||||
if (token != world) {
|
||||
world = token;
|
||||
deps.cache().fullRescan();
|
||||
}
|
||||
}
|
||||
|
||||
private void place(final ColumnTarget target) {
|
||||
final var tracker = deps.tracker();
|
||||
tracker.observe(target.column(), deps.cache().done());
|
||||
session.at(target.column());
|
||||
final PlaceResult result = deps.strategy().tick(deps.ctx(), target);
|
||||
final boolean giveUp = switch (result) {
|
||||
case PLACED -> {
|
||||
session.onPlaced();
|
||||
yield false;
|
||||
}
|
||||
case FAILED -> {
|
||||
session.onFailed();
|
||||
yield tracker.failure();
|
||||
}
|
||||
case WAIT -> tracker.stall();
|
||||
};
|
||||
if (giveUp) {
|
||||
tracker.skip(target.column());
|
||||
}
|
||||
}
|
||||
|
||||
private void finishOrRepair() {
|
||||
if (deps.tracker().startRepair(deps.planner())) {
|
||||
deps.chat().accept("Ремонтный проход " + deps.tracker().passes() + ", дыр: "
|
||||
+ snapshot().holes());
|
||||
return;
|
||||
}
|
||||
final BuildSession.Snapshot shot = snapshot();
|
||||
session.finish();
|
||||
halt();
|
||||
deps.events().unsubscribe(blockListener);
|
||||
deps.chat().accept("Готово: " + shot.done() + "/" + shot.total() + ", дыр: " + shot.holes());
|
||||
}
|
||||
|
||||
private void halt() {
|
||||
deps.walker().cancel();
|
||||
if (deps.game().blockReason().isEmpty()) {
|
||||
deps.ctx().setVelocity(0, 0, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
package dev.loki.satura.feature.builder.engine;
|
||||
|
||||
import dev.loki.satura.feature.builder.scan.ColumnCache;
|
||||
import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"})
|
||||
/** Состояние сессии: этап, причина паузы, позиция, счётчики и статистика (прогресс — из ColumnCache). */
|
||||
public final class BuildSession {
|
||||
|
||||
private static final long MAX_STEP_MS = 250;
|
||||
private static final double MS_PER_SECOND = 1000.0;
|
||||
|
||||
/**
|
||||
* Снимок статистики.
|
||||
*
|
||||
* @param holes колонны, которые не удалось достроить
|
||||
*/
|
||||
public record Snapshot(Stage stage, String reason, int done, int total, double percent, int holes,
|
||||
int placed, int failed, double blocksPerSecond, Optional<BlockPos> column) {
|
||||
|
||||
public String describe() {
|
||||
final String why = stage == Stage.PAUSED ? " (" + reason + ")" : "";
|
||||
return String.format(Locale.ROOT, "%s%s %d/%d (%.1f%%), %.1f бл/с, дыр: %d",
|
||||
stage, why, done, total, percent, blocksPerSecond, holes);
|
||||
}
|
||||
}
|
||||
|
||||
private final ColumnCache cache;
|
||||
private Stage stage = Stage.IDLE;
|
||||
private String reason = "";
|
||||
private boolean autoResume;
|
||||
private int placed;
|
||||
private int failed;
|
||||
private long activeMs;
|
||||
private long lastTickMs = -1;
|
||||
private BlockPos column;
|
||||
|
||||
public BuildSession(final ColumnCache cache) {
|
||||
this.cache = cache;
|
||||
}
|
||||
|
||||
public Stage stage() {
|
||||
return stage;
|
||||
}
|
||||
|
||||
public boolean autoResume() {
|
||||
return autoResume;
|
||||
}
|
||||
|
||||
public void start() {
|
||||
stage = Stage.BUILD;
|
||||
reason = "";
|
||||
placed = 0;
|
||||
failed = 0;
|
||||
activeMs = 0;
|
||||
lastTickMs = -1;
|
||||
column = null;
|
||||
}
|
||||
|
||||
public void pause(final String why, final boolean auto) {
|
||||
stage = Stage.PAUSED;
|
||||
reason = why;
|
||||
autoResume = auto;
|
||||
}
|
||||
|
||||
public void resume() {
|
||||
stage = Stage.BUILD;
|
||||
reason = "";
|
||||
}
|
||||
|
||||
public void finish() {
|
||||
stage = Stage.DONE;
|
||||
column = null;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
stage = Stage.IDLE;
|
||||
column = null;
|
||||
}
|
||||
|
||||
/** Учёт времени: считается только время в BUILD, паузы не входят. */
|
||||
public void advance(final long nowMs) {
|
||||
if (stage == Stage.BUILD && lastTickMs >= 0) {
|
||||
activeMs += Math.min(nowMs - lastTickMs, MAX_STEP_MS);
|
||||
}
|
||||
lastTickMs = nowMs;
|
||||
}
|
||||
|
||||
public void onPlaced() {
|
||||
placed++;
|
||||
}
|
||||
|
||||
public void onFailed() {
|
||||
failed++;
|
||||
}
|
||||
|
||||
public void at(final BlockPos target) {
|
||||
column = target;
|
||||
}
|
||||
|
||||
public Snapshot snapshot(final int holes) {
|
||||
final double rate = activeMs <= 0 ? 0.0 : placed * MS_PER_SECOND / activeMs;
|
||||
return new Snapshot(stage, reason, cache.done(), cache.total(), cache.percent(), holes,
|
||||
placed, failed, rate, Optional.ofNullable(column));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
package dev.loki.satura.feature.builder.engine;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.Planner;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
|
||||
/** Дыры: колонны, которые не удалось достроить; пропуск, счётчики отказов и ремонтные проходы. */
|
||||
public final class RepairTracker {
|
||||
|
||||
public static final int MAX_FAILURES = 3;
|
||||
public static final int STALL_TICKS = 200;
|
||||
public static final int MAX_PASSES = 3;
|
||||
|
||||
private final Set<BlockPos> skipped = new HashSet<>();
|
||||
private final int maxPasses;
|
||||
private int passes;
|
||||
private BlockPos column;
|
||||
private int lastDone = -1;
|
||||
private int failures;
|
||||
private int waits;
|
||||
|
||||
public RepairTracker(final int maxPasses) {
|
||||
this.maxPasses = maxPasses;
|
||||
}
|
||||
|
||||
public boolean skipped(final BlockPos pos) {
|
||||
return skipped.contains(pos.withY(0));
|
||||
}
|
||||
|
||||
public int holes() {
|
||||
return skipped.size();
|
||||
}
|
||||
|
||||
public int passes() {
|
||||
return passes;
|
||||
}
|
||||
|
||||
/** Сбрасывает счётчики, если сменилась колонна или прибавился прогресс. */
|
||||
public void observe(final BlockPos target, final int done) {
|
||||
if (!target.equals(column) || done != lastDone) {
|
||||
column = target;
|
||||
lastDone = done;
|
||||
failures = 0;
|
||||
waits = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Отказ стратегии; true — лимит исчерпан. */
|
||||
public boolean failure() {
|
||||
return ++failures >= MAX_FAILURES;
|
||||
}
|
||||
|
||||
/** Ожидание без прогресса; true — колонна зависла. */
|
||||
public boolean stall() {
|
||||
return ++waits >= STALL_TICKS;
|
||||
}
|
||||
|
||||
public void skip(final BlockPos target) {
|
||||
skipped.add(target.withY(0));
|
||||
}
|
||||
|
||||
/** Ремонтный проход: вернуть пропущенные колонны в план; false — дыр нет или проходы кончились. */
|
||||
public boolean startRepair(final Planner planner) {
|
||||
if (skipped.isEmpty() || passes >= maxPasses) {
|
||||
return false;
|
||||
}
|
||||
passes++;
|
||||
skipped.clear();
|
||||
planner.reset();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
package dev.loki.satura.feature.builder.engine;
|
||||
|
||||
/** Этап сессии. TRANSIT и SUPPLY — точки расширения (переход к области, вылазка за блоками). */
|
||||
public enum Stage {
|
||||
IDLE,
|
||||
BUILD,
|
||||
PAUSED,
|
||||
DONE,
|
||||
TRANSIT,
|
||||
SUPPLY
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package dev.loki.satura.feature.builder.engine.host;
|
||||
|
||||
import dev.loki.satura.core.event.EventBus;
|
||||
import dev.loki.satura.feature.builder.engine.RepairTracker;
|
||||
import dev.loki.satura.feature.builder.engine.walk.Walker;
|
||||
import dev.loki.satura.feature.builder.plan.Planner;
|
||||
import dev.loki.satura.feature.builder.scan.ColumnCache;
|
||||
import dev.loki.satura.interaction.click.ClickScheduler;
|
||||
import dev.loki.satura.interaction.click.Clock;
|
||||
import dev.loki.satura.interaction.inventory.HotbarRefill;
|
||||
import dev.loki.satura.interaction.place.PlaceContext;
|
||||
import dev.loki.satura.interaction.place.PlaceStrategy;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Все зависимости движка (собираются снаружи, движок ничего не создаёт сам).
|
||||
*
|
||||
* @param chat сообщения пользователю
|
||||
* @param bar строка прогресса (actionBar)
|
||||
*/
|
||||
@SuppressWarnings("PMD.ExcessiveParameterList")
|
||||
public record EngineDeps(Planner planner, ColumnCache cache, RepairTracker tracker, PlaceStrategy strategy,
|
||||
PlaceContext ctx, HotbarRefill refill, ClickScheduler clicks, GameState game,
|
||||
Walker walker, Clock clock, EventBus events, Consumer<String> chat,
|
||||
Consumer<String> bar) {
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package dev.loki.satura.feature.builder.engine.host;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
/** Состояние игры, влияющее на работу движка; отделяет движок от клиента Minecraft. */
|
||||
public interface GameState {
|
||||
|
||||
/** Причина, по которой строить сейчас нельзя (экран, смерть, нет мира); пусто — можно. */
|
||||
Optional<String> blockReason();
|
||||
|
||||
/** Токен текущего мира: смена токена = смена мира. */
|
||||
Object worldToken();
|
||||
}
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
package dev.loki.satura.feature.builder.engine.host;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.Blocks;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.item.BlockItem;
|
||||
import net.minecraft.registry.Registries;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
/** Поиск блоков: по ID из реестра или по предмету в основной руке. */
|
||||
public final class MinecraftBlocks {
|
||||
|
||||
public static final String HAND = "hand";
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
||||
public MinecraftBlocks(final MinecraftClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
/** Блок по ID ({@code stone} или {@code minecraft:stone}) либо из руки при {@link #HAND}. */
|
||||
public Block resolve(final String id) {
|
||||
if (HAND.equalsIgnoreCase(id)) {
|
||||
return fromHand();
|
||||
}
|
||||
final Identifier key = Identifier.tryParse(id.toLowerCase(java.util.Locale.ROOT));
|
||||
final Block block = key == null ? Blocks.AIR : Registries.BLOCK.get(key);
|
||||
if (key == null || !Registries.BLOCK.containsId(key) || block == Blocks.AIR) {
|
||||
throw new IllegalArgumentException("неизвестный блок: " + id);
|
||||
}
|
||||
return block;
|
||||
}
|
||||
|
||||
public List<String> ids() {
|
||||
return Registries.BLOCK.getIds().stream().map(Identifier::getPath).sorted().toList();
|
||||
}
|
||||
|
||||
private Block fromHand() {
|
||||
if (client.player != null && client.player.getMainHandStack().getItem() instanceof BlockItem item) {
|
||||
return item.getBlock();
|
||||
}
|
||||
throw new IllegalStateException("в руке нет блока");
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package dev.loki.satura.feature.builder.engine.host;
|
||||
|
||||
import java.util.Optional;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
|
||||
/** Тонкий адаптер {@link GameState} к клиенту Minecraft. */
|
||||
public final class MinecraftGameState implements GameState {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
||||
public MinecraftGameState(final MinecraftClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<String> blockReason() {
|
||||
if (client.player == null || client.world == null) {
|
||||
return Optional.of("нет мира");
|
||||
}
|
||||
if (!client.player.isAlive()) {
|
||||
return Optional.of("смерть");
|
||||
}
|
||||
if (client.currentScreen != null) {
|
||||
return Optional.of("открыт экран");
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object worldToken() {
|
||||
return client.world;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package dev.loki.satura.feature.builder.engine.walk;
|
||||
|
||||
/** Ходок «нет»: ничего не умеет. */
|
||||
public final class NoWalker implements Walker {
|
||||
|
||||
@Override
|
||||
public boolean walkTo(final double x, final double z) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void cancel() {
|
||||
// нечего отменять
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package dev.loki.satura.feature.builder.engine.walk;
|
||||
|
||||
/** Ходок для наземных стратегий (S5/S6); мост к Baritone подключается позже. */
|
||||
public interface Walker {
|
||||
|
||||
/** Начать путь к точке (x, z); false — ходок недоступен или команда не принята. */
|
||||
boolean walkTo(double x, double z);
|
||||
|
||||
void cancel();
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
package dev.loki.satura.feature.builder.plan;
|
||||
|
||||
import java.util.List;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Колонна с ещё не построенными ячейками текущего Y-окна (по возрастанию Y). */
|
||||
public record ColumnTarget(BlockPos column, List<BlockPos> cells) {
|
||||
|
||||
public ColumnTarget {
|
||||
cells = List.copyOf(cells);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
package dev.loki.satura.feature.builder.plan;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.shape.Shape;
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Predicate;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Режет область на Y-окна и отдаёт следующую недостроенную колонну по змейке. */
|
||||
public final class Planner {
|
||||
|
||||
public static final int MIN_BAND_LAYERS = 1;
|
||||
public static final int MAX_BAND_LAYERS = 3;
|
||||
|
||||
private final Area area;
|
||||
private final Shape shape;
|
||||
private final int bandLayers;
|
||||
private final Predicate<BlockPos> done;
|
||||
private final List<BlockPos> columns;
|
||||
private int bandFloor;
|
||||
|
||||
public Planner(final Area area, final Shape shape, final int bandLayers,
|
||||
final Predicate<BlockPos> done) {
|
||||
this.area = area;
|
||||
this.shape = shape;
|
||||
this.bandLayers = Math.max(MIN_BAND_LAYERS, Math.min(MAX_BAND_LAYERS, bandLayers));
|
||||
this.done = done;
|
||||
this.columns = area.columns();
|
||||
this.bandFloor = area.min().getY();
|
||||
}
|
||||
|
||||
/** Следующая цель; окно сдвигается вверх, когда текущее достроено. Пусто = всё готово. */
|
||||
public Optional<ColumnTarget> next() {
|
||||
final int top = area.max().getY();
|
||||
while (bandFloor <= top) {
|
||||
final int bandEnd = Math.min(bandFloor + bandLayers - 1, top);
|
||||
for (final BlockPos column : columns) {
|
||||
final List<BlockPos> pending = pending(column, bandFloor, bandEnd);
|
||||
if (!pending.isEmpty()) {
|
||||
return Optional.of(new ColumnTarget(column, pending));
|
||||
}
|
||||
}
|
||||
bandFloor = bandEnd + 1;
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** Нижний Y текущего окна. */
|
||||
public int bandStart() {
|
||||
return bandFloor;
|
||||
}
|
||||
|
||||
/** Вернуться к нижнему окну (для ремонтного прохода). */
|
||||
public void reset() {
|
||||
bandFloor = area.min().getY();
|
||||
}
|
||||
|
||||
private List<BlockPos> pending(final BlockPos column, final int fromY, final int toY) {
|
||||
final List<BlockPos> cells = new ArrayList<>();
|
||||
for (int y = fromY; y <= toY; y++) {
|
||||
final BlockPos pos = new BlockPos(column.getX(), y, column.getZ());
|
||||
if (shape.includes(area, pos) && !done.test(pos)) {
|
||||
cells.add(pos);
|
||||
}
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
package dev.loki.satura.feature.builder.plan.shape;
|
||||
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Сплошной параллелепипед. */
|
||||
public final class BoxShape implements Shape {
|
||||
|
||||
@Override
|
||||
public boolean includes(final Area area, final BlockPos pos) {
|
||||
return area.contains(pos);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
package dev.loki.satura.feature.builder.plan.shape;
|
||||
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Шахматка: чётность x+z относительно угла min области. */
|
||||
public final class CheckerShape implements Shape {
|
||||
|
||||
@Override
|
||||
public boolean includes(final Area area, final BlockPos pos) {
|
||||
if (!area.contains(pos)) {
|
||||
return false;
|
||||
}
|
||||
final int dx = pos.getX() - area.min().getX();
|
||||
final int dz = pos.getZ() - area.min().getZ();
|
||||
return ((dx + dz) & 1) == 0;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package dev.loki.satura.feature.builder.plan.shape;
|
||||
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Какие ячейки области нужно строить. */
|
||||
public interface Shape {
|
||||
|
||||
boolean includes(Area area, BlockPos pos);
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package dev.loki.satura.feature.builder.plan.shape;
|
||||
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Только внешний периметр (стены) по всей высоте. */
|
||||
public final class WallsShape implements Shape {
|
||||
|
||||
@Override
|
||||
public boolean includes(final Area area, final BlockPos pos) {
|
||||
if (!area.contains(pos)) {
|
||||
return false;
|
||||
}
|
||||
final int x = pos.getX();
|
||||
final int z = pos.getZ();
|
||||
return x == area.min().getX() || x == area.max().getX()
|
||||
|| z == area.min().getZ() || z == area.max().getZ();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package dev.loki.satura.feature.builder.scan;
|
||||
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Источник состояния блоков; отделяет подсчёт от клиента Minecraft. */
|
||||
public interface BlockProbe {
|
||||
|
||||
boolean isFilled(BlockPos pos);
|
||||
}
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
package dev.loki.satura.feature.builder.scan;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.shape.Shape;
|
||||
import dev.loki.satura.feature.builder.selection.Area;
|
||||
import java.util.Arrays;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Инкрементальные счётчики заполненности по колоннам области (вместо полного X*Y*Z-скана). */
|
||||
public final class ColumnCache {
|
||||
|
||||
private static final double PERCENT_FULL = 100.0;
|
||||
|
||||
private final Area area;
|
||||
private final Shape shape;
|
||||
private final BlockProbe probe;
|
||||
private final int[] built;
|
||||
private final int[] required;
|
||||
private int doneTotal;
|
||||
private int requiredTotal;
|
||||
|
||||
public ColumnCache(final Area area, final Shape shape, final BlockProbe probe) {
|
||||
this.area = area;
|
||||
this.shape = shape;
|
||||
this.probe = probe;
|
||||
final int columns = area.sizeX() * area.sizeZ();
|
||||
this.built = new int[columns];
|
||||
this.required = new int[columns];
|
||||
fullRescan();
|
||||
}
|
||||
|
||||
/** Полный пересчёт всей области. */
|
||||
public void fullRescan() {
|
||||
doneTotal = 0;
|
||||
requiredTotal = 0;
|
||||
Arrays.fill(built, 0);
|
||||
Arrays.fill(required, 0);
|
||||
for (final BlockPos column : area.columns()) {
|
||||
recount(column.getX(), column.getZ());
|
||||
}
|
||||
}
|
||||
|
||||
/** Пересчитывает только колонну изменённого блока; вне области — игнор. */
|
||||
public void onBlockChanged(final BlockPos pos) {
|
||||
if (area.contains(pos)) {
|
||||
recount(pos.getX(), pos.getZ());
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isDone(final BlockPos pos) {
|
||||
return probe.isFilled(pos);
|
||||
}
|
||||
|
||||
public int done() {
|
||||
return doneTotal;
|
||||
}
|
||||
|
||||
public int total() {
|
||||
return requiredTotal;
|
||||
}
|
||||
|
||||
public int remaining() {
|
||||
return requiredTotal - doneTotal;
|
||||
}
|
||||
|
||||
/** Построено клеток формы в колонне (x, z). */
|
||||
public int builtIn(final int x, final int z) {
|
||||
return built[index(x, z)];
|
||||
}
|
||||
|
||||
/** Осталось построить в колонне (x, z). */
|
||||
public int remainingIn(final int x, final int z) {
|
||||
final int i = index(x, z);
|
||||
return required[i] - built[i];
|
||||
}
|
||||
|
||||
public double percent() {
|
||||
return requiredTotal == 0 ? PERCENT_FULL : PERCENT_FULL * doneTotal / requiredTotal;
|
||||
}
|
||||
|
||||
private int index(final int x, final int z) {
|
||||
return (z - area.min().getZ()) * area.sizeX() + (x - area.min().getX());
|
||||
}
|
||||
|
||||
private void recount(final int x, final int z) {
|
||||
final int i = index(x, z);
|
||||
doneTotal -= built[i];
|
||||
requiredTotal -= required[i];
|
||||
int need = 0;
|
||||
int have = 0;
|
||||
for (int y = area.min().getY(); y <= area.max().getY(); y++) {
|
||||
final BlockPos pos = new BlockPos(x, y, z);
|
||||
if (shape.includes(area, pos)) {
|
||||
need++;
|
||||
if (probe.isFilled(pos)) {
|
||||
have++;
|
||||
}
|
||||
}
|
||||
}
|
||||
required[i] = need;
|
||||
built[i] = have;
|
||||
requiredTotal += need;
|
||||
doneTotal += have;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
package dev.loki.satura.feature.builder.scan;
|
||||
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.client.world.ClientWorld;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Заполнено = не воздух и не заменяемое (трава, вода и т.п.). Мир берётся лениво. */
|
||||
@SuppressWarnings("PMD.CloseResource")
|
||||
public final class WorldBlockProbe implements BlockProbe {
|
||||
|
||||
private final Supplier<ClientWorld> world;
|
||||
|
||||
public WorldBlockProbe(final Supplier<ClientWorld> world) {
|
||||
this.world = world;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isFilled(final BlockPos pos) {
|
||||
final ClientWorld w = world.get();
|
||||
if (w == null) {
|
||||
return false;
|
||||
}
|
||||
final BlockState state = w.getBlockState(pos);
|
||||
return !state.isAir() && !state.isReplaceable();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
package dev.loki.satura.feature.builder.selection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Прямоугольная область мира (границы включительно). */
|
||||
public record Area(BlockPos min, BlockPos max) {
|
||||
|
||||
private static final int EVEN_DIVISOR = 2;
|
||||
|
||||
public static Area of(BlockPos a, BlockPos b) {
|
||||
return new Area(
|
||||
new BlockPos(Math.min(a.getX(), b.getX()), Math.min(a.getY(), b.getY()),
|
||||
Math.min(a.getZ(), b.getZ())),
|
||||
new BlockPos(Math.max(a.getX(), b.getX()), Math.max(a.getY(), b.getY()),
|
||||
Math.max(a.getZ(), b.getZ())));
|
||||
}
|
||||
|
||||
public boolean contains(BlockPos p) {
|
||||
return p.getX() >= min.getX() && p.getX() <= max.getX()
|
||||
&& p.getY() >= min.getY() && p.getY() <= max.getY()
|
||||
&& p.getZ() >= min.getZ() && p.getZ() <= max.getZ();
|
||||
}
|
||||
|
||||
public long volume() {
|
||||
return (long) sizeX() * sizeY() * sizeZ();
|
||||
}
|
||||
|
||||
public int sizeX() {
|
||||
return max.getX() - min.getX() + 1;
|
||||
}
|
||||
|
||||
public int sizeY() {
|
||||
return max.getY() - min.getY() + 1;
|
||||
}
|
||||
|
||||
public int sizeZ() {
|
||||
return max.getZ() - min.getZ() + 1;
|
||||
}
|
||||
|
||||
/** Колонны на y = min.y: ряды по z, чётные ряды по x вверх, нечётные вниз. */
|
||||
public List<BlockPos> columns() {
|
||||
int sx = sizeX();
|
||||
int sz = sizeZ();
|
||||
List<BlockPos> out = new ArrayList<>(sx * sz);
|
||||
for (int r = 0; r < sz; r++) {
|
||||
boolean forward = r % EVEN_DIVISOR == 0;
|
||||
for (int i = 0; i < sx; i++) {
|
||||
int dx = forward ? i : sx - 1 - i;
|
||||
out.add(new BlockPos(min.getX() + dx, min.getY(), min.getZ() + r));
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
package dev.loki.satura.feature.builder.selection;
|
||||
|
||||
import dev.loki.satura.core.command.Command;
|
||||
import java.util.List;
|
||||
import java.util.function.BiConsumer;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** {@code .pos1} / {@code .pos2} — запомнить позицию ног игрока. */
|
||||
public final class PosCommand implements Command {
|
||||
|
||||
private final String label;
|
||||
private final Supplier<BlockPos> feet;
|
||||
private final BiConsumer<Selection, BlockPos> setter;
|
||||
private final Selection selection;
|
||||
|
||||
public PosCommand(String name, Selection selection, Supplier<BlockPos> feet,
|
||||
BiConsumer<Selection, BlockPos> setter) {
|
||||
this.label = name;
|
||||
this.selection = selection;
|
||||
this.feet = feet;
|
||||
this.setter = setter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "запомнить позицию ног как " + label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(List<String> args, Consumer<String> reply) {
|
||||
BlockPos pos = feet.get();
|
||||
if (pos == null) {
|
||||
reply.accept("Нет игрока (зайди в мир)");
|
||||
return;
|
||||
}
|
||||
setter.accept(selection, pos);
|
||||
reply.accept(label + " = " + pos.toShortString());
|
||||
selection.area().ifPresent(a -> reply.accept("Область: " + a.sizeX() + "x"
|
||||
+ a.sizeY() + "x" + a.sizeZ() + " (" + a.volume() + " блоков)"));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
package dev.loki.satura.feature.builder.selection;
|
||||
|
||||
import dev.loki.satura.core.command.Command;
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** {@code .sel clear} — сбросить выделение. */
|
||||
public final class SelCommand implements Command {
|
||||
|
||||
private static final String CLEAR = "clear";
|
||||
|
||||
private final Selection selection;
|
||||
|
||||
public SelCommand(Selection selection) {
|
||||
this.selection = selection;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String name() {
|
||||
return "sel";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "управление выделением: .sel clear";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void execute(List<String> args, Consumer<String> reply) {
|
||||
if (args.size() == 1 && CLEAR.equalsIgnoreCase(args.get(0))) {
|
||||
selection.clear();
|
||||
reply.accept("Выделение сброшено");
|
||||
return;
|
||||
}
|
||||
reply.accept("Использование: .sel clear");
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> suggest(List<String> args) {
|
||||
return List.of(CLEAR);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,40 @@
|
|||
package dev.loki.satura.feature.builder.selection;
|
||||
|
||||
import java.util.Optional;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Две точки выделения; область существует, когда заданы обе. */
|
||||
public final class Selection {
|
||||
|
||||
private Optional<BlockPos> first = Optional.empty();
|
||||
private Optional<BlockPos> second = Optional.empty();
|
||||
|
||||
public void setPos1(BlockPos pos) {
|
||||
first = Optional.of(pos);
|
||||
}
|
||||
|
||||
public void setPos2(BlockPos pos) {
|
||||
second = Optional.of(pos);
|
||||
}
|
||||
|
||||
public Optional<BlockPos> pos1() {
|
||||
return first;
|
||||
}
|
||||
|
||||
public Optional<BlockPos> pos2() {
|
||||
return second;
|
||||
}
|
||||
|
||||
public boolean isComplete() {
|
||||
return first.isPresent() && second.isPresent();
|
||||
}
|
||||
|
||||
public Optional<Area> area() {
|
||||
return isComplete() ? Optional.of(Area.of(first.get(), second.get())) : Optional.empty();
|
||||
}
|
||||
|
||||
public void clear() {
|
||||
first = Optional.empty();
|
||||
second = Optional.empty();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
package dev.loki.satura.interaction.click;
|
||||
|
||||
import java.util.random.RandomGenerator;
|
||||
|
||||
/**
|
||||
* Настройки темпа кликов по контейнерам.
|
||||
*
|
||||
* @param minDelayMs базовая пауза между кликами
|
||||
* @param jitter доля случайного разброса паузы (0.3 = плюс-минус 30%)
|
||||
* @param confirmTimeoutMs сколько ждать подтверждения клика до повтора
|
||||
* @param maxAttempts сколько раз кликнуть, прежде чем сдаться
|
||||
*/
|
||||
public record ClickConfig(long minDelayMs, double jitter, long confirmTimeoutMs, int maxAttempts) {
|
||||
|
||||
public static final long DEFAULT_DELAY_MS = 120;
|
||||
public static final double DEFAULT_JITTER = 0.3;
|
||||
public static final long DEFAULT_CONFIRM_TIMEOUT_MS = 1000;
|
||||
public static final int DEFAULT_ATTEMPTS = 3;
|
||||
|
||||
public static final ClickConfig DEFAULT =
|
||||
new ClickConfig(DEFAULT_DELAY_MS, DEFAULT_JITTER, DEFAULT_CONFIRM_TIMEOUT_MS, DEFAULT_ATTEMPTS);
|
||||
|
||||
public ClickConfig {
|
||||
if (minDelayMs < 0 || jitter < 0 || jitter > 1 || confirmTimeoutMs <= 0 || maxAttempts < 1) {
|
||||
throw new IllegalArgumentException("Bad click config");
|
||||
}
|
||||
}
|
||||
|
||||
public ClickConfig withDelay(long delayMs) {
|
||||
return new ClickConfig(delayMs, jitter, confirmTimeoutMs, maxAttempts);
|
||||
}
|
||||
|
||||
/** Следующая пауза: minDelayMs * (1 +- jitter), равномерно. */
|
||||
public long nextDelay(RandomGenerator random) {
|
||||
double factor = 1 + jitter * (2 * random.nextDouble() - 1);
|
||||
return Math.round(minDelayMs * factor);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
package dev.loki.satura.interaction.click;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.Deque;
|
||||
import java.util.random.RandomGenerator;
|
||||
|
||||
/**
|
||||
* Единая очередь контейнерных кликов: пауза с джиттером между кликами и подтверждение
|
||||
* каждого клика по синхронизации слотов (таймаут, повтор). Тикается владельцем раз в тик.
|
||||
*/
|
||||
public final class ClickScheduler {
|
||||
|
||||
private final Deque<ClickTask> queue = new ArrayDeque<>();
|
||||
private final Clock clock;
|
||||
private final RandomGenerator random;
|
||||
private ClickConfig config;
|
||||
private ClickTask current;
|
||||
private boolean clicked;
|
||||
private int attempts;
|
||||
private long nextClickAt;
|
||||
private long deadline;
|
||||
|
||||
public ClickScheduler(ClickConfig config, Clock clock, RandomGenerator random) {
|
||||
this.config = config;
|
||||
this.clock = clock;
|
||||
this.random = random;
|
||||
}
|
||||
|
||||
public void configure(ClickConfig newConfig) {
|
||||
this.config = newConfig;
|
||||
}
|
||||
|
||||
public void submit(ClickTask task) {
|
||||
queue.add(task);
|
||||
}
|
||||
|
||||
public boolean isIdle() {
|
||||
return current == null && queue.isEmpty();
|
||||
}
|
||||
|
||||
public int pending() {
|
||||
return queue.size() + (current == null ? 0 : 1);
|
||||
}
|
||||
|
||||
/** Отложить следующий клик минимум на delayMs (пауза «человека» после открытия экрана). */
|
||||
public void delayNext(long delayMs) {
|
||||
nextClickAt = Math.max(nextClickAt, clock.nowMillis() + delayMs);
|
||||
}
|
||||
|
||||
@SuppressWarnings("PMD.NullAssignment")
|
||||
public void clear() {
|
||||
queue.clear();
|
||||
current = null;
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
long now = clock.nowMillis();
|
||||
if (current == null) {
|
||||
current = queue.poll();
|
||||
clicked = false;
|
||||
attempts = 0;
|
||||
}
|
||||
if (current == null) {
|
||||
return;
|
||||
}
|
||||
if (clicked) {
|
||||
awaitConfirmation(now);
|
||||
} else if (now >= nextClickAt) {
|
||||
fire(now);
|
||||
}
|
||||
}
|
||||
|
||||
private void fire(long now) {
|
||||
attempts++;
|
||||
clicked = true;
|
||||
deadline = now + config.confirmTimeoutMs();
|
||||
current.click().run();
|
||||
}
|
||||
|
||||
private void awaitConfirmation(long now) {
|
||||
if (current.confirmed().getAsBoolean()) {
|
||||
finish(now, ClickTask.Outcome.CONFIRMED);
|
||||
} else if (now >= deadline) {
|
||||
if (attempts >= config.maxAttempts()) {
|
||||
finish(now, ClickTask.Outcome.FAILED);
|
||||
} else {
|
||||
clicked = false;
|
||||
nextClickAt = now + config.nextDelay(random);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("PMD.NullAssignment")
|
||||
private void finish(long now, ClickTask.Outcome outcome) {
|
||||
ClickTask done = current;
|
||||
current = null;
|
||||
nextClickAt = now + config.nextDelay(random);
|
||||
done.onDone().accept(outcome);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
package dev.loki.satura.interaction.click;
|
||||
|
||||
import java.util.function.BooleanSupplier;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Один клик по контейнеру.
|
||||
*
|
||||
* @param click действие клика (вызов clickSlot)
|
||||
* @param confirmed true, когда результат клика виден в слотах (синхронизация пришла)
|
||||
* @param onDone итог задачи
|
||||
*/
|
||||
public record ClickTask(Runnable click, BooleanSupplier confirmed, Consumer<Outcome> onDone) {
|
||||
|
||||
/** Итог задачи. */
|
||||
public enum Outcome { CONFIRMED, FAILED }
|
||||
|
||||
public static ClickTask of(Runnable click, BooleanSupplier confirmed) {
|
||||
return new ClickTask(click, confirmed, outcome -> { });
|
||||
}
|
||||
}
|
||||
10
src/main/java/dev/loki/satura/interaction/click/Clock.java
Normal file
10
src/main/java/dev/loki/satura/interaction/click/Clock.java
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
package dev.loki.satura.interaction.click;
|
||||
|
||||
/** Источник времени; подменяется в тестах. */
|
||||
@FunctionalInterface
|
||||
public interface Clock {
|
||||
|
||||
Clock SYSTEM = System::currentTimeMillis;
|
||||
|
||||
long nowMillis();
|
||||
}
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
package dev.loki.satura.interaction.inventory;
|
||||
|
||||
import dev.loki.satura.interaction.click.ClickScheduler;
|
||||
import dev.loki.satura.interaction.click.ClickTask;
|
||||
|
||||
/**
|
||||
* Пополнение хотбара: когда в выбранном слоте осталось не больше порога, самый полный стак
|
||||
* из инвентаря меняется с пустеющим слотом хотбара (SWAP) через общий ClickScheduler.
|
||||
*/
|
||||
public final class HotbarRefill {
|
||||
|
||||
/** Порог: слот с таким или меньшим числом блоков считается пустым. */
|
||||
public static final int LOW = 2;
|
||||
|
||||
/** Состояние пополнения. */
|
||||
public enum State { READY, REFILLING, EMPTY }
|
||||
|
||||
private final InventoryView inventory;
|
||||
private final ClickScheduler scheduler;
|
||||
private final RefillPlanner planner;
|
||||
private boolean swapPending;
|
||||
|
||||
public HotbarRefill(InventoryView inventory, ClickScheduler scheduler) {
|
||||
this(inventory, scheduler, LOW);
|
||||
}
|
||||
|
||||
public HotbarRefill(InventoryView inventory, ClickScheduler scheduler, int low) {
|
||||
this.inventory = inventory;
|
||||
this.scheduler = scheduler;
|
||||
this.planner = new RefillPlanner(low);
|
||||
}
|
||||
|
||||
/** Один тик логики; сам планировщик кликов тикает владелец. */
|
||||
public State tick() {
|
||||
if (swapPending) {
|
||||
return State.REFILLING;
|
||||
}
|
||||
int[] counts = new int[InventoryView.SLOTS];
|
||||
for (int i = 0; i < counts.length; i++) {
|
||||
counts[i] = inventory.count(i);
|
||||
}
|
||||
RefillPlanner.Decision decision = planner.plan(counts, inventory.selectedSlot());
|
||||
return switch (decision.kind()) {
|
||||
case READY -> State.READY;
|
||||
case SELECT -> select(decision.from());
|
||||
case SWAP -> swap(decision.from(), decision.to(), counts[decision.from()]);
|
||||
case EMPTY -> State.EMPTY;
|
||||
};
|
||||
}
|
||||
|
||||
private State select(int slot) {
|
||||
inventory.select(slot);
|
||||
return State.READY;
|
||||
}
|
||||
|
||||
@SuppressWarnings("PMD.UnusedAssignment")
|
||||
private State swap(int src, int dst, int movedCount) {
|
||||
swapPending = true;
|
||||
scheduler.submit(new ClickTask(
|
||||
() -> inventory.swapToHotbar(src, dst),
|
||||
() -> inventory.count(dst) == movedCount,
|
||||
outcome -> swapPending = false));
|
||||
return State.REFILLING;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
package dev.loki.satura.interaction.inventory;
|
||||
|
||||
/** Вид на инвентарь игрока относительно целевого предмета. Слоты 0-8 хотбар, 9-35 инвентарь. */
|
||||
public interface InventoryView {
|
||||
|
||||
int SLOTS = 36;
|
||||
int HOTBAR_SIZE = 9;
|
||||
|
||||
/** Сколько целевых предметов в слоте (0, если слот пуст или там другое). */
|
||||
int count(int slot);
|
||||
|
||||
int selectedSlot();
|
||||
|
||||
void select(int slot);
|
||||
|
||||
/** Клик SWAP: стак из слота инвентаря src меняется местами со слотом хотбара hotbarSlot. */
|
||||
void swapToHotbar(int src, int hotbarSlot);
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
package dev.loki.satura.interaction.inventory;
|
||||
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.network.ClientPlayerEntity;
|
||||
import net.minecraft.item.BlockItem;
|
||||
import net.minecraft.item.ItemStack;
|
||||
import net.minecraft.screen.slot.SlotActionType;
|
||||
|
||||
/** Тонкий адаптер к клиенту Minecraft: инвентарь игрока относительно одного блока. */
|
||||
public final class MinecraftInventoryView implements InventoryView {
|
||||
|
||||
private final MinecraftClient client;
|
||||
private final Block block;
|
||||
|
||||
public MinecraftInventoryView(MinecraftClient client, Block block) {
|
||||
this.client = client;
|
||||
this.block = block;
|
||||
}
|
||||
|
||||
@Override
|
||||
@SuppressWarnings("PMD.CompareObjectsWithEquals")
|
||||
public int count(int slot) {
|
||||
ClientPlayerEntity player = client.player;
|
||||
if (player == null) {
|
||||
return 0;
|
||||
}
|
||||
ItemStack stack = player.getInventory().getStack(slot);
|
||||
boolean match = !stack.isEmpty() && stack.getItem() instanceof BlockItem item && item.getBlock() == block;
|
||||
return match ? stack.getCount() : 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int selectedSlot() {
|
||||
return client.player == null ? 0 : client.player.getInventory().getSelectedSlot();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void select(int slot) {
|
||||
if (client.player != null) {
|
||||
client.player.getInventory().setSelectedSlot(slot);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swapToHotbar(int src, int hotbarSlot) {
|
||||
ClientPlayerEntity player = client.player;
|
||||
if (player != null && client.interactionManager != null) {
|
||||
client.interactionManager.clickSlot(
|
||||
player.currentScreenHandler.syncId, src, hotbarSlot, SlotActionType.SWAP, player);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
package dev.loki.satura.interaction.inventory;
|
||||
|
||||
/** Чистый выбор действия по заполненности слотов. */
|
||||
public final class RefillPlanner {
|
||||
|
||||
/** Тип решения. */
|
||||
public enum Kind { READY, SELECT, SWAP, EMPTY }
|
||||
|
||||
/**
|
||||
* Решение: SELECT - выбрать хотбар-слот from; SWAP - обменять from (инвентарь) на to (хотбар).
|
||||
*/
|
||||
public record Decision(Kind kind, int from, int to) {
|
||||
|
||||
static Decision of(Kind kind) {
|
||||
return new Decision(kind, -1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
private final int low;
|
||||
|
||||
public RefillPlanner(int low) {
|
||||
this.low = low;
|
||||
}
|
||||
|
||||
public Decision plan(int[] counts, int selected) {
|
||||
if (counts[selected] > low) {
|
||||
return Decision.of(Kind.READY);
|
||||
}
|
||||
int best = fullest(counts, 0, InventoryView.HOTBAR_SIZE);
|
||||
if (counts[best] > low) {
|
||||
return new Decision(Kind.SELECT, best, -1);
|
||||
}
|
||||
int src = fullest(counts, InventoryView.HOTBAR_SIZE, InventoryView.SLOTS);
|
||||
int dst = firstLow(counts);
|
||||
if (counts[src] > 0 && dst >= 0 && counts[src] > counts[dst]) {
|
||||
return new Decision(Kind.SWAP, src, dst);
|
||||
}
|
||||
if (counts[best] > 0) {
|
||||
return new Decision(Kind.SELECT, best, -1);
|
||||
}
|
||||
return Decision.of(Kind.EMPTY);
|
||||
}
|
||||
|
||||
@SuppressWarnings("PMD.UseVarargs")
|
||||
private int firstLow(int[] counts) {
|
||||
for (int i = 0; i < InventoryView.HOTBAR_SIZE; i++) {
|
||||
if (counts[i] <= low) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static int fullest(int[] counts, int from, int to) {
|
||||
int best = from;
|
||||
for (int i = from; i < to; i++) {
|
||||
if (counts[i] > counts[best]) {
|
||||
best = i;
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
package dev.loki.satura.interaction.movement;
|
||||
|
||||
/** Чистая математика углов (градусы, система Minecraft). */
|
||||
public final class Angles {
|
||||
|
||||
private static final float FULL_TURN = 360f;
|
||||
private static final float HALF_TURN = 180f;
|
||||
private static final float QUARTER_TURN = 90f;
|
||||
|
||||
private Angles() {
|
||||
}
|
||||
|
||||
public static float wrap(float degrees) {
|
||||
float d = degrees % FULL_TURN;
|
||||
if (d >= HALF_TURN) {
|
||||
d -= FULL_TURN;
|
||||
} else if (d < -HALF_TURN) {
|
||||
d += FULL_TURN;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
public static float yawTo(double dx, double dz) {
|
||||
return (float) Math.toDegrees(Math.atan2(dz, dx)) - QUARTER_TURN;
|
||||
}
|
||||
|
||||
public static float pitchTo(double dy, double horizontal) {
|
||||
float pitch = (float) -Math.toDegrees(Math.atan2(dy, horizontal));
|
||||
return Math.max(-QUARTER_TURN, Math.min(QUARTER_TURN, pitch));
|
||||
}
|
||||
|
||||
public static float clamp(float value, float limit) {
|
||||
return Math.max(-limit, Math.min(limit, value));
|
||||
}
|
||||
|
||||
/** Шаг от current к target не больше maxStep по кратчайшей дуге. */
|
||||
public static float approachYaw(float current, float target, float maxStep) {
|
||||
return current + clamp(wrap(target - current), maxStep);
|
||||
}
|
||||
|
||||
public static float approachPitch(float current, float target, float maxStep) {
|
||||
return current + clamp(target - current, maxStep);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package dev.loki.satura.interaction.movement;
|
||||
|
||||
import dev.loki.satura.interaction.movement.io.PlayerPose;
|
||||
|
||||
/** Управление взглядом: плавный доворот с клампом °/тик и мгновенный взгляд вниз. */
|
||||
public final class LookController {
|
||||
|
||||
public static final float MAX_YAW_STEP = 25f;
|
||||
public static final float MAX_PITCH_STEP = 20f;
|
||||
public static final float SNAP_EPSILON = 0.4f;
|
||||
public static final float DOWN_PITCH = 90f;
|
||||
|
||||
private final PlayerPose pose;
|
||||
|
||||
public LookController(PlayerPose pose) {
|
||||
this.pose = pose;
|
||||
}
|
||||
|
||||
/** Доворот к точке за один тик; true, когда взгляд уже на цели. */
|
||||
public boolean lookAtSmooth(double x, double y, double z) {
|
||||
double dx = x - pose.x();
|
||||
double dz = z - pose.z();
|
||||
float targetYaw = Angles.yawTo(dx, dz);
|
||||
float targetPitch = Angles.pitchTo(y - pose.eyeY(), Math.hypot(dx, dz));
|
||||
float dYaw = Angles.wrap(targetYaw - pose.yaw());
|
||||
float dPitch = targetPitch - pose.pitch();
|
||||
if (Math.abs(dYaw) < SNAP_EPSILON && Math.abs(dPitch) < SNAP_EPSILON) {
|
||||
pose.setYaw(targetYaw);
|
||||
pose.setPitch(targetPitch);
|
||||
return true;
|
||||
}
|
||||
pose.setYaw(Angles.approachYaw(pose.yaw(), targetYaw, MAX_YAW_STEP));
|
||||
pose.setPitch(Angles.approachPitch(pose.pitch(), targetPitch, MAX_PITCH_STEP));
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Мгновенно смотреть строго вниз (для стратегий столбика/пола). */
|
||||
public void lookDown() {
|
||||
pose.setPitch(DOWN_PITCH);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
package dev.loki.satura.interaction.movement;
|
||||
|
||||
import dev.loki.satura.interaction.movement.io.KeyInput;
|
||||
import dev.loki.satura.interaction.movement.io.PlayerPose;
|
||||
|
||||
/** Ходьба к точке фейк-клавишами: кламп поворота, прыжок на препятствии, сайдстеп при застревании. */
|
||||
public final class MovementController {
|
||||
|
||||
public static final float MAX_TURN_STEP = 35f;
|
||||
public static final float ALIGN_TOLERANCE = 45f;
|
||||
public static final double ARRIVE_DIST_SQ = 0.09;
|
||||
public static final double STUCK_MIN_MOVE_SQ = 0.0004;
|
||||
public static final int STUCK_TICKS = 10;
|
||||
public static final int SIDESTEP_TICKS = 8;
|
||||
|
||||
private final KeyInput keys;
|
||||
private final PlayerPose pose;
|
||||
private double lastX = Double.NaN;
|
||||
private double lastZ = Double.NaN;
|
||||
private int stillTicks;
|
||||
private int sidestepLeft;
|
||||
private boolean sidestepRight = true;
|
||||
|
||||
public MovementController(KeyInput keys, PlayerPose pose) {
|
||||
this.keys = keys;
|
||||
this.pose = pose;
|
||||
}
|
||||
|
||||
public void stop() {
|
||||
keys.releaseAll();
|
||||
stillTicks = 0;
|
||||
sidestepLeft = 0;
|
||||
lastX = Double.NaN;
|
||||
}
|
||||
|
||||
public void sneak(boolean on) {
|
||||
keys.setSneak(on);
|
||||
}
|
||||
|
||||
public void pillarKeys() {
|
||||
keys.releaseAll();
|
||||
keys.setJump(true);
|
||||
}
|
||||
|
||||
/** Один тик ходьбы к (x, z); true, когда дошли (клавиши отпущены). */
|
||||
public boolean walkTo(double x, double z) {
|
||||
double dx = x - pose.x();
|
||||
double dz = z - pose.z();
|
||||
if (dx * dx + dz * dz <= ARRIVE_DIST_SQ) {
|
||||
stop();
|
||||
return true;
|
||||
}
|
||||
if (sidestepLeft > 0) {
|
||||
sidestep();
|
||||
return false;
|
||||
}
|
||||
float target = Angles.yawTo(dx, dz);
|
||||
pose.setYaw(Angles.approachYaw(pose.yaw(), target, MAX_TURN_STEP));
|
||||
boolean aligned = Math.abs(Angles.wrap(target - pose.yaw())) < ALIGN_TOLERANCE;
|
||||
keys.releaseAll();
|
||||
keys.setForward(aligned);
|
||||
keys.setJump(pose.horizontalCollision());
|
||||
trackStuck(aligned);
|
||||
return false;
|
||||
}
|
||||
|
||||
private void sidestep() {
|
||||
sidestepLeft--;
|
||||
keys.releaseAll();
|
||||
keys.setLeft(!sidestepRight);
|
||||
keys.setRight(sidestepRight);
|
||||
keys.setJump(true);
|
||||
if (sidestepLeft == 0) {
|
||||
sidestepRight = !sidestepRight;
|
||||
stillTicks = 0;
|
||||
}
|
||||
}
|
||||
|
||||
private void trackStuck(boolean pushing) {
|
||||
double moved = Double.isNaN(lastX) ? Double.MAX_VALUE : sq(pose.x() - lastX) + sq(pose.z() - lastZ);
|
||||
lastX = pose.x();
|
||||
lastZ = pose.z();
|
||||
stillTicks = pushing && moved < STUCK_MIN_MOVE_SQ ? stillTicks + 1 : 0;
|
||||
if (stillTicks >= STUCK_TICKS) {
|
||||
sidestepLeft = SIDESTEP_TICKS;
|
||||
}
|
||||
}
|
||||
|
||||
private static double sq(double v) {
|
||||
return v * v;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package dev.loki.satura.interaction.movement.io;
|
||||
|
||||
/** Фейковые клавиши движения. */
|
||||
public interface KeyInput {
|
||||
|
||||
void setForward(boolean pressed);
|
||||
|
||||
void setBack(boolean pressed);
|
||||
|
||||
void setLeft(boolean pressed);
|
||||
|
||||
void setRight(boolean pressed);
|
||||
|
||||
void setJump(boolean pressed);
|
||||
|
||||
void setSneak(boolean pressed);
|
||||
|
||||
default void releaseAll() {
|
||||
setForward(false);
|
||||
setBack(false);
|
||||
setLeft(false);
|
||||
setRight(false);
|
||||
setJump(false);
|
||||
setSneak(false);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
package dev.loki.satura.interaction.movement.io;
|
||||
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
|
||||
/** Адаптер клавиш к настройкам клиента Minecraft. */
|
||||
public final class MinecraftKeyInput implements KeyInput {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
||||
public MinecraftKeyInput(MinecraftClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setForward(boolean pressed) {
|
||||
client.options.forwardKey.setPressed(pressed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setBack(boolean pressed) {
|
||||
client.options.backKey.setPressed(pressed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setLeft(boolean pressed) {
|
||||
client.options.leftKey.setPressed(pressed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setRight(boolean pressed) {
|
||||
client.options.rightKey.setPressed(pressed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setJump(boolean pressed) {
|
||||
client.options.jumpKey.setPressed(pressed);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setSneak(boolean pressed) {
|
||||
client.options.sneakKey.setPressed(pressed);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
package dev.loki.satura.interaction.movement.io;
|
||||
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.network.ClientPlayerEntity;
|
||||
|
||||
/** Адаптер позы к ClientPlayerEntity; без игрока (мир не загружен) работает как заглушка. */
|
||||
public final class MinecraftPlayerPose implements PlayerPose {
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
||||
public MinecraftPlayerPose(MinecraftClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
private ClientPlayerEntity player() {
|
||||
return client.player;
|
||||
}
|
||||
|
||||
@Override
|
||||
public double x() {
|
||||
return player() == null ? 0 : player().getX();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double y() {
|
||||
return player() == null ? 0 : player().getY();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double z() {
|
||||
return player() == null ? 0 : player().getZ();
|
||||
}
|
||||
|
||||
@Override
|
||||
public double eyeY() {
|
||||
return player() == null ? 0 : player().getEyeY();
|
||||
}
|
||||
|
||||
@Override
|
||||
public float yaw() {
|
||||
return player() == null ? 0 : player().getYaw();
|
||||
}
|
||||
|
||||
@Override
|
||||
public float pitch() {
|
||||
return player() == null ? 0 : player().getPitch();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setYaw(float yaw) {
|
||||
if (player() != null) {
|
||||
player().setYaw(yaw);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setPitch(float pitch) {
|
||||
if (player() != null) {
|
||||
player().setPitch(pitch);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean horizontalCollision() {
|
||||
return player() != null && player().horizontalCollision;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package dev.loki.satura.interaction.movement.io;
|
||||
|
||||
/** Положение и взгляд игрока (градусы по Minecraft: yaw 0 = юг, pitch + вниз). */
|
||||
public interface PlayerPose {
|
||||
|
||||
double x();
|
||||
|
||||
double y();
|
||||
|
||||
double z();
|
||||
|
||||
double eyeY();
|
||||
|
||||
float yaw();
|
||||
|
||||
float pitch();
|
||||
|
||||
void setYaw(float yaw);
|
||||
|
||||
void setPitch(float pitch);
|
||||
|
||||
boolean horizontalCollision();
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
package dev.loki.satura.interaction.place;
|
||||
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Всё, чем стратегия касается игры. Узкий интерфейс, чтобы логику можно было тестировать фейком. */
|
||||
public interface PlaceContext {
|
||||
|
||||
/** Позиция ног игрока. */
|
||||
Vec3d feetPos();
|
||||
|
||||
/** Позиция глаз игрока. */
|
||||
Vec3d eyePos();
|
||||
|
||||
/** Годится ли блок как опора. */
|
||||
boolean isSolid(BlockPos pos);
|
||||
|
||||
/** Клик ПКМ по блоку; true - клиент принял действие. */
|
||||
boolean interact(BlockHitResult hit);
|
||||
|
||||
void swing();
|
||||
|
||||
/** Мгновенно взгляд строго вниз. */
|
||||
void lookDown();
|
||||
|
||||
void setVelocity(double x, double y, double z);
|
||||
|
||||
/** Включить полёт, если он разрешён. */
|
||||
void enableFlight();
|
||||
|
||||
long nowMs();
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
package dev.loki.satura.interaction.place;
|
||||
|
||||
/** Итог одного тика стратегии. */
|
||||
public enum PlaceResult {
|
||||
/** Блок поставлен в этом тике. */
|
||||
PLACED,
|
||||
/** Ничего не делали: летим, кулдаун, ждём ответ сервера. */
|
||||
WAIT,
|
||||
/** Цель сейчас не поставить (нет опоры / вне досягаемости): движок вправе пересчитать цель. */
|
||||
FAILED
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
package dev.loki.satura.interaction.place;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.ColumnTarget;
|
||||
import dev.loki.satura.interaction.place.option.Option;
|
||||
import dev.loki.satura.interaction.place.option.OptionValues;
|
||||
import java.util.List;
|
||||
|
||||
/** Способ ставить блоки в колонну. Движок вызывает {@link #tick} каждый тик, пока колонна не достроена. */
|
||||
public interface PlaceStrategy {
|
||||
|
||||
/** Стабильный ключ для конфига. */
|
||||
String id();
|
||||
|
||||
/** Название для GUI. */
|
||||
String label();
|
||||
|
||||
/** Объявление параметров; GUI рисует их генерично. */
|
||||
List<Option> options();
|
||||
|
||||
/** Текущие значения параметров (живые - GUI может менять). */
|
||||
OptionValues values();
|
||||
|
||||
PlaceResult tick(PlaceContext ctx, ColumnTarget target);
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package dev.loki.satura.interaction.place;
|
||||
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/**
|
||||
* Один клик: ставим блок в {@code target}, кликая по грани {@code face} опоры {@code support}.
|
||||
* {@code standPos} - откуда кликать (может быть {@code null}, если стратегии это не важно).
|
||||
*/
|
||||
public record Placement(BlockPos target, BlockPos support, Direction face, Vec3d hitVec, Vec3d standPos) {
|
||||
|
||||
public BlockHitResult hitResult() {
|
||||
return new BlockHitResult(hitVec, face, support, false);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,70 @@
|
|||
package dev.loki.satura.interaction.place.client;
|
||||
|
||||
import dev.loki.satura.interaction.place.PlaceContext;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.network.ClientPlayerEntity;
|
||||
import net.minecraft.util.Hand;
|
||||
import net.minecraft.util.hit.BlockHitResult;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Реальный игрок и мир за интерфейсом {@link PlaceContext}. Клиент передаётся в конструктор. */
|
||||
public final class MinecraftPlaceContext implements PlaceContext {
|
||||
|
||||
private static final float PITCH_DOWN = 90.0F;
|
||||
|
||||
private final MinecraftClient client;
|
||||
|
||||
public MinecraftPlaceContext(final MinecraftClient client) {
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vec3d feetPos() {
|
||||
return client.player.getEntityPos();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Vec3d eyePos() {
|
||||
return client.player.getEyePos();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isSolid(final BlockPos pos) {
|
||||
final var state = client.world.getBlockState(pos);
|
||||
return !state.isAir() && state.isSolidBlock(client.world, pos);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean interact(final BlockHitResult hit) {
|
||||
return client.interactionManager.interactBlock(client.player, Hand.MAIN_HAND, hit).isAccepted();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void swing() {
|
||||
client.player.swingHand(Hand.MAIN_HAND);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void lookDown() {
|
||||
client.player.setPitch(PITCH_DOWN);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setVelocity(final double x, final double y, final double z) {
|
||||
client.player.setVelocity(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void enableFlight() {
|
||||
final ClientPlayerEntity player = client.player;
|
||||
if (player.getAbilities().allowFlying) {
|
||||
player.getAbilities().flying = true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public long nowMs() {
|
||||
return System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
package dev.loki.satura.interaction.place.option;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.Planner;
|
||||
|
||||
/** Параметры, общие для нескольких стратегий (значения по yatwinkle BaseBuilder). */
|
||||
@SuppressWarnings("PMD.DataClass")
|
||||
public final class CommonOptions {
|
||||
|
||||
public static final Option DELAY_MS =
|
||||
new Option("delayMs", "Задержка установки (мс)", OptionType.INT, 0, 300, 5, 0);
|
||||
public static final Option REACH =
|
||||
new Option("reach", "Дальность", OptionType.DOUBLE, 3.0, 6.0, 0.1, 4.5);
|
||||
public static final Option HOVER =
|
||||
new Option("hover", "Высота над слоем", OptionType.DOUBLE, 0.0, 1.5, 0.5, 1.0);
|
||||
public static final Option FLY_SPEED =
|
||||
new Option("flySpeed", "Скорость полёта", OptionType.DOUBLE, 0.05, 1.0, 0.05, 0.25);
|
||||
public static final Option BAND_LAYERS =
|
||||
new Option("bandLayers", "Слоёв за проход", OptionType.INT,
|
||||
Planner.MIN_BAND_LAYERS, Planner.MAX_BAND_LAYERS, 1, 2);
|
||||
|
||||
private CommonOptions() {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
package dev.loki.satura.interaction.place.option;
|
||||
|
||||
/** Описание параметра стратегии. Для BOOL: min=0, max=1. */
|
||||
public record Option(String key, String label, OptionType type,
|
||||
double min, double max, double step, double def) {
|
||||
|
||||
public Option {
|
||||
if (min > max || def < min || def > max) {
|
||||
throw new IllegalArgumentException("bad option range: " + key);
|
||||
}
|
||||
}
|
||||
|
||||
public double clamp(final double value) {
|
||||
final double bounded = Math.max(min, Math.min(max, value));
|
||||
return type == OptionType.INT ? Math.round(bounded) : bounded;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
package dev.loki.satura.interaction.place.option;
|
||||
|
||||
/** Вид виджета для параметра. */
|
||||
public enum OptionType {
|
||||
INT,
|
||||
DOUBLE,
|
||||
BOOL
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package dev.loki.satura.interaction.place.option;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/** Значения параметров стратегии по ключам; всегда в пределах диапазона опции. */
|
||||
@SuppressWarnings("PMD.LooseCoupling")
|
||||
public final class OptionValues {
|
||||
|
||||
private final Map<String, Double> values = new HashMap<>();
|
||||
private final Map<String, Option> known = new HashMap<>();
|
||||
|
||||
public OptionValues(final List<Option> options) {
|
||||
for (final Option option : options) {
|
||||
known.put(option.key(), option);
|
||||
}
|
||||
}
|
||||
|
||||
public double get(final Option option) {
|
||||
return values.getOrDefault(option.key(), option.def());
|
||||
}
|
||||
|
||||
public int getInt(final Option option) {
|
||||
return (int) get(option);
|
||||
}
|
||||
|
||||
public boolean getBool(final Option option) {
|
||||
return get(option) >= 1.0;
|
||||
}
|
||||
|
||||
/** Записать значение по ключу; false - такого параметра нет. */
|
||||
public boolean set(final String key, final double value) {
|
||||
final Option option = known.get(key);
|
||||
if (option == null) {
|
||||
return false;
|
||||
}
|
||||
values.put(key, option.clamp(value));
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
package dev.loki.satura.interaction.place.strategy;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.ColumnTarget;
|
||||
import dev.loki.satura.interaction.place.PlaceContext;
|
||||
import dev.loki.satura.interaction.place.PlaceResult;
|
||||
import dev.loki.satura.interaction.place.PlaceStrategy;
|
||||
import dev.loki.satura.interaction.place.option.CommonOptions;
|
||||
import dev.loki.satura.interaction.place.option.Option;
|
||||
import dev.loki.satura.interaction.place.option.OptionValues;
|
||||
import dev.loki.satura.interaction.place.support.BlockPlacer;
|
||||
import java.util.List;
|
||||
|
||||
/** S2: за один визит колонны ставим 1..3 слоя подряд снизу вверх (yatwinkle bandLayers). */
|
||||
public final class BandStack implements PlaceStrategy {
|
||||
|
||||
private static final List<Option> DECLARED = List.of(
|
||||
CommonOptions.BAND_LAYERS, CommonOptions.DELAY_MS, CommonOptions.REACH,
|
||||
CommonOptions.HOVER, CommonOptions.FLY_SPEED);
|
||||
|
||||
private final OptionValues params = new OptionValues(DECLARED);
|
||||
private final ColumnPlacing core;
|
||||
|
||||
public BandStack(final BlockPlacer placer) {
|
||||
this.core = new ColumnPlacing(params, () -> params.getInt(CommonOptions.BAND_LAYERS), placer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return "band_stack";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "BandStack";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Option> options() {
|
||||
return DECLARED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionValues values() {
|
||||
return params;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlaceResult tick(final PlaceContext ctx, final ColumnTarget target) {
|
||||
return core.tick(ctx, target);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,50 @@
|
|||
package dev.loki.satura.interaction.place.strategy;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.ColumnTarget;
|
||||
import dev.loki.satura.interaction.place.PlaceContext;
|
||||
import dev.loki.satura.interaction.place.PlaceResult;
|
||||
import dev.loki.satura.interaction.place.PlaceStrategy;
|
||||
import dev.loki.satura.interaction.place.option.CommonOptions;
|
||||
import dev.loki.satura.interaction.place.option.Option;
|
||||
import dev.loki.satura.interaction.place.option.OptionValues;
|
||||
import dev.loki.satura.interaction.place.support.BlockPlacer;
|
||||
import java.util.List;
|
||||
|
||||
/** S1: полёт над слоем, pitch=90, по одному слою за визит колонны (yatwinkle без bandLayers). */
|
||||
public final class ColumnDrop implements PlaceStrategy {
|
||||
|
||||
private static final List<Option> DECLARED = List.of(
|
||||
CommonOptions.DELAY_MS, CommonOptions.REACH, CommonOptions.HOVER, CommonOptions.FLY_SPEED);
|
||||
|
||||
private final OptionValues params = new OptionValues(DECLARED);
|
||||
private final ColumnPlacing core;
|
||||
|
||||
public ColumnDrop(final BlockPlacer placer) {
|
||||
this.core = new ColumnPlacing(params, () -> 1, placer);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return "column_drop";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "ColumnDrop";
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Option> options() {
|
||||
return DECLARED;
|
||||
}
|
||||
|
||||
@Override
|
||||
public OptionValues values() {
|
||||
return params;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlaceResult tick(final PlaceContext ctx, final ColumnTarget target) {
|
||||
return core.tick(ctx, target);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,89 @@
|
|||
package dev.loki.satura.interaction.place.strategy;
|
||||
|
||||
import dev.loki.satura.feature.builder.plan.ColumnTarget;
|
||||
import dev.loki.satura.interaction.place.PlaceContext;
|
||||
import dev.loki.satura.interaction.place.PlaceResult;
|
||||
import dev.loki.satura.interaction.place.option.CommonOptions;
|
||||
import dev.loki.satura.interaction.place.option.OptionValues;
|
||||
import dev.loki.satura.interaction.place.support.BlockPlacer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.IntSupplier;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Ядро yatwinkle-стиля: висим над колонной, смотрим вниз, ставим слои band снизу вверх. */
|
||||
final class ColumnPlacing {
|
||||
|
||||
/** Запас: глаза 1.62 + ~0.08 (yatwinkle {@code layerY + reach - 1.7}). */
|
||||
static final double EYE_MARGIN = 1.7;
|
||||
/** Столько тиков не повторяем клик в ту же ячейку, пока сервер не ответил. */
|
||||
static final int PENDING_TTL_TICKS = 2;
|
||||
private static final double FEET_EPS = 0.1;
|
||||
private static final double CENTER = 0.5;
|
||||
|
||||
private final OptionValues values;
|
||||
private final IntSupplier layers;
|
||||
private final BlockPlacer placer;
|
||||
private int ticks;
|
||||
private BlockPos lastPos;
|
||||
private int lastTick;
|
||||
|
||||
ColumnPlacing(final OptionValues values, final IntSupplier layers, final BlockPlacer placer) {
|
||||
this.values = values;
|
||||
this.layers = layers;
|
||||
this.placer = placer;
|
||||
}
|
||||
|
||||
PlaceResult tick(final PlaceContext ctx, final ColumnTarget target) {
|
||||
ticks++;
|
||||
final List<BlockPos> band = band(target.cells(), layers.getAsInt());
|
||||
if (band.isEmpty()) {
|
||||
return PlaceResult.WAIT;
|
||||
}
|
||||
final BlockPos column = target.column();
|
||||
final int layerY = band.get(0).getY();
|
||||
final int bandTop = band.get(band.size() - 1).getY();
|
||||
ctx.enableFlight();
|
||||
final double reach = values.get(CommonOptions.REACH);
|
||||
final double height = FlightControl.height(layerY, bandTop, values.get(CommonOptions.HOVER),
|
||||
reach, EYE_MARGIN);
|
||||
final Vec3d feet = ctx.feetPos();
|
||||
final Vec3d goal = new Vec3d(column.getX() + CENTER, height, column.getZ() + CENTER);
|
||||
final Vec3d v = FlightControl.velocity(feet, goal, values.get(CommonOptions.FLY_SPEED));
|
||||
ctx.setVelocity(v.x, v.y, v.z);
|
||||
ctx.lookDown();
|
||||
if (!overColumn(feet, column) || feet.y < bandTop + 1.0 - FEET_EPS) {
|
||||
return PlaceResult.WAIT;
|
||||
}
|
||||
final BlockPos pos = band.get(0);
|
||||
if (pos.equals(lastPos) && ticks - lastTick <= PENDING_TTL_TICKS) {
|
||||
return PlaceResult.WAIT;
|
||||
}
|
||||
final PlaceResult result = placer.place(ctx, pos, reach, values.getInt(CommonOptions.DELAY_MS));
|
||||
if (result == PlaceResult.PLACED) {
|
||||
lastPos = pos;
|
||||
lastTick = ticks;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Ячейки окна: от самой нижней до {@code layers} слоёв вверх (cells - по возрастанию Y). */
|
||||
static List<BlockPos> band(final List<BlockPos> cells, final int layers) {
|
||||
final List<BlockPos> band = new ArrayList<>();
|
||||
if (cells.isEmpty()) {
|
||||
return band;
|
||||
}
|
||||
final int limit = cells.get(0).getY() + Math.max(1, layers) - 1;
|
||||
for (final BlockPos cell : cells) {
|
||||
if (cell.getY() <= limit) {
|
||||
band.add(cell);
|
||||
}
|
||||
}
|
||||
return band;
|
||||
}
|
||||
|
||||
static boolean overColumn(final Vec3d feet, final BlockPos column) {
|
||||
return (int) Math.floor(feet.x) == column.getX() && (int) Math.floor(feet.z) == column.getZ();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package dev.loki.satura.interaction.place.strategy;
|
||||
|
||||
import net.minecraft.util.math.MathHelper;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Скорость полёта setVelocity как в yatwinkle BaseBuilder.flyTo: прямой вектор к точке, без физики клавиш. */
|
||||
final class FlightControl {
|
||||
|
||||
private static final double ARRIVE_EPS = 0.05;
|
||||
|
||||
private FlightControl() {
|
||||
}
|
||||
|
||||
static Vec3d velocity(final Vec3d feet, final Vec3d goal, final double speed) {
|
||||
final double dx = goal.x - feet.x;
|
||||
final double dz = goal.z - feet.z;
|
||||
final double dist = Math.hypot(dx, dz);
|
||||
double vx = 0.0;
|
||||
double vz = 0.0;
|
||||
if (dist > ARRIVE_EPS) {
|
||||
final double step = Math.min(speed, dist);
|
||||
vx = dx / dist * step;
|
||||
vz = dz / dist * step;
|
||||
}
|
||||
final double vy = MathHelper.clamp(goal.y - feet.y, -speed, speed);
|
||||
return new Vec3d(vx, vy, vz);
|
||||
}
|
||||
|
||||
/** Высота полёта: min(bandTop+hover, layerY+reach-1.7), но не ниже верха слоя (чтобы не стоять в блоке). */
|
||||
static double height(final int layerY, final int bandTop, final double hover,
|
||||
final double reach, final double eyeMargin) {
|
||||
final double capped = Math.min(bandTop + hover, layerY + reach - eyeMargin);
|
||||
return Math.max(capped, bandTop + 1.0);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
package dev.loki.satura.interaction.place.support;
|
||||
|
||||
import dev.loki.satura.interaction.place.PlaceContext;
|
||||
import dev.loki.satura.interaction.place.PlaceResult;
|
||||
import dev.loki.satura.interaction.place.Placement;
|
||||
import java.util.Optional;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
|
||||
/** Общая часть всех стратегий: кулдаун, поиск опоры, клик и взмах руки. */
|
||||
public final class BlockPlacer {
|
||||
|
||||
private final SupportFinder finder;
|
||||
private final Cooldown cooldown;
|
||||
|
||||
public BlockPlacer(final SupportFinder finder, final Cooldown cooldown) {
|
||||
this.finder = finder;
|
||||
this.cooldown = cooldown;
|
||||
}
|
||||
|
||||
/** WAIT - кулдаун; FAILED - нет опоры в досягаемости или клиент отклонил клик; иначе PLACED. */
|
||||
public PlaceResult place(final PlaceContext ctx, final BlockPos target,
|
||||
final double reach, final long delayMs) {
|
||||
final long now = ctx.nowMs();
|
||||
if (!cooldown.ready(now, delayMs)) {
|
||||
return PlaceResult.WAIT;
|
||||
}
|
||||
final Optional<Placement> placement = finder.find(ctx, target, reach);
|
||||
if (placement.isEmpty() || !ctx.interact(placement.get().hitResult())) {
|
||||
return PlaceResult.FAILED;
|
||||
}
|
||||
ctx.swing();
|
||||
cooldown.mark(now);
|
||||
return PlaceResult.PLACED;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package dev.loki.satura.interaction.place.support;
|
||||
|
||||
/** Кулдаун между постановками в миллисекундах. */
|
||||
public final class Cooldown {
|
||||
|
||||
private long lastMs = Long.MIN_VALUE / 2;
|
||||
|
||||
public boolean ready(final long nowMs, final long delayMs) {
|
||||
return delayMs <= 0 || nowMs - lastMs >= delayMs;
|
||||
}
|
||||
|
||||
public void mark(final long nowMs) {
|
||||
lastMs = nowMs;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
package dev.loki.satura.interaction.place.support;
|
||||
|
||||
import dev.loki.satura.interaction.place.PlaceContext;
|
||||
import dev.loki.satura.interaction.place.Placement;
|
||||
import java.util.Optional;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.math.Vec3d;
|
||||
|
||||
/** Выбор опоры: сначала снизу, затем остальные 5 направлений (кроме низа). */
|
||||
public final class SupportFinder {
|
||||
|
||||
/** Клик по боковой грани чуть ниже верха блока, чтобы не попасть в стык. */
|
||||
public static final double SIDE_CLICK_Y = 0.94;
|
||||
private static final double HALF = 0.5;
|
||||
|
||||
public Optional<Placement> find(final PlaceContext ctx, final BlockPos target, final double reach) {
|
||||
final Vec3d eye = ctx.eyePos();
|
||||
for (final Direction dir : searchOrder()) {
|
||||
final BlockPos support = target.offset(dir);
|
||||
if (!ctx.isSolid(support)) {
|
||||
continue;
|
||||
}
|
||||
final Direction face = dir.getOpposite();
|
||||
final Vec3d hit = clickPoint(support, face);
|
||||
if (eye.distanceTo(hit) <= reach) {
|
||||
return Optional.of(new Placement(target, support, face, hit, null));
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** Порядок осмотра соседей цели: DOWN, затем UP и 4 стороны. */
|
||||
static Direction[] searchOrder() {
|
||||
return new Direction[] {
|
||||
Direction.DOWN, Direction.NORTH, Direction.SOUTH, Direction.WEST, Direction.EAST, Direction.UP
|
||||
};
|
||||
}
|
||||
|
||||
static Vec3d clickPoint(final BlockPos support, final Direction face) {
|
||||
final double x = support.getX() + HALF + face.getOffsetX() * HALF;
|
||||
final double z = support.getZ() + HALF + face.getOffsetZ() * HALF;
|
||||
final double y = face.getAxis().isHorizontal()
|
||||
? support.getY() + SIDE_CLICK_Y
|
||||
: support.getY() + HALF + face.getOffsetY() * HALF;
|
||||
return new Vec3d(x, y, z);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package dev.loki.satura.mixin;
|
||||
|
||||
import com.mojang.brigadier.suggestion.SuggestionsBuilder;
|
||||
import dev.loki.satura.core.CoreServices;
|
||||
import dev.loki.satura.core.command.SuggestHelper;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import net.minecraft.client.gui.screen.ChatInputSuggestor;
|
||||
import net.minecraft.client.gui.widget.TextFieldWidget;
|
||||
import org.spongepowered.asm.mixin.Final;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.Shadow;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ChatInputSuggestor.class)
|
||||
public abstract class ChatInputSuggestorMixin {
|
||||
|
||||
@Shadow @Final TextFieldWidget textField;
|
||||
@Shadow private CompletableFuture<com.mojang.brigadier.suggestion.Suggestions> pendingSuggestions;
|
||||
|
||||
@Shadow public abstract void setWindowActive(boolean windowActive);
|
||||
|
||||
@Shadow public abstract void show(boolean narrateFirstSuggestion);
|
||||
|
||||
@Inject(method = "refresh", at = @At("HEAD"), cancellable = true)
|
||||
private void satura$refresh(CallbackInfo ci) {
|
||||
CoreServices core = CoreServices.get();
|
||||
String text = textField.getText();
|
||||
if (core == null || !SuggestHelper.isCommand(text)) {
|
||||
return;
|
||||
}
|
||||
ci.cancel();
|
||||
setWindowActive(true);
|
||||
String toCursor = text.substring(0, Math.min(textField.getCursor(), text.length()));
|
||||
SuggestionsBuilder builder = new SuggestionsBuilder(toCursor, SuggestHelper.tokenStart(toCursor));
|
||||
core.commands().suggest(toCursor).forEach(builder::suggest);
|
||||
pendingSuggestions = CompletableFuture.completedFuture(builder.build());
|
||||
show(false);
|
||||
}
|
||||
}
|
||||
31
src/main/java/dev/loki/satura/mixin/ChatScreenMixin.java
Normal file
31
src/main/java/dev/loki/satura/mixin/ChatScreenMixin.java
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package dev.loki.satura.mixin;
|
||||
|
||||
import dev.loki.satura.core.CoreServices;
|
||||
import dev.loki.satura.core.command.SuggestHelper;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.gui.screen.ChatScreen;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(ChatScreen.class)
|
||||
@SuppressWarnings("PMD.AbstractClassWithoutAbstractMethod")
|
||||
public abstract class ChatScreenMixin {
|
||||
|
||||
@Inject(method = "sendMessage", at = @At("HEAD"), cancellable = true)
|
||||
private void satura$sendMessage(String message, boolean addToHistory, CallbackInfo ci) {
|
||||
CoreServices core = CoreServices.get();
|
||||
if (core == null || !SuggestHelper.isCommand(message)) {
|
||||
return;
|
||||
}
|
||||
if (addToHistory) {
|
||||
MinecraftClient.getInstance().inGameHud.getChatHud().addToMessageHistory(message);
|
||||
}
|
||||
String line = message.substring(SuggestHelper.PREFIX.length());
|
||||
if (!line.isBlank()) {
|
||||
core.commands().execute(line);
|
||||
}
|
||||
ci.cancel();
|
||||
}
|
||||
}
|
||||
25
src/main/java/dev/loki/satura/mixin/ClientWorldMixin.java
Normal file
25
src/main/java/dev/loki/satura/mixin/ClientWorldMixin.java
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
package dev.loki.satura.mixin;
|
||||
|
||||
import dev.loki.satura.core.CoreServices;
|
||||
import dev.loki.satura.core.event.world.BlockChangeEvent;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.client.world.ClientWorld;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(ClientWorld.class)
|
||||
@SuppressWarnings({"PMD.AbstractClassWithoutAbstractMethod", "PMD.UnusedFormalParameter"})
|
||||
public abstract class ClientWorldMixin {
|
||||
|
||||
@Inject(method = "setBlockState", at = @At("RETURN"))
|
||||
private void saturaBlockChanged(BlockPos pos, BlockState state, int flags, int depth,
|
||||
CallbackInfoReturnable<Boolean> cir) {
|
||||
final CoreServices core = CoreServices.get();
|
||||
if (core != null && cir.getReturnValueZ()) {
|
||||
core.events().post(new BlockChangeEvent(pos.toImmutable()));
|
||||
}
|
||||
}
|
||||
}
|
||||
19
src/main/java/dev/loki/satura/mixin/GameRendererMixin.java
Normal file
19
src/main/java/dev/loki/satura/mixin/GameRendererMixin.java
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
package dev.loki.satura.mixin;
|
||||
|
||||
import dev.loki.satura.render.Renderer;
|
||||
import net.minecraft.client.render.GameRenderer;
|
||||
import net.minecraft.client.render.RenderTickCounter;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(GameRenderer.class)
|
||||
@SuppressWarnings({"PMD.AbstractClassWithoutAbstractMethod", "PMD.UnusedFormalParameter"})
|
||||
public abstract class GameRendererMixin {
|
||||
|
||||
@Inject(method = "render", at = @At("RETURN"))
|
||||
private void saturaEndFrame(RenderTickCounter tickCounter, boolean tick, CallbackInfo ci) {
|
||||
Renderer.shared().endFrame();
|
||||
}
|
||||
}
|
||||
60
src/main/java/dev/loki/satura/render/RenderDebug.java
Normal file
60
src/main/java/dev/loki/satura/render/RenderDebug.java
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
package dev.loki.satura.render;
|
||||
|
||||
import dev.loki.satura.render.geom.Bounds;
|
||||
import dev.loki.satura.render.msdf.MsdfFont;
|
||||
import dev.loki.satura.render.msdf.MsdfFonts;
|
||||
|
||||
/** Тестовая отрисовка возможностей рендера; только при -Dsatura.renderDebug=true. */
|
||||
public final class RenderDebug {
|
||||
|
||||
private static final String FLAG = "satura.renderDebug";
|
||||
private static final float ORIGIN = 20f;
|
||||
private static final float PAD = 12f;
|
||||
private static final float PANEL_W = 220f;
|
||||
private static final float PANEL_H = 120f;
|
||||
private static final float TITLE = 16f;
|
||||
private static final float BODY = 11f;
|
||||
private static final float LINE_1 = 34f;
|
||||
private static final float LINE_2 = 52f;
|
||||
private static final float LINE_3 = 70f;
|
||||
private static final float CLIP_Y = 94f;
|
||||
private static final float CLIP_W = 100f;
|
||||
private static final float CLIP_H = 14f;
|
||||
private static final float BOX_X = 130f;
|
||||
private static final float BOX_W = 80f;
|
||||
private static final float BOX_H = 22f;
|
||||
private static final float GLOW_SIZE = 8f;
|
||||
private static final float GLOW_INTENSITY = 0.6f;
|
||||
|
||||
private final Renderer renderer;
|
||||
|
||||
private RenderDebug(Renderer renderer) {
|
||||
this.renderer = renderer;
|
||||
}
|
||||
|
||||
public static void installIfEnabled(Renderer renderer) {
|
||||
if (Boolean.getBoolean(FLAG)) {
|
||||
renderer.onFrame(new RenderDebug(renderer)::draw);
|
||||
}
|
||||
}
|
||||
|
||||
private void draw() {
|
||||
Bounds panel = new Bounds(ORIGIN, ORIGIN, PANEL_W, PANEL_H);
|
||||
renderer.blur(panel, Theme.RADIUS, 1f);
|
||||
renderer.rect(panel, Theme.RADIUS, Theme.PANEL & 0xE6FFFFFF);
|
||||
renderer.outline(panel, Theme.RADIUS, Theme.BORDER_WIDTH, Theme.BORDER);
|
||||
MsdfFont bold = renderer.text().font(MsdfFonts.BOLD);
|
||||
float x = ORIGIN + PAD;
|
||||
renderer.text().draw(bold, "Satura render", x, ORIGIN + PAD, TITLE, Theme.TEXT);
|
||||
renderer.text().draw("Montserrat: rect + blur + outline", x, ORIGIN + LINE_1, BODY, Theme.TEXT_MUTED);
|
||||
renderer.text().drawGradient(bold, "Gradient text", x, ORIGIN + LINE_2, BODY, Theme.ACCENT_PRESSED,
|
||||
Theme.ACCENT_HOVER);
|
||||
renderer.text().drawGlow(bold, "Glow text", x, ORIGIN + LINE_3, TITLE, Theme.TEXT, Theme.ACCENT, 1f);
|
||||
renderer.pushScissor(new Bounds(x, ORIGIN + CLIP_Y, CLIP_W, CLIP_H));
|
||||
renderer.text().draw("Scissor ok", x, ORIGIN + CLIP_Y, BODY, Theme.TEXT);
|
||||
renderer.popScissor();
|
||||
Bounds box = new Bounds(ORIGIN + BOX_X, ORIGIN + CLIP_Y - 4f, BOX_W, BOX_H);
|
||||
renderer.rect(box, Theme.RADIUS_SMALL, Theme.ACCENT);
|
||||
renderer.glow(box, Theme.RADIUS_SMALL, 0f, GLOW_SIZE, GLOW_INTENSITY, Theme.ACCENT);
|
||||
}
|
||||
}
|
||||
29
src/main/java/dev/loki/satura/render/RenderHooks.java
Normal file
29
src/main/java/dev/loki/satura/render/RenderHooks.java
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
package dev.loki.satura.render;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Очереди отрисовки "поверх GUI": постоянные оверлеи и разовые задачи на кадр.
|
||||
* Вызывается из GameRenderer после того, как ванильный GUI уже нарисован.
|
||||
*/
|
||||
public final class RenderHooks {
|
||||
|
||||
private final List<Runnable> overlays = new ArrayList<>();
|
||||
private final List<Runnable> once = new ArrayList<>();
|
||||
|
||||
public void addOverlay(Runnable overlay) {
|
||||
overlays.add(overlay);
|
||||
}
|
||||
|
||||
public void defer(Runnable task) {
|
||||
once.add(task);
|
||||
}
|
||||
|
||||
void dispatch() {
|
||||
overlays.forEach(Runnable::run);
|
||||
List<Runnable> tasks = List.copyOf(once);
|
||||
once.clear();
|
||||
tasks.forEach(Runnable::run);
|
||||
}
|
||||
}
|
||||
137
src/main/java/dev/loki/satura/render/Renderer.java
Normal file
137
src/main/java/dev/loki/satura/render/Renderer.java
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
package dev.loki.satura.render;
|
||||
|
||||
import dev.loki.satura.render.blur.BlurPipeline;
|
||||
import dev.loki.satura.render.color.Colors;
|
||||
import dev.loki.satura.render.geom.Bounds;
|
||||
import dev.loki.satura.render.geom.Radii;
|
||||
import dev.loki.satura.render.gpu.Viewport;
|
||||
import dev.loki.satura.render.msdf.MsdfFonts;
|
||||
import dev.loki.satura.render.pipeline.GlowOutlinePipeline;
|
||||
import dev.loki.satura.render.pipeline.GlowOutlinePipeline.Glow;
|
||||
import dev.loki.satura.render.pipeline.GlowPipeline;
|
||||
import dev.loki.satura.render.pipeline.OutlinePipeline;
|
||||
import dev.loki.satura.render.pipeline.RectPipeline;
|
||||
import dev.loki.satura.render.pipeline.image.TexturePipeline;
|
||||
import dev.loki.satura.render.scissor.Scissor;
|
||||
import dev.loki.satura.render.text.TextRenderer;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.util.Identifier;
|
||||
|
||||
/**
|
||||
* Фасад рендера: скруглённые прямоугольники, обводка, свечение, тень, блюр, текстуры, MSDF-текст, scissor.
|
||||
* Координаты — GUI (как у DrawContext), цвета — ARGB int. Рисует прямо в главный фреймбуфер,
|
||||
* поэтому для отображения поверх ванильного GUI вызывать из {@link #onFrame} / {@link #defer}.
|
||||
*/
|
||||
@SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
|
||||
public final class Renderer {
|
||||
|
||||
private static final float SHADOW_SIZE = 12f;
|
||||
private static final float SHADOW_INTENSITY = 0.55f;
|
||||
private static final float SHADOW_SOFTNESS = 2.2f;
|
||||
private static final float MIN_SOFTNESS = 0.1f;
|
||||
|
||||
private static Renderer shared;
|
||||
|
||||
private final Viewport viewport = new Viewport();
|
||||
private final Scissor scissor = new Scissor(viewport);
|
||||
private final RenderHooks hooks = new RenderHooks();
|
||||
private final TextRenderer text = new TextRenderer(new MsdfFonts(), viewport, scissor);
|
||||
private final RectPipeline rect = new RectPipeline(scissor);
|
||||
private final OutlinePipeline outline = new OutlinePipeline(scissor);
|
||||
private final GlowPipeline glowCircle = new GlowPipeline(scissor);
|
||||
private final GlowOutlinePipeline glowOutline = new GlowOutlinePipeline(scissor);
|
||||
private final TexturePipeline texture = new TexturePipeline(scissor);
|
||||
private final BlurPipeline blur = new BlurPipeline(scissor, viewport);
|
||||
|
||||
private Renderer() {
|
||||
}
|
||||
|
||||
public static synchronized Renderer shared() {
|
||||
if (shared == null) {
|
||||
shared = new Renderer();
|
||||
}
|
||||
return shared;
|
||||
}
|
||||
|
||||
public TextRenderer text() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public Viewport viewport() {
|
||||
return viewport;
|
||||
}
|
||||
|
||||
public void rect(Bounds b, float radius, int... colors) {
|
||||
rect(b, Radii.all(radius), colors);
|
||||
}
|
||||
|
||||
public void rect(Bounds b, Radii radii, int... colors) {
|
||||
rect.draw(viewport.projection(), b, radii, colors);
|
||||
}
|
||||
|
||||
public void outline(Bounds b, float radius, float thickness, int... colors) {
|
||||
outline.draw(viewport.projection(), b, Radii.all(radius), thickness, colors);
|
||||
}
|
||||
|
||||
public void outline(Bounds b, Radii radii, float thickness, int... colors) {
|
||||
outline.draw(viewport.projection(), b, radii, thickness, colors);
|
||||
}
|
||||
|
||||
public void glow(Bounds b, float radius, float thickness, float size, float intensity, int color) {
|
||||
glowOutline.draw(viewport.projection(), b, radius, thickness,
|
||||
new Glow(size, Math.clamp(intensity, 0f, 1f), 0f), color);
|
||||
}
|
||||
|
||||
public void glowCircle(float x, float y, float size, int color) {
|
||||
glowCircle.draw(viewport.projection(), x, y, size, color);
|
||||
}
|
||||
|
||||
public void shadow(Bounds b, float radius, int color) {
|
||||
shadow(b, radius, SHADOW_SIZE, SHADOW_INTENSITY, SHADOW_SOFTNESS, color);
|
||||
}
|
||||
|
||||
public void shadow(Bounds b, float radius, float size, float intensity, float softness, int color) {
|
||||
if (size <= 0f || intensity <= 0f) {
|
||||
return;
|
||||
}
|
||||
glowOutline.draw(viewport.projection(), b, radius, 0f,
|
||||
new Glow(size, Math.clamp(intensity, 0f, 1f), Math.max(MIN_SOFTNESS, softness)), color);
|
||||
}
|
||||
|
||||
public void blur(Bounds b, float radius, float strength) {
|
||||
blur.draw(viewport.projection(), b, radius, strength);
|
||||
}
|
||||
|
||||
public void texture(Identifier id, float x, float y, float size, float radius, int tint) {
|
||||
texture.draw(viewport.projection(), x, y, size,
|
||||
MinecraftClient.getInstance().getTextureManager().getTexture(id).getGlTextureView(), tint, radius);
|
||||
}
|
||||
|
||||
public void texture(Identifier id, float x, float y, float size) {
|
||||
texture(id, x, y, size, 0f, Colors.WHITE);
|
||||
}
|
||||
|
||||
public void pushScissor(Bounds area) {
|
||||
scissor.push(area);
|
||||
}
|
||||
|
||||
public void popScissor() {
|
||||
scissor.pop();
|
||||
}
|
||||
|
||||
/** Постоянный оверлей: вызывается каждый кадр поверх всего GUI. */
|
||||
public void onFrame(Runnable overlay) {
|
||||
hooks.addOverlay(overlay);
|
||||
}
|
||||
|
||||
/** Разовая задача: выполнится в конце текущего кадра поверх GUI (для вызова из HUD/Screen). */
|
||||
public void defer(Runnable task) {
|
||||
hooks.defer(task);
|
||||
}
|
||||
|
||||
public void endFrame() {
|
||||
if (MinecraftClient.getInstance().getOverlay() == null) {
|
||||
hooks.dispatch();
|
||||
}
|
||||
}
|
||||
}
|
||||
28
src/main/java/dev/loki/satura/render/Theme.java
Normal file
28
src/main/java/dev/loki/satura/render/Theme.java
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
package dev.loki.satura.render;
|
||||
|
||||
/** Палитра и размеры оформления (минимализм): цвета ARGB, радиусы в GUI-единицах. */
|
||||
@SuppressWarnings("PMD.DataClass")
|
||||
public final class Theme {
|
||||
|
||||
public static final int BACKGROUND = 0xFF121212;
|
||||
public static final int BACKGROUND_ALT = 0xFF1A1A1A;
|
||||
public static final int PANEL = 0xFF202020;
|
||||
public static final int BORDER = 0xFF2E2E2E;
|
||||
|
||||
public static final int ACCENT = 0xFFE8792B;
|
||||
public static final int ACCENT_HOVER = 0xFFF08A3F;
|
||||
public static final int ACCENT_PRESSED = 0xFFC9621C;
|
||||
|
||||
public static final int TEXT = 0xFFE6E6E6;
|
||||
public static final int TEXT_MUTED = 0xFF8A8A8A;
|
||||
|
||||
public static final float RADIUS_SMALL = 4f;
|
||||
public static final float RADIUS = 6f;
|
||||
public static final float BORDER_WIDTH = 1f;
|
||||
|
||||
public static final boolean GRADIENTS = false;
|
||||
public static final boolean GLOW = false;
|
||||
|
||||
private Theme() {
|
||||
}
|
||||
}
|
||||
36
src/main/java/dev/loki/satura/render/blur/BlurData.java
Normal file
36
src/main/java/dev/loki/satura/render/blur/BlurData.java
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package dev.loki.satura.render.blur;
|
||||
|
||||
import dev.loki.satura.render.geom.Bounds;
|
||||
import dev.loki.satura.render.gpu.UniformData;
|
||||
import java.nio.ByteBuffer;
|
||||
import org.joml.Matrix4f;
|
||||
|
||||
/** Запись юниформа BlurData для промежуточных проходов и финального вывода. */
|
||||
final class BlurData {
|
||||
|
||||
static final int SIZE = 256;
|
||||
private static final float UNIT = 1f;
|
||||
|
||||
private final UniformData data = new UniformData(SIZE);
|
||||
|
||||
ByteBuffer pass(int screenW, int screenH, int texW, int texH, float offset, float strength) {
|
||||
return data.begin()
|
||||
.vec4(0f, 0f, 0f, 0f).vec4(0f, 0f, 0f, 0f).vec4(0f, 0f, 0f, 0f).vec4(0f, 0f, 0f, 0f)
|
||||
.vec4(0f, 0f, screenW, screenH)
|
||||
.vec4(screenW, screenH, UNIT, offset)
|
||||
.vec4(texW, texH, UNIT, strength)
|
||||
.vec4(0f, 0f, 0f, 0f)
|
||||
.vec4(0f, 0f, 0f, 0f)
|
||||
.end();
|
||||
}
|
||||
|
||||
ByteBuffer last(Matrix4f projection, Bounds b, int guiW, int guiH, float radius) {
|
||||
return data.begin().matrix(projection)
|
||||
.vec4(b.x(), b.y(), b.width(), b.height())
|
||||
.vec4(guiW, guiH, 0f, 0f)
|
||||
.vec4(guiW, guiH, UNIT, 0f)
|
||||
.vec4(radius, radius, radius, radius)
|
||||
.vec4(0f, 0f, 0f, 0f)
|
||||
.end();
|
||||
}
|
||||
}
|
||||
162
src/main/java/dev/loki/satura/render/blur/BlurPipeline.java
Normal file
162
src/main/java/dev/loki/satura/render/blur/BlurPipeline.java
Normal file
|
|
@ -0,0 +1,162 @@
|
|||
package dev.loki.satura.render.blur;
|
||||
|
||||
import com.mojang.blaze3d.buffers.GpuBuffer;
|
||||
import com.mojang.blaze3d.buffers.GpuBufferSlice;
|
||||
import com.mojang.blaze3d.pipeline.BlendFunction;
|
||||
import com.mojang.blaze3d.pipeline.RenderPipeline;
|
||||
import com.mojang.blaze3d.platform.DepthTestFunction;
|
||||
import com.mojang.blaze3d.systems.CommandEncoder;
|
||||
import com.mojang.blaze3d.systems.RenderPass;
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.textures.FilterMode;
|
||||
import com.mojang.blaze3d.textures.GpuTextureView;
|
||||
import com.mojang.blaze3d.vertex.VertexFormat;
|
||||
import dev.loki.satura.render.geom.Bounds;
|
||||
import dev.loki.satura.render.gpu.ScissorSource;
|
||||
import dev.loki.satura.render.gpu.ShaderPass;
|
||||
import dev.loki.satura.render.gpu.Viewport;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.OptionalDouble;
|
||||
import java.util.OptionalInt;
|
||||
import net.minecraft.client.MinecraftClient;
|
||||
import net.minecraft.client.gl.Framebuffer;
|
||||
import net.minecraft.client.gl.GpuSampler;
|
||||
import net.minecraft.client.gl.RenderPipelines;
|
||||
import net.minecraft.client.gl.UniformType;
|
||||
import net.minecraft.client.render.VertexFormats;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.joml.Matrix4f;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector4f;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Блюр фона под прямоугольником: копия кадра, даунсэмпл, N проходов размытия, вывод со скруглением.
|
||||
* Размытие пересчитывается раз в кадр, остальные вызовы переиспользуют результат.
|
||||
*/
|
||||
@SuppressWarnings({"PMD.AvoidCatchingGenericException", "PMD.InvalidLogMessageFormat", "PMD.CloseResource"})
|
||||
public final class BlurPipeline {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger("satura/render");
|
||||
private static final int BASE_ITERATIONS = 5;
|
||||
private static final int MIN_ITERATIONS = 2;
|
||||
private static final float[] OFFSETS = {1f, 2f, 2f, 3f};
|
||||
private static final long FRAME_NANOS = 16_666_666L;
|
||||
private static final float STRENGTH_EPSILON = 0.01f;
|
||||
private static final String UNIFORM = "BlurData";
|
||||
|
||||
private final ScissorSource scissor;
|
||||
private final Viewport viewport;
|
||||
private final BlurTargets targets = new BlurTargets();
|
||||
private final BlurData data = new BlurData();
|
||||
private RenderPipeline passPipeline;
|
||||
private RenderPipeline finalPipeline;
|
||||
private GpuBuffer uniform;
|
||||
private GpuBuffer dummyVertex;
|
||||
private long lastFrame = -1;
|
||||
private float lastStrength;
|
||||
private int resultIndex;
|
||||
private boolean failed;
|
||||
|
||||
public BlurPipeline(ScissorSource scissor, Viewport viewport) {
|
||||
this.scissor = scissor;
|
||||
this.viewport = viewport;
|
||||
}
|
||||
|
||||
public void draw(Matrix4f projection, Bounds bounds, float radius, float strength) {
|
||||
Framebuffer fb = MinecraftClient.getInstance().getFramebuffer();
|
||||
if (failed || fb == null || fb.getColorAttachment() == null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
init();
|
||||
render(fb, projection, bounds, radius, strength);
|
||||
} catch (RuntimeException e) {
|
||||
failed = true;
|
||||
LOG.error("[satura/render] blur disabled", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void render(Framebuffer fb, Matrix4f projection, Bounds bounds, float radius, float strength) {
|
||||
if (targets.ensure(fb.textureWidth, fb.textureHeight)) {
|
||||
lastFrame = -1;
|
||||
}
|
||||
long frame = System.nanoTime() / FRAME_NANOS;
|
||||
GpuSampler sampler = RenderSystem.getSamplerCache().get(FilterMode.LINEAR);
|
||||
GpuBufferSlice transforms = RenderSystem.getDynamicUniforms().write(RenderSystem.getModelViewMatrix(),
|
||||
new Vector4f(1f, 1f, 1f, 1f), new Vector3f(), new Matrix4f());
|
||||
CommandEncoder encoder = RenderSystem.getDevice().createCommandEncoder();
|
||||
if (frame != lastFrame || Math.abs(strength - lastStrength) > STRENGTH_EPSILON) {
|
||||
blurFrame(encoder, fb, sampler, transforms, strength);
|
||||
lastFrame = frame;
|
||||
lastStrength = strength;
|
||||
}
|
||||
ByteBuffer last = data.last(projection, bounds, viewport.width(), viewport.height(), radius);
|
||||
run(encoder, "final", fb.getColorAttachmentView(), finalPipeline, targets.view(resultIndex),
|
||||
sampler, transforms, last, scissor);
|
||||
}
|
||||
|
||||
private void blurFrame(CommandEncoder encoder, Framebuffer fb, GpuSampler sampler,
|
||||
GpuBufferSlice transforms, float strength) {
|
||||
int fbW = fb.textureWidth;
|
||||
int fbH = fb.textureHeight;
|
||||
int w = fbW / BlurTargets.DOWNSAMPLE;
|
||||
int h = fbH / BlurTargets.DOWNSAMPLE;
|
||||
encoder.copyTextureToTexture(fb.getColorAttachment(), targets.copyTexture(), 0, 0, 0, 0, 0, fbW, fbH);
|
||||
run(encoder, "down", targets.view(0), passPipeline, targets.copyView(), sampler, transforms,
|
||||
data.pass(fbW, fbH, w, h, 1f, strength), ScissorSource.NONE);
|
||||
int iterations = Math.max(MIN_ITERATIONS, (int) (BASE_ITERATIONS * strength));
|
||||
for (int i = 0; i < iterations; i++) {
|
||||
float offset = OFFSETS[Math.min(i, OFFSETS.length - 1)];
|
||||
run(encoder, "pass" + i, targets.view((i + 1) % 2), passPipeline, targets.view(i % 2),
|
||||
sampler, transforms, data.pass(w, h, w, h, offset, 1f), ScissorSource.NONE);
|
||||
}
|
||||
resultIndex = iterations % 2;
|
||||
}
|
||||
|
||||
private void run(CommandEncoder encoder, String label, GpuTextureView target, RenderPipeline pipeline,
|
||||
GpuTextureView source, GpuSampler sampler, GpuBufferSlice transforms, ByteBuffer params,
|
||||
ScissorSource clip) {
|
||||
encoder.writeToBuffer(uniform.slice(), params);
|
||||
try (RenderPass pass = encoder.createRenderPass(() -> "satura:blur_" + label, target,
|
||||
OptionalInt.empty(), null, OptionalDouble.empty())) {
|
||||
clip.applyTo(pass);
|
||||
pass.setPipeline(pipeline);
|
||||
pass.setVertexBuffer(0, dummyVertex);
|
||||
pass.bindTexture("Sampler0", source, sampler);
|
||||
RenderSystem.bindDefaultUniforms(pass);
|
||||
pass.setUniform("DynamicTransforms", transforms);
|
||||
pass.setUniform(UNIFORM, uniform);
|
||||
pass.draw(0, 6);
|
||||
}
|
||||
}
|
||||
|
||||
private void init() {
|
||||
if (uniform != null) {
|
||||
return;
|
||||
}
|
||||
passPipeline = register("blur_pass");
|
||||
finalPipeline = register("blur_final");
|
||||
uniform = RenderSystem.getDevice().createBuffer(() -> "satura:blur_uniform",
|
||||
GpuBuffer.USAGE_UNIFORM | GpuBuffer.USAGE_COPY_DST, BlurData.SIZE);
|
||||
ByteBuffer dummy = ByteBuffer.allocateDirect(Integer.BYTES);
|
||||
dummyVertex = RenderSystem.getDevice().createBuffer(() -> "satura:blur_dummy", GpuBuffer.USAGE_VERTEX,
|
||||
dummy);
|
||||
}
|
||||
|
||||
private static RenderPipeline register(String name) {
|
||||
return RenderPipelines.register(RenderPipeline.builder(RenderPipelines.TRANSFORMS_AND_PROJECTION_SNIPPET)
|
||||
.withLocation(Identifier.of(ShaderPass.NAMESPACE, name))
|
||||
.withVertexShader(Identifier.of(ShaderPass.NAMESPACE, name + "_vertex"))
|
||||
.withFragmentShader(Identifier.of(ShaderPass.NAMESPACE, name + "_fragment"))
|
||||
.withVertexFormat(VertexFormats.EMPTY, VertexFormat.DrawMode.TRIANGLES)
|
||||
.withUniform(UNIFORM, UniformType.UNIFORM_BUFFER)
|
||||
.withSampler("Sampler0")
|
||||
.withBlend(BlendFunction.TRANSLUCENT)
|
||||
.withDepthTestFunction(DepthTestFunction.NO_DEPTH_TEST)
|
||||
.withDepthWrite(false)
|
||||
.withCull(false)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
79
src/main/java/dev/loki/satura/render/blur/BlurTargets.java
Normal file
79
src/main/java/dev/loki/satura/render/blur/BlurTargets.java
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
package dev.loki.satura.render.blur;
|
||||
|
||||
import com.mojang.blaze3d.systems.RenderSystem;
|
||||
import com.mojang.blaze3d.textures.GpuTexture;
|
||||
import com.mojang.blaze3d.textures.GpuTextureView;
|
||||
import com.mojang.blaze3d.textures.TextureFormat;
|
||||
|
||||
/** Текстуры блюра: копия кадра полного размера и два буфера половинного размера (ping-pong). */
|
||||
@SuppressWarnings({"PMD.AvoidFieldNameMatchingMethodName", "PMD.NullAssignment"})
|
||||
final class BlurTargets {
|
||||
|
||||
static final int DOWNSAMPLE = 2;
|
||||
private static final int PING_PONG = 2;
|
||||
|
||||
private GpuTexture copy;
|
||||
private GpuTextureView copyView;
|
||||
private final GpuTexture[] pong = new GpuTexture[PING_PONG];
|
||||
private final GpuTextureView[] pongViews = new GpuTextureView[PING_PONG];
|
||||
private int width;
|
||||
private int height;
|
||||
|
||||
/** Пересоздаёт текстуры при смене размера; true — если пересоздали. */
|
||||
boolean ensure(int fbWidth, int fbHeight) {
|
||||
if (copy != null && fbWidth == width && fbHeight == height) {
|
||||
return false;
|
||||
}
|
||||
close();
|
||||
copy = create("copy", fbWidth, fbHeight, GpuTexture.USAGE_COPY_DST | GpuTexture.USAGE_TEXTURE_BINDING);
|
||||
copyView = RenderSystem.getDevice().createTextureView(copy);
|
||||
for (int i = 0; i < PING_PONG; i++) {
|
||||
pong[i] = create("pp" + i, fbWidth / DOWNSAMPLE, fbHeight / DOWNSAMPLE,
|
||||
GpuTexture.USAGE_COPY_DST | GpuTexture.USAGE_TEXTURE_BINDING
|
||||
| GpuTexture.USAGE_RENDER_ATTACHMENT);
|
||||
pongViews[i] = RenderSystem.getDevice().createTextureView(pong[i]);
|
||||
}
|
||||
width = fbWidth;
|
||||
height = fbHeight;
|
||||
return true;
|
||||
}
|
||||
|
||||
GpuTexture copyTexture() {
|
||||
return copy;
|
||||
}
|
||||
|
||||
GpuTextureView copyView() {
|
||||
return copyView;
|
||||
}
|
||||
|
||||
GpuTextureView view(int index) {
|
||||
return pongViews[index];
|
||||
}
|
||||
|
||||
void close() {
|
||||
closeAll(copyView, copy);
|
||||
copyView = null;
|
||||
copy = null;
|
||||
for (int i = 0; i < PING_PONG; i++) {
|
||||
closeAll(pongViews[i], pong[i]);
|
||||
pongViews[i] = null;
|
||||
pong[i] = null;
|
||||
}
|
||||
width = 0;
|
||||
height = 0;
|
||||
}
|
||||
|
||||
private static GpuTexture create(String label, int w, int h, int usage) {
|
||||
return RenderSystem.getDevice().createTexture(() -> "satura:blur_" + label, usage,
|
||||
TextureFormat.RGBA8, w, h, 1, 1);
|
||||
}
|
||||
|
||||
private static void closeAll(GpuTextureView view, GpuTexture texture) {
|
||||
if (view != null) {
|
||||
view.close();
|
||||
}
|
||||
if (texture != null) {
|
||||
texture.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue