Compare commits

..
15 Commits
Author SHA1 Message Date
Glease 2574f61ef4 more documentation efforts 2022-09-15 18:16:28 +08:00
Glease 339d6da99c push members from StructureEvent down to concrete class 2022-09-15 18:07:03 +08:00
Glease c16d2aa5e1 drop MP 2022-09-15 18:02:53 +08:00
Glease 6f8ac8e33e Spotless 2022-09-15 16:24:57 +08:00
Glease 5d5a731af3 make API compatibility statement 2022-09-15 16:21:20 +08:00
Glease d9d237ed3a more documentation efforts... 2022-09-15 16:15:12 +08:00
Glease 3b9a77b9fd Add instrumenting API 2022-09-15 16:05:15 +08:00
Glease 5d0f63e2e9 remove unused imports 2022-09-14 13:11:45 +08:00
Glease f43aaecfb6 expose what IStructureDefinition this constructable is using 2022-09-14 13:08:34 +08:00
Glease 857150e18d expose what blocks this element might place 2022-09-13 21:22:34 +08:00
Glease ce8b0b011a Improve documentation on IItemSource 2022-09-13 16:46:01 +08:00
Glease f5b2f41ad6 fix default implementation for IItemSource having inverted output 2022-09-13 16:37:06 +08:00
Glease 9700499da2 fix tests 2022-09-12 19:16:22 +08:00
github-actions[bot]GleaseGitHub GTNH Actions
003825915d Spotless apply for branch feature/survival-autoplace-argument-object for #13 (#14)
Co-authored-by: Glease <[email protected]>
Co-authored-by: GitHub GTNH Actions <>
2022-09-12 19:03:31 +08:00
Glease b2b39c3fa5 Use argument object for survival autoplace 2022-09-12 18:57:46 +08:00
86 changed files with 2578 additions and 2853 deletions

No files matched your search

-2
View File
@@ -1,2 +0,0 @@
# Ignore spotlessApply reformat
464e44de8541a46833f50c3bd363d50e1677a685
+20 -42
View File
@@ -1,44 +1,22 @@
* text eol=lf # Auto detect text files and perform LF normalization
* text=auto
*.[jJ][aA][rR] binary # Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
*.[pP][nN][gG] binary # Standard to msysgit
*.[jJ][pP][gG] binary *.doc diff=astextplain
*.[jJ][pP][eE][gG] binary *.DOC diff=astextplain
*.[gG][iI][fF] binary *.docx diff=astextplain
*.[tT][iI][fF] binary *.DOCX diff=astextplain
*.[tT][iI][fF][fF] binary *.dot diff=astextplain
*.[iI][cC][oO] binary *.DOT diff=astextplain
*.[sS][vV][gG] text *.pdf diff=astextplain
*.[eE][pP][sS] binary *.PDF diff=astextplain
*.[xX][cC][fF] binary *.rtf diff=astextplain
*.RTF diff=astextplain
*.[kK][aA][rR] binary
*.[mM]4[aA] binary
*.[mM][iI][dD] binary
*.[mM][iI][dD][iI] binary
*.[mM][pP]3 binary
*.[oO][gG][gG] binary
*.[rR][aA] binary
*.7[zZ] binary
*.[gG][zZ] binary
*.[tT][aA][rR] binary
*.[tT][gG][zZ] binary
*.[zZ][iI][pP] binary
*.[tT][cC][nN] binary
*.[sS][oO] binary
*.[dD][lL][lL] binary
*.[dD][yY][lL][iI][bB] binary
*.[pP][sS][dD] binary
*.[tT][tT][fF] binary
*.[oO][tT][fF] binary
*.[pP][aA][tT][cC][hH] -text
*.[bB][aA][tT] text eol=crlf
*.[cC][mM][dD] text eol=crlf
*.[pP][sS]1 text eol=crlf
*[aA][uU][tT][oO][gG][eE][nN][eE][rR][aA][tT][eE][dD]* binary
+2 -5
View File
@@ -8,8 +8,6 @@ javadoc {
include "com/gtnewhorizon/structurelib/StructureLibAPI.java" include "com/gtnewhorizon/structurelib/StructureLibAPI.java"
include "com/gtnewhorizon/structurelib/StructureEvent.java" include "com/gtnewhorizon/structurelib/StructureEvent.java"
classpath += sourceSets.patchedMc.output
options { options {
overview "src/main/javadoc/overview.html" overview "src/main/javadoc/overview.html"
links 'https://docs.oracle.com/javase/8/docs/api/' links 'https://docs.oracle.com/javase/8/docs/api/'
@@ -17,9 +15,8 @@ javadoc {
} }
} }
tasks.register('javadocJar', Jar) { task javadocJar(type: Jar, dependsOn: javadoc) {
dependsOn javadoc classifier = 'javadoc'
archiveClassifier = 'javadoc'
from javadoc.destinationDir from javadoc.destinationDir
} }
+549 -869
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -1,9 +1,9 @@
// Add your dependencies here // Add your dependencies here
dependencies { dependencies {
api("com.github.GTNewHorizons:GTNHLib:0.0.10:dev") compile("com.github.GTNewHorizons:GTNHLib:0.0.1:dev")
runtimeOnly("com.github.GTNewHorizons:NotEnoughItems:2.3.25-GTNH:dev") runtime("com.github.GTNewHorizons:NotEnoughItems:2.2.20-GTNH:dev")
testImplementation(platform('org.junit:junit-bom:5.9.2')) testImplementation(platform('org.junit:junit-bom:5.8.2'))
testImplementation('org.junit.jupiter:junit-jupiter') testImplementation('org.junit.jupiter:junit-jupiter')
} }
Binary file not shown.
+1 -2
View File
@@ -1,6 +1,5 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.6-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.1-bin.zip
networkTimeout=10000
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists zipStorePath=wrapper/dists
Vendored Executable → Regular
+108 -164
View File
@@ -1,7 +1,7 @@
#!/bin/sh #!/usr/bin/env sh
# #
# Copyright © 2015-2021 the original authors. # Copyright 2015 the original author or authors.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. # you may not use this file except in compliance with the License.
@@ -17,113 +17,78 @@
# #
############################################################################## ##############################################################################
# ##
# Gradle start up script for POSIX generated by Gradle. ## Gradle start up script for UN*X
# ##
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/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 # Attempt to set APP_HOME
# Resolve links: $0 may be a link # Resolve links: $0 may be a link
app_path=$0 PRG="$0"
# Need this for relative symlinks.
# Need this for daisy-chained symlinks. while [ -h "$PRG" ] ; do
while ls=`ls -ld "$PRG"`
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path link=`expr "$ls" : '.*-> \(.*\)$'`
[ -h "$app_path" ] if expr "$link" : '/.*' > /dev/null; then
do PRG="$link"
ls=$( ls -ld "$app_path" ) else
link=${ls#*' -> '} PRG=`dirname "$PRG"`"/$link"
case $link in #( fi
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
# This is normally unused APP_NAME="Gradle"
# shellcheck disable=SC2034 APP_BASE_NAME=`basename "$0"`
APP_BASE_NAME=${0##*/}
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. # 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"' DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD="maximum"
warn () { warn () {
echo "$*" echo "$*"
} >&2 }
die () { die () {
echo echo
echo "$*" echo "$*"
echo echo
exit 1 exit 1
} >&2 }
# OS specific support (must be 'true' or 'false'). # OS specific support (must be 'true' or 'false').
cygwin=false cygwin=false
msys=false msys=false
darwin=false darwin=false
nonstop=false nonstop=false
case "$( uname )" in #( case "`uname`" in
CYGWIN* ) cygwin=true ;; #( CYGWIN* )
Darwin* ) darwin=true ;; #( cygwin=true
MSYS* | MINGW* ) msys=true ;; #( ;;
NONSTOP* ) nonstop=true ;; Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM. # Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables # IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java JAVACMD="$JAVA_HOME/jre/sh/java"
else else
JAVACMD=$JAVA_HOME/bin/java JAVACMD="$JAVA_HOME/bin/java"
fi fi
if [ ! -x "$JAVACMD" ] ; then if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
@@ -132,7 +97,7 @@ Please set the JAVA_HOME variable in your environment to match the
location of your Java installation." location of your Java installation."
fi fi
else else
JAVACMD=java JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. which java >/dev/null 2>&1 || 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 Please set the JAVA_HOME variable in your environment to match the
@@ -140,105 +105,84 @@ location of your Java installation."
fi fi
# Increase the maximum file descriptors if we can. # Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
case $MAX_FD in #( MAX_FD_LIMIT=`ulimit -H -n`
max*) if [ $? -eq 0 ] ; then
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
# shellcheck disable=SC3045 MAX_FD="$MAX_FD_LIMIT"
MAX_FD=$( ulimit -H -n ) || fi
warn "Could not query maximum file descriptor limit" ulimit -n $MAX_FD
esac if [ $? -ne 0 ] ; then
case $MAX_FD in #( warn "Could not set maximum file descriptor limit: $MAX_FD"
'' | soft) :;; #( fi
*) else
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
# shellcheck disable=SC3045 fi
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi fi
# Collect all arguments for the java command, stacking in reverse order: # For Darwin, add options to specify how the application appears in the dock
# * args from the command line if $darwin; then
# * the main class name GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
# * -classpath fi
# * -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 # For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
JAVACMD=$( cygpath --unix "$JAVACMD" ) # We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
# Now convert the arguments - kludge to limit ourselves to /bin/sh SEP=""
for arg do for dir in $ROOTDIRSRAW ; do
if ROOTDIRS="$ROOTDIRS$SEP$dir"
case $arg in #( SEP="|"
-*) 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 done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi fi
# Collect all arguments for the java command; # Escape application args
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of save () {
# shell script including quotes and variable substitutions, so put them in for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
# double quotes to make sure that they get re-expanded; and echo " "
# * put everything else in single quotes, so that it's not re-expanded. }
APP_ARGS=$(save "$@")
set -- \ # Collect all arguments for the java command, following the shell quoting and substitution rules
"-Dorg.gradle.appname=$APP_BASE_NAME" \ eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available. # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if ! command -v xargs >/dev/null 2>&1 if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
then cd "$(dirname "$0")"
die "xargs is not available"
fi 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" "$@" exec "$JAVACMD" "$@"
Vendored
+23 -15
View File
@@ -14,7 +14,7 @@
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@if "%DEBUG%"=="" @echo off @if "%DEBUG%" == "" @echo off
@rem ########################################################################## @rem ##########################################################################
@rem @rem
@rem Gradle startup script for Windows @rem Gradle startup script for Windows
@@ -25,14 +25,10 @@
if "%OS%"=="Windows_NT" setlocal if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0 set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=. if "%DIRNAME%" == "" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0 set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME% 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. @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" set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@@ -41,7 +37,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1 %JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute if "%ERRORLEVEL%" == "0" goto init
echo. echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
@@ -55,7 +51,7 @@ goto fail
set JAVA_HOME=%JAVA_HOME:"=% set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute if exist "%JAVA_EXE%" goto init
echo. echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
@@ -65,26 +61,38 @@ echo location of your Java installation.
goto fail goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute :execute
@rem Setup the command line @rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle @rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end :end
@rem End local scope for the variables with windows NT shell @rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd if "%ERRORLEVEL%"=="0" goto mainEnd
:fail :fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code! rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL% if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
if %EXIT_CODE% equ 0 set EXIT_CODE=1 exit /b 1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd :mainEnd
if "%OS%"=="Windows_NT" endlocal if "%OS%"=="Windows_NT" endlocal
+3 -21
View File
@@ -1,28 +1,10 @@
pluginManagement {
repositories {
maven {
// RetroFuturaGradle
name "GTNH Maven"
url "http://jenkins.usrv.eu:8081/nexus/content/groups/public/"
allowInsecureProtocol = true
mavenContent {
includeGroup("com.gtnewhorizons.retrofuturagradle")
}
}
gradlePluginPortal()
mavenCentral()
mavenLocal()
}
}
plugins { plugins {
id 'com.diffplug.blowdryerSetup' version '1.6.0' id 'com.diffplug.blowdryerSetup' version '1.6.0'
id 'org.gradle.toolchains.foojay-resolver-convention' version '0.4.0' // Provides java toolchains
} }
apply plugin: 'com.diffplug.blowdryerSetup'
blowdryerSetup { blowdryerSetup {
repoSubfolder 'gtnhShared' github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.1.4')
github('GTNewHorizons/ExampleMod1.7.10', 'tag', '0.2.0')
//devLocal '.' // Use this when testing config updates locally //devLocal '.' // Use this when testing config updates locally
} }
@@ -2,8 +2,14 @@ package com.gtnewhorizon.structurelib;
import static com.gtnewhorizon.structurelib.StructureLib.RANDOM; import static com.gtnewhorizon.structurelib.StructureLib.RANDOM;
import com.gtnewhorizon.structurelib.entity.fx.WeightlessParticleFX;
import com.gtnewhorizon.structurelib.net.SetChannelDataMessage;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
import java.util.*; import java.util.*;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiNewChat; import net.minecraft.client.gui.GuiNewChat;
@@ -25,22 +31,12 @@ import net.minecraft.world.World;
import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.event.world.WorldEvent;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import com.gtnewhorizon.structurelib.entity.fx.WeightlessParticleFX;
import com.gtnewhorizon.structurelib.net.SetChannelDataMessage;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent.ClientTickEvent;
import cpw.mods.fml.common.gameevent.TickEvent.Phase;
public class ClientProxy extends CommonProxy { public class ClientProxy extends CommonProxy {
private static final short[] RGBA_NO_TINT = { 255, 255, 255, 255 }; private static final short[] RGBA_NO_TINT = {255, 255, 255, 255};
private static final short[] RGBA_RED_TINT = { 255, 128, 128, 0 }; private static final short[] RGBA_RED_TINT = {255, 128, 128, 0};
private static final Map<HintParticleInfo, HintGroup> allHints = new HashMap<>(); private static final Map<HintParticleInfo, HintGroup> allHints = new HashMap<>();
/** /**
* All batches of hints. * All batches of hints.
@@ -59,10 +55,11 @@ public class ClientProxy extends CommonProxy {
*/ */
private static final List<HintParticleInfo> allHintsForRender = new ArrayList<>(10000); private static final List<HintParticleInfo> allHintsForRender = new ArrayList<>(10000);
/** /**
* If the diff to current player position is too great sort the allHints. Initial value is very far off below y=0 * If the diff to current player position is too great sort the allHints.
* but not huge enough to make a NaN. * Initial value is very far off below y=0 but not huge enough to make a NaN.
* <p> * <p>
* We are using this supposedly immutable object as a mutable object here. So be aware. * We are using this supposedly immutable object as a mutable object here.
* So be aware.
*/ */
private static final Vec3 lastPlayerPos = Vec3.createVectorHelper(0, -1e30, 0); private static final Vec3 lastPlayerPos = Vec3.createVectorHelper(0, -1e30, 0);
/** /**
@@ -161,7 +158,11 @@ public class ClientProxy extends CommonProxy {
} }
@Override @Override
public void addThrottledChat(Object throttleKey, EntityPlayer player, IChatComponent text, short intervalRequired, public void addThrottledChat(
Object throttleKey,
EntityPlayer player,
IChatComponent text,
short intervalRequired,
boolean forceUpdateLastSend) { boolean forceUpdateLastSend) {
if (player instanceof EntityPlayerMP) if (player instanceof EntityPlayerMP)
super.addThrottledChat(throttleKey, player, text, intervalRequired, forceUpdateLastSend); super.addThrottledChat(throttleKey, player, text, intervalRequired, forceUpdateLastSend);
@@ -249,7 +250,6 @@ public class ClientProxy extends CommonProxy {
} }
private static class HintGroup { private static class HintGroup {
private final List<HintParticleInfo> hints = new LinkedList<>(); private final List<HintParticleInfo> hints = new LinkedList<>();
private int creationTime = -1; private int creationTime = -1;
@@ -267,7 +267,6 @@ public class ClientProxy extends CommonProxy {
} }
private static class HintParticleInfo { private static class HintParticleInfo {
private final World w; private final World w;
// these are the block coordinate for e.g. w.getBlock() // these are the block coordinate for e.g. w.getBlock()
private final int x, y, z; private final int x, y, z;
@@ -419,7 +418,6 @@ public class ClientProxy extends CommonProxy {
} }
public static class FMLEventHandler { public static class FMLEventHandler {
private void resetPlayerLocation() { private void resetPlayerLocation() {
lastPlayerPos.xCoord = Minecraft.getMinecraft().thePlayer.posX; lastPlayerPos.xCoord = Minecraft.getMinecraft().thePlayer.posX;
lastPlayerPos.yCoord = Minecraft.getMinecraft().thePlayer.posY; lastPlayerPos.yCoord = Minecraft.getMinecraft().thePlayer.posY;
@@ -468,7 +466,6 @@ public class ClientProxy extends CommonProxy {
} }
public static class ForgeEventHandler { public static class ForgeEventHandler {
@SubscribeEvent @SubscribeEvent
public void onWorldLoad(WorldEvent.Load e) { public void onWorldLoad(WorldEvent.Load e) {
if (e.world.isRemote) { if (e.world.isRemote) {
@@ -1,9 +1,11 @@
package com.gtnewhorizon.structurelib; package com.gtnewhorizon.structurelib;
import com.gtnewhorizon.structurelib.net.ErrorHintParticleMessage;
import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
@@ -13,12 +15,7 @@ import net.minecraft.util.IChatComponent;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
import net.minecraft.world.World; import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.net.ErrorHintParticleMessage;
import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
public class CommonProxy { public class CommonProxy {
public void hintParticleTinted(World w, int x, int y, int z, IIcon[] icons, short[] RGBa) {} public void hintParticleTinted(World w, int x, int y, int z, IIcon[] icons, short[] RGBa) {}
public void hintParticleTinted(World w, int x, int y, int z, Block block, int meta, short[] RGBa) {} public void hintParticleTinted(World w, int x, int y, int z, Block block, int meta, short[] RGBa) {}
@@ -71,7 +68,11 @@ public class CommonProxy {
private final Map<EntityPlayerMP, Map<Object, Long>> throttleMap = new WeakHashMap<>(); private final Map<EntityPlayerMP, Map<Object, Long>> throttleMap = new WeakHashMap<>();
public void addThrottledChat(Object throttleKey, EntityPlayer player, IChatComponent text, short intervalRequired, public void addThrottledChat(
Object throttleKey,
EntityPlayer player,
IChatComponent text,
short intervalRequired,
boolean forceUpdateLastSend) { boolean forceUpdateLastSend) {
if (player instanceof EntityPlayerMP) { if (player instanceof EntityPlayerMP) {
Map<Object, Long> submap = throttleMap.computeIfAbsent((EntityPlayerMP) player, p -> new HashMap<>()); Map<Object, Long> submap = throttleMap.computeIfAbsent((EntityPlayerMP) player, p -> new HashMap<>());
@@ -79,8 +80,13 @@ public class CommonProxy {
} }
} }
protected static void addThrottledChat(Object throttleKey, EntityPlayer player, IChatComponent text, protected static void addThrottledChat(
short intervalRequired, boolean forceUpdateLastSend, Map<Object, Long> submap) { Object throttleKey,
EntityPlayer player,
IChatComponent text,
short intervalRequired,
boolean forceUpdateLastSend,
Map<Object, Long> submap) {
long now = System.currentTimeMillis(); long now = System.currentTimeMillis();
Long old; Long old;
if (forceUpdateLastSend) { if (forceUpdateLastSend) {
@@ -1,18 +1,15 @@
package com.gtnewhorizon.structurelib; package com.gtnewhorizon.structurelib;
import java.io.File;
import java.util.Map;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.client.event.ConfigChangedEvent;
import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import java.io.File;
import java.util.Map;
import net.minecraftforge.common.config.ConfigCategory;
import net.minecraftforge.common.config.Configuration;
import net.minecraftforge.common.config.Property;
public enum ConfigurationHandler { public enum ConfigurationHandler {
INSTANCE; INSTANCE;
private Configuration config; private Configuration config;
@@ -57,8 +54,8 @@ public enum ConfigurationHandler {
"client.hologram", "client.hologram",
true, true,
"An attempt will be made to remove an existing hologram if it collides with a new hologram."); "An attempt will be made to remove an existing hologram if it collides with a new hologram.");
hintLifespan = config hintLifespan =
.getInt("hintLifespan", "client.hologram", 400, 1, 20000, "Ticks before a hologram disappears."); config.getInt("hintLifespan", "client.hologram", 400, 1, 20000, "Ticks before a hologram disappears.");
hintTransparency = config.getInt( hintTransparency = config.getInt(
"hintTransparency", "hintTransparency",
"client.hologram", "client.hologram",
@@ -2,15 +2,11 @@ package com.gtnewhorizon.structurelib;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Configuration;
enum ConfigurationVersion { enum ConfigurationVersion {
V1 { V1 {
@Override @Override
protected void step(Configuration c) {} protected void step(Configuration c) {}
}; };
@@ -34,8 +30,10 @@ enum ConfigurationVersion {
} }
public static ConfigurationVersion identify(Configuration c) { public static ConfigurationVersion identify(Configuration c) {
return Arrays.stream(VALUES).filter(v -> Objects.equals(c.getLoadedConfigVersion(), v.getVersionMarker())) return Arrays.stream(VALUES)
.findFirst().orElse(V1); .filter(v -> Objects.equals(c.getLoadedConfigVersion(), v.getVersionMarker()))
.findFirst()
.orElse(V1);
} }
@Nullable @Nullable
@@ -1,14 +1,11 @@
package com.gtnewhorizon.structurelib; package com.gtnewhorizon.structurelib;
import cpw.mods.fml.client.IModGuiFactory;
import java.util.Set; import java.util.Set;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import cpw.mods.fml.client.IModGuiFactory;
public class GuiFactory implements IModGuiFactory { public class GuiFactory implements IModGuiFactory {
@Override @Override
public void initialize(Minecraft minecraftInstance) {} public void initialize(Minecraft minecraftInstance) {}
@@ -1,13 +1,11 @@
package com.gtnewhorizon.structurelib; package com.gtnewhorizon.structurelib;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.gui.GuiScreenConfigureChannels; import com.gtnewhorizon.structurelib.gui.GuiScreenConfigureChannels;
import cpw.mods.fml.common.network.IGuiHandler; import cpw.mods.fml.common.network.IGuiHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
public class GuiHandler implements IGuiHandler { public class GuiHandler implements IGuiHandler {
@Override @Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) { public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z) {
return null; return null;
@@ -1,17 +1,14 @@
package com.gtnewhorizon.structurelib; package com.gtnewhorizon.structurelib;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.ConfigElement;
import net.minecraftforge.common.config.Configuration; import net.minecraftforge.common.config.Configuration;
import cpw.mods.fml.client.config.GuiConfig;
import cpw.mods.fml.client.config.IConfigElement;
public class GuiModConfig extends GuiConfig { public class GuiModConfig extends GuiConfig {
public GuiModConfig(GuiScreen guiScreen) { public GuiModConfig(GuiScreen guiScreen) {
super( super(
guiScreen, guiScreen,
@@ -19,13 +16,16 @@ public class GuiModConfig extends GuiConfig {
StructureLibAPI.MOD_ID, StructureLibAPI.MOD_ID,
false, false,
false, false,
GuiConfig.getAbridgedConfigPath(ConfigurationHandler.INSTANCE.getConfig().toString())); GuiConfig.getAbridgedConfigPath(
ConfigurationHandler.INSTANCE.getConfig().toString()));
} }
@SuppressWarnings("rawtypes") @SuppressWarnings("rawtypes")
private static List<IConfigElement> getConfigElements() { private static List<IConfigElement> getConfigElements() {
final Configuration config = ConfigurationHandler.INSTANCE.getConfig(); final Configuration config = ConfigurationHandler.INSTANCE.getConfig();
return config.getCategoryNames().stream().filter(name -> name.indexOf('.') == -1) return config.getCategoryNames().stream()
.map(name -> new ConfigElement(config.getCategory(name))).collect(Collectors.toList()); .filter(name -> name.indexOf('.') == -1)
.map(name -> new ConfigElement(config.getCategory(name)))
.collect(Collectors.toList());
} }
} }
@@ -3,6 +3,5 @@ package com.gtnewhorizon.structurelib;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
public interface IStructureCompat { public interface IStructureCompat {
void markTextureUsed(IIcon o); void markTextureUsed(IIcon o);
} }
@@ -1,10 +1,9 @@
package com.gtnewhorizon.structurelib; package com.gtnewhorizon.structurelib;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
import com.gtnewhorizon.structurelib.structure.IStructureElement; import com.gtnewhorizon.structurelib.structure.IStructureElement;
import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.common.eventhandler.Event;
import net.minecraft.world.World;
import net.minecraftforge.common.MinecraftForge;
/** /**
* Subscribers are <b>required</b> to not keep reference to these events, nor to depend on values of these events after * Subscribers are <b>required</b> to not keep reference to these events, nor to depend on values of these events after
@@ -13,11 +12,10 @@ import cpw.mods.fml.common.eventhandler.Event;
* All of these events will be fired on the {@link net.minecraftforge.common.MinecraftForge#EVENT_BUS}, if they are * All of these events will be fired on the {@link net.minecraftforge.common.MinecraftForge#EVENT_BUS}, if they are
* enabled by {@link StructureLibAPI#enableInstrument(Object)}. * enabled by {@link StructureLibAPI#enableInstrument(Object)}.
* <p> * <p>
* All public stuff in this class and its enclosed classes are considered part of the public API. Backwards * All public stuff in this class and its enclosed classes are considered part of the public API.
* compatibility is maintained to the maximum extend possible. * Backwards compatibility is maintained to the maximum extend possible.
*/ */
public abstract class StructureEvent extends Event { public abstract class StructureEvent extends Event {
/* /*
* In case the event is passed to another thread for processing. * In case the event is passed to another thread for processing.
*/ */
@@ -37,21 +35,20 @@ public abstract class StructureEvent extends Event {
* Fired <b>just before</b> any structure element is visited. * Fired <b>just before</b> any structure element is visited.
*/ */
public static final class StructureElementVisitedEvent extends StructureEvent { public static final class StructureElementVisitedEvent extends StructureEvent {
private final World world; private final World world;
private final int x, y, z; private final int x, y, z;
private final int a, b, c; private final int a, b, c;
private final IStructureElement<?> element; private final IStructureElement<?> element;
/** /**
* Fire this event on {@link MinecraftForge#EVENT_BUS} by populating it with given arguments. Do nothing if * Fire this event on {@link MinecraftForge#EVENT_BUS} by populating it with given arguments.
* instrumenting isn't enabled for current thread. * Do nothing if instrumenting isn't enabled for current thread.
* <p> * <p>
* Any {@link Exception} thrown by event listeners will be logged and ignored. {@link Error} will be propagated * Any {@link Exception} thrown by event listeners will be logged and ignored. {@link Error} will be propagated
* as is. * as is.
*/ */
public static void fireEvent(World world, int x, int y, int z, int a, int b, int c, public static void fireEvent(
IStructureElement<?> element) { World world, int x, int y, int z, int a, int b, int c, IStructureElement<?> element) {
if (StructureLibAPI.isInstrumentEnabled()) { if (StructureLibAPI.isInstrumentEnabled()) {
try { try {
MinecraftForge.EVENT_BUS.post(new StructureElementVisitedEvent(world, x, y, z, a, b, c, element)); MinecraftForge.EVENT_BUS.post(new StructureElementVisitedEvent(world, x, y, z, a, b, c, element));
@@ -61,8 +58,8 @@ public abstract class StructureEvent extends Event {
} }
} }
StructureElementVisitedEvent(World world, int x, int y, int z, int a, int b, int c, StructureElementVisitedEvent(
IStructureElement<?> element) { World world, int x, int y, int z, int a, int b, int c, IStructureElement<?> element) {
this.world = world; this.world = world;
this.x = x; this.x = x;
this.y = y; this.y = y;
@@ -110,22 +107,14 @@ public abstract class StructureEvent extends Event {
@Override @Override
public String toString() { public String toString() {
return "StructureElementVisitedEvent{" + "a=" return "StructureElementVisitedEvent{" + "a="
+ a + a + ", b="
+ ", b=" + b + ", c="
+ b + c + ", element="
+ ", c=" + element + ", world="
+ c + getWorld() + ", x="
+ ", element=" + getX() + ", y="
+ element + getY() + ", z="
+ ", world=" + getZ() + '}';
+ getWorld()
+ ", x="
+ getX()
+ ", y="
+ getY()
+ ", z="
+ getZ()
+ '}';
} }
/** /**
@@ -1,15 +1,5 @@
package com.gtnewhorizon.structurelib; package com.gtnewhorizon.structurelib;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.gtnewhorizon.structurelib.block.BlockHint; import com.gtnewhorizon.structurelib.block.BlockHint;
import com.gtnewhorizon.structurelib.command.CommandConfigureChannels; import com.gtnewhorizon.structurelib.command.CommandConfigureChannels;
import com.gtnewhorizon.structurelib.item.ItemBlockHint; import com.gtnewhorizon.structurelib.item.ItemBlockHint;
@@ -20,7 +10,6 @@ import com.gtnewhorizon.structurelib.net.ErrorHintParticleMessage;
import com.gtnewhorizon.structurelib.net.SetChannelDataMessage; import com.gtnewhorizon.structurelib.net.SetChannelDataMessage;
import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage; import com.gtnewhorizon.structurelib.net.UpdateHintParticleMessage;
import com.gtnewhorizon.structurelib.util.XSTR; import com.gtnewhorizon.structurelib.util.XSTR;
import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.SidedProxy;
@@ -31,6 +20,14 @@ import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper;
import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.GameRegistry;
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.launchwrapper.Launch;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/** /**
* This class does not contain a stable API. Refrain from using this class. * This class does not contain a stable API. Refrain from using this class.
@@ -42,7 +39,6 @@ import cpw.mods.fml.relauncher.SideOnly;
acceptableRemoteVersions = "*", acceptableRemoteVersions = "*",
guiFactory = "com.gtnewhorizon.structurelib.GuiFactory") guiFactory = "com.gtnewhorizon.structurelib.GuiFactory")
public class StructureLib { public class StructureLib {
private static final String STRUCTURECOMPAT_MODID = "structurecompat"; private static final String STRUCTURECOMPAT_MODID = "structurecompat";
public static boolean DEBUG_MODE; public static boolean DEBUG_MODE;
public static boolean PANIC_MODE = Boolean.getBoolean("structurelib.panic"); public static boolean PANIC_MODE = Boolean.getBoolean("structurelib.panic");
@@ -57,10 +53,7 @@ public class StructureLib {
static { static {
net.registerMessage( net.registerMessage(
AlignmentMessage.ServerHandler.class, AlignmentMessage.ServerHandler.class, AlignmentMessage.AlignmentQuery.class, 0, Side.SERVER);
AlignmentMessage.AlignmentQuery.class,
0,
Side.SERVER);
net.registerMessage(AlignmentMessage.ClientHandler.class, AlignmentMessage.AlignmentData.class, 1, Side.CLIENT); net.registerMessage(AlignmentMessage.ClientHandler.class, AlignmentMessage.AlignmentData.class, 1, Side.CLIENT);
net.registerMessage(UpdateHintParticleMessage.Handler.class, UpdateHintParticleMessage.class, 2, Side.CLIENT); net.registerMessage(UpdateHintParticleMessage.Handler.class, UpdateHintParticleMessage.class, 2, Side.CLIENT);
net.registerMessage(SetChannelDataMessage.Handler.class, SetChannelDataMessage.class, 3, Side.SERVER); net.registerMessage(SetChannelDataMessage.Handler.class, SetChannelDataMessage.class, 3, Side.SERVER);
@@ -87,7 +80,6 @@ public class StructureLib {
static Item itemFrontRotationTool; static Item itemFrontRotationTool;
static Item itemConstructableTrigger; static Item itemConstructableTrigger;
public static final CreativeTabs creativeTab = new CreativeTabs("structurelib") { public static final CreativeTabs creativeTab = new CreativeTabs("structurelib") {
@Override @Override
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public Item getTabIconItem() { public Item getTabIconItem() {
@@ -101,8 +93,7 @@ public class StructureLib {
GameRegistry.registerBlock(blockHint = new BlockHint(), ItemBlockHint.class, "blockhint"); GameRegistry.registerBlock(blockHint = new BlockHint(), ItemBlockHint.class, "blockhint");
itemBlockHint = ItemBlock.getItemFromBlock(StructureLibAPI.getBlockHint()); itemBlockHint = ItemBlock.getItemFromBlock(StructureLibAPI.getBlockHint());
GameRegistry.registerItem( GameRegistry.registerItem(
itemFrontRotationTool = new ItemFrontRotationTool(), itemFrontRotationTool = new ItemFrontRotationTool(), itemFrontRotationTool.getUnlocalizedName());
itemFrontRotationTool.getUnlocalizedName());
GameRegistry.registerItem( GameRegistry.registerItem(
itemConstructableTrigger = new ItemConstructableTrigger(), itemConstructableTrigger = new ItemConstructableTrigger(),
itemConstructableTrigger.getUnlocalizedName()); itemConstructableTrigger.getUnlocalizedName());
@@ -110,7 +101,10 @@ public class StructureLib {
NetworkRegistry.INSTANCE.registerGuiHandler(instance(), new GuiHandler()); NetworkRegistry.INSTANCE.registerGuiHandler(instance(), new GuiHandler());
if (Loader.isModLoaded(STRUCTURECOMPAT_MODID)) { if (Loader.isModLoaded(STRUCTURECOMPAT_MODID)) {
COMPAT = Loader.instance().getIndexedModList().get(STRUCTURECOMPAT_MODID).getMod(); COMPAT = Loader.instance()
.getIndexedModList()
.get(STRUCTURECOMPAT_MODID)
.getMod();
} }
} }
@@ -2,6 +2,13 @@ package com.gtnewhorizon.structurelib;
import static com.gtnewhorizon.structurelib.StructureLib.proxy; import static com.gtnewhorizon.structurelib.StructureLib.proxy;
import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.IAlignmentProvider;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.net.AlignmentMessage;
import com.gtnewhorizon.structurelib.structure.AutoPlaceEnvironment;
import com.gtnewhorizon.structurelib.structure.IStructureDefinition;
import cpw.mods.fml.common.network.NetworkRegistry;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
@@ -11,20 +18,10 @@ import net.minecraft.util.IChatComponent;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
import net.minecraft.world.World; import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.IAlignmentProvider;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.net.AlignmentMessage;
import com.gtnewhorizon.structurelib.structure.AutoPlaceEnvironment;
import com.gtnewhorizon.structurelib.structure.IStructureDefinition;
import cpw.mods.fml.common.network.NetworkRegistry;
/** /**
* A stable interface into the structure lib's internals. Backwards compatibility is maintained to the maximum extend * A stable interface into the structure lib's internals. Backwards compatibility is maintained to the maximum extend possible.
* possible.
*/ */
public class StructureLibAPI { public class StructureLibAPI {
public static final String MOD_ID = "structurelib"; public static final String MOD_ID = "structurelib";
public static final int HINT_BLOCK_META_GENERIC_0 = 0; public static final int HINT_BLOCK_META_GENERIC_0 = 0;
public static final int HINT_BLOCK_META_GENERIC_1 = 1; public static final int HINT_BLOCK_META_GENERIC_1 = 1;
@@ -50,13 +47,12 @@ public class StructureLibAPI {
* appropriate. Otherwise, these events will not be sent at all, regardless of whether a listener for these events * appropriate. Otherwise, these events will not be sent at all, regardless of whether a listener for these events
* are registered. * are registered.
* <p> * <p>
* Identifiers are required to be value-comparable, i.e. overrides {@link Object#equals(Object)}. Suggested * Identifiers are required to be value-comparable, i.e. overrides {@link Object#equals(Object)}.
* identifier includes * Suggested identifier includes
* <ul> * <ul>
* <li>Mod Instance or {@link cpw.mods.fml.common.ModContainer}</li> * <li>Mod Instance or {@link cpw.mods.fml.common.ModContainer}</li>
* <li>{@link com.gtnewhorizon.structurelib.alignment.constructable.IConstructable} and its friends, if you are * <li>{@link com.gtnewhorizon.structurelib.alignment.constructable.IConstructable} and its friends, if you are triggering structure check via this interface.</li>
* triggering structure check via this interface.</li> * <li>{@link net.minecraft.util.ResourceLocation}</li>
* <li>{@link net.minecraft.util.ResourceLocation}</li>
* </ul> * </ul>
* <p> * <p>
* It's an API abuse for normal {@link IStructureDefinition} users to depend on this feature. They have full control * It's an API abuse for normal {@link IStructureDefinition} users to depend on this feature. They have full control
@@ -86,7 +82,6 @@ public class StructureLibAPI {
/** /**
* Check if instrumenting is enabled. * Check if instrumenting is enabled.
*
* @return true if enabled, false otherwise * @return true if enabled, false otherwise
*/ */
public static boolean isInstrumentEnabled() { public static boolean isInstrumentEnabled() {
@@ -94,22 +89,18 @@ public class StructureLibAPI {
} }
/** /**
* Start a batch of hinting. All hints particles generated during one batch will be considered to belong to one * Start a batch of hinting. All hints particles generated during one batch will be considered to belong to one hologram.
* hologram.
* <p> * <p>
* You don't need to call this unless your constructable tool didn't call * You don't need to call this unless your constructable tool didn't call {@link com.gtnewhorizon.structurelib.alignment.constructable.ConstructableUtility#handle(ItemStack, EntityPlayer, World, int, int, int, int)}
* {@link com.gtnewhorizon.structurelib.alignment.constructable.ConstructableUtility#handle(ItemStack, EntityPlayer, World, int, int, int, int)}
*/ */
public static void startHinting(World w) { public static void startHinting(World w) {
proxy.startHinting(w); proxy.startHinting(w);
} }
/** /**
* End current batch of hinting. All hints particles generated during one batch will be considered to belong to one * End current batch of hinting. All hints particles generated during one batch will be considered to belong to one hologram.
* hologram.
* <p> * <p>
* You don't need to call this unless your constructable tool didn't call * You don't need to call this unless your constructable tool didn't call {@link com.gtnewhorizon.structurelib.alignment.constructable.ConstructableUtility#handle(ItemStack, EntityPlayer, World, int, int, int, int)}
* {@link com.gtnewhorizon.structurelib.alignment.constructable.ConstructableUtility#handle(ItemStack, EntityPlayer, World, int, int, int, int)}
*/ */
public static void endHinting(World w) { public static void endHinting(World w) {
proxy.endHinting(w); proxy.endHinting(w);
@@ -123,8 +114,7 @@ public class StructureLibAPI {
* @param y y coord * @param y y coord
* @param z z coord * @param z z coord
* @param icons 6 texture. in forge direction order. * @param icons 6 texture. in forge direction order.
* @param RGBa a 4 short array. tint in rgba form. currently alpha channel is ignored, but we might change this * @param RGBa a 4 short array. tint in rgba form. currently alpha channel is ignored, but we might change this later on.
* later on.
*/ */
public static void hintParticleTinted(World w, int x, int y, int z, IIcon[] icons, short[] RGBa) { public static void hintParticleTinted(World w, int x, int y, int z, IIcon[] icons, short[] RGBa) {
proxy.hintParticleTinted(w, x, y, z, icons, RGBa); proxy.hintParticleTinted(w, x, y, z, icons, RGBa);
@@ -139,8 +129,7 @@ public class StructureLibAPI {
* @param z z coord * @param z z coord
* @param block block to take texture from * @param block block to take texture from
* @param meta the meta of block to take texture from * @param meta the meta of block to take texture from
* @param RGBa a 4 short array. tint in rgba form. currently alpha channel is ignored, but we might change this * @param RGBa a 4 short array. tint in rgba form. currently alpha channel is ignored, but we might change this later on.
* later on.
*/ */
public static void hintParticleTinted(World w, int x, int y, int z, Block block, int meta, short[] RGBa) { public static void hintParticleTinted(World w, int x, int y, int z, Block block, int meta, short[] RGBa) {
proxy.hintParticleTinted(w, x, y, z, block, meta, RGBa); proxy.hintParticleTinted(w, x, y, z, block, meta, RGBa);
@@ -176,8 +165,9 @@ public class StructureLibAPI {
/** /**
* Update the tint of given hint particle. Do nothing if particle not found. * Update the tint of given hint particle. Do nothing if particle not found.
* <p> * <p>
* Can be called on either client side or server side. Server side will schedule a network message to update it for * Can be called on either client side or server side.
* this player only. Will do nothing if no hint particle is found at given location. * Server side will schedule a network message to update it for this player only.
* Will do nothing if no hint particle is found at given location.
* *
* @return false if nothing updated. true if updated or update instruction sent. * @return false if nothing updated. true if updated or update instruction sent.
*/ */
@@ -195,13 +185,11 @@ public class StructureLibAPI {
} }
/** /**
* Query the ExtendedFacing of this tile entity from client side. Can be sent only on client side. The * Query the ExtendedFacing of this tile entity from client side. Can be sent only on client side.
* ExtendedFacing will later be set onto given tile entity via * The ExtendedFacing will later be set onto given tile entity via {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)}
* {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} upon arrival of * upon arrival of server reply.
* server reply.
* <p> * <p>
* The server side will query the {@link ExtendedFacing} of this provider using * The server side will query the {@link ExtendedFacing} of this provider using {@link IAlignment#getExtendedFacing()}
* {@link IAlignment#getExtendedFacing()}
* *
* @throws IllegalArgumentException if is not tile entity or provided a null alignment * @throws IllegalArgumentException if is not tile entity or provided a null alignment
*/ */
@@ -212,8 +200,7 @@ public class StructureLibAPI {
/** /**
* Send the ExtendedFacing of this Tile Entity to all players. Can be called on server side only. * Send the ExtendedFacing of this Tile Entity to all players. Can be called on server side only.
* <p> * <p>
* The receiving tile entity will receive the {@link ExtendedFacing} via its * The receiving tile entity will receive the {@link ExtendedFacing} via its {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* *
* @throws IllegalArgumentException if is not tile entity or provided a null alignment * @throws IllegalArgumentException if is not tile entity or provided a null alignment
*/ */
@@ -224,8 +211,7 @@ public class StructureLibAPI {
/** /**
* Send the ExtendedFacing of this Tile Entity to given player. Can be called on server side only. * Send the ExtendedFacing of this Tile Entity to given player. Can be called on server side only.
* <p> * <p>
* The receiving tile entity will receive the {@link ExtendedFacing} via its * The receiving tile entity will receive the {@link ExtendedFacing} via its {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* *
* @throws IllegalArgumentException if is not tile entity or provided a null alignment * @throws IllegalArgumentException if is not tile entity or provided a null alignment
*/ */
@@ -234,11 +220,9 @@ public class StructureLibAPI {
} }
/** /**
* Send the ExtendedFacing of this Tile Entity to all players around target point. Can be called on server side * Send the ExtendedFacing of this Tile Entity to all players around target point. Can be called on server side only.
* only.
* <p> * <p>
* The receiving tile entity will receive the {@link ExtendedFacing} via its * The receiving tile entity will receive the {@link ExtendedFacing} via its {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* *
* @throws IllegalArgumentException if is not tile entity or provided a null alignment * @throws IllegalArgumentException if is not tile entity or provided a null alignment
*/ */
@@ -249,8 +233,7 @@ public class StructureLibAPI {
/** /**
* Send the ExtendedFacing of this Tile Entity to all players in that dimension. Can be called on server side only. * Send the ExtendedFacing of this Tile Entity to all players in that dimension. Can be called on server side only.
* <p> * <p>
* The receiving tile entity will receive the {@link ExtendedFacing} via its * The receiving tile entity will receive the {@link ExtendedFacing} via its {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* {@link com.gtnewhorizon.structurelib.alignment.IAlignment#setExtendedFacing(ExtendedFacing)} method.
* *
* @throws IllegalArgumentException if is not tile entity or provided a null alignment * @throws IllegalArgumentException if is not tile entity or provided a null alignment
*/ */
@@ -272,13 +255,6 @@ public class StructureLibAPI {
return StructureLib.itemBlockHint; return StructureLib.itemBlockHint;
} }
/**
* Get the hologram item.
*/
public static Item getDefaultHologramItem() {
return StructureLib.itemConstructableTrigger;
}
/** /**
* Check if structure debug mode is on. * Check if structure debug mode is on.
* *
@@ -293,11 +269,10 @@ public class StructureLibAPI {
} }
/** /**
* Determines if given block can be replaced without much effort. The exact predicate clauses is not stable and will * Determines if given block can be replaced without much effort. The exact predicate clauses is not stable and
* be changed, but the general idea will always stay the same. * will be changed, but the general idea will always stay the same.
* <p> * <p>
* Use this in your * Use this in your {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
* {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
*/ */
@Deprecated @Deprecated
public static boolean isBlockTriviallyReplaceable(World w, int x, int y, int z, EntityPlayerMP actor) { public static boolean isBlockTriviallyReplaceable(World w, int x, int y, int z, EntityPlayerMP actor) {
@@ -305,11 +280,10 @@ public class StructureLibAPI {
} }
/** /**
* Determines if given block can be replaced without much effort. The exact predicate clauses is not stable and will * Determines if given block can be replaced without much effort. The exact predicate clauses is not stable and
* be changed, but the general idea will always stay the same. * will be changed, but the general idea will always stay the same.
* <p> * <p>
* Use this in your * Use this in your {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
* {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
*/ */
public static boolean isBlockTriviallyReplaceable(World w, int x, int y, int z, EntityPlayer actor) { public static boolean isBlockTriviallyReplaceable(World w, int x, int y, int z, EntityPlayer actor) {
// TODO extend this function a bit // TODO extend this function a bit
@@ -320,33 +294,35 @@ public class StructureLibAPI {
/** /**
* Send chat to player, but throttled. * Send chat to player, but throttled.
* *
* @param throttleKey throttle key. Must properly implement {@link Object#hashCode()} and * @param throttleKey throttle key. Must properly implement {@link Object#hashCode()} and {@link Object#equals(Object)}
* {@link Object#equals(Object)} to handle value equality. * to handle value equality.
* @param player player to send chat to * @param player player to send chat to
* @param text chat to send * @param text chat to send
* @param intervalRequired interval required before last recorded time to actually send the message. unit in * @param intervalRequired interval required before last recorded time to actually send the message. unit in millisecond.
* millisecond. we purposefully chose to not use a bigger data type to limit how long this * we purposefully chose to not use a bigger data type to limit how long this interval can be
* interval can be
*/ */
public static void addThrottledChat(Object throttleKey, EntityPlayer player, IChatComponent text, public static void addThrottledChat(
short intervalRequired) { Object throttleKey, EntityPlayer player, IChatComponent text, short intervalRequired) {
addThrottledChat(throttleKey, player, text, intervalRequired, false); addThrottledChat(throttleKey, player, text, intervalRequired, false);
} }
/** /**
* Send chat to player, but throttled. * Send chat to player, but throttled.
* *
* @param throttleKey throttle key. Must properly implement {@link Object#hashCode()} and * @param throttleKey throttle key. Must properly implement {@link Object#hashCode()} and {@link Object#equals(Object)}
* {@link Object#equals(Object)} to handle value equality. * to handle value equality.
* @param player player to send chat to * @param player player to send chat to
* @param text chat to send * @param text chat to send
* @param intervalRequired interval required before last recorded time to actually send the message. unit in * @param intervalRequired interval required before last recorded time to actually send the message. unit in millisecond.
* millisecond. we purposefully chose to not use a bigger data type to limit how long * we purposefully chose to not use a bigger data type to limit how long this interval can be
* this interval can be
* @param forceUpdateLastSend if true, always update the last send time, even if the message isn't actually sent. * @param forceUpdateLastSend if true, always update the last send time, even if the message isn't actually sent.
*/ */
public static void addThrottledChat(Object throttleKey, EntityPlayer player, IChatComponent text, public static void addThrottledChat(
short intervalRequired, boolean forceUpdateLastSend) { Object throttleKey,
EntityPlayer player,
IChatComponent text,
short intervalRequired,
boolean forceUpdateLastSend) {
proxy.addThrottledChat(throttleKey, player, text, intervalRequired, forceUpdateLastSend); proxy.addThrottledChat(throttleKey, player, text, intervalRequired, forceUpdateLastSend);
} }
} }
@@ -1,9 +1,8 @@
package com.gtnewhorizon.structurelib.alignment; package com.gtnewhorizon.structurelib.alignment;
import net.minecraftforge.common.util.ForgeDirection;
import com.gtnewhorizon.structurelib.alignment.enumerable.Flip; import com.gtnewhorizon.structurelib.alignment.enumerable.Flip;
import com.gtnewhorizon.structurelib.alignment.enumerable.Rotation; import com.gtnewhorizon.structurelib.alignment.enumerable.Rotation;
import net.minecraftforge.common.util.ForgeDirection;
class AlignmentLimits implements IAlignmentLimits { class AlignmentLimits implements IAlignmentLimits {
@@ -7,7 +7,6 @@ import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.FakePlayer;
public class AlignmentUtility { public class AlignmentUtility {
private AlignmentUtility() {} private AlignmentUtility() {}
public static boolean handle(EntityPlayer aPlayer, World aWorld, int aX, int aY, int aZ) { public static boolean handle(EntityPlayer aPlayer, World aWorld, int aX, int aY, int aZ) {
@@ -1,14 +1,12 @@
package com.gtnewhorizon.structurelib.alignment; package com.gtnewhorizon.structurelib.alignment;
import net.minecraftforge.common.util.ForgeDirection;
import com.gtnewhorizon.structurelib.alignment.enumerable.Direction; import com.gtnewhorizon.structurelib.alignment.enumerable.Direction;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing; import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.alignment.enumerable.Flip; import com.gtnewhorizon.structurelib.alignment.enumerable.Flip;
import com.gtnewhorizon.structurelib.alignment.enumerable.Rotation; import com.gtnewhorizon.structurelib.alignment.enumerable.Rotation;
import net.minecraftforge.common.util.ForgeDirection;
public interface IAlignment extends IAlignmentLimits, IAlignmentProvider { public interface IAlignment extends IAlignmentLimits, IAlignmentProvider {
int DIRECTIONS_COUNT = Direction.VALUES.length; int DIRECTIONS_COUNT = Direction.VALUES.length;
int ROTATIONS_COUNT = Rotation.VALUES.length; int ROTATIONS_COUNT = Rotation.VALUES.length;
int FLIPS_COUNT = Flip.VALUES.length; int FLIPS_COUNT = Flip.VALUES.length;
@@ -17,8 +15,8 @@ public interface IAlignment extends IAlignmentLimits, IAlignmentProvider {
ExtendedFacing getExtendedFacing(); ExtendedFacing getExtendedFacing();
/** /**
* Set the facing without additional checks. Tools altering facing should use * Set the facing without additional checks.
* {@link #toolSetExtendedFacing(ExtendedFacing)} instead. * Tools altering facing should use {@link #toolSetExtendedFacing(ExtendedFacing)} instead.
*/ */
void setExtendedFacing(ExtendedFacing alignment); void setExtendedFacing(ExtendedFacing alignment);
@@ -59,8 +57,9 @@ public interface IAlignment extends IAlignmentLimits, IAlignmentProvider {
default boolean toolSetDirection(ForgeDirection direction) { default boolean toolSetDirection(ForgeDirection direction) {
if (direction == null || direction == ForgeDirection.UNKNOWN) { if (direction == null || direction == ForgeDirection.UNKNOWN) {
for (int i = 0, j = getDirection().ordinal() + 1, valuesLength = Direction.VALUES.length; i for (int i = 0, j = getDirection().ordinal() + 1, valuesLength = Direction.VALUES.length;
< valuesLength; i++) { i < valuesLength;
i++) {
if (toolSetDirection(Direction.VALUES[(j + i) % valuesLength].getForgeDirection())) { if (toolSetDirection(Direction.VALUES[(j + i) % valuesLength].getForgeDirection())) {
return true; return true;
} }
@@ -98,11 +97,8 @@ public interface IAlignment extends IAlignmentLimits, IAlignmentProvider {
int rotations = Rotation.VALUES.length; int rotations = Rotation.VALUES.length;
for (int ii = 0, jj = getFlip().ordinal(); ii < flips; ii++) { for (int ii = 0, jj = getFlip().ordinal(); ii < flips; ii++) {
for (int i = 1, j = getRotation().ordinal(); i < rotations; i++) { for (int i = 1, j = getRotation().ordinal(); i < rotations; i++) {
if (checkedSetExtendedFacing( if (checkedSetExtendedFacing(ExtendedFacing.of(
ExtendedFacing.of( getDirection(), Rotation.VALUES[(j + i) % rotations], Flip.VALUES[(jj + ii) % flips]))) {
getDirection(),
Rotation.VALUES[(j + i) % rotations],
Flip.VALUES[(jj + ii) % flips]))) {
return true; return true;
} }
} }
@@ -144,8 +140,9 @@ public interface IAlignment extends IAlignmentLimits, IAlignmentProvider {
default boolean toolSetExtendedFacing(ExtendedFacing extendedFacing) { default boolean toolSetExtendedFacing(ExtendedFacing extendedFacing) {
if (extendedFacing == null) { if (extendedFacing == null) {
for (int i = 0, j = getExtendedFacing().ordinal() + 1, valuesLength = ExtendedFacing.VALUES.length; i for (int i = 0, j = getExtendedFacing().ordinal() + 1, valuesLength = ExtendedFacing.VALUES.length;
< valuesLength; i++) { i < valuesLength;
i++) {
if (checkedSetExtendedFacing(ExtendedFacing.VALUES[(j + i) % valuesLength])) { if (checkedSetExtendedFacing(ExtendedFacing.VALUES[(j + i) % valuesLength])) {
return true; return true;
} }
@@ -2,15 +2,13 @@ package com.gtnewhorizon.structurelib.alignment;
import static com.gtnewhorizon.structurelib.alignment.IAlignment.STATES_COUNT; import static com.gtnewhorizon.structurelib.alignment.IAlignment.STATES_COUNT;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import net.minecraftforge.common.util.ForgeDirection;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing; import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.alignment.enumerable.Flip; import com.gtnewhorizon.structurelib.alignment.enumerable.Flip;
import com.gtnewhorizon.structurelib.alignment.enumerable.Rotation; import com.gtnewhorizon.structurelib.alignment.enumerable.Rotation;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Function;
import net.minecraftforge.common.util.ForgeDirection;
public interface IAlignmentLimits { public interface IAlignmentLimits {
@@ -39,7 +37,6 @@ public interface IAlignmentLimits {
} }
class Builder { class Builder {
protected final boolean[] validStates = new boolean[STATES_COUNT]; protected final boolean[] validStates = new boolean[STATES_COUNT];
private Builder() {} private Builder() {}
@@ -57,13 +54,15 @@ public interface IAlignmentLimits {
} }
public Builder deny(ForgeDirection fd) { public Builder deny(ForgeDirection fd) {
ExtendedFacing.getAllWith(fd).stream().mapToInt(ExtendedFacing::getIndex) ExtendedFacing.getAllWith(fd).stream()
.mapToInt(ExtendedFacing::getIndex)
.forEach(v -> validStates[v] = false); .forEach(v -> validStates[v] = false);
return this; return this;
} }
public Builder allow(ForgeDirection fd) { public Builder allow(ForgeDirection fd) {
ExtendedFacing.getAllWith(fd).stream().mapToInt(ExtendedFacing::getIndex) ExtendedFacing.getAllWith(fd).stream()
.mapToInt(ExtendedFacing::getIndex)
.forEach(v -> validStates[v] = true); .forEach(v -> validStates[v] = true);
return this; return this;
} }
@@ -79,25 +78,29 @@ public interface IAlignmentLimits {
} }
public Builder deny(Rotation fd) { public Builder deny(Rotation fd) {
ExtendedFacing.getAllWith(fd).stream().mapToInt(ExtendedFacing::getIndex) ExtendedFacing.getAllWith(fd).stream()
.mapToInt(ExtendedFacing::getIndex)
.forEach(v -> validStates[v] = false); .forEach(v -> validStates[v] = false);
return this; return this;
} }
public Builder allow(Rotation fd) { public Builder allow(Rotation fd) {
ExtendedFacing.getAllWith(fd).stream().mapToInt(ExtendedFacing::getIndex) ExtendedFacing.getAllWith(fd).stream()
.mapToInt(ExtendedFacing::getIndex)
.forEach(v -> validStates[v] = true); .forEach(v -> validStates[v] = true);
return this; return this;
} }
public Builder deny(Flip fd) { public Builder deny(Flip fd) {
ExtendedFacing.getAllWith(fd).stream().mapToInt(ExtendedFacing::getIndex) ExtendedFacing.getAllWith(fd).stream()
.mapToInt(ExtendedFacing::getIndex)
.forEach(v -> validStates[v] = false); .forEach(v -> validStates[v] = false);
return this; return this;
} }
public Builder allow(Flip fd) { public Builder allow(Flip fd) {
ExtendedFacing.getAllWith(fd).stream().mapToInt(ExtendedFacing::getIndex) ExtendedFacing.getAllWith(fd).stream()
.mapToInt(ExtendedFacing::getIndex)
.forEach(v -> validStates[v] = true); .forEach(v -> validStates[v] = true);
return this; return this;
} }
@@ -3,7 +3,6 @@ package com.gtnewhorizon.structurelib.alignment;
import javax.annotation.Nullable; import javax.annotation.Nullable;
public interface IAlignmentProvider { public interface IAlignmentProvider {
@Nullable @Nullable
IAlignment getAlignment(); IAlignment getAlignment();
} }
@@ -2,14 +2,12 @@ package com.gtnewhorizon.structurelib.alignment;
import static java.lang.Math.abs; import static java.lang.Math.abs;
import com.gtnewhorizon.structurelib.alignment.enumerable.Direction;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
import net.minecraft.util.Vec3; import net.minecraft.util.Vec3;
import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.common.util.ForgeDirection;
import com.gtnewhorizon.structurelib.alignment.enumerable.Direction;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
public class IntegerAxisSwap { public class IntegerAxisSwap {
private final Vec3Impl forFirstAxis; private final Vec3Impl forFirstAxis;
private final Vec3Impl forSecondAxis; private final Vec3Impl forSecondAxis;
private final Vec3Impl forThirdAxis; private final Vec3Impl forThirdAxis;
@@ -22,49 +20,61 @@ public class IntegerAxisSwap {
|| abs(this.forFirstAxis.get1()) + abs(this.forSecondAxis.get1()) + abs(this.forThirdAxis.get1()) != 1 || abs(this.forFirstAxis.get1()) + abs(this.forSecondAxis.get1()) + abs(this.forThirdAxis.get1()) != 1
|| abs(this.forFirstAxis.get2()) + abs(this.forSecondAxis.get2()) + abs(this.forThirdAxis.get2()) || abs(this.forFirstAxis.get2()) + abs(this.forSecondAxis.get2()) + abs(this.forThirdAxis.get2())
!= 1) { != 1) {
throw new IllegalArgumentException( throw new IllegalArgumentException("Axis are overlapping/missing! " + forFirstAxis.name()
"Axis are overlapping/missing! " + forFirstAxis + " " + forSecondAxis.name()
.name() + " " + forSecondAxis.name() + " " + forThirdAxis.name()); + " " + forThirdAxis.name());
} }
} }
public Vec3Impl translate(Vec3Impl point) { public Vec3Impl translate(Vec3Impl point) {
return new Vec3Impl( return new Vec3Impl(
forFirstAxis.get0() * point.get0() + forFirstAxis.get1() * point.get1() forFirstAxis.get0() * point.get0()
+ forFirstAxis.get1() * point.get1()
+ forFirstAxis.get2() * point.get2(), + forFirstAxis.get2() * point.get2(),
forSecondAxis.get0() * point.get0() + forSecondAxis.get1() * point.get1() forSecondAxis.get0() * point.get0()
+ forSecondAxis.get1() * point.get1()
+ forSecondAxis.get2() * point.get2(), + forSecondAxis.get2() * point.get2(),
forThirdAxis.get0() * point.get0() + forThirdAxis.get1() * point.get1() forThirdAxis.get0() * point.get0()
+ forThirdAxis.get1() * point.get1()
+ forThirdAxis.get2() * point.get2()); + forThirdAxis.get2() * point.get2());
} }
public Vec3Impl inverseTranslate(Vec3Impl point) { public Vec3Impl inverseTranslate(Vec3Impl point) {
return new Vec3Impl( return new Vec3Impl(
forFirstAxis.get0() * point.get0() + forSecondAxis.get0() * point.get1() forFirstAxis.get0() * point.get0()
+ forSecondAxis.get0() * point.get1()
+ forThirdAxis.get0() * point.get2(), + forThirdAxis.get0() * point.get2(),
forFirstAxis.get1() * point.get0() + forSecondAxis.get1() * point.get1() forFirstAxis.get1() * point.get0()
+ forSecondAxis.get1() * point.get1()
+ forThirdAxis.get1() * point.get2(), + forThirdAxis.get1() * point.get2(),
forFirstAxis.get2() * point.get0() + forSecondAxis.get2() * point.get1() forFirstAxis.get2() * point.get0()
+ forSecondAxis.get2() * point.get1()
+ forThirdAxis.get2() * point.get2()); + forThirdAxis.get2() * point.get2());
} }
public Vec3 translate(Vec3 point) { public Vec3 translate(Vec3 point) {
return Vec3.createVectorHelper( return Vec3.createVectorHelper(
forFirstAxis.get0() * point.xCoord + forFirstAxis.get1() * point.yCoord forFirstAxis.get0() * point.xCoord
+ forFirstAxis.get1() * point.yCoord
+ forFirstAxis.get2() * point.zCoord, + forFirstAxis.get2() * point.zCoord,
forSecondAxis.get0() * point.xCoord + forSecondAxis.get1() * point.yCoord forSecondAxis.get0() * point.xCoord
+ forSecondAxis.get1() * point.yCoord
+ forSecondAxis.get2() * point.zCoord, + forSecondAxis.get2() * point.zCoord,
forThirdAxis.get0() * point.xCoord + forThirdAxis.get1() * point.yCoord forThirdAxis.get0() * point.xCoord
+ forThirdAxis.get1() * point.yCoord
+ forThirdAxis.get2() * point.zCoord); + forThirdAxis.get2() * point.zCoord);
} }
public Vec3 inverseTranslate(Vec3 point) { public Vec3 inverseTranslate(Vec3 point) {
return Vec3.createVectorHelper( return Vec3.createVectorHelper(
forFirstAxis.get0() * point.xCoord + forSecondAxis.get0() * point.yCoord forFirstAxis.get0() * point.xCoord
+ forSecondAxis.get0() * point.yCoord
+ forThirdAxis.get0() * point.zCoord, + forThirdAxis.get0() * point.zCoord,
forFirstAxis.get1() * point.xCoord + forSecondAxis.get1() * point.yCoord forFirstAxis.get1() * point.xCoord
+ forSecondAxis.get1() * point.yCoord
+ forThirdAxis.get1() * point.zCoord, + forThirdAxis.get1() * point.zCoord,
forFirstAxis.get2() * point.xCoord + forSecondAxis.get2() * point.yCoord forFirstAxis.get2() * point.xCoord
+ forSecondAxis.get2() * point.yCoord
+ forThirdAxis.get2() * point.zCoord); + forThirdAxis.get2() * point.zCoord);
} }
@@ -3,27 +3,23 @@ package com.gtnewhorizon.structurelib.alignment.constructable;
import static com.gtnewhorizon.structurelib.util.MiscUtils.getTagKeys; import static com.gtnewhorizon.structurelib.util.MiscUtils.getTagKeys;
import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND; import static net.minecraftforge.common.util.Constants.NBT.TAG_COMPOUND;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import java.util.Locale; import java.util.Locale;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.stream.Stream; import java.util.stream.Stream;
import net.minecraft.init.Items; import net.minecraft.init.Items;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.util.Constants.NBT; import net.minecraftforge.common.util.Constants.NBT;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.ImmutablePair;
import com.gtnewhorizon.structurelib.StructureLibAPI;
/** /**
* Provide accessor methods for channel data from trigger item. * Provide accessor methods for channel data from trigger item.
* *
* <a href="{@docRoot}/overview-summary.html#channels">Channels section on overview</a> * <a href="{@docRoot}/overview-summary.html#channels">Channels section on overview</a>
*/ */
public class ChannelDataAccessor { public class ChannelDataAccessor {
private static final String SECONDARY_HINT_TAG = "channels"; private static final String SECONDARY_HINT_TAG = "channels";
private ChannelDataAccessor() {} private ChannelDataAccessor() {}
@@ -31,25 +27,29 @@ public class ChannelDataAccessor {
/** /**
* Return a trigger item that * Return a trigger item that
* <ul> * <ul>
* <li>Still carry all the subchannel in some unspecified ways</li> * <li>Still carry all the subchannel in some unspecified ways</li>
* <li>Have its master channel data replaced with specified subchannel's data</li> * <li>Have its master channel data replaced with specified subchannel's data</li>
* </ul> * </ul>
* *
* If given subchannel does not exist, masterStack may or may not be returned to save performance. Code within * If given subchannel does not exist, masterStack may or may not be returned to save performance.
* StructureLib can depend on this behavior, you cannot. * Code within StructureLib can depend on this behavior, you cannot.
* *
* @param masterStack trigger item. can be the return value of another {@link #withChannel(ItemStack, String)} call * @param masterStack trigger item. can be the return value of another {@link #withChannel(ItemStack, String)} call
* @param channel subchannel to use. will use current master channel data instead if this channel does not exist * @param channel subchannel to use. will use current master channel data instead if this channel does not exist
* Note: all channel identifiers are supposed to be lower case and not empty. * Note: all channel identifiers are supposed to be lower case and not empty.
* @return a trigger item with new master channel * @return a trigger item with new master channel
*/ */
public static ItemStack withChannel(ItemStack masterStack, String channel) { public static ItemStack withChannel(ItemStack masterStack, String channel) {
if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException(); if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException();
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel)) if (StructureLibAPI.isDebugEnabled()
&& !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY"); throw new IllegalArgumentException("Channel name can be lower case ONLY");
if (!masterStack.hasTagCompound() || !masterStack.stackTagCompound.hasKey(SECONDARY_HINT_TAG, TAG_COMPOUND) if (!masterStack.hasTagCompound()
|| !masterStack.stackTagCompound.getCompoundTag(SECONDARY_HINT_TAG).hasKey(channel, NBT.TAG_INT)) || !masterStack.stackTagCompound.hasKey(SECONDARY_HINT_TAG, TAG_COMPOUND)
return masterStack; || !masterStack
.stackTagCompound
.getCompoundTag(SECONDARY_HINT_TAG)
.hasKey(channel, NBT.TAG_INT)) return masterStack;
ItemStack ret = new ItemStack( ItemStack ret = new ItemStack(
masterStack.getItem(), masterStack.getItem(),
masterStack.stackTagCompound.getCompoundTag(SECONDARY_HINT_TAG).getInteger(channel), masterStack.stackTagCompound.getCompoundTag(SECONDARY_HINT_TAG).getInteger(channel),
@@ -60,7 +60,6 @@ public class ChannelDataAccessor {
/** /**
* Check if given trigger item contains any subchannel * Check if given trigger item contains any subchannel
*
* @param masterStack trigger stack to check * @param masterStack trigger stack to check
* @return true if contains any subchannel * @return true if contains any subchannel
*/ */
@@ -71,47 +70,57 @@ public class ChannelDataAccessor {
/** /**
* Check if given trigger item contains specified subchannel * Check if given trigger item contains specified subchannel
*
* @param masterStack trigger stack to check * @param masterStack trigger stack to check
* @param channel channel identifier. Note: all channel identifiers are supposed to be lower case and not empty. * @param channel channel identifier.
* Note: all channel identifiers are supposed to be lower case and not empty.
* @return true if contains specified subchannel * @return true if contains specified subchannel
*/ */
public static boolean hasSubChannel(ItemStack masterStack, String channel) { public static boolean hasSubChannel(ItemStack masterStack, String channel) {
if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException(); if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException();
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel)) if (StructureLibAPI.isDebugEnabled()
&& !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY"); throw new IllegalArgumentException("Channel name can be lower case ONLY");
return !channel.isEmpty() && masterStack.hasTagCompound() return !channel.isEmpty()
&& masterStack.hasTagCompound()
&& masterStack.stackTagCompound.hasKey(SECONDARY_HINT_TAG, TAG_COMPOUND) && masterStack.stackTagCompound.hasKey(SECONDARY_HINT_TAG, TAG_COMPOUND)
&& masterStack.stackTagCompound.getCompoundTag(SECONDARY_HINT_TAG).hasKey(channel, NBT.TAG_INT); && masterStack
.stackTagCompound
.getCompoundTag(SECONDARY_HINT_TAG)
.hasKey(channel, NBT.TAG_INT);
} }
/** /**
* Get the subchannel data from given trigger item. Will use master channel instead if not present. * Get the subchannel data from given trigger item. Will use master channel instead if not present.
*
* @param masterStack trigger stack to query from * @param masterStack trigger stack to query from
* @param channel channel identifier. Note: all channel identifiers are supposed to be lower case and not empty. * @param channel channel identifier.
* Note: all channel identifiers are supposed to be lower case and not empty.
* @return channel data * @return channel data
*/ */
public static int getChannelData(ItemStack masterStack, String channel) { public static int getChannelData(ItemStack masterStack, String channel) {
if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException(); if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException();
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel)) if (StructureLibAPI.isDebugEnabled()
&& !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY"); throw new IllegalArgumentException("Channel name can be lower case ONLY");
if (!masterStack.hasTagCompound() || !masterStack.stackTagCompound.hasKey(SECONDARY_HINT_TAG, TAG_COMPOUND) if (!masterStack.hasTagCompound()
|| !masterStack.stackTagCompound.getCompoundTag(SECONDARY_HINT_TAG).hasKey(channel, NBT.TAG_INT)) || !masterStack.stackTagCompound.hasKey(SECONDARY_HINT_TAG, TAG_COMPOUND)
return masterStack.stackSize; || !masterStack
.stackTagCompound
.getCompoundTag(SECONDARY_HINT_TAG)
.hasKey(channel, NBT.TAG_INT)) return masterStack.stackSize;
return masterStack.stackTagCompound.getCompoundTag(SECONDARY_HINT_TAG).getInteger(channel); return masterStack.stackTagCompound.getCompoundTag(SECONDARY_HINT_TAG).getInteger(channel);
} }
/** /**
* Set the subchannel data on given trigger item * Set the subchannel data on given trigger item
*
* @param masterStack trigger stack to check * @param masterStack trigger stack to check
* @param channel channel identifier. Note: all channel identifiers are supposed to be lower case and not empty. * @param channel channel identifier.
* @param data subchannel data. should always be a positive value * Note: all channel identifiers are supposed to be lower case and not empty.
* @param data subchannel data. should always be a positive value
*/ */
public static void setChannelData(ItemStack masterStack, String channel, int data) { public static void setChannelData(ItemStack masterStack, String channel, int data) {
if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException(); if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException();
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel)) if (StructureLibAPI.isDebugEnabled()
&& !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY"); throw new IllegalArgumentException("Channel name can be lower case ONLY");
if (data <= 0) throw new IllegalArgumentException(); if (data <= 0) throw new IllegalArgumentException();
if (masterStack.stackTagCompound == null) masterStack.stackTagCompound = new NBTTagCompound(); if (masterStack.stackTagCompound == null) masterStack.stackTagCompound = new NBTTagCompound();
@@ -122,13 +131,14 @@ public class ChannelDataAccessor {
/** /**
* Clear the given subchannel from given trigger item, if it exists * Clear the given subchannel from given trigger item, if it exists
*
* @param masterStack trigger stack to unset * @param masterStack trigger stack to unset
* @param channel channel identifier. Note: all channel identifiers are supposed to be lower case and not empty. * @param channel channel identifier.
* Note: all channel identifiers are supposed to be lower case and not empty.
*/ */
public static void unsetChannelData(ItemStack masterStack, String channel) { public static void unsetChannelData(ItemStack masterStack, String channel) {
if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException(); if (StringUtils.isEmpty(channel) || masterStack == null) throw new IllegalArgumentException();
if (StructureLibAPI.isDebugEnabled() && !channel.toLowerCase(Locale.ROOT).equals(channel)) if (StructureLibAPI.isDebugEnabled()
&& !channel.toLowerCase(Locale.ROOT).equals(channel))
throw new IllegalArgumentException("Channel name can be lower case ONLY"); throw new IllegalArgumentException("Channel name can be lower case ONLY");
if (masterStack.stackTagCompound == null) masterStack.stackTagCompound = new NBTTagCompound(); if (masterStack.stackTagCompound == null) masterStack.stackTagCompound = new NBTTagCompound();
NBTTagCompound main = masterStack.stackTagCompound; NBTTagCompound main = masterStack.stackTagCompound;
@@ -141,7 +151,6 @@ public class ChannelDataAccessor {
/** /**
* Wipe all subchannel data on given trigger item * Wipe all subchannel data on given trigger item
*
* @param masterStack trigger stack to wipe * @param masterStack trigger stack to wipe
*/ */
public static void wipeChannelData(ItemStack masterStack) { public static void wipeChannelData(ItemStack masterStack) {
@@ -151,11 +160,10 @@ public class ChannelDataAccessor {
/** /**
* Iterate over all subchannel data on trigger stack. Does not include master channel!! * Iterate over all subchannel data on trigger stack. Does not include master channel!!
*
* @param masterStack trigger stack to check * @param masterStack trigger stack to check
* @return A java8 stream of pairs. Key is channel identifier and value is channel data. Pairs do not support * @return A java8 stream of pairs. Key is channel identifier and value is channel data. Pairs do not support
* mutation nor removal. Can still cause {@link java.util.ConcurrentModificationException} if underlying * mutation nor removal. Can still cause {@link java.util.ConcurrentModificationException} if underlying channel
* channel data is modified while stream is working. * data is modified while stream is working.
*/ */
public static Stream<Entry<String, Integer>> iterateChannelData(ItemStack masterStack) { public static Stream<Entry<String, Integer>> iterateChannelData(ItemStack masterStack) {
if (!hasSubChannel(masterStack)) return Stream.empty(); if (!hasSubChannel(masterStack)) return Stream.empty();
@@ -165,7 +173,6 @@ public class ChannelDataAccessor {
/** /**
* Get the number of subchannels present on given trigger item. Does not include master channel. * Get the number of subchannels present on given trigger item. Does not include master channel.
*
* @param masterStack trigger stack to query from * @param masterStack trigger stack to query from
* @return subchannel count * @return subchannel count
*/ */
@@ -1,7 +1,13 @@
package com.gtnewhorizon.structurelib.alignment.constructable; package com.gtnewhorizon.structurelib.alignment.constructable;
import com.gtnewhorizon.structurelib.ConfigurationHandler;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.IItemSource;
import com.gtnewhorizon.structurelib.structure.ISurvivalBuildEnvironment;
import java.util.WeakHashMap; import java.util.WeakHashMap;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
@@ -11,14 +17,6 @@ import net.minecraft.world.World;
import net.minecraftforge.common.util.FakePlayer; import net.minecraftforge.common.util.FakePlayer;
import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.common.util.ForgeDirection;
import com.gtnewhorizon.structurelib.ConfigurationHandler;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.IItemSource;
import com.gtnewhorizon.structurelib.structure.ISurvivalBuildEnvironment;
public class ConstructableUtility { public class ConstructableUtility {
private static final WeakHashMap<EntityPlayerMP, Long> lastUse = new WeakHashMap<>(); private static final WeakHashMap<EntityPlayerMP, Long> lastUse = new WeakHashMap<>();
@@ -26,16 +24,16 @@ public class ConstructableUtility {
private ConstructableUtility() {} private ConstructableUtility() {}
public static boolean handle(ItemStack aStack, EntityPlayer aPlayer, World aWorld, int aX, int aY, int aZ, public static boolean handle(
int aSide) { ItemStack aStack, EntityPlayer aPlayer, World aWorld, int aX, int aY, int aZ, int aSide) {
StructureLibAPI.startHinting(aWorld); StructureLibAPI.startHinting(aWorld);
boolean ret = handle0(aStack, aPlayer, aWorld, aX, aY, aZ, aSide); boolean ret = handle0(aStack, aPlayer, aWorld, aX, aY, aZ, aSide);
StructureLibAPI.endHinting(aWorld); StructureLibAPI.endHinting(aWorld);
return ret; return ret;
} }
private static boolean handle0(ItemStack aStack, EntityPlayer aPlayer, World aWorld, int aX, int aY, int aZ, private static boolean handle0(
int aSide) { ItemStack aStack, EntityPlayer aPlayer, World aWorld, int aX, int aY, int aZ, int aSide) {
TileEntity tTileEntity = aWorld.getTileEntity(aX, aY, aZ); TileEntity tTileEntity = aWorld.getTileEntity(aX, aY, aZ);
if (tTileEntity == null || aPlayer instanceof FakePlayer) { if (tTileEntity == null || aPlayer instanceof FakePlayer) {
return aPlayer instanceof EntityPlayerMP; return aPlayer instanceof EntityPlayerMP;
@@ -46,10 +44,9 @@ public class ConstructableUtility {
long timePast = System.currentTimeMillis() - getLastUseMilis(aPlayer); long timePast = System.currentTimeMillis() - getLastUseMilis(aPlayer);
if (timePast < ConfigurationHandler.INSTANCE.getAutoPlaceInterval()) { if (timePast < ConfigurationHandler.INSTANCE.getAutoPlaceInterval()) {
aPlayer.addChatComponentMessage( aPlayer.addChatComponentMessage(new ChatComponentTranslation(
new ChatComponentTranslation( "item.structurelib.constructableTrigger.too_fast",
"item.structurelib.constructableTrigger.too_fast", ConfigurationHandler.INSTANCE.getAutoPlaceInterval() - timePast));
ConfigurationHandler.INSTANCE.getAutoPlaceInterval() - timePast));
return true; return true;
} }
} else if (!StructureLib.isCurrentPlayer(aPlayer)) { } else if (!StructureLib.isCurrentPlayer(aPlayer)) {
@@ -62,7 +59,8 @@ public class ConstructableUtility {
else if (tTileEntity instanceof IConstructable) { else if (tTileEntity instanceof IConstructable) {
constructable = (IConstructable) tTileEntity; constructable = (IConstructable) tTileEntity;
} else if (IMultiblockInfoContainer.contains(tTileEntity.getClass())) { } else if (IMultiblockInfoContainer.contains(tTileEntity.getClass())) {
ExtendedFacing facing = tTileEntity instanceof IAlignment ? ((IAlignment) tTileEntity).getExtendedFacing() ExtendedFacing facing = tTileEntity instanceof IAlignment
? ((IAlignment) tTileEntity).getExtendedFacing()
: ExtendedFacing.of(ForgeDirection.getOrientation(aSide)); : ExtendedFacing.of(ForgeDirection.getOrientation(aSide));
constructable = IMultiblockInfoContainer.<TileEntity>get(tTileEntity.getClass()) constructable = IMultiblockInfoContainer.<TileEntity>get(tTileEntity.getClass())
.toConstructable(tTileEntity, facing); .toConstructable(tTileEntity, facing);
@@ -77,10 +75,11 @@ public class ConstructableUtility {
if (aPlayer.capabilities.isCreativeMode) { if (aPlayer.capabilities.isCreativeMode) {
constructable.construct(aStack, false); constructable.construct(aStack, false);
} else if (constructable instanceof ISurvivalConstructable) { } else if (constructable instanceof ISurvivalConstructable) {
int built = ((ISurvivalConstructable) constructable).survivalConstruct( int built = ((ISurvivalConstructable) constructable)
aStack, .survivalConstruct(
ConfigurationHandler.INSTANCE.getAutoPlaceBudget(), aStack,
ISurvivalBuildEnvironment.create(IItemSource.fromPlayer(playerMP), playerMP)); ConfigurationHandler.INSTANCE.getAutoPlaceBudget(),
ISurvivalBuildEnvironment.create(IItemSource.fromPlayer(playerMP), playerMP));
if (built > 0) { if (built > 0) {
playerMP.addChatMessage(new ChatComponentTranslation("structurelib.autoplace.built_stat", built)); playerMP.addChatMessage(new ChatComponentTranslation("structurelib.autoplace.built_stat", built));
} else if (built == -1) { } else if (built == -1) {
@@ -1,17 +1,14 @@
package com.gtnewhorizon.structurelib.alignment.constructable; package com.gtnewhorizon.structurelib.alignment.constructable;
import net.minecraft.item.ItemStack;
import com.gtnewhorizon.structurelib.structure.IStructureDefinition; import com.gtnewhorizon.structurelib.structure.IStructureDefinition;
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.item.ItemStack;
/** /**
* Created by Tec on 24.03.2017. * Created by Tec on 24.03.2017.
*/ */
public interface IConstructable { public interface IConstructable {
void construct(ItemStack stackSize, boolean hintsOnly); void construct(ItemStack stackSize, boolean hintsOnly);
/** /**
@@ -6,7 +6,6 @@ import javax.annotation.Nullable;
* Implement this interface if this tile entity MIGHT be constructable * Implement this interface if this tile entity MIGHT be constructable
*/ */
public interface IConstructableProvider { public interface IConstructableProvider {
/** /**
* @return null if not constructable, an instance otherwise. * @return null if not constructable, an instance otherwise.
*/ */
@@ -1,23 +1,19 @@
package com.gtnewhorizon.structurelib.alignment.constructable; package com.gtnewhorizon.structurelib.alignment.constructable;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.IItemSource;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.HashMap; import java.util.HashMap;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World; import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.IItemSource;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
/** /**
* To implement IConstructable on not own TileEntities * To implement IConstructable on not own TileEntities
*/ */
public interface IMultiblockInfoContainer<T> { public interface IMultiblockInfoContainer<T> {
HashMap<String, IMultiblockInfoContainer<?>> MULTIBLOCK_MAP = new HashMap<>(); HashMap<String, IMultiblockInfoContainer<?>> MULTIBLOCK_MAP = new HashMap<>();
/** /**
@@ -40,13 +36,16 @@ public interface IMultiblockInfoContainer<T> {
void construct(ItemStack stackSize, boolean hintsOnly, T tileEntity, ExtendedFacing aSide); void construct(ItemStack stackSize, boolean hintsOnly, T tileEntity, ExtendedFacing aSide);
/** /**
* Construct the structure using * Construct the structure using {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, IItemSource, EntityPlayerMP, java.util.function.Consumer)}
* {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, IItemSource, EntityPlayerMP, java.util.function.Consumer)}
*
* @return -1 if done, a helping pointer * @return -1 if done, a helping pointer
*/ */
default int survivalConstruct(ItemStack stackSize, int elementBudge, IItemSource source, default int survivalConstruct(
EntityPlayerMP actorProfile, T tileEntity, ExtendedFacing aSide) { ItemStack stackSize,
int elementBudge,
IItemSource source,
EntityPlayerMP actorProfile,
T tileEntity,
ExtendedFacing aSide) {
return -1; return -1;
} }
@@ -59,7 +58,6 @@ public interface IMultiblockInfoContainer<T> {
*/ */
default IConstructable toConstructable(T tileEntity, ExtendedFacing aSide) { default IConstructable toConstructable(T tileEntity, ExtendedFacing aSide) {
return new IConstructable() { return new IConstructable() {
@Override @Override
public void construct(ItemStack stackSize, boolean hintsOnly) { public void construct(ItemStack stackSize, boolean hintsOnly) {
IMultiblockInfoContainer.this.construct(stackSize, hintsOnly, tileEntity, aSide); IMultiblockInfoContainer.this.construct(stackSize, hintsOnly, tileEntity, aSide);
@@ -72,13 +70,12 @@ public interface IMultiblockInfoContainer<T> {
}; };
} }
static <T> ISurvivalConstructable toConstructable(IMultiblockInfoContainer<T> thiz, T tileEntity, static <T> ISurvivalConstructable toConstructable(
ExtendedFacing aSide) { IMultiblockInfoContainer<T> thiz, T tileEntity, ExtendedFacing aSide) {
return new ISurvivalConstructable() { return new ISurvivalConstructable() {
@Override @Override
public int survivalConstruct(ItemStack stackSize, int elementBudget, IItemSource source, public int survivalConstruct(
EntityPlayerMP actor) { ItemStack stackSize, int elementBudget, IItemSource source, EntityPlayerMP actor) {
return thiz.survivalConstruct(stackSize, elementBudget, source, actor, tileEntity, aSide); return thiz.survivalConstruct(stackSize, elementBudget, source, actor, tileEntity, aSide);
} }
@@ -1,35 +1,31 @@
package com.gtnewhorizon.structurelib.alignment.constructable; package com.gtnewhorizon.structurelib.alignment.constructable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing; import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.AutoPlaceEnvironment; import com.gtnewhorizon.structurelib.structure.AutoPlaceEnvironment;
import com.gtnewhorizon.structurelib.structure.IItemSource; import com.gtnewhorizon.structurelib.structure.IItemSource;
import com.gtnewhorizon.structurelib.structure.ISurvivalBuildEnvironment; import com.gtnewhorizon.structurelib.structure.ISurvivalBuildEnvironment;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
/** /**
* An extension to {@link IConstructable}. Tile Entities (or delegates returned by * An extension to {@link IConstructable}. Tile Entities (or delegates returned by {@link IConstructableProvider#getConstructable()}
* {@link IConstructableProvider#getConstructable()} should implement this interface to allow third party tools and * should implement this interface to allow third party tools and StructureLib builtin constructable tools to trigger
* StructureLib builtin constructable tools to trigger autoplace in survival mode. * autoplace in survival mode.
* <p> * <p>
* While not originally planned, a creative player can also use this interface to trigger autoplace by using an * While not originally planned, a creative player can also use this interface to trigger autoplace by using an
* {@link IItemSource} with every possible items in the game. * {@link IItemSource} with every possible items in the game.
*/ */
public interface ISurvivalConstructable extends IConstructable { public interface ISurvivalConstructable extends IConstructable {
/** /**
* End player might want to disable this hack if it turns out to be too crashy * End player might want to disable this hack if it turns out to be too crashy
*/ */
boolean DISABLE_HACKY_MIGRATION_CODE = Boolean.getBoolean("structurelib.disable_isc_migration_hack"); boolean DISABLE_HACKY_MIGRATION_CODE = Boolean.getBoolean("structurelib.disable_isc_migration_hack");
/** /**
* Construct the structure using * Construct the structure using {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, IItemSource, EntityPlayerMP, java.util.function.Consumer)}
* {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, IItemSource, EntityPlayerMP, java.util.function.Consumer)} * or {@link com.gtnewhorizon.structurelib.structure.IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, IItemSource, EntityPlayerMP, boolean)}
* or
* {@link com.gtnewhorizon.structurelib.structure.IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, IItemSource, EntityPlayerMP, boolean)}
* *
* @param elementBudget The server configured element budget. The implementor can choose to tune this up a bit if * @param elementBudget The server configured element budget. The implementor can choose to tune this up a bit if
* the structure is too big, but generally should not be a 4 digits number to not overwhelm the * the structure is too big, but generally should not be a 4 digits number to not overwhelm the
@@ -42,16 +38,14 @@ public interface ISurvivalConstructable extends IConstructable {
} }
/** /**
* Construct the structure using * Construct the structure using {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
* {@link com.gtnewhorizon.structurelib.structure.IStructureElement#survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)} * or {@link com.gtnewhorizon.structurelib.structure.IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, ISurvivalBuildEnvironment, boolean)}
* or
* {@link com.gtnewhorizon.structurelib.structure.IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, ISurvivalBuildEnvironment, boolean)}
* *
* @param elementBudget The server configured element budget. The implementor can choose to tune this up a bit if * @param elementBudget The server configured element budget. The implementor can choose to tune this up a bit if
* the structure is too big, but generally should not be a 4 digits number to not overwhelm the * the structure is too big, but generally should not be a 4 digits number to not overwhelm the
* server * server
* @return -1 if done, -2 if not supported (e.g. due to an incompatible change in the API of env, otherwise number * @return -1 if done, -2 if not supported (e.g. due to an incompatible change in the API of env, otherwise number
* of elements placed this round * of elements placed this round
*/ */
default int survivalConstruct(ItemStack stackSize, int elementBudget, ISurvivalBuildEnvironment env) { default int survivalConstruct(ItemStack stackSize, int elementBudget, ISurvivalBuildEnvironment env) {
EntityPlayer actor = env.getActor(); EntityPlayer actor = env.getActor();
@@ -80,6 +74,5 @@ public interface ISurvivalConstructable extends IConstructable {
} }
class GlobalStates { class GlobalStates {
public static final ThreadLocal<EntityPlayer> entityPlayer = new ThreadLocal<>(); public static final ThreadLocal<EntityPlayer> entityPlayer = new ThreadLocal<>();
} }
@@ -1,16 +1,13 @@
package com.gtnewhorizon.structurelib.alignment.enumerable; package com.gtnewhorizon.structurelib.alignment.enumerable;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
import java.util.Arrays; import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.common.util.ForgeDirection;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
public enum Direction { public enum Direction {
DOWN(ForgeDirection.DOWN), DOWN(ForgeDirection.DOWN),
UP(ForgeDirection.UP), UP(ForgeDirection.UP),
NORTH(ForgeDirection.NORTH), NORTH(ForgeDirection.NORTH),
@@ -21,8 +18,8 @@ public enum Direction {
private final ForgeDirection forgeDirection; private final ForgeDirection forgeDirection;
private final Vec3Impl axisVector; private final Vec3Impl axisVector;
public static final Direction[] VALUES = values(); public static final Direction[] VALUES = values();
private static final Map<Vec3Impl, Direction> reverseMap = Arrays.stream(VALUES) private static final Map<Vec3Impl, Direction> reverseMap =
.collect(Collectors.toMap(d -> d.axisVector, Function.identity())); Arrays.stream(VALUES).collect(Collectors.toMap(d -> d.axisVector, Function.identity()));
Direction(ForgeDirection forgeDirection) { Direction(ForgeDirection forgeDirection) {
this.forgeDirection = forgeDirection; this.forgeDirection = forgeDirection;
@@ -6,19 +6,16 @@ import static java.lang.Math.abs;
import static java.util.Arrays.stream; import static java.util.Arrays.stream;
import static java.util.stream.Collectors.*; import static java.util.stream.Collectors.*;
import java.util.*;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
import net.minecraftforge.common.util.ForgeDirection;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.gtnewhorizon.structurelib.alignment.IAlignment; import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.IntegerAxisSwap; import com.gtnewhorizon.structurelib.alignment.IntegerAxisSwap;
import com.gtnewhorizon.structurelib.util.Vec3Impl; import com.gtnewhorizon.structurelib.util.Vec3Impl;
import java.util.*;
import net.minecraft.util.StatCollector;
import net.minecraft.util.Vec3;
import net.minecraftforge.common.util.ForgeDirection;
public enum ExtendedFacing { public enum ExtendedFacing {
DOWN_NORMAL_NONE("down normal none"), DOWN_NORMAL_NONE("down normal none"),
DOWN_NORMAL_HORIZONTAL("down normal horizontal"), DOWN_NORMAL_HORIZONTAL("down normal horizontal"),
DOWN_NORMAL_VERTICAL("down normal vertical"), DOWN_NORMAL_VERTICAL("down normal vertical"),
@@ -122,31 +119,31 @@ public enum ExtendedFacing {
public static final int STATES_COUNT = VALUES.length; public static final int STATES_COUNT = VALUES.length;
static { static {
stream(values()).forEach( stream(values())
extendedFacing -> FOR_FACING.compute(extendedFacing.direction, ((forgeDirection, extendedFacings) -> { .forEach(extendedFacing ->
if (extendedFacings == null) { FOR_FACING.compute(extendedFacing.direction, ((forgeDirection, extendedFacings) -> {
extendedFacings = new ArrayList<>(); if (extendedFacings == null) {
} extendedFacings = new ArrayList<>();
extendedFacings.add(extendedFacing); }
return extendedFacings; extendedFacings.add(extendedFacing);
}))); return extendedFacings;
})));
} }
private static final Map<String, ExtendedFacing> NAME_LOOKUP = stream(VALUES) private static final Map<String, ExtendedFacing> NAME_LOOKUP =
.collect(toMap(ExtendedFacing::getName2, (extendedFacing) -> extendedFacing)); stream(VALUES).collect(toMap(ExtendedFacing::getName2, (extendedFacing) -> extendedFacing));
private static final EnumMap<ForgeDirection, ImmutableSet<ExtendedFacing>> LOOKUP_BY_DIRECTION = stream(VALUES) private static final EnumMap<ForgeDirection, ImmutableSet<ExtendedFacing>> LOOKUP_BY_DIRECTION = stream(VALUES)
.collect( .collect(groupingBy(
groupingBy( ExtendedFacing::getDirection,
ExtendedFacing::getDirection, () -> new EnumMap<>(ForgeDirection.class),
() -> new EnumMap<>(ForgeDirection.class), collectingAndThen(toSet(), ImmutableSet::copyOf)));
collectingAndThen(toSet(), ImmutableSet::copyOf))); private static final EnumMap<Rotation, ImmutableSet<ExtendedFacing>> LOOKUP_BY_ROTATION = stream(VALUES)
private static final EnumMap<Rotation, ImmutableSet<ExtendedFacing>> LOOKUP_BY_ROTATION = stream(VALUES).collect( .collect(groupingBy(
groupingBy(
ExtendedFacing::getRotation, ExtendedFacing::getRotation,
() -> new EnumMap<>(Rotation.class), () -> new EnumMap<>(Rotation.class),
collectingAndThen(toSet(), ImmutableSet::copyOf))); collectingAndThen(toSet(), ImmutableSet::copyOf)));
private static final EnumMap<Flip, ImmutableSet<ExtendedFacing>> LOOKUP_BY_FLIP = stream(VALUES).collect( private static final EnumMap<Flip, ImmutableSet<ExtendedFacing>> LOOKUP_BY_FLIP = stream(VALUES)
groupingBy( .collect(groupingBy(
ExtendedFacing::getFlip, ExtendedFacing::getFlip,
() -> new EnumMap<>(Flip.class), () -> new EnumMap<>(Flip.class),
collectingAndThen(toSet(), ImmutableSet::copyOf))); collectingAndThen(toSet(), ImmutableSet::copyOf)));
@@ -336,7 +333,7 @@ public enum ExtendedFacing {
} }
/** /**
* Translates relative to front facing offset to world offset * Translates relative to front facing offset to world offset
* *
* @param abcOffset A,B,C offset (facing relative {@code L-->R,U-->D,F-->B}) * @param abcOffset A,B,C offset (facing relative {@code L-->R,U-->D,F-->B})
* @return X, Y, Z offset in world * @return X, Y, Z offset in world
@@ -380,10 +377,10 @@ public enum ExtendedFacing {
} }
/** /**
* Translates world offset to relative front facing offset * Translates world offset to relative front facing offset
* *
* @param xyzOffset X,Y,Z offset in world * @param xyzOffset X,Y,Z offset in world
* @return A, B, C offset (facing relative {@code L-->R,U-->D,F-->B}) * @return A, B, C offset (facing relative {@code L-->R,U-->D,F-->B})
*/ */
public Vec3 getOffsetABC(Vec3 xyzOffset) { public Vec3 getOffsetABC(Vec3 xyzOffset) {
return integerAxisSwap.translate(xyzOffset); return integerAxisSwap.translate(xyzOffset);
@@ -7,11 +7,9 @@ import static java.util.stream.Collectors.toMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public enum Flip { public enum Flip {
NONE(3, "none"), NONE(3, "none"),
HORIZONTAL(2, "horizontal"), HORIZONTAL(2, "horizontal"),
VERTICAL(1, "vertical"), VERTICAL(1, "vertical"),
@@ -7,11 +7,9 @@ import static java.util.stream.Collectors.toMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Random; import java.util.Random;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
public enum Rotation { public enum Rotation {
NORMAL(2, "normal"), NORMAL(2, "normal"),
CLOCKWISE(3, "clockwise"), CLOCKWISE(3, "clockwise"),
UPSIDE_DOWN(0, "upside down"), UPSIDE_DOWN(0, "upside down"),
@@ -21,8 +19,8 @@ public enum Rotation {
private final String name; private final String name;
public static final Rotation[] VALUES = values(); public static final Rotation[] VALUES = values();
private static final Map<String, Rotation> NAME_LOOKUP = stream(VALUES) private static final Map<String, Rotation> NAME_LOOKUP =
.collect(toMap(Rotation::getName2, (rotation) -> rotation)); stream(VALUES).collect(toMap(Rotation::getName2, (rotation) -> rotation));
Rotation(int oppositeIn, String nameIn) { Rotation(int oppositeIn, String nameIn) {
this.opposite = oppositeIn; this.opposite = oppositeIn;
@@ -1,7 +1,7 @@
/** /**
* This package provide a framework for rotating a given block, or a multiblock structure. * This package provide a framework for rotating a given block, or a multiblock structure.
* <p> * <p>
* All public stuff in this package and its subpackages are considered part of the public API. Backwards compatibility * All public stuff in this package and its subpackages are considered part of the public API.
* is maintained to the maximum extend possible. * Backwards compatibility is maintained to the maximum extend possible.
*/ */
package com.gtnewhorizon.structurelib.alignment; package com.gtnewhorizon.structurelib.alignment;
@@ -1,7 +1,10 @@
package com.gtnewhorizon.structurelib.block; package com.gtnewhorizon.structurelib.block;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List; import java.util.List;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.block.material.Material; import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.client.renderer.texture.IIconRegister;
@@ -11,14 +14,7 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.IIcon; import net.minecraft.util.IIcon;
import net.minecraft.world.IBlockAccess; import net.minecraft.world.IBlockAccess;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class BlockHint extends Block { public class BlockHint extends Block {
private static final IIcon[] hint = new IIcon[16]; private static final IIcon[] hint = new IIcon[16];
public BlockHint() { public BlockHint() {
@@ -1,9 +1,10 @@
package com.gtnewhorizon.structurelib.command; package com.gtnewhorizon.structurelib.command;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import net.minecraft.command.CommandBase; import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender; import net.minecraft.command.ICommandSender;
import net.minecraft.command.WrongUsageException; import net.minecraft.command.WrongUsageException;
@@ -12,11 +13,7 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.ChatComponentText; import net.minecraft.util.ChatComponentText;
import net.minecraft.util.ChatComponentTranslation; import net.minecraft.util.ChatComponentTranslation;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger;
public class CommandConfigureChannels extends CommandBase { public class CommandConfigureChannels extends CommandBase {
@Override @Override
public String getCommandName() { public String getCommandName() {
return "sl_channel"; return "sl_channel";
@@ -61,12 +58,13 @@ public class CommandConfigureChannels extends CommandBase {
if (!ChannelDataAccessor.hasSubChannel(heldItem)) { if (!ChannelDataAccessor.hasSubChannel(heldItem)) {
sender.addChatMessage(new ChatComponentText("No subchannel")); sender.addChatMessage(new ChatComponentText("No subchannel"));
} else { } else {
sender.addChatMessage( sender.addChatMessage(new ChatComponentTranslation(
new ChatComponentTranslation( "item.structurelib.constructableTrigger.desc.lshift.0",
"item.structurelib.constructableTrigger.desc.lshift.0", ChannelDataAccessor.countChannelData(heldItem)));
ChannelDataAccessor.countChannelData(heldItem))); ChannelDataAccessor.iterateChannelData(heldItem)
ChannelDataAccessor.iterateChannelData(heldItem).map(e -> e.getKey() + ": " + e.getValue()) .map(e -> e.getKey() + ": " + e.getValue())
.map(ChatComponentText::new).forEach(player::addChatMessage); .map(ChatComponentText::new)
.forEach(player::addChatMessage);
} }
return; return;
case "wipe": case "wipe":
@@ -75,11 +73,13 @@ public class CommandConfigureChannels extends CommandBase {
case "get": case "get":
case "unset": case "unset":
if (args.length < 2) throw new WrongUsageException(getCommandUsage(sender)); if (args.length < 2) throw new WrongUsageException(getCommandUsage(sender));
channel = args.length == 2 ? args[1] : Arrays.stream(args).skip(1).collect(Collectors.joining()); channel =
args.length == 2 ? args[1] : Arrays.stream(args).skip(1).collect(Collectors.joining());
break; break;
case "set": case "set":
if (args.length < 3) throw new WrongUsageException(getCommandUsage(sender)); if (args.length < 3) throw new WrongUsageException(getCommandUsage(sender));
channel = args.length == 3 ? args[1] channel = args.length == 3
? args[1]
: Arrays.stream(args).skip(1).limit(args.length - 2).collect(Collectors.joining()); : Arrays.stream(args).skip(1).limit(args.length - 2).collect(Collectors.joining());
break; break;
default: default:
@@ -88,9 +88,9 @@ public class CommandConfigureChannels extends CommandBase {
switch (args[0]) { switch (args[0]) {
case "get": case "get":
if (ChannelDataAccessor.hasSubChannel(heldItem, channel)) sender.addChatMessage( if (ChannelDataAccessor.hasSubChannel(heldItem, channel))
new ChatComponentText( sender.addChatMessage(new ChatComponentText(
channel + " value: " + ChannelDataAccessor.getChannelData(heldItem, channel))); channel + " value: " + ChannelDataAccessor.getChannelData(heldItem, channel)));
else sender.addChatMessage(new ChatComponentText(channel + " value: N/A")); else sender.addChatMessage(new ChatComponentText(channel + " value: N/A"));
break; break;
case "clear": case "clear":
@@ -1,16 +1,20 @@
package com.gtnewhorizon.structurelib.entity.fx; package com.gtnewhorizon.structurelib.entity.fx;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.world.World;
import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.client.particle.EntityFX;
import net.minecraft.world.World;
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public class WeightlessParticleFX extends EntityFX { public class WeightlessParticleFX extends EntityFX {
public WeightlessParticleFX(
public WeightlessParticleFX(World p_i1205_1_, double p_i1205_2_, double p_i1205_4_, double p_i1205_6_, World p_i1205_1_,
double p_i1205_8_, double p_i1205_10_, double p_i1205_12_) { double p_i1205_2_,
double p_i1205_4_,
double p_i1205_6_,
double p_i1205_8_,
double p_i1205_10_,
double p_i1205_12_) {
super(p_i1205_1_, p_i1205_2_, p_i1205_4_, p_i1205_6_, p_i1205_8_, p_i1205_10_, p_i1205_12_); super(p_i1205_1_, p_i1205_2_, p_i1205_4_, p_i1205_6_, p_i1205_8_, p_i1205_10_, p_i1205_12_);
this.motionX = p_i1205_8_ + (double) ((float) (Math.random() * 2.0D - 1.0D) * 0.05F); this.motionX = p_i1205_8_ + (double) ((float) (Math.random() * 2.0D - 1.0D) * 0.05F);
this.motionY = p_i1205_10_ + (double) ((float) (Math.random() * 2.0D - 1.0D) * 0.05F); this.motionY = p_i1205_10_ + (double) ((float) (Math.random() * 2.0D - 1.0D) * 0.05F);
@@ -1,10 +1,12 @@
package com.gtnewhorizon.structurelib.gui; package com.gtnewhorizon.structurelib.gui;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.gui.GuiScrollableList.IGuiScreen;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField; import net.minecraft.client.gui.GuiTextField;
@@ -13,18 +15,12 @@ import net.minecraft.client.resources.I18n;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.ResourceLocation; import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.lwjgl.input.Keyboard; import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse; import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.gui.GuiScrollableList.IGuiScreen;
public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen { public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen {
private static final int KEY_MAX_WIDTH = 50; private static final int KEY_MAX_WIDTH = 50;
private final ItemStack trigger; private final ItemStack trigger;
private final GuiChannelsList list; private final GuiChannelsList list;
@@ -52,7 +48,6 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
guiTop = (this.height - this.getYSize()) / 2; guiTop = (this.height - this.getYSize()) / 2;
key = new GuiTextField(fontRendererObj, guiLeft + 45, guiTop + 119, 151 + 12 - 45, 12) { key = new GuiTextField(fontRendererObj, guiLeft + 45, guiTop + 119, 151 + 12 - 45, 12) {
@Override @Override
public void writeText(String text) { public void writeText(String text) {
// force lower case // force lower case
@@ -63,7 +58,8 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
@Override @Override
public void mouseClicked(int p_146192_1_, int p_146192_2_, int p_146192_3_) { public void mouseClicked(int p_146192_1_, int p_146192_2_, int p_146192_3_) {
super.mouseClicked(p_146192_1_, p_146192_2_, p_146192_3_); super.mouseClicked(p_146192_1_, p_146192_2_, p_146192_3_);
boolean flag = p_146192_1_ >= this.xPosition && p_146192_1_ < this.xPosition + this.width boolean flag = p_146192_1_ >= this.xPosition
&& p_146192_1_ < this.xPosition + this.width
&& p_146192_2_ >= this.yPosition && p_146192_2_ >= this.yPosition
&& p_146192_2_ < this.yPosition + this.height; && p_146192_2_ < this.yPosition + this.height;
if (flag && p_146192_3_ == 1) { if (flag && p_146192_3_ == 1) {
@@ -79,7 +75,6 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
} }
}; };
value = new GuiTextField(fontRendererObj, guiLeft + 45, guiTop + 139, 151 + 12 - 45, 12) { value = new GuiTextField(fontRendererObj, guiLeft + 45, guiTop + 139, 151 + 12 - 45, 12) {
@Override @Override
public void writeText(String text) { public void writeText(String text) {
// ignore write requests containing non digit characters. // ignore write requests containing non digit characters.
@@ -109,7 +104,8 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
@Override @Override
public void mouseClicked(int p_146192_1_, int p_146192_2_, int p_146192_3_) { public void mouseClicked(int p_146192_1_, int p_146192_2_, int p_146192_3_) {
super.mouseClicked(p_146192_1_, p_146192_2_, p_146192_3_); super.mouseClicked(p_146192_1_, p_146192_2_, p_146192_3_);
boolean flag = p_146192_1_ >= this.xPosition && p_146192_1_ < this.xPosition + this.width boolean flag = p_146192_1_ >= this.xPosition
&& p_146192_1_ < this.xPosition + this.width
&& p_146192_2_ >= this.yPosition && p_146192_2_ >= this.yPosition
&& p_146192_2_ < this.yPosition + this.height; && p_146192_2_ < this.yPosition + this.height;
if (flag && p_146192_3_ == 1) { if (flag && p_146192_3_ == 1) {
@@ -126,30 +122,22 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
list.onGuiInit(this); list.onGuiInit(this);
addButton( addButton(new GuiButton(
new GuiButton( 0, guiLeft + 12, guiTop + 157, 47, 20, I18n.format("item.structurelib.constructableTrigger.gui.add")));
0, addButton(new GuiButton(
guiLeft + 12, 1,
guiTop + 157, guiLeft + 65,
47, guiTop + 157,
20, 47,
I18n.format("item.structurelib.constructableTrigger.gui.add"))); 20,
addButton( I18n.format("item.structurelib.constructableTrigger.gui.unset")));
new GuiButton( addButton(new GuiButton(
1, 2,
guiLeft + 65, guiLeft + 118,
guiTop + 157, guiTop + 157,
47, 47,
20, 20,
I18n.format("item.structurelib.constructableTrigger.gui.unset"))); I18n.format("item.structurelib.constructableTrigger.gui.wipe")));
addButton(
new GuiButton(
2,
guiLeft + 118,
guiTop + 157,
47,
20,
I18n.format("item.structurelib.constructableTrigger.gui.wipe")));
updateButtons(); updateButtons();
} }
@@ -250,7 +238,8 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
// STACKOVERFLOW! // STACKOVERFLOW!
String keyText = key.getText(); String keyText = key.getText();
boolean existing = !StringUtils.isEmpty(keyText) && ChannelDataAccessor.hasSubChannel(trigger, keyText); boolean existing = !StringUtils.isEmpty(keyText) && ChannelDataAccessor.hasSubChannel(trigger, keyText);
getButtonList().get(0).displayString = existing ? I18n.format("item.structurelib.constructableTrigger.gui.set") getButtonList().get(0).displayString = existing
? I18n.format("item.structurelib.constructableTrigger.gui.set")
: I18n.format("item.structurelib.constructableTrigger.gui.add"); : I18n.format("item.structurelib.constructableTrigger.gui.add");
getButtonList().get(0).enabled = !StringUtils.isBlank(value.getText()); getButtonList().get(0).enabled = !StringUtils.isBlank(value.getText());
getButtonList().get(1).enabled = existing && !StringUtils.isBlank(value.getText()); getButtonList().get(1).enabled = existing && !StringUtils.isBlank(value.getText());
@@ -311,21 +300,14 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
super.drawScreen(mX, mY, partialTick); super.drawScreen(mX, mY, partialTick);
list.drawScreen(mX, mY, partialTick); list.drawScreen(mX, mY, partialTick);
fontRendererObj.drawString( fontRendererObj.drawString(
I18n.format("item.structurelib.constructableTrigger.gui.key"), I18n.format("item.structurelib.constructableTrigger.gui.key"), guiLeft + 12, guiTop + 122, 0);
guiLeft + 12,
guiTop + 122,
0);
key.drawTextBox(); key.drawTextBox();
fontRendererObj.drawString( fontRendererObj.drawString(
I18n.format("item.structurelib.constructableTrigger.gui.value"), I18n.format("item.structurelib.constructableTrigger.gui.value"), guiLeft + 12, guiTop + 142, 0);
guiLeft + 12,
guiTop + 142,
0);
value.drawTextBox(); value.drawTextBox();
} }
private class GuiChannelsList extends GuiScrollableList<Entry<String, Integer>> { private class GuiChannelsList extends GuiScrollableList<Entry<String, Integer>> {
private List<Entry<String, Integer>> cache; private List<Entry<String, Integer>> cache;
public GuiChannelsList(int width, int height, int originX, int originY, int slotHeight) { public GuiChannelsList(int width, int height, int originX, int originY, int slotHeight) {
@@ -334,7 +316,11 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
@Override @Override
public Entry<String, Integer> getElementAt(int index) { public Entry<String, Integer> getElementAt(int index) {
return ChannelDataAccessor.iterateChannelData(trigger).sorted().skip(index).findFirst().orElse(null); return ChannelDataAccessor.iterateChannelData(trigger)
.sorted()
.skip(index)
.findFirst()
.orElse(null);
} }
@Override @Override
@@ -344,7 +330,8 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
@Override @Override
protected boolean elementClicked(int elementIndex, boolean doubleClick, int mXRelative, int mYRelative) { protected boolean elementClicked(int elementIndex, boolean doubleClick, int mXRelative, int mYRelative) {
if (mXRelative >= margin + 1 && mXRelative <= margin + 5 if (mXRelative >= margin + 1
&& mXRelative <= margin + 5
&& mYRelative >= margin / 2 + 1 && mYRelative >= margin / 2 + 1
&& mYRelative <= margin / 2 + 5) { && mYRelative <= margin / 2 + 5) {
Entry<String, Integer> e = getElementAt(elementIndex); Entry<String, Integer> e = getElementAt(elementIndex);
@@ -362,8 +349,8 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
} }
@Override @Override
protected void drawElement(int elementIndex, int x, int y, int height, Tessellator tessellator, protected void drawElement(
boolean isHovering) { int elementIndex, int x, int y, int height, Tessellator tessellator, boolean isHovering) {
if (elementIndex < 0 || elementIndex >= cache.size()) { if (elementIndex < 0 || elementIndex >= cache.size()) {
return; return;
} }
@@ -395,7 +382,8 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
// TODO optimize this to not create a billion string, or maybe cache this // TODO optimize this to not create a billion string, or maybe cache this
String s = fontRendererObj.trimStringToWidth(e, keyMaxWidth); String s = fontRendererObj.trimStringToWidth(e, keyMaxWidth);
if (s.length() != e.length()) { if (s.length() != e.length()) {
StringBuilder buffer = new StringBuilder(s).deleteCharAt(s.length() - 1).append("..."); StringBuilder buffer =
new StringBuilder(s).deleteCharAt(s.length() - 1).append("...");
while ((s = fontRendererObj.trimStringToWidth(buffer.toString(), keyMaxWidth)).length() while ((s = fontRendererObj.trimStringToWidth(buffer.toString(), keyMaxWidth)).length()
!= buffer.length()) != buffer.length())
// drop last original char // drop last original char
@@ -403,7 +391,9 @@ public class GuiScreenConfigureChannels extends GuiScreen implements IGuiScreen
do { do {
buffer.append('.'); buffer.append('.');
} while (fontRendererObj.getStringWidth(buffer.toString()) <= keyMaxWidth); } while (fontRendererObj.getStringWidth(buffer.toString()) <= keyMaxWidth);
s = buffer.deleteCharAt(s.length() - 1).insert(s.length() - 3, EnumChatFormatting.GRAY).toString(); s = buffer.deleteCharAt(s.length() - 1)
.insert(s.length() - 3, EnumChatFormatting.GRAY)
.toString();
} }
return s; return s;
} }
@@ -2,34 +2,31 @@ package com.gtnewhorizon.structurelib.gui;
import java.util.List; import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.Tessellator;
import org.lwjgl.input.Mouse; import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL11;
/** /**
* Shamelessly stolen from EnderCore, with some amount of edit to fit in one file. Original code from CrazyPants. * Shamelessly stolen from EnderCore, with some amount of edit to fit in one file. Original code from CrazyPants.
* <p> * <p>
* As the code has been released into public domain, it is now LGPL as part of this library as a whole. You can go to * As the code has been released into public domain, it is now LGPL as part of this library as a whole.
* EnderCore's repository to obtain a public domain copy though * You can go to EnderCore's repository to obtain a public domain copy though
* *
* Major edits * Major edits
* <ul> * <ul>
* <li>Separate dwheel handling to handleDWheel. The next event calls often cause the mouse click event to not fire on * <li>Separate dwheel handling to handleDWheel. The next event calls often cause the mouse click event to
* other widgets</li> * not fire on other widgets</li>
* <li>scrollbar are now rendered within width</li> * <li>scrollbar are now rendered within width</li>
* <li>added prepareDrawElements</li> * <li>added prepareDrawElements</li>
* </ul> * </ul>
* *
* @author CrazyPants * @author CrazyPants
* @author glee8e * @author glee8e
*/ */
public abstract class GuiScrollableList<T> { public abstract class GuiScrollableList<T> {
protected final int slotHeight; protected final int slotHeight;
private final Minecraft mc = Minecraft.getMinecraft(); private final Minecraft mc = Minecraft.getMinecraft();
protected final int originX; protected final int originX;
@@ -116,8 +113,8 @@ public abstract class GuiScrollableList<T> {
public abstract int getNumElements(); public abstract int getNumElements();
protected abstract void drawElement(int elementIndex, int x, int y, int height, Tessellator tessellator, protected abstract void drawElement(
boolean isHovering); int elementIndex, int x, int y, int height, Tessellator tessellator, boolean isHovering);
protected boolean elementClicked(int elementIndex, boolean doubleClick, int mXRelative, int mYRelative) { protected boolean elementClicked(int elementIndex, boolean doubleClick, int mXRelative, int mYRelative) {
return true; return true;
@@ -168,7 +165,8 @@ public abstract class GuiScrollableList<T> {
} }
/** /**
* draws the slot to the screen, pass in mouse's current x and y and partial ticks * draws the slot to the screen, pass in mouse's current x and y and partial
* ticks
*/ */
public void drawScreen(int mX, int mY, float partialTick) { public void drawScreen(int mX, int mY, float partialTick) {
this.mouseX = mX; this.mouseX = mX;
@@ -345,17 +343,15 @@ public abstract class GuiScrollableList<T> {
int y = mouseY - minY + (int) amountScrolled - margin; int y = mouseY - minY + (int) amountScrolled - margin;
int mouseOverElement = y / slotHeight; int mouseOverElement = y / slotHeight;
if (mouseX >= minX && mouseX <= maxX if (mouseX >= minX
&& mouseX <= maxX
&& mouseOverElement >= 0 && mouseOverElement >= 0
&& y >= 0 && y >= 0
&& mouseOverElement < getNumElements()) { && mouseOverElement < getNumElements()) {
boolean doubleClick = mouseOverElement == selectedIndex boolean doubleClick =
&& Minecraft.getSystemTime() - lastClickedTime < 250L; mouseOverElement == selectedIndex && Minecraft.getSystemTime() - lastClickedTime < 250L;
if (elementClicked( if (elementClicked(
mouseOverElement, mouseOverElement, doubleClick, mouseX - minX, y - slotHeight * mouseOverElement)) {
doubleClick,
mouseX - minX,
y - slotHeight * mouseOverElement)) {
setSelection(mouseOverElement); setSelection(mouseOverElement);
lastClickedTime = Minecraft.getSystemTime(); lastClickedTime = Minecraft.getSystemTime();
} }
@@ -3,7 +3,6 @@ package com.gtnewhorizon.structurelib.item;
import static net.minecraft.util.StatCollector.translateToLocal; import static net.minecraft.util.StatCollector.translateToLocal;
import java.util.List; import java.util.List;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.creativetab.CreativeTabs; import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
@@ -12,7 +11,6 @@ import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.EnumChatFormatting;
public class ItemBlockHint extends ItemBlock { public class ItemBlockHint extends ItemBlock {
public ItemBlockHint(Block p_i45328_1_) { public ItemBlockHint(Block p_i45328_1_) {
super(p_i45328_1_); super(p_i45328_1_);
setMaxDamage(0); setMaxDamage(0);
@@ -37,31 +35,29 @@ public class ItemBlockHint extends ItemBlock {
case 9: case 9:
case 10: case 10:
case 11: case 11:
aList.add( aList.add(EnumChatFormatting.AQUA.toString()
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.1")); // Placeholder for a certain + translateToLocal("structurelib.blockhint.desc.1")); // Placeholder for a certain group.
// group.
break; break;
case 12: case 12:
aList.add( aList.add(EnumChatFormatting.AQUA.toString()
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.2")); // General placeholder. + translateToLocal("structurelib.blockhint.desc.2")); // General placeholder.
break; break;
case 13: case 13:
aList.add( aList.add(EnumChatFormatting.AQUA.toString()
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.3")); // Make sure it contains Air + translateToLocal("structurelib.blockhint.desc.3")); // Make sure it contains Air material.
// material.
break; break;
case 14: case 14:
aList.add( aList.add(EnumChatFormatting.AQUA.toString()
EnumChatFormatting.AQUA.toString() + EnumChatFormatting.BOLD + EnumChatFormatting.BOLD
+ translateToLocal("structurelib.blockhint.desc.4")); // Make sure it does not contain + translateToLocal(
// Air material. "structurelib.blockhint.desc.4")); // Make sure it does not contain Air material.
break; break;
case 15: case 15:
aList.add(EnumChatFormatting.BLUE + translateToLocal("structurelib.blockhint.desc.5")); // ERROR, what aList.add(EnumChatFormatting.BLUE
// did u expect? + translateToLocal("structurelib.blockhint.desc.5")); // ERROR, what did u expect?
break; break;
default: // WTF? default: // WTF?
aList.add("Damn son where did you get that!?"); aList.add("Damn son where did you get that!?");
@@ -5,21 +5,17 @@ import static net.minecraft.util.EnumChatFormatting.BLUE;
import static net.minecraft.util.StatCollector.translateToLocal; import static net.minecraft.util.StatCollector.translateToLocal;
import static net.minecraft.util.StatCollector.translateToLocalFormatted; import static net.minecraft.util.StatCollector.translateToLocalFormatted;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.alignment.constructable.ConstructableUtility;
import java.util.List; import java.util.List;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.world.World; import net.minecraft.world.World;
import org.lwjgl.input.Keyboard; import org.lwjgl.input.Keyboard;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.alignment.constructable.ConstructableUtility;
public class ItemConstructableTrigger extends Item { public class ItemConstructableTrigger extends Item {
public ItemConstructableTrigger() { public ItemConstructableTrigger() {
setUnlocalizedName("structurelib.constructableTrigger"); setUnlocalizedName("structurelib.constructableTrigger");
setTextureName(MOD_ID + ":itemConstructableTrigger"); setTextureName(MOD_ID + ":itemConstructableTrigger");
@@ -34,8 +30,17 @@ public class ItemConstructableTrigger extends Item {
} }
@Override @Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, public boolean onItemUseFirst(
float hitX, float hitY, float hitZ) { ItemStack stack,
EntityPlayer player,
World world,
int x,
int y,
int z,
int side,
float hitX,
float hitY,
float hitZ) {
return ConstructableUtility.handle(stack, player, world, x, y, z, side); return ConstructableUtility.handle(stack, player, world, x, y, z, side);
} }
@@ -43,25 +48,27 @@ public class ItemConstructableTrigger extends Item {
@Override @Override
public void addInformation(ItemStack aStack, EntityPlayer ep, List aList, boolean boo) { public void addInformation(ItemStack aStack, EntityPlayer ep, List aList, boolean boo) {
if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) { if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {
aList.add( aList.add(translateToLocalFormatted(
translateToLocalFormatted( "item.structurelib.constructableTrigger.desc.lshift.0",
"item.structurelib.constructableTrigger.desc.lshift.0", ChannelDataAccessor.countChannelData(aStack)));
ChannelDataAccessor.countChannelData(aStack))); ChannelDataAccessor.iterateChannelData(aStack)
ChannelDataAccessor.iterateChannelData(aStack).map(e -> e.getKey() + ": " + e.getValue()) .map(e -> e.getKey() + ": " + e.getValue())
.forEach(aList::add); .forEach(aList::add);
} else { } else {
aList.add(translateToLocal("item.structurelib.constructableTrigger.desc.0")); // Triggers Constructable aList.add(translateToLocal(
// Interface "item.structurelib.constructableTrigger.desc.0")); // Triggers Constructable Interface
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.1")); // Shows multiblock aList.add(BLUE
// construction + translateToLocal(
// details, "item.structurelib.constructableTrigger.desc.1")); // Shows multiblock construction details,
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.2")); // just Use on a aList.add(BLUE
// multiblock + translateToLocal(
// controller. "item.structurelib.constructableTrigger.desc.2")); // just Use on a multiblock controller.
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.3")); // (Sneak Use in aList.add(BLUE
// creative to build) + translateToLocal(
aList.add(BLUE + translateToLocal("item.structurelib.constructableTrigger.desc.4")); // Quantity affects "item.structurelib.constructableTrigger.desc.3")); // (Sneak Use in creative to build)
// tier/mode/type aList.add(BLUE
+ translateToLocal(
"item.structurelib.constructableTrigger.desc.4")); // Quantity affects tier/mode/type
if (ChannelDataAccessor.hasSubChannel(aStack)) if (ChannelDataAccessor.hasSubChannel(aStack))
aList.add(translateToLocal("item.structurelib.constructableTrigger.desc.5")); aList.add(translateToLocal("item.structurelib.constructableTrigger.desc.5"));
} }
@@ -3,22 +3,18 @@ package com.gtnewhorizon.structurelib.item;
import static com.gtnewhorizon.structurelib.StructureLibAPI.MOD_ID; import static com.gtnewhorizon.structurelib.StructureLibAPI.MOD_ID;
import static net.minecraft.util.StatCollector.translateToLocal; import static net.minecraft.util.StatCollector.translateToLocal;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.AlignmentUtility;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import java.util.List; import java.util.List;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item; import net.minecraft.item.Item;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World; import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.AlignmentUtility;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemFrontRotationTool extends Item { public class ItemFrontRotationTool extends Item {
public ItemFrontRotationTool() { public ItemFrontRotationTool() {
setMaxStackSize(1); setMaxStackSize(1);
setUnlocalizedName("structurelib.frontRotationTool"); setUnlocalizedName("structurelib.frontRotationTool");
@@ -27,8 +23,17 @@ public class ItemFrontRotationTool extends Item {
} }
@Override @Override
public boolean onItemUseFirst(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, public boolean onItemUseFirst(
float hitX, float hitY, float hitZ) { ItemStack stack,
EntityPlayer player,
World world,
int x,
int y,
int z,
int side,
float hitX,
float hitY,
float hitZ) {
return AlignmentUtility.handle(player, world, x, y, z); return AlignmentUtility.handle(player, world, x, y, z);
} }
@@ -36,13 +41,9 @@ public class ItemFrontRotationTool extends Item {
@SideOnly(Side.CLIENT) @SideOnly(Side.CLIENT)
public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List aList, boolean p_77624_4_) { public void addInformation(ItemStack p_77624_1_, EntityPlayer p_77624_2_, List aList, boolean p_77624_4_) {
aList.add(translateToLocal("item.structurelib.frontRotationTool.desc.0")); // Triggers Front Rotation Interface aList.add(translateToLocal("item.structurelib.frontRotationTool.desc.0")); // Triggers Front Rotation Interface
aList.add(EnumChatFormatting.BLUE + translateToLocal("item.structurelib.frontRotationTool.desc.1")); // Rotates aList.add(EnumChatFormatting.BLUE
// only the + translateToLocal("item.structurelib.frontRotationTool.desc.1")); // Rotates only the front panel,
// front aList.add(EnumChatFormatting.BLUE
// panel, + translateToLocal("item.structurelib.frontRotationTool.desc.2")); // which allows structure rotation.
aList.add(EnumChatFormatting.BLUE + translateToLocal("item.structurelib.frontRotationTool.desc.2")); // which
// allows
// structure
// rotation.
} }
} }
@@ -1,23 +1,20 @@
package com.gtnewhorizon.structurelib.net; package com.gtnewhorizon.structurelib.net;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import com.gtnewhorizon.structurelib.StructureLib; import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.IAlignment; import com.gtnewhorizon.structurelib.alignment.IAlignment;
import com.gtnewhorizon.structurelib.alignment.IAlignmentProvider; import com.gtnewhorizon.structurelib.alignment.IAlignmentProvider;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing; import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
public abstract class AlignmentMessage implements IMessage { public abstract class AlignmentMessage implements IMessage {
int mPosX; int mPosX;
int mPosY; int mPosY;
int mPosZ; int mPosZ;
@@ -69,7 +66,6 @@ public abstract class AlignmentMessage implements IMessage {
} }
public static class AlignmentQuery extends AlignmentMessage { public static class AlignmentQuery extends AlignmentMessage {
public AlignmentQuery() {} public AlignmentQuery() {}
public AlignmentQuery(IAlignmentProvider provider) { public AlignmentQuery(IAlignmentProvider provider) {
@@ -82,7 +78,6 @@ public abstract class AlignmentMessage implements IMessage {
} }
public static class AlignmentData extends AlignmentMessage { public static class AlignmentData extends AlignmentMessage {
public AlignmentData() {} public AlignmentData() {}
private AlignmentData(AlignmentQuery query) { private AlignmentData(AlignmentQuery query) {
@@ -103,11 +98,11 @@ public abstract class AlignmentMessage implements IMessage {
} }
public static class ClientHandler implements IMessageHandler<AlignmentData, IMessage> { public static class ClientHandler implements IMessageHandler<AlignmentData, IMessage> {
@Override @Override
public IMessage onMessage(AlignmentData pMessage, MessageContext pCtx) { public IMessage onMessage(AlignmentData pMessage, MessageContext pCtx) {
if (StructureLib.getCurrentPlayer().worldObj.provider.dimensionId == pMessage.mPosD) { if (StructureLib.getCurrentPlayer().worldObj.provider.dimensionId == pMessage.mPosD) {
TileEntity te = StructureLib.getCurrentPlayer().worldObj TileEntity te = StructureLib.getCurrentPlayer()
.worldObj
.getTileEntity(pMessage.mPosX, pMessage.mPosY, pMessage.mPosZ); .getTileEntity(pMessage.mPosX, pMessage.mPosY, pMessage.mPosZ);
if (te instanceof IAlignmentProvider) { if (te instanceof IAlignmentProvider) {
IAlignment alignment = ((IAlignmentProvider) te).getAlignment(); IAlignment alignment = ((IAlignmentProvider) te).getAlignment();
@@ -121,7 +116,6 @@ public abstract class AlignmentMessage implements IMessage {
} }
public static class ServerHandler implements IMessageHandler<AlignmentQuery, AlignmentData> { public static class ServerHandler implements IMessageHandler<AlignmentQuery, AlignmentData> {
@Override @Override
public AlignmentData onMessage(AlignmentQuery pMessage, MessageContext pCtx) { public AlignmentData onMessage(AlignmentQuery pMessage, MessageContext pCtx) {
World world = DimensionManager.getWorld(pMessage.mPosD); World world = DimensionManager.getWorld(pMessage.mPosD);
@@ -4,14 +4,12 @@ import static com.gtnewhorizon.structurelib.StructureLib.LOGGER;
import com.gtnewhorizon.structurelib.StructureLib; import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI; import com.gtnewhorizon.structurelib.StructureLibAPI;
import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
public class ErrorHintParticleMessage implements IMessage { public class ErrorHintParticleMessage implements IMessage {
private int x; private int x;
private short y; private short y;
private int z; private int z;
@@ -39,21 +37,17 @@ public class ErrorHintParticleMessage implements IMessage {
} }
public static class Handler implements IMessageHandler<ErrorHintParticleMessage, IMessage> { public static class Handler implements IMessageHandler<ErrorHintParticleMessage, IMessage> {
@Override @Override
public IMessage onMessage(ErrorHintParticleMessage msg, MessageContext ctx) { public IMessage onMessage(ErrorHintParticleMessage msg, MessageContext ctx) {
boolean updateResult = StructureLibAPI.markHintParticleError( boolean updateResult = StructureLibAPI.markHintParticleError(
StructureLib.getCurrentPlayer(), StructureLib.getCurrentPlayer(), StructureLib.getCurrentPlayer().worldObj, msg.x, msg.y, msg.z);
StructureLib.getCurrentPlayer().worldObj, if (StructureLibAPI.isDebugEnabled())
msg.x, LOGGER.debug(
msg.y, "Server instructed to mark hint particle at ({}, {}, {}) error, result {}!",
msg.z); msg.x,
if (StructureLibAPI.isDebugEnabled()) LOGGER.debug( msg.y,
"Server instructed to mark hint particle at ({}, {}, {}) error, result {}!", msg.z,
msg.x, updateResult);
msg.y,
msg.z,
updateResult);
return null; return null;
} }
} }
@@ -1,27 +1,22 @@
package com.gtnewhorizon.structurelib.net; package com.gtnewhorizon.structurelib.net;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import org.apache.commons.lang3.tuple.Pair;
import com.gtnewhorizon.structurelib.StructureLib; import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor; import com.gtnewhorizon.structurelib.alignment.constructable.ChannelDataAccessor;
import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger; import com.gtnewhorizon.structurelib.item.ItemConstructableTrigger;
import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import org.apache.commons.lang3.tuple.Pair;
public class SetChannelDataMessage implements IMessage { public class SetChannelDataMessage implements IMessage {
private final List<Map.Entry<String, Integer>> data = new ArrayList<>(); private final List<Map.Entry<String, Integer>> data = new ArrayList<>();
public SetChannelDataMessage() {} public SetChannelDataMessage() {}
@@ -49,7 +44,6 @@ public class SetChannelDataMessage implements IMessage {
} }
public static class Handler implements IMessageHandler<SetChannelDataMessage, IMessage> { public static class Handler implements IMessageHandler<SetChannelDataMessage, IMessage> {
@Override @Override
public IMessage onMessage(SetChannelDataMessage message, MessageContext ctx) { public IMessage onMessage(SetChannelDataMessage message, MessageContext ctx) {
EntityPlayerMP player = ctx.getServerHandler().playerEntity; EntityPlayerMP player = ctx.getServerHandler().playerEntity;
@@ -4,14 +4,12 @@ import static com.gtnewhorizon.structurelib.StructureLib.LOGGER;
import com.gtnewhorizon.structurelib.StructureLib; import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI; import com.gtnewhorizon.structurelib.StructureLibAPI;
import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBuf;
public class UpdateHintParticleMessage implements IMessage { public class UpdateHintParticleMessage implements IMessage {
private int x; private int x;
private short y; private short y;
private int z; private int z;
@@ -55,7 +53,6 @@ public class UpdateHintParticleMessage implements IMessage {
} }
public static class Handler implements IMessageHandler<UpdateHintParticleMessage, IMessage> { public static class Handler implements IMessageHandler<UpdateHintParticleMessage, IMessage> {
@Override @Override
public IMessage onMessage(UpdateHintParticleMessage msg, MessageContext ctx) { public IMessage onMessage(UpdateHintParticleMessage msg, MessageContext ctx) {
boolean updateResult = StructureLibAPI.updateHintParticleTint( boolean updateResult = StructureLibAPI.updateHintParticleTint(
@@ -64,13 +61,16 @@ public class UpdateHintParticleMessage implements IMessage {
msg.x, msg.x,
msg.y, msg.y,
msg.z, msg.z,
new short[] { msg.r, msg.g, msg.b, msg.a, }); new short[] {
if (StructureLibAPI.isDebugEnabled()) LOGGER.debug( msg.r, msg.g, msg.b, msg.a,
"Server instructed to update hint particle at ({}, {}, {}), result {}!", });
msg.x, if (StructureLibAPI.isDebugEnabled())
msg.y, LOGGER.debug(
msg.z, "Server instructed to update hint particle at ({}, {}, {}), result {}!",
updateResult); msg.x,
msg.y,
msg.z,
updateResult);
return null; return null;
} }
} }
@@ -1,23 +1,19 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
/** /**
* Represent the environment in which autoplace of a single element took place. * Represent the environment in which autoplace of a single element took place.
*/ */
public class AutoPlaceEnvironment { public class AutoPlaceEnvironment {
private IItemSource source; private IItemSource source;
private final EntityPlayer actor; private final EntityPlayer actor;
private final Consumer<IChatComponent> chatter; private final Consumer<IChatComponent> chatter;
@@ -27,8 +23,8 @@ public class AutoPlaceEnvironment {
final int[] offsetABC; final int[] offsetABC;
private final int[] baseOffsetABC; private final int[] baseOffsetABC;
public static AutoPlaceEnvironment fromLegacy(IItemSource source, EntityPlayer actor, public static AutoPlaceEnvironment fromLegacy(
Consumer<IChatComponent> chatter) { IItemSource source, EntityPlayer actor, Consumer<IChatComponent> chatter) {
if (source instanceof WrappedIItemSource) { if (source instanceof WrappedIItemSource) {
AutoPlaceEnvironment original = ((WrappedIItemSource) source).container; AutoPlaceEnvironment original = ((WrappedIItemSource) source).container;
// feels like this is extremely likely to cause issues, but this does allow us to recover lost info. // feels like this is extremely likely to cause issues, but this does allow us to recover lost info.
@@ -44,8 +40,13 @@ public class AutoPlaceEnvironment {
return new AutoPlaceEnvironment(source, actor, chatter, null, null, null, null, null); return new AutoPlaceEnvironment(source, actor, chatter, null, null, null, null, null);
} }
AutoPlaceEnvironment(EntityPlayer actor, Consumer<IChatComponent> chatter, IStructureDefinition<?> definition, AutoPlaceEnvironment(
String piece, ExtendedFacing facing, int[] baseOffsetABC) { EntityPlayer actor,
Consumer<IChatComponent> chatter,
IStructureDefinition<?> definition,
String piece,
ExtendedFacing facing,
int[] baseOffsetABC) {
this.source = null; this.source = null;
this.actor = actor; this.actor = actor;
this.chatter = chatter; this.chatter = chatter;
@@ -56,8 +57,14 @@ public class AutoPlaceEnvironment {
this.baseOffsetABC = baseOffsetABC; this.baseOffsetABC = baseOffsetABC;
} }
AutoPlaceEnvironment(IItemSource source, EntityPlayer actor, Consumer<IChatComponent> chatter, AutoPlaceEnvironment(
IStructureDefinition<?> definition, String piece, ExtendedFacing facing, int[] offsetABC, IItemSource source,
EntityPlayer actor,
Consumer<IChatComponent> chatter,
IStructureDefinition<?> definition,
String piece,
ExtendedFacing facing,
int[] offsetABC,
int[] baseOffsetABC) { int[] baseOffsetABC) {
this.source = definition != null && !(source instanceof WrappedIItemSource) this.source = definition != null && !(source instanceof WrappedIItemSource)
? new WrappedIItemSource(this, source) ? new WrappedIItemSource(this, source)
@@ -90,7 +97,8 @@ public class AutoPlaceEnvironment {
} }
public APILevel getAPILevel() { public APILevel getAPILevel() {
return definition == null ? actor instanceof EntityPlayerMP ? APILevel.Legacy : APILevel.LegacyRelaxed return definition == null
? actor instanceof EntityPlayerMP ? APILevel.Legacy : APILevel.LegacyRelaxed
: APILevel.V2; : APILevel.V2;
} }
@@ -102,8 +110,8 @@ public class AutoPlaceEnvironment {
} }
/** /**
* The initiator of actions. for very critical errors you can also just send the error messages here, bypassing any * The initiator of actions. for very critical errors you can also just send the error messages here, bypassing
* filter that {@link #getChatter()} might have. You might want to use * any filter that {@link #getChatter()} might have. You might want to use
* {@link com.gtnewhorizon.structurelib.StructureLibAPI#addThrottledChat(Object, EntityPlayer, IChatComponent, short)} * {@link com.gtnewhorizon.structurelib.StructureLibAPI#addThrottledChat(Object, EntityPlayer, IChatComponent, short)}
* to help reduce spam. * to help reduce spam.
*/ */
@@ -171,7 +179,6 @@ public class AutoPlaceEnvironment {
} }
private static class WrappedIItemSource implements IItemSource { private static class WrappedIItemSource implements IItemSource {
final AutoPlaceEnvironment container; final AutoPlaceEnvironment container;
final IItemSource delegate; final IItemSource delegate;
@@ -214,13 +221,13 @@ public class AutoPlaceEnvironment {
*/ */
public enum APILevel { public enum APILevel {
/** /**
* Implements {@link #getChatter()}, {@link #getActor()} and {@link #getSource()}. {@link #getActor()} is * Implements {@link #getChatter()}, {@link #getActor()} and {@link #getSource()}.
* guaranteed to be an {@link net.minecraft.entity.player.EntityPlayerMP} * {@link #getActor()} is guaranteed to be an {@link net.minecraft.entity.player.EntityPlayerMP}
*/ */
Legacy, Legacy,
/** /**
* Implements {@link #getChatter()}, {@link #getActor()} and {@link #getSource()}. {@link #getActor()} is * Implements {@link #getChatter()}, {@link #getActor()} and {@link #getSource()}.
* <b>NOT</b> guaranteed to be an {@link net.minecraft.entity.player.EntityPlayerMP} * {@link #getActor()} is <b>NOT</b> guaranteed to be an {@link net.minecraft.entity.player.EntityPlayerMP}
*/ */
LegacyRelaxed, LegacyRelaxed,
/** /**
@@ -3,7 +3,6 @@ package com.gtnewhorizon.structurelib.structure;
class ChatThrottleKey { class ChatThrottleKey {
static class NoExplicitChannel { static class NoExplicitChannel {
private static final int hashOffset = NoExplicitChannel.class.hashCode(); private static final int hashOffset = NoExplicitChannel.class.hashCode();
private final String subchannel; private final String subchannel;
@@ -3,7 +3,6 @@ package com.gtnewhorizon.structurelib.structure;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
class DefaultSurvivalBuildEnvironment implements ISurvivalBuildEnvironment { class DefaultSurvivalBuildEnvironment implements ISurvivalBuildEnvironment {
private final IItemSource source; private final IItemSource source;
private final EntityPlayer actor; private final EntityPlayer actor;
@@ -3,6 +3,5 @@ package com.gtnewhorizon.structurelib.structure;
import net.minecraft.world.World; import net.minecraft.world.World;
public interface IBlockPosConsumer { public interface IBlockPosConsumer {
void consume(World world, int x, int y, int z); void consume(World world, int x, int y, int z);
} }
@@ -4,10 +4,9 @@ import net.minecraft.block.Block;
import net.minecraft.world.World; import net.minecraft.world.World;
public interface ICustomBlockSetting { public interface ICustomBlockSetting {
/** /**
* Default block setting calls {@link World#setBlock(int x, int y, int z, Block block, int meta, int updateType)} * Default block setting calls {@link World#setBlock(int x, int y, int z, Block block, int meta, int updateType)} like:
* like: {@code world.setBlock(x,y,z,this/block,meta,2)} where updateType 2 means to update lighting and stuff * {@code world.setBlock(x,y,z,this/block,meta,2)} where updateType 2 means to update lighting and stuff
* *
* @param world world that should be affected * @param world world that should be affected
* @param x x position to set * @param x x position to set
@@ -1,29 +1,25 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import java.util.Map;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import com.gtnewhorizon.structurelib.util.InventoryIterable; import com.gtnewhorizon.structurelib.util.InventoryIterable;
import com.gtnewhorizon.structurelib.util.InventoryUtility; import com.gtnewhorizon.structurelib.util.InventoryUtility;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate; import com.gtnewhorizon.structurelib.util.ItemStackPredicate;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode; import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
import java.util.Map;
import java.util.function.Predicate;
import javax.annotation.Nonnull;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
/** /**
* Represent an item source. Take only, cannot be placed back. * Represent an item source. Take only, cannot be placed back.
*/ */
public interface IItemSource { public interface IItemSource {
/** /**
* Retrieve some amount of items from this item source matching given filter. * Retrieve some amount of items from this item source matching given filter.
* <p> * <p>
* We probably don't need to get a lot of items from this method, so I don't care about the overhead of storing all * We probably don't need to get a lot of items from this method,
* fetched items even if downstream code doesn't need it * so I don't care about the overhead of storing all fetched items even if downstream code doesn't need it
* *
* @param predicate filtering predicate. should return true for ItemStacks that should be added to result collection * @param predicate filtering predicate. should return true for ItemStacks that should be added to result collection
* @param simulate whether to actually commit the modification. true for dry run, false otherwise. * @param simulate whether to actually commit the modification. true for dry run, false otherwise.
@@ -68,11 +64,11 @@ public interface IItemSource {
/** /**
* Take exactly one item. ItemStack given must have a stack size of 1. * Take exactly one item. ItemStack given must have a stack size of 1.
* <p> * <p>
* This is meant to be an optimized version of {@link #takeOne(Predicate, boolean)}. Implementations that support * This is meant to be an optimized version of {@link #takeOne(Predicate, boolean)}.
* item storage indexed by ItemStack can use this to speed up calculation. * Implementations that support item storage indexed by ItemStack can use this to speed up calculation.
* *
* @param stack what item to extract. The NBT tag of this ItemStack is siginifcant and will be considered during * @param stack what item to extract. The NBT tag of this ItemStack is siginifcant and will be
* matching. must have a stack size of 1. * considered during matching. must have a stack size of 1.
* @param simulate whether to actually commit the modification. true for dry run, false otherwise. * @param simulate whether to actually commit the modification. true for dry run, false otherwise.
* @return true if found. false otherwise * @return true if found. false otherwise
* @throws IllegalArgumentException if given stack is invalid, or has a stack size other than 1. * @throws IllegalArgumentException if given stack is invalid, or has a stack size other than 1.
@@ -86,8 +82,8 @@ public interface IItemSource {
/** /**
* Take some item. Will not take item if it cannot find enough items to take. * Take some item. Will not take item if it cannot find enough items to take.
* <p> * <p>
* This is meant to be an optimized version of {@link #takeOne(Predicate, boolean)}. Implementations that support * This is meant to be an optimized version of {@link #takeOne(Predicate, boolean)}.
* indexing off ItemStack can use this to speed up calculation. * Implementations that support indexing off ItemStack can use this to speed up calculation.
* *
* @param stack what item and how many to extract. The NBT tag of this ItemStack is siginifcant and will be * @param stack what item and how many to extract. The NBT tag of this ItemStack is siginifcant and will be
* considered during matching * considered during matching
@@ -114,7 +110,6 @@ public interface IItemSource {
*/ */
static IItemSource fromPlayer(EntityPlayerMP player) { static IItemSource fromPlayer(EntityPlayerMP player) {
return new IItemSource() { return new IItemSource() {
@Nonnull @Nonnull
@Override @Override
public Map<ItemStack, Integer> take(Predicate<ItemStack> p, boolean s, int c) { public Map<ItemStack, Integer> take(Predicate<ItemStack> p, boolean s, int c) {
@@ -3,6 +3,5 @@ package com.gtnewhorizon.structurelib.structure;
import net.minecraft.block.Block; import net.minecraft.block.Block;
public interface ISpecialItemBlock { public interface ISpecialItemBlock {
int getItemMetaFromBlockMeta(Block block, int blockMeta); int getItemMetaFromBlockMeta(Block block, int blockMeta);
} }
@@ -3,28 +3,26 @@ package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.structure.IStructureWalker.ignoreBlockUnloaded; import static com.gtnewhorizon.structurelib.structure.IStructureWalker.ignoreBlockUnloaded;
import static com.gtnewhorizon.structurelib.structure.IStructureWalker.skipBlockUnloaded; import static com.gtnewhorizon.structurelib.structure.IStructureWalker.skipBlockUnloaded;
import java.util.function.Function;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.StructureLib; import com.gtnewhorizon.structurelib.StructureLib;
import com.gtnewhorizon.structurelib.StructureLibAPI; import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable; import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing; import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import java.util.function.Function;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
/** /**
* This is the structure definition of your multi. You will have one of these for each multi. * This is the structure definition of your multi. You will have one of these for each multi.
* *
* <h2>Cache the instances of this class</h2> * <h2>Cache the instances of this class</h2>
* <p> * <p>
* You will construct this definition once per multi, either at class load or at first call to your variant of * You will construct this definition once per multi, either at class load or at first call to your variant of {@code getStructureDefinition()}.
* {@code getStructureDefinition()}. You can use a {@link ClassValue ClassValue&lt;IStructureDefinition&lt;?>>} if you * You can use a {@link ClassValue ClassValue&lt;IStructureDefinition&lt;?>>} if you have a template for subclass.
* have a template for subclass. You can also use {@link StructureUtility#defer(Function) defer()} or its overloads for * You can also use {@link StructureUtility#defer(Function) defer()} or its overloads for simpler cases, but it is
* simpler cases, but it is slightly less performant as it will allocate new objects on each structure check, whereas * slightly less performant as it will allocate new objects on each structure check, whereas {@link ClassValue} will
* {@link ClassValue} will allocate once and cache it onwards. * allocate once and cache it onwards.
* <p> * <p>
* <h2>Constructing</h2> * <h2>Constructing</h2>
* <p> * <p>
@@ -32,39 +30,30 @@ import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
* <p> * <p>
* Builder has two main methods: * Builder has two main methods:
* <ul> * <ul>
* <li>{@link com.gtnewhorizon.structurelib.structure.StructureDefinition.Builder#addShape(String, String[][]) * <li>{@link com.gtnewhorizon.structurelib.structure.StructureDefinition.Builder#addShape(String, String[][]) addShape()}
* addShape()} is a 2d string array describing the layout of structure. You can optionally use * is a 2d string array describing the layout of structure. You can optionally use `StructureUtility#transpose()`
* `StructureUtility#transpose()` to transpose the array to make the structure look nicer in source code. * to transpose the array to make the structure look nicer in source code.
* <li>{@link com.gtnewhorizon.structurelib.structure.StructureDefinition.Builder#addElement(Character, IStructureElement) * <li>{@link com.gtnewhorizon.structurelib.structure.StructureDefinition.Builder#addElement(Character, IStructureElement) addElement()}. It takes a char identifier (mapped to a char in any of {@link com.gtnewhorizon.structurelib.structure.StructureDefinition.Builder#addShape(String, String[][]) addShape()} calls) and a {@link IStructureElement}.
* addElement()}. It takes a char identifier (mapped to a char in any of
* {@link com.gtnewhorizon.structurelib.structure.StructureDefinition.Builder#addShape(String, String[][]) addShape()}
* calls) and a {@link IStructureElement}.
* </ul> * </ul>
* <h2>Position A, B and C</h2> * <h2>Position A, B and C</h2>
* *
* Imagine you stand in front of the controller, with controller facing towards you not rotated or flipped. * Imagine you stand in front of the controller, with controller facing towards you not rotated or flipped.
* <ul> * <ul>
* <li>The "A" position would be the number of blocks on the left side of the controller, not counting controller * <li>The "A" position would be the number of blocks on the left side of the controller, not counting controller itself.</li>
* itself.</li> * <li>The "B" position would be the number of blocks on the top side of the controller, not counting controller itself.</li>
* <li>The "B" position would be the number of blocks on the top side of the controller, not counting controller
* itself.</li>
* <li>The "C" position would be the number of blocks between you and controller, not counting controller itself.</li> * <li>The "C" position would be the number of blocks between you and controller, not counting controller itself.</li>
* </ul> * </ul>
*
* @param <T> Type of the context object. Usually this will be the multiblock controller. * @param <T> Type of the context object. Usually this will be the multiblock controller.
*/ */
public interface IStructureDefinition<T> { public interface IStructureDefinition<T> {
/** /**
* Used internally * Used internally
* <p> * <p>
* Might, but is not required, to throw {@link java.util.NoSuchElementException} if the given structure piece is not * Might, but is not required, to throw {@link java.util.NoSuchElementException} if the given structure piece is not found.
* found.
* *
* @param name same name as for other methods here * @param name same name as for other methods here
* @return the array of elements to process * @return the array of elements to process
* @throws java.util.NoSuchElementException if the given structure piece is not found and the moon phase perfectly * @throws java.util.NoSuchElementException if the given structure piece is not found and the moon phase perfectly matches
* matches
*/ */
IStructureElement<T>[] getStructureFor(String name); IStructureElement<T>[] getStructureFor(String name);
@@ -72,22 +61,30 @@ public interface IStructureDefinition<T> {
/** /**
* Run a structure check. * Run a structure check.
* * @param object context object. usually multiblock controller.
* @param object context object. usually multiblock controller. * @param piece the structure piece's string identifier.
* @param piece the structure piece's string identifier. * @param world the world object this check takes place in.
* @param world the world object this check takes place in. * @param extendedFacing the current structure's orientation.
* @param extendedFacing the current structure's orientation. * @param basePositionX X location of the structure
* @param basePositionX X location of the structure * @param basePositionY Y location of the structure
* @param basePositionY Y location of the structure * @param basePositionZ Z location of the structure
* @param basePositionZ Z location of the structure * @param basePositionA see class javadoc
* @param basePositionA see class javadoc * @param basePositionB see class javadoc
* @param basePositionB see class javadoc * @param basePositionC see class javadoc
* @param basePositionC see class javadoc
* @param forceCheckAllBlocks check all location even if chunk not currently loaded. * @param forceCheckAllBlocks check all location even if chunk not currently loaded.
* @return true if successful, false otherwise * @return true if successful, false otherwise
*/ */
default boolean check(T object, String piece, World world, ExtendedFacing extendedFacing, int basePositionX, default boolean check(
int basePositionY, int basePositionZ, int basePositionA, int basePositionB, int basePositionC, T object,
String piece,
World world,
ExtendedFacing extendedFacing,
int basePositionX,
int basePositionY,
int basePositionZ,
int basePositionA,
int basePositionB,
int basePositionC,
boolean forceCheckAllBlocks) { boolean forceCheckAllBlocks) {
return iterate( return iterate(
object, object,
@@ -107,21 +104,29 @@ public interface IStructureDefinition<T> {
/** /**
* Spawn hint particles. Should not be called on server side. * Spawn hint particles. Should not be called on server side.
* * @param object context object. usually multiblock controller.
* @param object context object. usually multiblock controller. * @param piece the structure piece's string identifier.
* @param piece the structure piece's string identifier. * @param world the world object this check takes place in.
* @param world the world object this check takes place in.
* @param extendedFacing the current structure's orientation. * @param extendedFacing the current structure's orientation.
* @param basePositionX X location of the structure * @param basePositionX X location of the structure
* @param basePositionY Y location of the structure * @param basePositionY Y location of the structure
* @param basePositionZ Z location of the structure * @param basePositionZ Z location of the structure
* @param basePositionA see class javadoc * @param basePositionA see class javadoc
* @param basePositionB see class javadoc * @param basePositionB see class javadoc
* @param basePositionC see class javadoc * @param basePositionC see class javadoc
* @return true if successful, false otherwise * @return true if successful, false otherwise
*/ */
default boolean hints(T object, ItemStack trigger, String piece, World world, ExtendedFacing extendedFacing, default boolean hints(
int basePositionX, int basePositionY, int basePositionZ, int basePositionA, int basePositionB, T object,
ItemStack trigger,
String piece,
World world,
ExtendedFacing extendedFacing,
int basePositionX,
int basePositionY,
int basePositionZ,
int basePositionA,
int basePositionB,
int basePositionC) { int basePositionC) {
return iterate( return iterate(
object, object,
@@ -143,21 +148,30 @@ public interface IStructureDefinition<T> {
* Build the multi in creative mode on a best-effort basis. Does not guarantee the structure is correct after a * Build the multi in creative mode on a best-effort basis. Does not guarantee the structure is correct after a
* successful call. * successful call.
* *
* @param object context object. usually multiblock controller. * @param object context object. usually multiblock controller.
* @param trigger The trigger item that contains channel data. * @param trigger The trigger item that contains channel data.
* @param piece the structure piece's string identifier. * @param piece the structure piece's string identifier.
* @param world the world object this check takes place in. * @param world the world object this check takes place in.
* @param extendedFacing the current structure's orientation. * @param extendedFacing the current structure's orientation.
* @param basePositionX X location of the structure * @param basePositionX X location of the structure
* @param basePositionY Y location of the structure * @param basePositionY Y location of the structure
* @param basePositionZ Z location of the structure * @param basePositionZ Z location of the structure
* @param basePositionA see class javadoc * @param basePositionA see class javadoc
* @param basePositionB see class javadoc * @param basePositionB see class javadoc
* @param basePositionC see class javadoc * @param basePositionC see class javadoc
* @return true if sucessful, false otherwise * @return true if sucessful, false otherwise
*/ */
default boolean build(T object, ItemStack trigger, String piece, World world, ExtendedFacing extendedFacing, default boolean build(
int basePositionX, int basePositionY, int basePositionZ, int basePositionA, int basePositionB, T object,
ItemStack trigger,
String piece,
World world,
ExtendedFacing extendedFacing,
int basePositionX,
int basePositionY,
int basePositionZ,
int basePositionA,
int basePositionB,
int basePositionC) { int basePositionC) {
return iterate( return iterate(
object, object,
@@ -176,29 +190,38 @@ public interface IStructureDefinition<T> {
} }
/** /**
* Call {@link #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)} if * Call {@link #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)} if {@code hintsOnly},
* {@code hintsOnly}, call * call {@link #hints(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)} otherwise.
* {@link #hints(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)} otherwise.
* *
* @param object context object. usually multiblock controller. * @param object context object. usually multiblock controller.
* @param trigger The trigger item that contains channel data. * @param trigger The trigger item that contains channel data.
* @param piece the structure piece's string identifier. * @param piece the structure piece's string identifier.
* @param world the world object this check takes place in. * @param world the world object this check takes place in.
* @param extendedFacing the current structure's orientation. * @param extendedFacing the current structure's orientation.
* @param basePositionX X location of the structure * @param basePositionX X location of the structure
* @param basePositionY Y location of the structure * @param basePositionY Y location of the structure
* @param basePositionZ Z location of the structure * @param basePositionZ Z location of the structure
* @param basePositionA see class javadoc * @param basePositionA see class javadoc
* @param basePositionB see class javadoc * @param basePositionB see class javadoc
* @param basePositionC see class javadoc * @param basePositionC see class javadoc
* @param hintsOnly whether to spawn hints or do creative build. * @param hintsOnly whether to spawn hints or do creative build.
* @return true if sucessful, false otherwise * @return true if sucessful, false otherwise
* @see #hints(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int) * @see #hints(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)
* @see #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int) * @see #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)
*/ */
default boolean buildOrHints(T object, ItemStack trigger, String piece, World world, ExtendedFacing extendedFacing, default boolean buildOrHints(
int basePositionX, int basePositionY, int basePositionZ, int basePositionA, int basePositionB, T object,
int basePositionC, boolean hintsOnly) { ItemStack trigger,
String piece,
World world,
ExtendedFacing extendedFacing,
int basePositionX,
int basePositionY,
int basePositionZ,
int basePositionA,
int basePositionB,
int basePositionC,
boolean hintsOnly) {
return iterate( return iterate(
object, object,
trigger, trigger,
@@ -218,31 +241,44 @@ public interface IStructureDefinition<T> {
/** /**
* Cause a survival build. * Cause a survival build.
* *
* @param object context object. usually multiblock controller. * @param object context object. usually multiblock controller.
* @param trigger The trigger item that contains channel data. * @param trigger The trigger item that contains channel data.
* @param piece the structure piece's string identifier. * @param piece the structure piece's string identifier.
* @param world the world object this check takes place in. * @param world the world object this check takes place in.
* @param extendedFacing the current structure's orientation. * @param extendedFacing the current structure's orientation.
* @param basePositionX X location of the structure * @param basePositionX X location of the structure
* @param basePositionY Y location of the structure * @param basePositionY Y location of the structure
* @param basePositionZ Z location of the structure * @param basePositionZ Z location of the structure
* @param basePositionA see class javadoc * @param basePositionA see class javadoc
* @param basePositionB see class javadoc * @param basePositionB see class javadoc
* @param basePositionC see class javadoc * @param basePositionC see class javadoc
* @param elementBudget build up to this many elements * @param elementBudget build up to this many elements
* @param source from where to drain resource * @param source from where to drain resource
* @param actor source of action * @param actor source of action
* @param check whether {@link IStructureElement#check(Object, World, int, int, int)} should be called if * @param check whether {@link IStructureElement#check(Object, World, int, int, int)} should be called if anything
* anything would be placed. use with caution. if in doubt, call * would be placed. use with caution.
* {@link #check(Object, String, World, ExtendedFacing, int, int, int, int, int, int, boolean)} * if in doubt, call {@link #check(Object, String, World, ExtendedFacing, int, int, int, int, int, int, boolean)}
* after this call and set this parameter to false * after this call and set this parameter to false
* @return number of elements built, or -1 if structure done * @return number of elements built, or -1 if structure done
* @see #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int) * @see #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)
*/ */
@Deprecated @Deprecated
default int survivalBuild(T object, ItemStack trigger, String piece, World world, ExtendedFacing extendedFacing, default int survivalBuild(
int basePositionX, int basePositionY, int basePositionZ, int basePositionA, int basePositionB, T object,
int basePositionC, int elementBudget, IItemSource source, EntityPlayerMP actor, boolean check) { ItemStack trigger,
String piece,
World world,
ExtendedFacing extendedFacing,
int basePositionX,
int basePositionY,
int basePositionZ,
int basePositionA,
int basePositionB,
int basePositionC,
int elementBudget,
IItemSource source,
EntityPlayerMP actor,
boolean check) {
EntityPlayer realActor; EntityPlayer realActor;
if (actor == null) { if (actor == null) {
realActor = ISurvivalConstructable.__get_player(); realActor = ISurvivalConstructable.__get_player();
@@ -270,29 +306,41 @@ public interface IStructureDefinition<T> {
/** /**
* Cause a survival build. * Cause a survival build.
* *
* @param object context object. usually multiblock controller. * @param object context object. usually multiblock controller.
* @param trigger The trigger item that contains channel data. * @param trigger The trigger item that contains channel data.
* @param piece the structure piece's string identifier. * @param piece the structure piece's string identifier.
* @param world the world object this check takes place in. * @param world the world object this check takes place in.
* @param extendedFacing the current structure's orientation. * @param extendedFacing the current structure's orientation.
* @param basePositionX X location of the structure * @param basePositionX X location of the structure
* @param basePositionY Y location of the structure * @param basePositionY Y location of the structure
* @param basePositionZ Z location of the structure * @param basePositionZ Z location of the structure
* @param basePositionA see class javadoc * @param basePositionA see class javadoc
* @param basePositionB see class javadoc * @param basePositionB see class javadoc
* @param basePositionC see class javadoc * @param basePositionC see class javadoc
* @param elementBudget build up to this many elements * @param elementBudget build up to this many elements
* @param env build environment. * @param env build environment.
* @param check whether {@link IStructureElement#check(Object, World, int, int, int)} should be called if * @param check whether {@link IStructureElement#check(Object, World, int, int, int)} should be called if anything
* anything would be placed. use with caution. if in doubt, call * would be placed. use with caution.
* {@link IStructureDefinition#check(Object, String, World, ExtendedFacing, int, int, int, int, int, int, boolean)} * if in doubt, call {@link IStructureDefinition#check(Object, String, World, ExtendedFacing, int, int, int, int, int, int, boolean)}
* after this call and set this parameter to false * after this call and set this parameter to false
* @return number of elements built, or -1 if structure done * @return number of elements built, or -1 if structure done
* @see #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int) * @see #build(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int)
*/ */
default int survivalBuild(T object, ItemStack trigger, String piece, World world, ExtendedFacing extendedFacing, default int survivalBuild(
int basePositionX, int basePositionY, int basePositionZ, int basePositionA, int basePositionB, T object,
int basePositionC, int elementBudget, ISurvivalBuildEnvironment env, boolean check) { ItemStack trigger,
String piece,
World world,
ExtendedFacing extendedFacing,
int basePositionX,
int basePositionY,
int basePositionZ,
int basePositionA,
int basePositionB,
int basePositionC,
int elementBudget,
ISurvivalBuildEnvironment env,
boolean check) {
SurvivalBuildStructureWalker<T> walker = new SurvivalBuildStructureWalker<>( SurvivalBuildStructureWalker<T> walker = new SurvivalBuildStructureWalker<>(
object, object,
trigger, trigger,
@@ -301,7 +349,7 @@ public interface IStructureDefinition<T> {
this, this,
piece, piece,
extendedFacing, extendedFacing,
new int[] { basePositionA, basePositionB, basePositionC }, new int[] {basePositionA, basePositionB, basePositionC},
check); check);
StructureUtility.iterateV2( StructureUtility.iterateV2(
getStructureFor(piece), getStructureFor(piece),
@@ -320,28 +368,37 @@ public interface IStructureDefinition<T> {
/** /**
* Low level utility. * Low level utility.
* * @param object context object. usually multiblock controller.
* @param object context object. usually multiblock controller. * @param trigger The trigger item that contains channel data.
* @param trigger The trigger item that contains channel data. * @param elements the structure piece
* @param elements the structure piece * @param world the world object this check takes place in.
* @param world the world object this check takes place in. * @param extendedFacing the current structure's orientation.
* @param extendedFacing the current structure's orientation. * @param basePositionX X location of the structure
* @param basePositionX X location of the structure * @param basePositionY Y location of the structure
* @param basePositionY Y location of the structure * @param basePositionZ Z location of the structure
* @param basePositionZ Z location of the structure * @param basePositionA see class javadoc
* @param basePositionA see class javadoc * @param basePositionB see class javadoc
* @param basePositionB see class javadoc * @param basePositionC see class javadoc
* @param basePositionC see class javadoc * @param hintsOnly whether to spawn hints or do creative build. no effect if {@code checkBlocksIfNotNullForceCheckAllIfTrue} is not null.
* @param hintsOnly whether to spawn hints or do creative build. no effect if * @param checkBlocksIfNotNullForceCheckAllIfTrue creative build or spawn hints if null. Force check not loaded chunk
* {@code checkBlocksIfNotNullForceCheckAllIfTrue} is not null. * if true. Check only loaded chunk is false.
* @param checkBlocksIfNotNullForceCheckAllIfTrue creative build or spawn hints if null. Force check not loaded
* chunk if true. Check only loaded chunk is false.
* @return true if iteration completed successfully. * @return true if iteration completed successfully.
* @param <T> type of context object. * @param <T> type of context object.
*/ */
static <T> boolean iterate(T object, ItemStack trigger, IStructureElement<T>[] elements, World world, static <T> boolean iterate(
ExtendedFacing extendedFacing, int basePositionX, int basePositionY, int basePositionZ, int basePositionA, T object,
int basePositionB, int basePositionC, boolean hintsOnly, Boolean checkBlocksIfNotNullForceCheckAllIfTrue) { ItemStack trigger,
IStructureElement<T>[] elements,
World world,
ExtendedFacing extendedFacing,
int basePositionX,
int basePositionY,
int basePositionZ,
int basePositionA,
int basePositionB,
int basePositionC,
boolean hintsOnly,
Boolean checkBlocksIfNotNullForceCheckAllIfTrue) {
if (!world.isRemote && hintsOnly) { if (!world.isRemote && hintsOnly) {
return false; return false;
} }
@@ -376,8 +433,8 @@ public interface IStructureDefinition<T> {
"check force"); "check force");
} }
if (StructureLibAPI.isDebugEnabled() && success) { if (StructureLibAPI.isDebugEnabled() && success) {
StructureLib.LOGGER StructureLib.LOGGER.info(
.info("Multi [" + basePositionX + ", " + basePositionY + ", " + basePositionZ + "] pass"); "Multi [" + basePositionX + ", " + basePositionY + ", " + basePositionZ + "] pass");
} }
return success; return success;
} else { } else {
@@ -420,7 +477,6 @@ public interface IStructureDefinition<T> {
/** /**
* Create a new instance of builder. * Create a new instance of builder.
*
* @param <T> type of context object * @param <T> type of context object
*/ */
static <T> StructureDefinition.Builder<T> builder() { static <T> StructureDefinition.Builder<T> builder() {
@@ -3,14 +3,15 @@ package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.StructureLib.LOGGER; import static com.gtnewhorizon.structurelib.StructureLib.LOGGER;
import static com.gtnewhorizon.structurelib.StructureLib.PANIC_MODE; import static com.gtnewhorizon.structurelib.StructureLib.PANIC_MODE;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
@@ -20,16 +21,11 @@ import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
/** /**
* Use StructureUtility to instantiate. These are the building blocks for your {@link IStructureDefinition}. It * Use StructureUtility to instantiate. These are the building blocks for your {@link IStructureDefinition}. It represents
* represents what a particular element can be and how this particular element should be autoplaced. * what a particular element can be and how this particular element should be autoplaced.
*/ */
public interface IStructureElement<T> { public interface IStructureElement<T> {
boolean check(T t, World world, int x, int y, int z); boolean check(T t, World world, int x, int y, int z);
boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger); boolean spawnHint(T t, World world, int x, int y, int z, ItemStack trigger);
@@ -39,27 +35,35 @@ public interface IStructureElement<T> {
/** /**
* Try place the block by taking resource from given IItemSource. * Try place the block by taking resource from given IItemSource.
* <p> * <p>
* You might want to use * You might want to use {@link StructureUtility#survivalPlaceBlock(Block, int, World, int, int, int, IItemSource, net.minecraft.entity.player.EntityPlayer)}
* {@link StructureUtility#survivalPlaceBlock(Block, int, World, int, int, int, IItemSource, net.minecraft.entity.player.EntityPlayer)}
* or its overloads to implement this. * or its overloads to implement this.
* *
* @param trigger trigger item * @param trigger trigger item
* @param s drain resources from this place * @param s drain resources from this place
* @param actor source of action. for very critical errors you can also just send the error messages here, * @param actor source of action. for very critical errors you can also just send the error messages here, bypassing
* bypassing any filter that chatter might have. * any filter that chatter might have.
* @param chatter send error messages here. Caller will choose an appropriate way to forward it to player if the * @param chatter send error messages here. Caller will choose an appropriate way to forward it to player if the
* other fallbacks also fails. * other fallbacks also fails.
* @deprecated caller should call the non deprecated overload. implementor for reusable {@link IStructureElement} * @deprecated caller should call the non deprecated overload. implementor for reusable {@link IStructureElement}
* should still implement this. implementor for private implementations can freely ignore this as long * should still implement this. implementor for private implementations can freely ignore this as long as you know
* as you know the caller will not call this overload. * the caller will not call this overload.
*/ */
@Deprecated @Deprecated
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, default PlaceResult survivalPlaceBlock(
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { T t,
World world,
int x,
int y,
int z,
ItemStack trigger,
IItemSource s,
EntityPlayerMP actor,
Consumer<IChatComponent> chatter) {
if (PANIC_MODE) throw new RuntimeException("Panic Tripwire hit"); if (PANIC_MODE) throw new RuntimeException("Panic Tripwire hit");
if (StructureLibAPI.isDebugEnabled()) LOGGER.error( if (StructureLibAPI.isDebugEnabled())
"Default implementation of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}", LOGGER.error(
getClass().getName()); "Default implementation of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}",
getClass().getName());
if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT; if (!StructureLibAPI.isBlockTriviallyReplaceable(world, x, y, z, actor)) return PlaceResult.REJECT;
return PlaceResult.SKIP; return PlaceResult.SKIP;
} }
@@ -69,64 +73,54 @@ public interface IStructureElement<T> {
* <p> * <p>
* <b>BY OVERRIDING THIS TO NULL, YOU ACKNOWLEDGE THAT THE {@link #check(Object, World, int, int, int)} OF THIS * <b>BY OVERRIDING THIS TO NULL, YOU ACKNOWLEDGE THAT THE {@link #check(Object, World, int, int, int)} OF THIS
* CLASS IS SIDE EFFECT FREE AND CAN HAVE ITS CHECK CALLED WITHOUT BREAKING ANYTHING. OTHERWISE OVERRIDE THE * CLASS IS SIDE EFFECT FREE AND CAN HAVE ITS CHECK CALLED WITHOUT BREAKING ANYTHING. OTHERWISE OVERRIDE THE
* {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)} TO PROVIDE A * {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)} TO PROVIDE A SIDEEFFECT
* SIDEEFFECT FREE {@link PlaceResult#SKIP}.</b> * FREE {@link PlaceResult#SKIP}.</b>
* <p> * <p>
* It should be noticed that this filter is only advisory and the actual * It should be noticed that this filter is only advisory and the actual {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
* {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)} or * or {@link #check(Object, World, int, int, int)} are free to reject/accept/place blocks not contained in this list,
* {@link #check(Object, World, int, int, int)} are free to reject/accept/place blocks not contained in this list,
* e.g. when the element can be placed anywhere in the structure, but no more than 3 overall; when the structure * e.g. when the element can be placed anywhere in the structure, but no more than 3 overall; when the structure
* element cannot know all blocks it will accept at the time of calling; when this is backed by a legacy * element cannot know all blocks it will accept at the time of calling; when this is backed by a legacy
* {@link IStructureElement} that just didn't implement this API. * {@link IStructureElement} that just didn't implement this API.
* *
* @param trigger trigger item * @param trigger trigger item
* @param env autoplacing environment * @param env autoplacing environment
* @return null if not implemented, otherwise an instance describing what kind of blocks will be placed by * @return null if not implemented, otherwise an instance describing what kind of blocks will be placed by {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
* {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}
*/ */
@Nullable @Nullable
default BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger, default BlocksToPlace getBlocksToPlace(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
return null; return null;
} }
/** /**
* Try place the block by taking resource from given {@link IItemSource}. * Try place the block by taking resource from given {@link IItemSource}.
* <p> * <p>
* You might want to use * You might want to use {@link StructureUtility#survivalPlaceBlock(Block, int, World, int, int, int, IItemSource, net.minecraft.entity.player.EntityPlayer)}
* {@link StructureUtility#survivalPlaceBlock(Block, int, World, int, int, int, IItemSource, net.minecraft.entity.player.EntityPlayer)}
* or its overloads to implement this. * or its overloads to implement this.
* <p> * <p>
* The default implementation provided will * The default implementation provided will
* <ol> * <ol>
* <li>Get {@link BlocksToPlace} via * <li>Get {@link BlocksToPlace} via {@link #getBlocksToPlace(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}. If not null
* {@link #getBlocksToPlace(Object, World, int, int, int, ItemStack, AutoPlaceEnvironment)}. If not null * <ol>
* <ol> * <li>call {@link #check(Object, World, int, int, int)}. If this returns {@code true}, {@link PlaceResult#SKIP} will be returned without further action.</li>
* <li>call {@link #check(Object, World, int, int, int)}. If this returns {@code true}, {@link PlaceResult#SKIP} * <li>Use the {@link BlocksToPlace} retrieved earlier and passed in {@link IItemSource} to determine an item to place</li>
* will be returned without further action.</li> * <li>Hand over control to {@link StructureUtility#survivalPlaceBlock(ItemStack, NBTMode, NBTTagCompound, boolean, World, int, int, int, IItemSource, EntityPlayer, Consumer)}</li>
* <li>Use the {@link BlocksToPlace} retrieved earlier and passed in {@link IItemSource} to determine an item to * </ol>
* place</li> * </li>
* <li>Hand over control to * <li>Call legacy {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, IItemSource, EntityPlayerMP, Consumer)} if {@code env.getActor()} contains an {@link EntityPlayerMP}</li>
* {@link StructureUtility#survivalPlaceBlock(ItemStack, NBTMode, NBTTagCompound, boolean, World, int, int, int, IItemSource, EntityPlayer, Consumer)}</li> * <li>Emit warning under debug mode (or throw exception under panic mode), then return {@link PlaceResult#SKIP}</li>
* </ol>
* </li>
* <li>Call legacy
* {@link #survivalPlaceBlock(Object, World, int, int, int, ItemStack, IItemSource, EntityPlayerMP, Consumer)} if
* {@code env.getActor()} contains an {@link EntityPlayerMP}</li>
* <li>Emit warning under debug mode (or throw exception under panic mode), then return
* {@link PlaceResult#SKIP}</li>
* </ol> * </ol>
* It should be noticed that the default implementation is likely to cause unexpected issues if the * It should be noticed that the default implementation is likely to cause unexpected issues if the
* {@link #check(Object, World, int, int, int)} is not side effect free, or is not idempotent. E.g. the * {@link #check(Object, World, int, int, int)} is not side effect free, or is not idempotent.
* {@link #check(Object, World, int, int, int)} will add current coord to a {@link java.util.List}. As this method * E.g. the {@link #check(Object, World, int, int, int)} will add current coord to a {@link java.util.List}. As
* might be invoked at a location that is already accepted, this will cause the machine to have multiple of this * this method might be invoked at a location that is already accepted, this will cause the machine to have multiple
* coord in its list. * of this coord in its list.
* *
* @param trigger trigger item * @param trigger trigger item
* @param env autoplacing environment * @param env autoplacing environment
*/ */
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, default PlaceResult survivalPlaceBlock(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
BlocksToPlace e = getBlocksToPlace(t, world, x, y, z, trigger, env); BlocksToPlace e = getBlocksToPlace(t, world, x, y, z, trigger, env);
IItemSource source = env.getSource(); IItemSource source = env.getSource();
EntityPlayer actor = env.getActor(); EntityPlayer actor = env.getActor();
@@ -136,41 +130,22 @@ public interface IStructureElement<T> {
if (e.getStacks() == null) { if (e.getStacks() == null) {
ItemStack taken = source.takeOne(e.getPredicate(), true); ItemStack taken = source.takeOne(e.getPredicate(), true);
return StructureUtility.survivalPlaceBlock( return StructureUtility.survivalPlaceBlock(
taken, taken, NBTMode.EXACT, taken.stackTagCompound, true, world, x, y, z, source, actor, chatter);
NBTMode.EXACT,
taken.stackTagCompound,
true,
world,
x,
y,
z,
source,
actor,
chatter);
} }
for (ItemStack stack : e.getStacks()) { for (ItemStack stack : e.getStacks()) {
if (!source.takeOne(stack, true)) continue; if (!source.takeOne(stack, true)) continue;
return StructureUtility.survivalPlaceBlock( return StructureUtility.survivalPlaceBlock(
stack, stack, NBTMode.EXACT, stack.stackTagCompound, true, world, x, y, z, source, actor, chatter);
NBTMode.EXACT,
stack.stackTagCompound,
true,
world,
x,
y,
z,
source,
actor,
chatter);
} }
return PlaceResult.REJECT; return PlaceResult.REJECT;
} }
if (actor instanceof EntityPlayerMP) if (actor instanceof EntityPlayerMP)
return survivalPlaceBlock(t, world, x, y, z, trigger, source, (EntityPlayerMP) actor, chatter); return survivalPlaceBlock(t, world, x, y, z, trigger, source, (EntityPlayerMP) actor, chatter);
if (PANIC_MODE) throw new RuntimeException("Panic Tripwire hit"); if (PANIC_MODE) throw new RuntimeException("Panic Tripwire hit");
if (StructureLibAPI.isDebugEnabled()) LOGGER.info( if (StructureLibAPI.isDebugEnabled())
"Fallback shim code of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}", LOGGER.info(
getClass().getName()); "Fallback shim code of survivalPlaceBlock hit! Things aren't going to work well! IStructureElement class: {}",
getClass().getName());
return PlaceResult.SKIP; return PlaceResult.SKIP;
} }
@@ -222,19 +197,18 @@ public interface IStructureElement<T> {
enum PlaceResult { enum PlaceResult {
/** /**
* This element either exists already, or does not yet have an implementation for survivalPlaceBlock, or some * This element either exists already, or does not yet have an implementation for survivalPlaceBlock, or
* other unforeseen situations. TODO this definition doesn't seem right. Should we separate SKIP from EXISTS, or * some other unforeseen situations.
* SKIP from ERROR? * TODO this definition doesn't seem right. Should we separate SKIP from EXISTS, or SKIP from ERROR?
*/ */
SKIP, SKIP,
/** /**
* This element's space is occupied by other stuff and require player attention, or player missing required * This element's space is occupied by other stuff and require player attention, or player missing required resource,
* resource, or the block cannot be placed due to obscure mechanisms, or some other unforeseen situations. * or the block cannot be placed due to obscure mechanisms, or some other unforeseen situations.
*/ */
REJECT, REJECT,
/** /**
* Autoplace cannot proceed within this tick. To proceed further would require stopping the placement and wait * Autoplace cannot proceed within this tick. To proceed further would require stopping the placement and wait for next round.
* for next round.
*/ */
STOP, STOP,
/** /**
@@ -250,7 +224,6 @@ public interface IStructureElement<T> {
} }
final class BlocksToPlace { final class BlocksToPlace {
public static final BlocksToPlace errored = createEmpty(); public static final BlocksToPlace errored = createEmpty();
private final Predicate<ItemStack> predicate; private final Predicate<ItemStack> predicate;
private final Iterable<ItemStack> stacks; private final Iterable<ItemStack> stacks;
@@ -1,24 +1,20 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import com.google.common.collect.Iterables;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Predicate; import java.util.function.Predicate;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
import com.google.common.collect.Iterables;
/** /**
* Use StructureUtility to instantiate * Use StructureUtility to instantiate
*/ */
public interface IStructureElementChain<T> extends IStructureElement<T> { public interface IStructureElementChain<T> extends IStructureElement<T> {
IStructureElement<T>[] fallbacks(); IStructureElement<T>[] fallbacks();
@Override @Override
@@ -53,8 +49,8 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
@Nullable @Nullable
@Override @Override
default BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger, default BlocksToPlace getBlocksToPlace(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
Predicate<ItemStack> predicate = null; Predicate<ItemStack> predicate = null;
List<Iterable<ItemStack>> is = new ArrayList<>(); List<Iterable<ItemStack>> is = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) { for (IStructureElement<T> fallback : fallbacks()) {
@@ -69,8 +65,16 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, default PlaceResult survivalPlaceBlock(
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { T t,
World world,
int x,
int y,
int z,
ItemStack trigger,
IItemSource s,
EntityPlayerMP actor,
Consumer<IChatComponent> chatter) {
boolean haveSkip = false; boolean haveSkip = false;
List<IChatComponent> bufferedNoise = new ArrayList<>(); List<IChatComponent> bufferedNoise = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) { for (IStructureElement<T> fallback : fallbacks()) {
@@ -92,13 +96,13 @@ public interface IStructureElementChain<T> extends IStructureElement<T> {
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, default PlaceResult survivalPlaceBlock(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
boolean haveSkip = false; boolean haveSkip = false;
List<IChatComponent> bufferedNoise = new ArrayList<>(); List<IChatComponent> bufferedNoise = new ArrayList<>();
for (IStructureElement<T> fallback : fallbacks()) { for (IStructureElement<T> fallback : fallbacks()) {
PlaceResult result = fallback PlaceResult result =
.survivalPlaceBlock(t, world, x, y, z, trigger, env.withChatter(bufferedNoise::add)); fallback.survivalPlaceBlock(t, world, x, y, z, trigger, env.withChatter(bufferedNoise::add));
switch (result) { switch (result) {
case REJECT: case REJECT:
break; break;
@@ -1,14 +1,12 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import java.util.function.Consumer; import java.util.function.Consumer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
public interface IStructureElementCheckOnly<T> extends IStructureElement<T> { public interface IStructureElementCheckOnly<T> extends IStructureElement<T> {
@Override @Override
default boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) { default boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return false; return false;
@@ -20,14 +18,22 @@ public interface IStructureElementCheckOnly<T> extends IStructureElement<T> {
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, default PlaceResult survivalPlaceBlock(
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { T t,
World world,
int x,
int y,
int z,
ItemStack trigger,
IItemSource s,
EntityPlayerMP actor,
Consumer<IChatComponent> chatter) {
return PlaceResult.SKIP; return PlaceResult.SKIP;
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, default PlaceResult survivalPlaceBlock(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
return PlaceResult.SKIP; return PlaceResult.SKIP;
} }
} }
@@ -3,5 +3,4 @@ package com.gtnewhorizon.structurelib.structure;
/** /**
* Use StructureUtility to instantiate * Use StructureUtility to instantiate
*/ */
public interface IStructureElementDeferred<T> extends IStructureElement<T> { public interface IStructureElementDeferred<T> extends IStructureElement<T> {}
}
@@ -1,28 +1,34 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import java.util.function.Consumer; import java.util.function.Consumer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
public interface IStructureElementNoPlacement<T> extends IStructureElement<T> { public interface IStructureElementNoPlacement<T> extends IStructureElement<T> {
@Override @Override
default boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) { default boolean placeBlock(T t, World world, int x, int y, int z, ItemStack trigger) {
return false; return false;
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, default PlaceResult survivalPlaceBlock(
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { T t,
World world,
int x,
int y,
int z,
ItemStack trigger,
IItemSource s,
EntityPlayerMP actor,
Consumer<IChatComponent> chatter) {
return PlaceResult.REJECT; return PlaceResult.REJECT;
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, default PlaceResult survivalPlaceBlock(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
return PlaceResult.REJECT; return PlaceResult.REJECT;
} }
@@ -1,7 +1,6 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import java.util.function.Consumer; import java.util.function.Consumer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
@@ -11,7 +10,6 @@ import net.minecraft.world.World;
* Use StructureUtility to instantiate * Use StructureUtility to instantiate
*/ */
interface IStructureNavigate<T> extends IStructureElement<T> { interface IStructureNavigate<T> extends IStructureElement<T> {
@Override @Override
default boolean check(T t, World world, int x, int y, int z) { default boolean check(T t, World world, int x, int y, int z) {
return true; return true;
@@ -28,14 +26,22 @@ interface IStructureNavigate<T> extends IStructureElement<T> {
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, default PlaceResult survivalPlaceBlock(
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { T t,
World world,
int x,
int y,
int z,
ItemStack trigger,
IItemSource s,
EntityPlayerMP actor,
Consumer<IChatComponent> chatter) {
return PlaceResult.SKIP; return PlaceResult.SKIP;
} }
@Override @Override
default PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, default PlaceResult survivalPlaceBlock(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
return PlaceResult.SKIP; return PlaceResult.SKIP;
} }
@@ -3,25 +3,23 @@ package com.gtnewhorizon.structurelib.structure;
import net.minecraft.world.World; import net.minecraft.world.World;
interface IStructureWalker<T> { interface IStructureWalker<T> {
boolean visit(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c); boolean visit(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c);
default boolean blockNotLoaded(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, default boolean blockNotLoaded(
int c) { IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c) {
return false; return false;
} }
static <T> IStructureWalker<T> ignoreBlockUnloaded(IStructureWalker<T> walker) { static <T> IStructureWalker<T> ignoreBlockUnloaded(IStructureWalker<T> walker) {
return new IStructureWalker<T>() { return new IStructureWalker<T>() {
@Override @Override
public boolean visit(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c) { public boolean visit(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c) {
return walker.visit(element, world, x, y, z, a, b, c); return walker.visit(element, world, x, y, z, a, b, c);
} }
@Override @Override
public boolean blockNotLoaded(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, public boolean blockNotLoaded(
int c) { IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c) {
return walker.visit(element, world, x, y, z, a, b, c); return walker.visit(element, world, x, y, z, a, b, c);
} }
}; };
@@ -29,15 +27,14 @@ interface IStructureWalker<T> {
static <T> IStructureWalker<T> skipBlockUnloaded(IStructureWalker<T> walker) { static <T> IStructureWalker<T> skipBlockUnloaded(IStructureWalker<T> walker) {
return new IStructureWalker<T>() { return new IStructureWalker<T>() {
@Override @Override
public boolean visit(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c) { public boolean visit(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c) {
return walker.visit(element, world, x, y, z, a, b, c); return walker.visit(element, world, x, y, z, a, b, c);
} }
@Override @Override
public boolean blockNotLoaded(IStructureElement<T> element, World world, int x, int y, int z, int a, int b, public boolean blockNotLoaded(
int c) { IStructureElement<T> element, World world, int x, int y, int z, int a, int b, int c) {
return true; return true;
} }
}; };
@@ -1,31 +1,25 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.world.World; import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
/* /*
* Architecture notes: this should never get any callback from survival build. All structure significant code belongs * Architecture notes: this should never get any callback from survival build. All structure significant code belongs
* within the IStructureElement. This will make the user easier to maintain the IStructureDefinition. Structure Element * within the IStructureElement. This will make the user easier to maintain the IStructureDefinition.
* knows the most about what this structure element should do, not the caller. * Structure Element knows the most about what this structure element should do, not the caller.
*/ */
public interface ISurvivalBuildEnvironment { public interface ISurvivalBuildEnvironment {
/** /**
* Get the source of the items. This will be invoked exactly once per structure element build. * Get the source of the items. This will be invoked exactly once per structure element build.
* <p> * <p>
* If the call chain ever got into the old API, this will be called at least once per * If the call chain ever got into the old API, this will be called at least once per {@link IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, ISurvivalBuildEnvironment, boolean)} call.
* {@link IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, ISurvivalBuildEnvironment, boolean)}
* call.
*/ */
IItemSource getSource(); IItemSource getSource();
/** /**
* Get the origin of action. This will be invoked at least once per * Get the origin of action. This will be invoked at least once per {@link IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, ISurvivalBuildEnvironment, boolean)} call.
* {@link IStructureDefinition#survivalBuild(Object, ItemStack, String, World, ExtendedFacing, int, int, int, int, int, int, int, ISurvivalBuildEnvironment, boolean)}
* call.
*/ */
EntityPlayer getActor(); EntityPlayer getActor();
@@ -9,6 +9,5 @@ import net.minecraft.block.Block;
*/ */
@FunctionalInterface @FunctionalInterface
public interface ITierConverter<TIER> { public interface ITierConverter<TIER> {
TIER convert(Block block, int meta); TIER convert(Block block, int meta);
} }
@@ -11,6 +11,5 @@ package com.gtnewhorizon.structurelib.structure;
* @param <CTX> the temporary state context * @param <CTX> the temporary state context
*/ */
public interface IWithExtendedContext<CTX> { public interface IWithExtendedContext<CTX> {
CTX getCurrentContext(); CTX getCurrentContext();
} }
@@ -2,16 +2,13 @@ package com.gtnewhorizon.structurelib.structure;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
import net.minecraft.world.World; import net.minecraft.world.World;
class LazyStructureElement<T> implements IStructureElementDeferred<T> { class LazyStructureElement<T> implements IStructureElementDeferred<T> {
private Function<T, IStructureElement<T>> to; private Function<T, IStructureElement<T>> to;
private IStructureElement<T> elem; private IStructureElement<T> elem;
@@ -44,20 +41,28 @@ class LazyStructureElement<T> implements IStructureElementDeferred<T> {
@Nullable @Nullable
@Override @Override
public BlocksToPlace getBlocksToPlace(T t, World world, int x, int y, int z, ItemStack trigger, public BlocksToPlace getBlocksToPlace(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
return get(t).getBlocksToPlace(t, world, x, y, z, trigger, env); return get(t).getBlocksToPlace(t, world, x, y, z, trigger, env);
} }
@Override @Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, public PlaceResult survivalPlaceBlock(
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { T t,
World world,
int x,
int y,
int z,
ItemStack trigger,
IItemSource s,
EntityPlayerMP actor,
Consumer<IChatComponent> chatter) {
return get(t).survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, chatter); return get(t).survivalPlaceBlock(t, world, x, y, z, trigger, s, actor, chatter);
} }
@Override @Override
public PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, public PlaceResult survivalPlaceBlock(
AutoPlaceEnvironment env) { T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env) {
return get(t).survivalPlaceBlock(t, world, x, y, z, trigger, env); return get(t).survivalPlaceBlock(t, world, x, y, z, trigger, env);
} }
} }
@@ -2,13 +2,11 @@ package com.gtnewhorizon.structurelib.structure;
import static com.gtnewhorizon.structurelib.structure.StructureUtility.*; import static com.gtnewhorizon.structurelib.structure.StructureUtility.*;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.gtnewhorizon.structurelib.util.Vec3Impl;
public class StructureDefinition<T> implements IStructureDefinition<T> { public class StructureDefinition<T> implements IStructureDefinition<T> {
private final Map<Character, IStructureElement<T>> elements; private final Map<Character, IStructureElement<T>> elements;
private final Map<String, String> shapes; private final Map<String, String> shapes;
private final Map<String, IStructureElement<T>[]> structures; private final Map<String, IStructureElement<T>[]> structures;
@@ -18,8 +16,11 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
return new Builder<>(); return new Builder<>();
} }
private StructureDefinition(Map<Character, IStructureElement<T>> elements, Map<String, String> shapes, private StructureDefinition(
Map<String, IStructureElement<T>[]> structures, Map<String, Set<Vec3Impl>> occupiedSpaces) { Map<Character, IStructureElement<T>> elements,
Map<String, String> shapes,
Map<String, IStructureElement<T>[]> structures,
Map<String, Set<Vec3Impl>> occupiedSpaces) {
this.elements = elements; this.elements = elements;
this.shapes = shapes; this.shapes = shapes;
this.structures = structures; this.structures = structures;
@@ -27,7 +28,6 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
} }
public static class Builder<T> { public static class Builder<T> {
private static final char A = '\uA000'; private static final char A = '\uA000';
private static final char B = '\uB000'; private static final char B = '\uB000';
private static final char C = '\uC000'; private static final char C = '\uC000';
@@ -54,10 +54,11 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
/** /**
* Adds shape. Shape is a two-dimensional string array. Each <b>character</b> inside any of these strings will * Adds shape. Shape is a two-dimensional string array. Each <b>character</b> inside any of these strings will
* be later mapped to a particular type of {@link IStructureElement} as indicated by * be later mapped to a particular type of {@link IStructureElement} as indicated by {@link #addElement(Character, IStructureElement)}.
* {@link #addElement(Character, IStructureElement)}.
* <p> * <p>
* next char is next block(a) next string is next line(b) next string[] is next slice(c) * next char is next block(a)
* next string is next line(b)
* next string[] is next slice(c)
* <p> * <p>
* There are a few special reserved characters that are pre-mapped to some common structure elements * There are a few special reserved characters that are pre-mapped to some common structure elements
* <ul> * <ul>
@@ -70,8 +71,7 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
* <p> * <p>
* *
* @param name unlocalized/code name * @param name unlocalized/code name
* @param structurePiece generated or written struct - DO NOT STORE IT ANYWHERE, or at least set them to null * @param structurePiece generated or written struct - DO NOT STORE IT ANYWHERE, or at least set them to null afterwards
* afterwards
* @return this builder * @return this builder
*/ */
public Builder<T> addShape(String name, String[][] structurePiece) { public Builder<T> addShape(String name, String[][] structurePiece) {
@@ -170,25 +170,22 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
public IStructureDefinition<T> build() { public IStructureDefinition<T> build() {
Map<String, IStructureElement<T>[]> structures = compileStructureMap(); Map<String, IStructureElement<T>[]> structures = compileStructureMap();
return new StructureDefinition<>( return new StructureDefinition<>(
new HashMap<>(elements), new HashMap<>(elements), new HashMap<>(shapes), structures, occupiedSpaces);
new HashMap<>(shapes),
structures,
occupiedSpaces);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
private Map<String, IStructureElement<T>[]> compileElementSetMap() { private Map<String, IStructureElement<T>[]> compileElementSetMap() {
Set<Integer> missing = findMissing(); Set<Integer> missing = findMissing();
if (missing.isEmpty()) { if (missing.isEmpty()) {
return shapes.entrySet().stream().collect( return shapes.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
Collectors.toMap( .chars()
Map.Entry::getKey, .mapToObj(c -> (char) c)
e -> e.getValue().chars().mapToObj(c -> (char) c).distinct().map(elements::get) .distinct()
.toArray(IStructureElement[]::new))); .map(elements::get)
.toArray(IStructureElement[]::new)));
} else { } else {
throw new RuntimeException( throw new RuntimeException("Missing Structure Element bindings for (chars as integers): "
"Missing Structure Element bindings for (chars as integers): " + Arrays.toString(missing.toArray()));
+ Arrays.toString(missing.toArray()));
} }
} }
@@ -196,21 +193,22 @@ public class StructureDefinition<T> implements IStructureDefinition<T> {
private Map<String, IStructureElement<T>[]> compileStructureMap() { private Map<String, IStructureElement<T>[]> compileStructureMap() {
Set<Integer> missing = findMissing(); Set<Integer> missing = findMissing();
if (missing.isEmpty()) { if (missing.isEmpty()) {
return shapes.entrySet().stream().collect( return shapes.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue()
Collectors.toMap( .chars()
Map.Entry::getKey, .mapToObj(c -> elements.get((char) c))
e -> e.getValue().chars().mapToObj(c -> elements.get((char) c)) .toArray(IStructureElement[]::new)));
.toArray(IStructureElement[]::new)));
} else { } else {
throw new RuntimeException( throw new RuntimeException("Missing Structure Element bindings for (chars as integers): "
"Missing Structure Element bindings for (chars as integers): " + Arrays.toString(missing.toArray()));
+ Arrays.toString(missing.toArray()));
} }
} }
private Set<Integer> findMissing() { private Set<Integer> findMissing() {
return shapes.values().stream().flatMapToInt(CharSequence::chars) return shapes.values().stream()
.filter(i -> !elements.containsKey((char) i)).boxed().collect(Collectors.toSet()); .flatMapToInt(CharSequence::chars)
.filter(i -> !elements.containsKey((char) i))
.boxed()
.collect(Collectors.toSet());
} }
} }
@@ -1,7 +1,6 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import java.util.function.Consumer; import java.util.function.Consumer;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import net.minecraft.util.IChatComponent; import net.minecraft.util.IChatComponent;
@@ -11,16 +10,23 @@ import net.minecraft.world.World;
* Internal bridge class for easing implementation * Internal bridge class for easing implementation
*/ */
abstract class StructureElement_Bridge<T> implements IStructureElement<T> { abstract class StructureElement_Bridge<T> implements IStructureElement<T> {
// seal the deprecated method to prevent accidental overrides // seal the deprecated method to prevent accidental overrides
@Deprecated @Deprecated
@Override @Override
public final PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, IItemSource s, public final PlaceResult survivalPlaceBlock(
EntityPlayerMP actor, Consumer<IChatComponent> chatter) { T t,
World world,
int x,
int y,
int z,
ItemStack trigger,
IItemSource s,
EntityPlayerMP actor,
Consumer<IChatComponent> chatter) {
return survivalPlaceBlock(t, world, x, y, z, trigger, AutoPlaceEnvironment.fromLegacy(s, actor, chatter)); return survivalPlaceBlock(t, world, x, y, z, trigger, AutoPlaceEnvironment.fromLegacy(s, actor, chatter));
} }
// clear the default implementation. we don't need that. // clear the default implementation. we don't need that.
public abstract PlaceResult survivalPlaceBlock(T t, World world, int x, int y, int z, ItemStack trigger, public abstract PlaceResult survivalPlaceBlock(
AutoPlaceEnvironment env); T t, World world, int x, int y, int z, ItemStack trigger, AutoPlaceEnvironment env);
} }
File diff suppressed because it is too large. Load diff
@@ -1,14 +1,12 @@
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import com.gtnewhorizon.structurelib.StructureLibAPI; import com.gtnewhorizon.structurelib.StructureLibAPI;
import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing; import com.gtnewhorizon.structurelib.alignment.enumerable.ExtendedFacing;
import com.gtnewhorizon.structurelib.structure.IStructureElement.PlaceResult; import com.gtnewhorizon.structurelib.structure.IStructureElement.PlaceResult;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> { class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
final T object; final T object;
final ItemStack trigger; final ItemStack trigger;
private final int elementBudget; private final int elementBudget;
@@ -18,9 +16,16 @@ class SurvivalBuildStructureWalker<T> implements IStructureWalker<T> {
private final AutoPlaceEnvironment env; private final AutoPlaceEnvironment env;
public SurvivalBuildStructureWalker(T object, ItemStack trigger, int elementBudget, public SurvivalBuildStructureWalker(
ISurvivalBuildEnvironment params, IStructureDefinition<?> definition, String piece, ExtendedFacing facing, T object,
int[] baseOffsetABC, boolean check) { ItemStack trigger,
int elementBudget,
ISurvivalBuildEnvironment params,
IStructureDefinition<?> definition,
String piece,
ExtendedFacing facing,
int[] baseOffsetABC,
boolean check) {
this.object = object; this.object = object;
this.trigger = trigger; this.trigger = trigger;
this.elementBudget = elementBudget; this.elementBudget = elementBudget;
@@ -3,7 +3,6 @@ package com.gtnewhorizon.structurelib.structure.adders;
import net.minecraft.block.Block; import net.minecraft.block.Block;
public interface IBlockAdder<T> { public interface IBlockAdder<T> {
/** /**
* Callback on block added, needs to check if block is valid (and add it) * Callback on block added, needs to check if block is valid (and add it)
* *
@@ -3,7 +3,6 @@ package com.gtnewhorizon.structurelib.structure.adders;
import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntity;
public interface ITileAdder<T> { public interface ITileAdder<T> {
/** /**
* Callback to add hatch, needs to check if tile is valid (and add it) * Callback to add hatch, needs to check if tile is valid (and add it)
* *
@@ -1,7 +1,7 @@
/** /**
* This package provide support for multiblock structure checking. * This package provide support for multiblock structure checking.
* <p> * <p>
* All public stuff in this package and its subpackages are considered part of the public API. Backwards compatibility * All public stuff in this package and its subpackages are considered part of the public API.
* is maintained to the maximum extend possible. * Backwards compatibility is maintained to the maximum extend possible.
*/ */
package com.gtnewhorizon.structurelib.structure; package com.gtnewhorizon.structurelib.structure;
@@ -2,12 +2,10 @@ package com.gtnewhorizon.structurelib.util;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import net.minecraft.inventory.IInventory; import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
public class InventoryIterable<Inv extends IInventory> implements Iterable<ItemStack> { public class InventoryIterable<Inv extends IInventory> implements Iterable<ItemStack> {
private final Inv inv; private final Inv inv;
private final int maxSlot; private final int maxSlot;
@@ -27,7 +25,6 @@ public class InventoryIterable<Inv extends IInventory> implements Iterable<ItemS
@Override @Override
public Iterator<ItemStack> iterator() { public Iterator<ItemStack> iterator() {
return new Iterator<ItemStack>() { return new Iterator<ItemStack>() {
private int ptr = 0; private int ptr = 0;
@Override @Override
@@ -1,27 +1,32 @@
/** /**
* Copyright (c) 2022, glee8e This file is part of StructureLib. * Copyright (c) 2022, glee8e
* This file is part of StructureLib.
* <p> * <p>
* StructureLib is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General * StructureLib is free software; you can redistribute it and/or modify
* Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any * it under the terms of the GNU Lesser General Public License as published by
* later version. * the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* <p> * <p>
* StructureLib is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * StructureLib is distributed in the hope that it will be useful,
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * but WITHOUT ANY WARRANTY; without even the implied warranty of
* details. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* <p> * <p>
* You should have received a copy of the GNU Lesser General Public License along with Foobar; if not, write to the Free * You should have received a copy of the GNU Lesser General Public License
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * along with Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/ */
package com.gtnewhorizon.structurelib.util; package com.gtnewhorizon.structurelib.util;
import com.gtnewhorizon.gtnhlib.util.map.ItemStackMap;
import com.gtnewhorizon.structurelib.util.InventoryUtility.ItemStackExtractor.APIType;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
import java.util.*; import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import javax.annotation.Nonnull; import javax.annotation.Nonnull;
import javax.annotation.Nullable; import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Items; import net.minecraft.init.Items;
@@ -29,15 +34,10 @@ import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.InventoryEnderChest; import net.minecraft.inventory.InventoryEnderChest;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import com.gtnewhorizon.gtnhlib.util.map.ItemStackMap;
import com.gtnewhorizon.structurelib.util.InventoryUtility.ItemStackExtractor.APIType;
import com.gtnewhorizon.structurelib.util.ItemStackPredicate.NBTMode;
/** /**
* This class is part of API, but is not stable. Use at your own risk. * This class is part of API, but is not stable. Use at your own risk.
*/ */
public class InventoryUtility { public class InventoryUtility {
private static final SortedRegistry<ItemStackExtractor> stackExtractors = new SortedRegistry<>(); private static final SortedRegistry<ItemStackExtractor> stackExtractors = new SortedRegistry<>();
private static final List<Predicate<? super EntityPlayerMP>> enableEnder = new CopyOnWriteArrayList<>(); private static final List<Predicate<? super EntityPlayerMP>> enableEnder = new CopyOnWriteArrayList<>();
/** /**
@@ -47,7 +47,6 @@ public class InventoryUtility {
static { static {
inventoryProviders.register("5000-main-inventory", new InventoryProvider<InventoryIterable<InventoryPlayer>>() { inventoryProviders.register("5000-main-inventory", new InventoryProvider<InventoryIterable<InventoryPlayer>>() {
@Override @Override
public InventoryIterable<InventoryPlayer> getInventory(EntityPlayerMP player) { public InventoryIterable<InventoryPlayer> getInventory(EntityPlayerMP player) {
return new InventoryIterable<>(player.inventory, player.inventory.mainInventory.length); return new InventoryIterable<>(player.inventory, player.inventory.mainInventory.length);
@@ -60,9 +59,8 @@ public class InventoryUtility {
inv.getInventory().player.inventoryContainer.detectAndSendChanges(); inv.getInventory().player.inventoryContainer.detectAndSendChanges();
} }
}); });
inventoryProviders inventoryProviders.register(
.register("7000-ender-inventory", new InventoryProvider<InventoryIterable<InventoryEnderChest>>() { "7000-ender-inventory", new InventoryProvider<InventoryIterable<InventoryEnderChest>>() {
@Override @Override
public InventoryIterable<InventoryEnderChest> getInventory(EntityPlayerMP player) { public InventoryIterable<InventoryEnderChest> getInventory(EntityPlayerMP player) {
if (enableEnder.stream().anyMatch(p -> p.test(player))) if (enableEnder.stream().anyMatch(p -> p.test(player)))
@@ -88,8 +86,8 @@ public class InventoryUtility {
stackExtractors.register(key, val); stackExtractors.register(key, val);
} }
public static <Inv extends IInventory> void registerStackExtractor(String key, public static <Inv extends IInventory> void registerStackExtractor(
Function<ItemStack, ? extends Inv> extractor) { String key, Function<ItemStack, ? extends Inv> extractor) {
registerStackExtractor(key, newItemStackProvider(extractor)); registerStackExtractor(key, newItemStackProvider(extractor));
} }
@@ -97,8 +95,8 @@ public class InventoryUtility {
inventoryProviders.register(key, val); inventoryProviders.register(key, val);
} }
public static <Inv extends IInventory> void registerInventoryProvider(String key, public static <Inv extends IInventory> void registerInventoryProvider(
Function<EntityPlayerMP, ? extends Inv> extractor) { String key, Function<EntityPlayerMP, ? extends Inv> extractor) {
registerInventoryProvider(key, newInventoryProvider(extractor)); registerInventoryProvider(key, newInventoryProvider(extractor));
} }
@@ -109,7 +107,6 @@ public class InventoryUtility {
public static <Inv extends IInventory> InventoryProvider<InventoryIterable<Inv>> newInventoryProvider( public static <Inv extends IInventory> InventoryProvider<InventoryIterable<Inv>> newInventoryProvider(
Function<EntityPlayerMP, ? extends Inv> extractor) { Function<EntityPlayerMP, ? extends Inv> extractor) {
return new InventoryProvider<InventoryIterable<Inv>>() { return new InventoryProvider<InventoryIterable<Inv>>() {
@Override @Override
public InventoryIterable<Inv> getInventory(EntityPlayerMP player) { public InventoryIterable<Inv> getInventory(EntityPlayerMP player) {
Inv inv = extractor.apply(player); Inv inv = extractor.apply(player);
@@ -125,26 +122,24 @@ public class InventoryUtility {
public static ItemStackExtractor newItemStackProvider(Function<ItemStack, ? extends IInventory> extractor) { public static ItemStackExtractor newItemStackProvider(Function<ItemStack, ? extends IInventory> extractor) {
return new ItemStackExtractor() { return new ItemStackExtractor() {
@Override @Override
public boolean isAPIImplemented(APIType type) { public boolean isAPIImplemented(APIType type) {
return type == APIType.MAIN; return type == APIType.MAIN;
} }
@Override @Override
public int takeFromStack(Predicate<ItemStack> predicate, boolean simulate, int count, public int takeFromStack(
ItemStackCounter store, ItemStack stack, ItemStack filter, EntityPlayerMP player) { Predicate<ItemStack> predicate,
boolean simulate,
int count,
ItemStackCounter store,
ItemStack stack,
ItemStack filter,
EntityPlayerMP player) {
IInventory inv = extractor.apply(stack); IInventory inv = extractor.apply(stack);
if (inv == null) return 0; if (inv == null) return 0;
int found = takeFromInventory( int found = takeFromInventory(
new InventoryIterable<>(inv), new InventoryIterable<>(inv), predicate, simulate, count, store, filter, player, false);
predicate,
simulate,
count,
store,
filter,
player,
false);
if (found > 0) inv.markDirty(); if (found > 0) inv.markDirty();
return found; return found;
} }
@@ -152,8 +147,8 @@ public class InventoryUtility {
} }
/** /**
* take count amount of stacks that matches given filter. might take partial amount of stuff, so simulation is * take count amount of stacks that matches given filter. might take partial amount of stuff, so simulation is suggested
* suggested if you ever need to take more than one. * if you ever need to take more than one.
* *
* @param player source of stacks * @param player source of stacks
* @param predicate item stack filter * @param predicate item stack filter
@@ -161,8 +156,8 @@ public class InventoryUtility {
* @param count let's hope int size is enough... * @param count let's hope int size is enough...
* @return amount taken. never negative nor bigger than count... * @return amount taken. never negative nor bigger than count...
*/ */
public static Map<ItemStack, Integer> takeFromInventory(EntityPlayerMP player, Predicate<ItemStack> predicate, public static Map<ItemStack, Integer> takeFromInventory(
boolean simulate, int count) { EntityPlayerMP player, Predicate<ItemStack> predicate, boolean simulate, int count) {
ItemStackCounterImpl store = new ItemStackCounterImpl(); ItemStackCounterImpl store = new ItemStackCounterImpl();
int sum = 0; int sum = 0;
for (InventoryProvider<?> provider : inventoryProviders) { for (InventoryProvider<?> provider : inventoryProviders) {
@@ -173,8 +168,8 @@ public class InventoryUtility {
} }
/** /**
* take count amount of stacks that matches given filter. might take partial amount of stuff, so simulation is * take count amount of stacks that matches given filter. might take partial amount of stuff, so simulation is suggested
* suggested if you ever need to take more than one. * if you ever need to take more than one.
* *
* @param player source of stacks * @param player source of stacks
* @param filter the precise type of item to extract. stackSize matters * @param filter the precise type of item to extract. stackSize matters
@@ -194,9 +189,14 @@ public class InventoryUtility {
} }
// workaround java generics issue // workaround java generics issue
private static <R extends Iterable<ItemStack>> int takeFromPlayer(EntityPlayerMP player, private static <R extends Iterable<ItemStack>> int takeFromPlayer(
Predicate<ItemStack> predicate, boolean simulate, int count, ItemStackCounterImpl store, EntityPlayerMP player,
InventoryProvider<R> provider, ItemStack filter) { Predicate<ItemStack> predicate,
boolean simulate,
int count,
ItemStackCounterImpl store,
InventoryProvider<R> provider,
ItemStack filter) {
R inv = provider.getInventory(player); R inv = provider.getInventory(player);
if (inv == null) return 0; if (inv == null) return 0;
int taken = takeFromInventory(inv, predicate, simulate, count, store, filter, player, true); int taken = takeFromInventory(inv, predicate, simulate, count, store, filter, player, true);
@@ -215,23 +215,29 @@ public class InventoryUtility {
* @param recursive do recursive lookup using {@link #getStackExtractors() stack extractors} * @param recursive do recursive lookup using {@link #getStackExtractors() stack extractors}
* @return amount taken. never negative nor bigger than count... * @return amount taken. never negative nor bigger than count...
*/ */
public static Map<ItemStack, Integer> takeFromInventory(Iterable<ItemStack> inv, Predicate<ItemStack> predicate, public static Map<ItemStack, Integer> takeFromInventory(
boolean simulate, int count, boolean recursive) { Iterable<ItemStack> inv, Predicate<ItemStack> predicate, boolean simulate, int count, boolean recursive) {
ItemStackCounterImpl store = new ItemStackCounterImpl(); ItemStackCounterImpl store = new ItemStackCounterImpl();
takeFromInventory(inv, predicate, simulate, count, store, null, null, recursive); takeFromInventory(inv, predicate, simulate, count, store, null, null, recursive);
return store.getStore(); return store.getStore();
} }
private static int takeFromInventory(@Nonnull Iterable<ItemStack> inv, @Nonnull Predicate<ItemStack> predicate, private static int takeFromInventory(
boolean simulate, int count, @Nonnull ItemStackCounter store, @Nullable ItemStack filter, @Nonnull Iterable<ItemStack> inv,
@Nullable EntityPlayerMP player, boolean recursive) { @Nonnull Predicate<ItemStack> predicate,
boolean simulate,
int count,
@Nonnull ItemStackCounter store,
@Nullable ItemStack filter,
@Nullable EntityPlayerMP player,
boolean recursive) {
int found = 0; int found = 0;
ItemStack copiedFilter = null; ItemStack copiedFilter = null;
if (filter != null) { if (filter != null) {
copiedFilter = new ItemStack(filter.getItem(), filter.stackSize, Items.feather.getDamage(filter)); copiedFilter = new ItemStack(filter.getItem(), filter.stackSize, Items.feather.getDamage(filter));
copiedFilter.setTagCompound(filter.stackTagCompound); copiedFilter.setTagCompound(filter.stackTagCompound);
} }
for (Iterator<ItemStack> iterator = inv.iterator(); iterator.hasNext();) { for (Iterator<ItemStack> iterator = inv.iterator(); iterator.hasNext(); ) {
ItemStack stack = iterator.next(); ItemStack stack = iterator.next();
// invalid stack // invalid stack
if (stack == null || stack.getItem() == null || stack.stackSize <= 0) continue; if (stack == null || stack.getItem() == null || stack.stackSize <= 0) continue;
@@ -266,10 +272,9 @@ public class InventoryUtility {
} }
public interface OptimizedExtractor { public interface OptimizedExtractor {
/** /**
* Extract a particular type of item. The extractor can choose to not return all items contained within this * Extract a particular type of item. The extractor can choose to not return all items contained within this item
* item as long as it makes sense, but the author should inform the player of this. * as long as it makes sense, but the author should inform the player of this.
* <p> * <p>
* Whether optimized extractor do recursive extraction is at the discretion of implementor. * Whether optimized extractor do recursive extraction is at the discretion of implementor.
* *
@@ -283,14 +288,12 @@ public class InventoryUtility {
} }
public interface InventoryProvider<R extends Iterable<ItemStack>> { public interface InventoryProvider<R extends Iterable<ItemStack>> {
R getInventory(EntityPlayerMP player); R getInventory(EntityPlayerMP player);
void markDirty(R inv); void markDirty(R inv);
} }
public interface ItemStackExtractor { public interface ItemStackExtractor {
enum APIType { enum APIType {
MAIN, MAIN,
EXTRACT_ONE_STACK, EXTRACT_ONE_STACK,
@@ -299,13 +302,13 @@ public class InventoryUtility {
boolean isAPIImplemented(APIType type); boolean isAPIImplemented(APIType type);
/** /**
* Extract a particular type of item. The extractor can choose to not return all items contained within this * Extract a particular type of item. The extractor can choose to not return all items contained within this item
* item as long as it makes sense, but the author should inform the player of this. * as long as it makes sense, but the author should inform the player of this.
* <p> * <p>
* Whether this method does recursive extraction is at the discretion of implementor. * Whether this method does recursive extraction is at the discretion of implementor.
* *
* @param predicate the main filtering predicate. never null. It's assumed predicate always returns true on * @param predicate the main filtering predicate. never null. It's assumed predicate always returns true on filter,
* filter, if that is not null * if that is not null
* @param store where to store extracted items. Should increment the * @param store where to store extracted items. Should increment the
* @param source from where an extraction should be attempted * @param source from where an extraction should be attempted
* @param filter stack to extract. should not be mutated! match the NBT tag using EXACT mode. might be null. * @param filter stack to extract. should not be mutated! match the NBT tag using EXACT mode. might be null.
@@ -313,12 +316,18 @@ public class InventoryUtility {
* @param player executor of extraction, or null if from a machine * @param player executor of extraction, or null if from a machine
* @return amount extracted, or -1 if this is not implemented * @return amount extracted, or -1 if this is not implemented
*/ */
int takeFromStack(Predicate<ItemStack> predicate, boolean simulate, int count, ItemStackCounter store, int takeFromStack(
ItemStack source, ItemStack filter, EntityPlayerMP player); Predicate<ItemStack> predicate,
boolean simulate,
int count,
ItemStackCounter store,
ItemStack source,
ItemStack filter,
EntityPlayerMP player);
/** /**
* Extract a particular type of item. The extractor can choose to not return all items contained within this * Extract a particular type of item. The extractor can choose to not return all items contained within this item
* item as long as it makes sense, but the author should inform the player of this. * as long as it makes sense, but the author should inform the player of this.
* <p> * <p>
* Whether this method does recursive extraction is at the discretion of implementor. * Whether this method does recursive extraction is at the discretion of implementor.
* *
@@ -334,15 +343,20 @@ public class InventoryUtility {
static ItemStackExtractor createOnlyOptimized(@Nonnull OptimizedExtractor optimizedExtractor) { static ItemStackExtractor createOnlyOptimized(@Nonnull OptimizedExtractor optimizedExtractor) {
return new ItemStackExtractor() { return new ItemStackExtractor() {
@Override @Override
public boolean isAPIImplemented(APIType type) { public boolean isAPIImplemented(APIType type) {
return type == APIType.EXTRACT_ONE_STACK; return type == APIType.EXTRACT_ONE_STACK;
} }
@Override @Override
public int takeFromStack(Predicate<ItemStack> predicate, boolean simulate, int count, public int takeFromStack(
ItemStackCounter store, ItemStack stack, ItemStack filter, EntityPlayerMP player) { Predicate<ItemStack> predicate,
boolean simulate,
int count,
ItemStackCounter store,
ItemStack stack,
ItemStack filter,
EntityPlayerMP player) {
return 0; return 0;
} }
@@ -355,7 +369,6 @@ public class InventoryUtility {
} }
public interface ItemStackCounter { public interface ItemStackCounter {
/** /**
* Add some amount of stack. Note stackSize is used instead of stack.stackSize. * Add some amount of stack. Note stackSize is used instead of stack.stackSize.
*/ */
@@ -363,7 +376,6 @@ public class InventoryUtility {
} }
private static class ItemStackCounterImpl implements ItemStackCounter { private static class ItemStackCounterImpl implements ItemStackCounter {
private final Map<ItemStack, Integer> store = new ItemStackMap<>(true); private final Map<ItemStack, Integer> store = new ItemStackMap<>(true);
@Override @Override
@@ -1,11 +1,9 @@
package com.gtnewhorizon.structurelib.util; package com.gtnewhorizon.structurelib.util;
import java.util.Iterator; import java.util.Iterator;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
public class ItemStackArrayIterable implements Iterable<ItemStack> { public class ItemStackArrayIterable implements Iterable<ItemStack> {
private final ItemStack[] stacks; private final ItemStack[] stacks;
public ItemStackArrayIterable(ItemStack[] stacks) { public ItemStackArrayIterable(ItemStack[] stacks) {
@@ -19,7 +17,6 @@ public class ItemStackArrayIterable implements Iterable<ItemStack> {
@Override @Override
public Iterator<ItemStack> iterator() { public Iterator<ItemStack> iterator() {
return new Iterator<ItemStack>() { return new Iterator<ItemStack>() {
private int ptr = 0; private int ptr = 0;
@Override @Override
@@ -3,7 +3,6 @@ package com.gtnewhorizon.structurelib.util;
import java.util.Objects; import java.util.Objects;
import java.util.function.BiPredicate; import java.util.function.BiPredicate;
import java.util.function.Predicate; import java.util.function.Predicate;
import net.minecraft.block.Block; import net.minecraft.block.Block;
import net.minecraft.init.Items; import net.minecraft.init.Items;
import net.minecraft.item.Item; import net.minecraft.item.Item;
@@ -12,7 +11,6 @@ import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
public final class ItemStackPredicate implements Predicate<ItemStack> { public final class ItemStackPredicate implements Predicate<ItemStack> {
public static ItemStackPredicate from(Item item) { public static ItemStackPredicate from(Item item) {
return new ItemStackPredicate(item); return new ItemStackPredicate(item);
} }
@@ -22,7 +20,8 @@ public final class ItemStackPredicate implements Predicate<ItemStack> {
} }
public static ItemStackPredicate from(ItemStack itemStack, NBTMode mode) { public static ItemStackPredicate from(ItemStack itemStack, NBTMode mode) {
return new ItemStackPredicate(itemStack.getItem()).setMeta(Items.feather.getDamage(itemStack)) return new ItemStackPredicate(itemStack.getItem())
.setMeta(Items.feather.getDamage(itemStack))
.setTag(mode, itemStack.stackTagCompound); .setTag(mode, itemStack.stackTagCompound);
} }
@@ -64,16 +63,13 @@ public final class ItemStackPredicate implements Predicate<ItemStack> {
} }
public enum NBTMode implements BiPredicate<NBTTagCompound, NBTTagCompound> { public enum NBTMode implements BiPredicate<NBTTagCompound, NBTTagCompound> {
IGNORE { IGNORE {
@Override @Override
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) { public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
return true; return true;
} }
}, },
IN { IN {
@Override @Override
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) { public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
if (lhs == null || lhs.hasNoTags()) return true; if (lhs == null || lhs.hasNoTags()) return true;
@@ -91,7 +87,6 @@ public final class ItemStackPredicate implements Predicate<ItemStack> {
} }
}, },
EXACT { EXACT {
@Override @Override
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) { public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
if (lhs != null && lhs.hasNoTags()) lhs = null; if (lhs != null && lhs.hasNoTags()) lhs = null;
@@ -100,7 +95,6 @@ public final class ItemStackPredicate implements Predicate<ItemStack> {
} }
}, },
IGNORE_KNOWN_INSIGNIFICANT_TAGS { IGNORE_KNOWN_INSIGNIFICANT_TAGS {
@Override @Override
public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) { public boolean test(NBTTagCompound lhs, NBTTagCompound rhs) {
// fast path for empty tags // fast path for empty tags
@@ -111,8 +105,8 @@ public final class ItemStackPredicate implements Predicate<ItemStack> {
return EXACT.test(lhs, rhs); return EXACT.test(lhs, rhs);
} }
}; };
private static final String[] KNOWN_INSIGNIFICANT_TAGS = {
private static final String[] KNOWN_INSIGNIFICANT_TAGS = { "display", // TODO expand/refine this "display", // TODO expand/refine this
}; };
} }
} }
@@ -1,14 +1,12 @@
package com.gtnewhorizon.structurelib.util; package com.gtnewhorizon.structurelib.util;
import java.util.Set; import java.util.Set;
import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagCompound;
/** /**
* not related to a certain mod! * not related to a certain mod!
*/ */
public class MiscUtils { public class MiscUtils {
private MiscUtils() {} private MiscUtils() {}
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@@ -4,7 +4,6 @@ import java.util.*;
import java.util.function.Consumer; import java.util.function.Consumer;
public class SortedRegistry<V> implements Iterable<V> { public class SortedRegistry<V> implements Iterable<V> {
private final NavigableMap<String, V> store = new TreeMap<>(); private final NavigableMap<String, V> store = new TreeMap<>();
/** /**
* Store stuff in an array for faster iteration access than a red black tree * Store stuff in an array for faster iteration access than a red black tree
@@ -3,12 +3,10 @@ package com.gtnewhorizon.structurelib.util;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.function.Function; import java.util.function.Function;
import net.minecraft.dispenser.IPosition; import net.minecraft.dispenser.IPosition;
import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.common.util.ForgeDirection;
public class Vec3Impl implements Comparable<Vec3Impl> { public class Vec3Impl implements Comparable<Vec3Impl> {
public static final Vec3Impl NULL_VECTOR = new Vec3Impl(0, 0, 0); public static final Vec3Impl NULL_VECTOR = new Vec3Impl(0, 0, 0);
private static final Map<Vec3Impl, Vec3Impl> pool = new HashMap<>(); private static final Map<Vec3Impl, Vec3Impl> pool = new HashMap<>();
private final int val0; private final int val0;
@@ -71,7 +69,8 @@ public class Vec3Impl implements Comparable<Vec3Impl> {
} }
public Vec3Impl offset(ForgeDirection facing, int n) { public Vec3Impl offset(ForgeDirection facing, int n) {
return n == 0 ? this return n == 0
? this
: new Vec3Impl(val0 + facing.offsetX * n, val1 + facing.offsetY * n, val2 + facing.offsetZ * n); : new Vec3Impl(val0 + facing.offsetX * n, val1 + facing.offsetY * n, val2 + facing.offsetZ * n);
} }
@@ -1,20 +1,37 @@
package com.gtnewhorizon.structurelib.util; package com.gtnewhorizon.structurelib.util;
/* /*
* A subclass of java.util.random that implements the Xorshift random number generator <p> - it is 30% faster than the A subclass of java.util.random that implements the Xorshift random number
* generator from Java's library - it produces random sequences of higher quality than java.util.Random - this class generator
* also provides a clone() function <p> Usage: XSRandom rand = new XSRandom(); //Instantiation x = rand.nextInt(); <p>
* //pull a random number <p> To use the class in legacy code, you may also instantiate an XSRandom object and assign it - it is 30% faster than the generator from Java's library - it produces
* to a java.util.Random object: java.util.Random rand = new XSRandom(); <p> for an explanation of the algorithm, see random sequences of higher quality than java.util.Random - this class also
* http://demesos.blogspot.com/2011/09/pseudo-random-number-generators.html provides a clone() function
* @author Wilfried Elmenreich University of Klagenfurt/Lakeside Labs http://www.elmenreich.tk <p> This code is released <p>
* under the GNU Lesser General Public License Version 3 http://www.gnu.org/licenses/lgpl-3.0.txt Usage: XSRandom rand = new XSRandom(); //Instantiation x = rand.nextInt();
*/ //pull a random number
<p>
To use the class in legacy code, you may also instantiate an XSRandom object
and assign it to a java.util.Random object: java.util.Random rand = new
XSRandom();
<p>
for an explanation of the algorithm, see
http://demesos.blogspot.com/2011/09/pseudo-random-number-generators.html
@author Wilfried Elmenreich University of Klagenfurt/Lakeside Labs
* http://www.elmenreich.tk
* <p>
* This code is released under the GNU Lesser General Public License Version 3
* http://www.gnu.org/licenses/lgpl-3.0.txt
*/
import java.util.Random; import java.util.Random;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
/** /**
* XSTR - Xorshift ThermiteRandom Modified by Bogdan-G 03.06.2016 version 0.0.4 * XSTR - Xorshift ThermiteRandom
* Modified by Bogdan-G
* 03.06.2016
* version 0.0.4
*/ */
public class XSTR extends Random { public class XSTR extends Random {
@@ -23,11 +40,10 @@ public class XSTR extends Random {
private static final long GAMMA = 0x9e3779b97f4a7c15L; private static final long GAMMA = 0x9e3779b97f4a7c15L;
private static final int PROBE_INCREMENT = 0x9e3779b9; private static final int PROBE_INCREMENT = 0x9e3779b9;
private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL; private static final long SEEDER_INCREMENT = 0xbb67ae8584caa73bL;
private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53) private static final double DOUBLE_UNIT = 0x1.0p-53; // 1.0 / (1L << 53)
private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24) private static final float FLOAT_UNIT = 0x1.0p-24f; // 1.0f / (1 << 24)
private static final AtomicLong seedUniquifier = new AtomicLong(8682522807148012L); private static final AtomicLong seedUniquifier = new AtomicLong(8682522807148012L);
public static final XSTR XSTR_INSTANCE = new XSTR() { public static final XSTR XSTR_INSTANCE = new XSTR() {
@Override @Override
public synchronized void setSeed(long seed) { public synchronized void setSeed(long seed) {
if (!Thread.currentThread().getStackTrace()[2].getClassName().equals(Random.class.getName())) { if (!Thread.currentThread().getStackTrace()[2].getClassName().equals(Random.class.getName())) {
@@ -37,11 +53,13 @@ public class XSTR extends Random {
}; };
/* /*
* MODIFIED BY: Robotia Modification: Implemented Random class seed generator MODIFIED BY: Robotia
*/ Modification: Implemented Random class seed generator
*/
/** /**
* Creates a new pseudo random number generator. The seed is initialized to the current time, as if by * Creates a new pseudo random number generator. The seed is initialized to
* the current time, as if by
* <code>setSeed(System.currentTimeMillis());</code>. * <code>setSeed(System.currentTimeMillis());</code>.
*/ */
public XSTR() { public XSTR() {
@@ -61,8 +79,8 @@ public class XSTR extends Random {
} }
/** /**
* Creates a new pseudo random number generator, starting with the specified seed, using * Creates a new pseudo random number generator, starting with the specified
* <code>setSeed(seed);</code>. * seed, using <code>setSeed(seed);</code>.
* *
* @param seed the initial seed * @param seed the initial seed
*/ */
@@ -90,8 +108,9 @@ public class XSTR extends Random {
} }
/** /**
* Sets the seed for this pseudo random number generator. As described above, two instances of the same random * Sets the seed for this pseudo random number generator. As described
* class, starting with the same seed, produce the same results, if the same methods are called. * above, two instances of the same random class, starting with the same
* seed, produce the same results, if the same methods are called.
* *
* @param seed the new seed * @param seed the new seed
*/ */
@@ -109,8 +128,9 @@ public class XSTR extends Random {
} }
/** /**
* Implementation of George Marsaglia's elegant Xorshift random generator 30% faster and better quality than the * Implementation of George Marsaglia's elegant Xorshift random generator
* built-in java.util.random see also see http://www.javamex.com/tutorials/random_numbers/xorshift.shtml * 30% faster and better quality than the built-in java.util.random see also
* see http://www.javamex.com/tutorials/random_numbers/xorshift.shtml
* *
* @param nbits will shift nbits bits * @param nbits will shift nbits bits
* @return next seed * @return next seed
@@ -150,14 +170,15 @@ public class XSTR extends Random {
} }
/** /**
* Returns a pseudorandom, uniformly distributed {@code int} value between 0 (inclusive) and the specified value * Returns a pseudorandom, uniformly distributed {@code int} value between 0
* (exclusive), drawn from this random number generator's sequence. The general contract of {@code nextInt} is that * (inclusive) and the specified value (exclusive), drawn from this random
* one {@code int} value in the specified range is pseudorandomly generated and returned. All {@code bound} possible * number generator's sequence. The general contract of {@code nextInt} is
* {@code int} values are produced with (approximately) equal probability. The method {@code nextInt(int bound)} is * that one {@code int} value in the specified range is pseudorandomly
* implemented by class {@code Random} as if by: * generated and returned. All {@code bound} possible {@code int} values are
* * produced with (approximately) equal probability. The method
* <pre> * {@code nextInt(int bound)} is implemented by class {@code Random} as if
* {@code * by:
* <pre> {@code
* public int nextInt(int bound) { * public int nextInt(int bound) {
* if (bound <= 0) * if (bound <= 0)
* throw new IllegalArgumentException("bound must be positive"); * throw new IllegalArgumentException("bound must be positive");
@@ -171,29 +192,35 @@ public class XSTR extends Random {
* val = bits % bound; * val = bits % bound;
* } while (bits - val + (bound-1) < 0); * } while (bits - val + (bound-1) < 0);
* return val; * return val;
* }} * }}</pre>
* </pre>
* *
* <p>The hedge "approx
* imately" is used in the foregoing description only because the next
* method is only approximately an unbiased source of independently chosen
* bits. If it were a perfect source of randomly chosen bits, then the
* algorithm shown would choose {@code int} values from the stated range
* with perfect uniformity.
* <p> * <p>
* The hedge "approx imately" is used in the foregoing description only because the next method is only * The algorithm is slightly tricky. It rejects values that would result in
* approximately an unbiased source of independently chosen bits. If it were a perfect source of randomly chosen * an uneven distribution (due to the fact that 2^31 is not divisible by n).
* bits, then the algorithm shown would choose {@code int} values from the stated range with perfect uniformity. * The probability of a value being rejected depends on n. The worst case is
* n=2^30+1, for which the probability of a reject is 1/2, and the expected
* number of iterations before the loop terminates is 2.
* <p> * <p>
* The algorithm is slightly tricky. It rejects values that would result in an uneven distribution (due to the fact * The algorithm treats the case where n is a power of two specially: it
* that 2^31 is not divisible by n). The probability of a value being rejected depends on n. The worst case is * returns the correct number of high-order bits from the underlying
* n=2^30+1, for which the probability of a reject is 1/2, and the expected number of iterations before the loop * pseudo-random number generator. In the absence of special treatment, the
* terminates is 2. * correct number of <i>low-order</i> bits would be returned. Linear
* <p> * congruential pseudo-random number generators such as the one implemented
* The algorithm treats the case where n is a power of two specially: it returns the correct number of high-order * by this class are known to have short periods in the sequence of values
* bits from the underlying pseudo-random number generator. In the absence of special treatment, the correct number * of their low-order bits. Thus, this special case greatly increases the
* of <i>low-order</i> bits would be returned. Linear congruential pseudo-random number generators such as the one * length of the sequence of values returned by successive calls to this
* implemented by this class are known to have short periods in the sequence of values of their low-order bits. * method if n is a small power of two.
* Thus, this special case greatly increases the length of the sequence of values returned by successive calls to
* this method if n is a small power of two.
* *
* @param bound the upper bound (exclusive). Must be positive. * @param bound the upper bound (exclusive). Must be positive.
* @return the next pseudorandom, uniformly distributed {@code int} value between zero (inclusive) and {@code bound} * @return the next pseudorandom, uniformly distributed {@code int} value
* (exclusive) from this random number generator's sequence * between zero (inclusive) and {@code bound} (exclusive) from this random
* number generator's sequence
* @throws IllegalArgumentException if bound is not positive * @throws IllegalArgumentException if bound is not positive
* @since 1.2 * @since 1.2
*/ */
@@ -203,10 +230,18 @@ public class XSTR extends Random {
// throw new RuntimeException("BadBound"); // throw new RuntimeException("BadBound");
// } // }
/* /*int r = next(31);
* int r = next(31); int m = bound - 1; if ((bound & m) == 0) // i.e., bound is a power of 2 { r = (int) ((bound int m = bound - 1;
* * (long) r) >> 31); } else { for (int u = r; u - (r = u % bound) + m < 0; u = next(31)) ; } return r; if ((bound & m) == 0) // i.e., bound is a power of 2
*/ {
r = (int) ((bound * (long) r) >> 31);
} else {
for (int u = r;
u - (r = u % bound) + m < 0;
u = next(31))
;
}
return r;*/
// speedup, new nextInt ~+40% // speedup, new nextInt ~+40%
long last = seed ^ seed << 21; long last = seed ^ seed << 21;
last ^= last >>> 35; last ^= last >>> 35;
@@ -234,9 +269,10 @@ public class XSTR extends Random {
@Override @Override
public void nextBytes(byte[] bytes_arr) { public void nextBytes(byte[] bytes_arr) {
for (int iba = 0, lenba = bytes_arr.length; iba < lenba;) { for (int iba = 0, lenba = bytes_arr.length; iba < lenba; ) {
for (int rndba = nextInt(), nba = Math.min(lenba - iba, Integer.SIZE / Byte.SIZE); nba-- for (int rndba = nextInt(), nba = Math.min(lenba - iba, Integer.SIZE / Byte.SIZE);
> 0; rndba >>= Byte.SIZE) { nba-- > 0;
rndba >>= Byte.SIZE) {
bytes_arr[iba++] = (byte) rndba; bytes_arr[iba++] = (byte) rndba;
} }
} }
+1 -1
View File
@@ -221,7 +221,7 @@ import com.gtnewhorizon.structurelib.structure.IStructureElement;
public class MyHatchElement&lt;T> implements IStructureElement&lt;T> { public class MyHatchElement&lt;T> implements IStructureElement&lt;T> {
//... //...
{@literal @}Override @Override
public PlaceResult survivalPlaceBlock( public PlaceResult survivalPlaceBlock(
Object o, Object o,
World world, World world,
@@ -4,7 +4,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.common.util.ForgeDirection;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
class ExtendedFacingTest { class ExtendedFacingTest {