original commit

This commit is contained in:
gamma-delta 2021-12-25 10:58:16 -06:00
commit ef5fd6aa46
39 changed files with 2020 additions and 0 deletions

5
.gitattributes vendored Normal file
View File

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

25
.gitignore vendored Normal file
View File

@ -0,0 +1,25 @@
# eclipse
bin
*.launch
.settings
.metadata
.classpath
.project
# idea
out
*.ipr
*.iws
*.iml
.idea
# gradle
build
.gradle
# other
eclipse
run
# Files from Forge MDK
forge*changelog.txt

65
CREDITS.txt Normal file
View File

@ -0,0 +1,65 @@
Minecraft Forge: Credits/Thank You
Forge is a set of tools and modifications to the Minecraft base game code to assist
mod developers in creating new and exciting content. It has been in development for
several years now, but I would like to take this time thank a few people who have
helped it along it's way.
First, the people who originally created the Forge projects way back in Minecraft
alpha. Eloraam of RedPower, and SpaceToad of Buildcraft, without their acceptiance
of me taking over the project, who knows what Minecraft modding would be today.
Secondly, someone who has worked with me, and developed some of the core features
that allow modding to be as functional, and as simple as it is, cpw. For developing
FML, which stabelized the client and server modding ecosystem. As well as the base
loading system that allows us to modify Minecraft's code as elegently as possible.
Mezz, who has stepped up as the issue and pull request manager. Helping to keep me
sane as well as guiding the community into creating better additions to Forge.
Searge, Bspks, Fesh0r, ProfMobious, and all the rest over on the MCP team {of which
I am a part}. For creating some of the core tools needed to make Minecraft modding
both possible, and as stable as can be.
On that note, here is some specific information of the MCP data we use:
* Minecraft Coder Pack (MCP) *
Forge Mod Loader and Minecraft Forge have permission to distribute and automatically
download components of MCP and distribute MCP data files. This permission is not
transitive and others wishing to redistribute the Minecraft Forge source independently
should seek permission of MCP or remove the MCP data files and request their users
to download MCP separately.
And lastly, the countless community members who have spent time submitting bug reports,
pull requests, and just helping out the community in general. Thank you.
--LexManos
=========================================================================
This is Forge Mod Loader.
You can find the source code at all times at https://github.com/MinecraftForge/MinecraftForge/tree/1.12.x/src/main/java/net/minecraftforge/fml
This minecraft mod is a clean open source implementation of a mod loader for minecraft servers
and minecraft clients.
The code is authored by cpw.
It began by partially implementing an API defined by the client side ModLoader, authored by Risugami.
http://www.minecraftforum.net/topic/75440-
This support has been dropped as of Minecraft release 1.7, as Risugami no longer maintains ModLoader.
It also contains suggestions and hints and generous helpings of code from LexManos, author of MinecraftForge.
http://www.minecraftforge.net/
Additionally, it contains an implementation of topological sort based on that
published at http://keithschwarz.com/interesting/code/?dir=topological-sort
It also contains code from the Maven project for performing versioned dependency
resolution. http://maven.apache.org/
It also contains a partial repackaging of the javaxdelta library from http://sourceforge.net/projects/javaxdelta/
with credit to it's authors.
Forge Mod Loader downloads components from the Minecraft Coder Pack
(http://mcp.ocean-labs.de/index.php/Main_Page) with kind permission from the MCP team.

16
README.md Normal file
View File

@ -0,0 +1,16 @@
# Hex
A minecraft mod about casting spells, inspired by PSI.
## To Cast A Spell
- Get a Wand, which stores mana.
- Right-click with it to start casting a *Hex*.
- Look around to draw a *pattern*, a sequence of lines on the invisible hexagonal grid that permeates reality.
- When you are done with your pattern, release right-click. Hopefully, that pattern corresponds to an *action*. (If not,
you blow up.)
- Actions manipulate a stack of data. The stack starts empty when you first start casting a hex. Some actions just push
data, while some pop off some arguments and push some arguments in return.
- Certain actions, will push a *spell* to the stack. When the stack is empty except for one spell, the hex is
successfully cast with the given effect.

46
README.txt Normal file
View File

@ -0,0 +1,46 @@
Source installation information for modders
-------------------------------------------
This code follows the Minecraft Forge installation methodology. It will apply
some small patches to the vanilla MCP source code, giving you and it access
to some of the data and functions you need to build a successful mod.
Note also that the patches are built against "un-renamed" MCP source code (aka
SRG Names) - this means that you will not be able to read them directly against
normal code.
Setup Process:
==============================
Step 1: Open your command-line and browse to the folder where you extracted the zip file.
Step 2: You're left with a choice.
If you prefer to use Eclipse:
1. Run the following command: `gradlew genEclipseRuns` (`./gradlew genEclipseRuns` if you are on Mac/Linux)
2. Open Eclipse, Import > Existing Gradle Project > Select Folder
or run `gradlew eclipse` to generate the project.
If you prefer to use IntelliJ:
1. Open IDEA, and import project.
2. Select your build.gradle file and have it import.
3. Run the following command: `gradlew genIntellijRuns` (`./gradlew genIntellijRuns` if you are on Mac/Linux)
4. Refresh the Gradle Project in IDEA if required.
If at any point you are missing libraries in your IDE, or you've run into problems you can
run `gradlew --refresh-dependencies` to refresh the local cache. `gradlew clean` to reset everything
{this does not affect your code} and then start the process again.
Mapping Names:
=============================
By default, the MDK is configured to use the official mapping names from Mojang for methods and fields
in the Minecraft codebase. These names are covered by a specific license. All modders should be aware of this
license, if you do not agree with it you can change your mapping names to other crowdsourced names in your
build.gradle. For the latest license text, refer to the mapping file itself, or the reference copy here:
https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
Additional Resources:
=========================
Community Documentation: http://mcforge.readthedocs.io/en/latest/gettingstarted/
LexManos' Install Video: https://www.youtube.com/watch?v=8VEdtQLuLO0
Forge Forum: https://forums.minecraftforge.net/
Forge Discord: https://discord.gg/UvedJ9m

207
build.gradle Normal file
View File

@ -0,0 +1,207 @@
buildscript {
repositories {
// These repositories are only for Gradle plugins, put any other repositories in the repository block further below
maven { url = 'https://maven.minecraftforge.net' }
maven { url = 'https://maven.parchmentmc.org' }
mavenCentral()
}
dependencies {
classpath group: 'net.minecraftforge.gradle', name: 'ForgeGradle', version: '5.1.+', changing: true
classpath 'org.parchmentmc:librarian:1.+'
}
}
apply plugin: 'net.minecraftforge.gradle'
// Only edit below this line, the above code adds and enables the necessary things for Forge to be setup.
apply plugin: 'eclipse'
apply plugin: 'maven-publish'
apply plugin: 'net.minecraftforge.gradle'
apply plugin: 'org.parchmentmc.librarian.forgegradle'
version = '0.1.0'
group = 'at.petra-k.hex' // http://maven.apache.org/guides/mini/guide-naming-conventions.html
archivesBaseName = 'hex'
// Mojang ships Java 17 to end users in 1.18+, so your mod should target Java 17.
java.toolchain.languageVersion = JavaLanguageVersion.of(17)
// Adds the Kotlin Gradle plugin
buildscript {
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.0"
// OPTIONAL Kotlin Serialization plugin
classpath 'org.jetbrains.kotlin:kotlin-serialization:1.6.0'
}
}
apply plugin: 'kotlin'
// OPTIONAL Kotlin Serialization plugin
apply plugin: 'kotlinx-serialization'
// Adds KFF as dependency and Kotlin libs to the runtime classpath
// If you already know how to add the Kotlin plugin to Gradle, this is the only line you need for KFF
apply from: 'https://raw.githubusercontent.com/thedarkcolour/KotlinForForge/site/thedarkcolour/kotlinforforge/gradle/kff-3.0.0.gradle'
println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
minecraft {
// The mappings can be changed at any time and must be in the following format.
// Channel: Version:
// snapshot YYYYMMDD Snapshot are built nightly.
// stable # Stables are built at the discretion of the MCP team.
// official MCVersion Official field/method names from Mojang mapping files
//
// You must be aware of the Mojang license when using the 'official' mappings.
// See more information here: https://github.com/MinecraftForge/MCPConfig/blob/master/Mojang.md
//
// Use non-default mappings at your own risk. They may not always work.
// Simply re-run your setup task after changing the mappings to update your workspace.
mappings channel: 'parchment', version: '2021.12.19-1.18.1'
// accessTransformer = file('src/main/resources/META-INF/accesstransformer.cfg') // Currently, this location cannot be changed from the default.
// Default run configurations.
// These can be tweaked, removed, or duplicated as needed.
runs {
client {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
hex {
source sourceSets.main
}
}
}
server {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
mods {
hex {
source sourceSets.main
}
}
}
data {
workingDirectory project.file('run')
// Recommended logging data for a userdev environment
// The markers can be added/remove as needed separated by commas.
// "SCAN": For mods scan.
// "REGISTRIES": For firing of registry events.
// "REGISTRYDUMP": For getting the contents of all registries.
property 'forge.logging.markers', 'REGISTRIES'
// Recommended logging level for the console
// You can set various levels here.
// Please read: https://stackoverflow.com/questions/2031163/when-to-use-the-different-log-levels
property 'forge.logging.console.level', 'debug'
// Specify the modid for data generation, where to output the resulting resource, and where to look for existing resources.
args '--mod', 'hex', '--all', '--output', file('src/generated/resources/'), '--existing', file('src/main/resources/')
mods {
hex {
source sourceSets.main
}
}
}
}
}
// Include resources generated by data generators.
sourceSets.main.resources { srcDir 'src/generated/resources' }
repositories {
mavenCentral()
// Put repositories for dependencies here
// ForgeGradle automatically adds the Forge maven and Maven Central for you
// If you have mod jar dependencies in ./libs, you can declare them as a repository like so:
// flatDir {
// dir 'libs'
// }
}
dependencies {
// Specify the version of Minecraft to use. If this is any group other than 'net.minecraft', it is assumed
// that the dep is a ForgeGradle 'patcher' dependency, and its patches will be applied.
// The userdev artifact is a special name and will get all sorts of transformations applied to it.
minecraft 'net.minecraftforge:forge:1.18.1-39.0.8'
// Real mod deobf dependency examples - these get remapped to your current mappings
// compileOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}:api") // Adds JEI API as a compile dependency
// runtimeOnly fg.deobf("mezz.jei:jei-${mc_version}:${jei_version}") // Adds the full JEI mod as a runtime dependency
// implementation fg.deobf("com.tterrag.registrate:Registrate:MC${mc_version}-${registrate_version}") // Adds registrate as a dependency
// Examples using mod jars from ./libs
// implementation fg.deobf("blank:coolmod-${mc_version}:${coolmod_version}")
// For more info...
// http://www.gradle.org/docs/current/userguide/artifact_dependencies_tutorial.html
// http://www.gradle.org/docs/current/userguide/dependency_management.html
}
// Example for how to get properties into the manifest for reading at runtime.
jar {
manifest {
attributes([
"Specification-Title" : "hex",
"Specification-Vendor" : "petrak-at",
"Specification-Version" : "1", // We are version 1 of ourselves
"Implementation-Title" : project.name,
"Implementation-Version" : project.jar.archiveVersion,
"Implementation-Vendor" : "petrak-at",
"Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
])
}
}
// Example configuration to allow publishing using the maven-publish plugin
// This is the preferred method to reobfuscate your jar file
jar.finalizedBy('reobfJar')
// However if you are in a multi-project build, dev time needs unobfed jar files, so you can delay the obfuscation until publishing by doing
// publish.dependsOn('reobfJar')
publishing {
publications {
mavenJava(MavenPublication) {
artifact jar
}
}
repositories {
maven {
url "file://${project.projectDir}/mcmodsrepo"
}
}
}
compileKotlin {
kotlinOptions {
}
}
compileTestKotlin {
kotlinOptions {
}
}

142
changelog.txt Normal file
View File

@ -0,0 +1,142 @@
Build: 1.18.1-39.0.8 - Wed Dec 22 13:22:32 GMT 2021
JTK222:
Fixed incorrect generic in PermissionAPI (#8317)
=========
Build: 1.18.1-39.0.7 - Mon Dec 20 18:35:11 GMT 2021
JTK222:
Redo of the whole PermissionAPI (#7780)
Co-authored-by: LexManos <LexManos@gmail.com>
=========
Build: 1.18.1-39.0.6 - Sun Dec 19 18:28:43 GMT 2021
JTK222:
Fix misplaced patch in SpreadingSnowyDirtBlock.
Fixes #8308.
=========
Build: 1.18.1-39.0.5 - Mon Dec 13 21:58:30 GMT 2021
pupnewfster:
Add RenderArmEvent to make overriding just the arm rendering not require copying nearly as much vanilla code (#8254)
=========
Build: 1.18.1-39.0.4 - Mon Dec 13 21:32:20 GMT 2021
bageldotjpg:
Add MobEffect tags (#8231)
=========
Build: 1.18.1-39.0.3 - Mon Dec 13 19:49:00 GMT 2021
xfacthd:
Log missing or unsupported dependencies (#8218)
=========
Build: 1.18.1-39.0.2 - Mon Dec 13 19:33:05 GMT 2021
sciwhiz12:
Fix datagen test for sounds definitions provider (#8249)
=========
Build: 1.18.1-39.0.1 - Mon Dec 13 19:14:15 GMT 2021
williewillus:
Fix wrong stage being declared in transition to common (#8267)
=========
Build: 1.18.1-39.0.0 - Fri Dec 10 19:32:24 GMT 2021
curle:
Update to 1.18.1
Co-Authored by:
- Curle
_ Orion
=========
Build: 1.18-38.0.17 - Fri Dec 10 09:23:45 GMT 2021
oriondevelopment:
[CVE-2021-44228]: Update Log4J to fix the security issue inside it. (#8268)
=========
Build: 1.18-38.0.16 - Wed Dec 08 00:09:40 GMT 2021
jaredlll08:
Fix KeyMappings only checking if they conflict with themselves. (#8256)
=========
Build: 1.18-38.0.15 - Sun Dec 05 19:40:15 GMT 2021
xfacthd:
Fix ChunkWatchEvent not being fired (#8253)
=========
Build: 1.18-38.0.14 - Sat Dec 04 01:30:30 GMT 2021
git:
Call handleUpdateTag for BlockEntities again (#8237)
=========
Build: 1.18-38.0.13 - Fri Dec 03 22:10:25 GMT 2021
commoble:
Fix test worldgen data (#8248)
=========
Build: 1.18-38.0.12 - Thu Dec 02 20:16:47 GMT 2021
lexmanos:
Allow Forge Registries to return key information for overridden objects. Fixes #8230
=========
Build: 1.18-38.0.11 - Thu Dec 02 19:17:12 GMT 2021
curle:
Save Chunk capabilities to the chunk, rather than recursively to the capabilities.
=========
Build: 1.18-38.0.10 - Thu Dec 02 15:24:47 GMT 2021
gigaherz:
Make HandshakeConsumer public again.
Fixes #8241
gigaherz:
Fix LevelChunk capability attach crash.
Fix client chunks not having capability providers attached.
Add capability attach tests.
=========
Build: 1.18-38.0.8 - Thu Dec 02 00:44:15 GMT 2021
curle:
Add missing biomes back to the BiomeDictionary
curle:
Complete TODO in ShapedRecipe patch causing logspam related to minecraft:air
=========
Build: 1.18-38.0.6 - Wed Dec 01 22:12:05 GMT 2021
curle:
Readd Mixin 0.8.5 to fix modules issues.
=========
Build: 1.18-38.0.5 - Wed Dec 01 16:56:24 GMT 2021
curle:
Readd PoseStack field to RenderTooltipEvent.
=========
Build: 1.18-38.0.4 - Wed Dec 01 01:29:57 GMT 2021
curle:
Fix custom loot serializers using wrong registry names
=========
Build: 1.18-38.0.3 - Wed Dec 01 01:15:13 GMT 2021
lexmanos:
Fix DungeonHooks not returning correct values. Fixes dungeons in world spawning pigs.
=========
Build: 1.18-38.0.2 - Wed Dec 01 00:23:23 GMT 2021
lexmanos:
Fix dedicated server install. Closes #8226
Fix example mod
Fix obf issue with records. Closes #8228
Fix dependencies beingg out of sync from vanilla. Closes #8227
Disable mixin due to module incompatibility.
=========
Build: 1.18-38.0.1 - Tue Nov 30 20:56:52 GMT 2021
gigaherz:
Fix mod resources not loading.
Add BreakingItemParticle.java.patch which I forgot to commit during the porting.

4
gradle.properties Normal file
View File

@ -0,0 +1,4 @@
# Sets default memory used for gradle commands. Can be overridden by user or command line properties.
# This is required to provide enough memory for the Minecraft decompilation process.
org.gradle.jvmargs=-Xmx3G
org.gradle.daemon=false

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

Binary file not shown.

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

234
gradlew vendored Normal file
View File

@ -0,0 +1,234 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/master/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
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
APP_NAME="Gradle"
APP_BASE_NAME=${0##*/}
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
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
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Collect all arguments for the java command;
# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
# shell script including quotes and variable substitutions, so put them in
# double quotes to make sure that they get re-expanded; and
# * put everything else in single quotes, so that it's not re-expanded.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# 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" "$@"

89
gradlew.bat vendored Normal file
View File

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

View File

@ -0,0 +1,24 @@
package at.petrak.hex;
import at.petrak.hex.client.HexRenderOverlays;
import at.petrak.hex.items.HexItems;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@Mod(HexMod.MOD_ID)
public class HexMod {
// hmm today I will use a popular logging framework :clueless:
public static final Logger LOGGER = LogManager.getLogger();
public static final String MOD_ID = "hex";
public HexMod() {
// Register ourselves for server and other game events we are interested in
MinecraftForge.EVENT_BUS.register(this);
HexItems.ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
MinecraftForge.EVENT_BUS.register(HexRenderOverlays.class);
}
}

View File

@ -0,0 +1,20 @@
package at.petrak.hex
import net.minecraft.nbt.LongArrayTag
import net.minecraft.world.phys.Vec3
object HexUtils {
@JvmStatic
fun Vec3.serializeToNBT(): LongArrayTag =
LongArrayTag(longArrayOf(this.x.toRawBits(), this.y.toRawBits(), this.z.toRawBits()))
@JvmStatic
fun deserializeVec3FromNBT(tag: LongArray): Vec3 =
Vec3(
Double.fromBits(tag[0]),
Double.fromBits(tag[1]),
Double.fromBits(tag[2])
)
const val TAU = Math.PI * 2.0
}

View File

@ -0,0 +1,8 @@
Hello, intrepid Github reader!
The "flavor text" words for things in this mod and the internal names are different. (Sorry.)
- A "Hex" is a `Spell`, cast through a [`CastingHarness`](casting/CastingHarness.kt)
- A "Pattern" is a [`HexPattern`](hexes/HexPattern.kt)
- An "Action" is a [`SpellOperator`](casting/operators/SpellOperator.kt)

View File

@ -0,0 +1,55 @@
package at.petrak.hex.casting
import at.petrak.hex.hexes.HexPattern
class CastException(val reason: Reason, vararg val data: Any) : Exception() {
enum class Reason {
// Compilation
/**
* We couldn't match this pattern to an operator.
*
* `pattern: HexPattern`
*/
INVALID_PATTERN,
/**
* Completely invalid type for spellcasting.
* If you're seeing this error I messed up really bad
*
* `perpetrator: Any`
*/
INVALID_TYPE,
// Pre-execution
/**
* When executing an operator we expected a different type.
*
* `expected: Class<*>, got: Any`
*/
OP_WRONG_TYPE,
/**
* We need at least this much on the stack to cast the spell but only got this much.
*
* `requiredArgc: Int, gotArgc: Int`
*/
NOT_ENOUGH_ARGS,
// Execution
/**
* Tried to interact with a vector that was too far away
*
* `<no args>`
*/
TOO_FAR,
}
override val message: String
get() = when (this.reason) {
Reason.INVALID_PATTERN -> "could not match pattern to operator: ${this.data[0] as HexPattern}"
Reason.INVALID_TYPE -> "cannot use ${this.data[0]} as a SpellDatum (type ${this.data[0].javaClass.typeName})"
Reason.OP_WRONG_TYPE -> "operator expected ${(this.data[0] as Class<*>).typeName} but got ${this.data[1]} (type ${this.data[1].javaClass.typeName})"
Reason.NOT_ENOUGH_ARGS -> "required at least ${this.data[0] as Int} args on the stack but only had ${this.data[1] as Int}"
Reason.TOO_FAR -> "tried to interact with something too far away"
}
}

View File

@ -0,0 +1,14 @@
package at.petrak.hex.casting
import net.minecraft.server.level.ServerLevel
import net.minecraft.server.level.ServerPlayer
/**
* Info about the moment the spell started being cast.
*/
@JvmRecord
data class CastingContext(
val caster: ServerPlayer,
) {
val world: ServerLevel get() = caster.getLevel()
}

View File

@ -0,0 +1,273 @@
package at.petrak.hex.casting
import at.petrak.hex.HexMod
import at.petrak.hex.HexUtils
import at.petrak.hex.HexUtils.TAU
import at.petrak.hex.HexUtils.deserializeVec3FromNBT
import at.petrak.hex.HexUtils.serializeToNBT
import at.petrak.hex.casting.operators.SpellOperator
import at.petrak.hex.hexes.HexAngle
import at.petrak.hex.hexes.HexDir
import at.petrak.hex.hexes.HexPattern
import net.minecraft.nbt.*
import net.minecraft.server.level.ServerPlayer
import net.minecraft.world.phys.Vec3
import java.util.*
import kotlin.math.*
/**
* Keeps track of a player casting a spell
*/
class CastingHarness private constructor(
val stack: MutableList<SpellDatum<*>>,
var patternDrawState: PatternDrawState,
val worldPoints: MutableList<MutableList<Vec3>>,
val ctx: CastingContext,
) {
/**
* Internally update its own state based on the player's actions.
*/
fun update(): CastResult {
val caster = this.ctx.caster
return when (patternDrawState) {
is PatternDrawState.BetweenPatterns -> {
if (caster.isUsingItem) {
HexMod.LOGGER.info("Started drawing new pattern")
this.patternDrawState = PatternDrawState.JustStarted(caster.lookAngle)
worldPoints.add(mutableListOf(caster.lookAngle.add(caster.position())))
CastResult.Nothing
} else {
CastResult.QuitCasting
}
}
is PatternDrawState.JustStarted -> {
val (anchor) = patternDrawState as PatternDrawState.JustStarted
if (caster.isUsingItem) {
val dir = anchor.hexDirBetween(caster.lookAngle)
if (dir.isPresent) {
val pat = HexPattern(dir.get())
HexMod.LOGGER.info("Started casting spell: $pat")
this.patternDrawState = PatternDrawState.Drawing(caster.lookAngle, pat)
worldPoints.last().add(caster.lookAngle.add(caster.position()))
}
CastResult.Nothing
} else {
// We never finished drawing the line
this.patternDrawState = PatternDrawState.BetweenPatterns
worldPoints.removeLastOrNull()
CastResult.Nothing
}
}
is PatternDrawState.Drawing -> {
val (anchor, pat) = patternDrawState as PatternDrawState.Drawing
if (caster.isUsingItem) {
val dir = anchor.hexDirBetween(caster.lookAngle)
if (dir.isPresent && pat.tryAppendDir(dir.get())) {
// nice! another line on the pattern
HexMod.LOGGER.info("Added dir to pattern: $pat")
(patternDrawState as PatternDrawState.Drawing).anchorLookPos = caster.lookAngle
worldPoints.last().add(caster.lookAngle.add(caster.position()))
}
CastResult.Nothing
} else {
// Finish the current pattern!
patternDrawState = PatternDrawState.BetweenPatterns
try {
val operator = SpellOperator.fromPattern(pat)
// now execute the operator
if (operator.argc > this.stack.size)
throw CastException(CastException.Reason.NOT_ENOUGH_ARGS, operator.argc, this.stack.size)
val args = this.stack.takeLast(operator.argc)
// there's gotta be a better way to do this
for (_idx in 0 until operator.argc)
this.stack.removeLast()
val newData = operator.execute(args, this.ctx)
this.stack.addAll(newData)
if (this.stack.isEmpty()) {
return CastResult.QuitCasting
}
val maybeSpell = this.stack[0]
if (this.stack.size == 1 && maybeSpell.payload is RenderedSpell) {
CastResult.Success(maybeSpell.payload)
} else {
CastResult.Nothing
}
} catch (e: CastException) {
CastResult.Error(e)
}
}
}
}
}
fun serializeToNBT(): CompoundTag {
val out = CompoundTag()
val stackTag = ListTag()
for (datum in this.stack)
stackTag.add(datum.serializeToNBT())
out.put(TAG_STACK, stackTag)
out.put(TAG_PDS, this.patternDrawState.serializeToNBT())
val pointsTag = ListTag()
for (patblob in this.worldPoints) {
val subtag = ListTag()
for (point in patblob) {
subtag.add(point.serializeToNBT())
}
pointsTag.add(subtag)
}
out.put(TAG_POINTS, pointsTag)
return out
}
companion object {
const val TAG_STACK = "stack"
const val TAG_PDS = "pds"
const val TAG_POINTS = "points"
@JvmStatic
fun DeserializeFromNBT(nbt: Tag?, caster: ServerPlayer): CastingHarness {
val ctx = CastingContext(caster)
return try {
val nbt = nbt as CompoundTag
val stack = mutableListOf<SpellDatum<*>>()
val stackTag = nbt.getList(TAG_STACK, Tag.TAG_COMPOUND.toInt())
for (subtag in stackTag) {
val datum = SpellDatum.DeserializeFromNBT(subtag as CompoundTag, ctx)
stack.add(datum)
}
val pds = PatternDrawState.DeserializeFromNBT(nbt.getCompound(TAG_PDS))
val pointsTag = nbt.getList(TAG_POINTS, Tag.TAG_LIST.toInt())
val points = pointsTag.map { patgroup ->
(patgroup as ListTag).map { posTag ->
val pos = posTag as LongArrayTag
deserializeVec3FromNBT(pos.asLongArray)
}.toMutableList()
}.toMutableList()
CastingHarness(stack, pds, points, ctx)
} catch (exn: Exception) {
HexMod.LOGGER.warn("Couldn't load harness from nbt tag, falling back to default: ${exn.message}")
CastingHarness(mutableListOf(), PatternDrawState.BetweenPatterns, mutableListOf(), ctx)
}
}
// this is on a unit sphere, where 0 is straight ahead and 1 is straight up (or similar)
const val HEX_GRID_SPACING = 1.0 / 8.0
/** Check if the two vectors are far enough apart to be more than one hex coord apart */
private fun Vec3.hexDirBetween(look: Vec3): Optional<HexDir> {
// https://gist.github.com/Alwinfy/d6f3e9b22e4432f4446a58ace8812a3c
// no idea how any of this works
fun pythag(x: Double, y: Double): Double = sqrt(x * x + y * y)
if (look.x.absoluteValue <= 1e-30 || look.z.absoluteValue <= 1e-30)
return Optional.empty()
val dist = (this.normalize().subtract(look.normalize())).length()
if (dist < HEX_GRID_SPACING)
return Optional.empty()
val yaw = atan2(this.x, this.z)
val pitch = atan2(this.y, pythag(this.x, this.z))
val zeroYaw = look.yRot(-yaw.toFloat())
val zeroPitch = zeroYaw.xRot(-pitch.toFloat()).normalize()
val angle = atan2(asin(zeroPitch.y), asin(-zeroPitch.x))
// 0 is right, increases clockwise(?)
val snappedAngle = angle.div(TAU).mod(6.0).times(6).roundToInt()
return Optional.of(HexDir.values()[(-snappedAngle + 1).mod(6)])
}
}
sealed class PatternDrawState {
/** We're waiting on the player to right-click again */
object BetweenPatterns : PatternDrawState()
/** We just started drawing and haven't drawn the first line yet. */
data class JustStarted(val anchorLookPos: Vec3) : PatternDrawState()
/** We've started drawing a pattern for real. */
data class Drawing(var anchorLookPos: Vec3, val wipPattern: HexPattern) : PatternDrawState()
fun serializeToNBT(): CompoundTag {
val (key, value) = when (this) {
BetweenPatterns -> Pair(TAG_BETWEEN_PATTERNS, ListTag())
is JustStarted -> {
val (anchor) = this
Pair(TAG_JUST_STARTED, anchor.serializeToNBT())
}
is Drawing -> {
val (anchor, pat) = this
val subtag = CompoundTag()
subtag.put(TAG_ANCHOR, anchor.serializeToNBT())
subtag.put(TAG_START_DIR, ByteTag.valueOf(pat.startDir.ordinal.toByte()))
val anglesTag = ByteArrayTag(pat.angles.map { it.ordinal.toByte() })
subtag.put(TAG_ANGLES, anglesTag)
Pair(TAG_DRAWING, subtag)
}
}
val out = CompoundTag()
out.put(key, value)
return out
}
companion object {
const val TAG_BETWEEN_PATTERNS = "between_patterns"
const val TAG_JUST_STARTED = "just_started"
const val TAG_DRAWING = "drawing"
const val TAG_ANCHOR = "anchor"
const val TAG_START_DIR = "start_dir"
const val TAG_ANGLES = "angles"
fun DeserializeFromNBT(nbt: CompoundTag): PatternDrawState {
val keys = nbt.allKeys
if (keys.size != 1)
throw IllegalArgumentException("Expected exactly one kv pair: $nbt")
return when (val key = keys.iterator().next()) {
TAG_BETWEEN_PATTERNS -> BetweenPatterns
TAG_JUST_STARTED -> {
val anchor = HexUtils.deserializeVec3FromNBT(nbt.getLongArray(key))
JustStarted(anchor)
}
TAG_DRAWING -> {
val subtag = nbt.getCompound(key)
val anchor = HexUtils.deserializeVec3FromNBT(subtag.getLongArray(TAG_ANCHOR))
val startDir = HexDir.values()[subtag.getByte(TAG_START_DIR).toInt()]
val angles = subtag.getByteArray(TAG_ANGLES).map { HexAngle.values()[it.toInt()] }
Drawing(anchor, HexPattern(startDir, angles.toMutableList()))
}
else -> throw IllegalArgumentException("Unknown key $key: $nbt")
}
}
}
}
sealed class CastResult {
/** Casting still in progress */
object Nothing : CastResult()
/** Non-catastrophic quit */
object QuitCasting : CastResult()
/** Finished casting */
data class Success(val spell: RenderedSpell) : CastResult()
/** uh-oh */
data class Error(val exn: CastException) : CastResult()
}
}

View File

@ -0,0 +1,13 @@
package at.petrak.hex.casting
/**
* The result of a spell being cast.
*
* A "spell" is just a [SpellOperator] that returns a [RenderedSpell],
* Once a spell stack has nothing on it but a single [RenderedSpell], the casting is nearly successful.
* If the caster has enough mana to cast the [RenderedSpell], it is cast! (Otherwise, we might cast from
* hitpoints or just kill the caster.)
*/
fun interface RenderedSpell {
fun cast(ctx: CastingContext)
}

View File

@ -0,0 +1,121 @@
package at.petrak.hex.casting
import at.petrak.hex.HexUtils
import at.petrak.hex.HexUtils.serializeToNBT
import net.minecraft.nbt.*
import net.minecraft.world.entity.Entity
import net.minecraft.world.phys.Vec3
/**
* Data allowed into a spell.
*
* We use the following types:
* * [Entity]
* * [Double]
* * [Vec3][net.minecraft.world.phys.Vec3] as both position and (when normalized) direction
* * [Unit] as our type-safe null
* * [ArrayList<SpellDatum<*>>][ArrayList]
* The constructor guarantees we won't pass a type that isn't one of those types.
*
* Please do not access the `payload` field directly (use [tryGet])
*/
class SpellDatum<T : Any> private constructor(val payload: T) {
val clazz: Class<T> = payload.javaClass
inline fun <reified U> tryGet(): U =
if (payload is U) {
// learning from psi's mistakes
if (payload is Double && !payload.isFinite())
0.0 as U
else
payload
} else {
throw CastException(CastException.Reason.OP_WRONG_TYPE, U::class.java, clazz)
}
fun serializeToNBT(): CompoundTag {
val out = CompoundTag()
when (val pl = this.payload) {
is Entity -> out.put(
TAG_ENTITY, NbtUtils.createUUID(pl.uuid)
)
is Double -> out.put(
TAG_DOUBLE, DoubleTag.valueOf(pl)
)
is Vec3 -> out.put(
TAG_VEC3, pl.serializeToNBT()
)
// use an empty list as unit? works for me i guess
// it doesn't really matter what we put
is Unit -> out.put(TAG_UNIT, ListTag())
is ArrayList<*> -> {
val subtag = ListTag()
for (elt in pl)
subtag.add((elt as SpellDatum<*>).serializeToNBT())
out.put(TAG_LIST, subtag)
}
else -> throw RuntimeException("cannot serialize $pl because it is of type ${pl.javaClass.canonicalName} which is not serializable")
}
return out
}
companion object {
fun <T : Any> make(payload: T): SpellDatum<T> =
if (!IsValidType(payload)) {
throw CastException(CastException.Reason.INVALID_TYPE, payload)
} else {
SpellDatum(payload)
}
fun DeserializeFromNBT(nbt: CompoundTag, ctx: CastingContext): SpellDatum<*> {
val keys = nbt.allKeys
if (keys.size != 1)
throw IllegalArgumentException("Expected exactly one kv pair: $nbt")
return when (val key = keys.iterator().next()) {
TAG_ENTITY -> {
val uuid = nbt.getUUID(key)
val entity = ctx.world.getEntity(uuid)
// If the entity died or something return Unit
SpellDatum(if (entity == null || !entity.isAlive) Unit else entity)
}
TAG_DOUBLE -> SpellDatum(nbt.getDouble(key))
TAG_VEC3 -> SpellDatum(HexUtils.deserializeVec3FromNBT(nbt.getLongArray(key)))
TAG_UNIT -> SpellDatum(Unit)
TAG_LIST -> {
val arr = nbt.getList(key, Tag.TAG_COMPOUND.toInt())
val out = ArrayList<SpellDatum<*>>(arr.size)
for (subtag in arr) {
// this is safe because otherwise we wouldn't have been able to get the list before
out.add(DeserializeFromNBT(subtag as CompoundTag, ctx))
}
SpellDatum(out)
}
else -> throw IllegalArgumentException("Unknown key $key: $nbt")
}
}
// Maps the class to the tag name
val ValidTypes: Set<Class<*>> = setOf(
Entity::class.java,
Double::class.java,
Vec3::class.java,
Unit::class.java,
ArrayList::class.java,
)
const val TAG_ENTITY = "entity"
const val TAG_DOUBLE = "double"
const val TAG_VEC3 = "vec3"
const val TAG_UNIT = "unit"
const val TAG_LIST = "list"
fun <T : Any> IsValidType(checkee: T): Boolean =
if (checkee is ArrayList<*>) {
checkee.all { it is SpellDatum<*> && IsValidType(it) }
} else {
ValidTypes.any { clazz -> clazz.isAssignableFrom(checkee.javaClass) }
}
}
}

View File

@ -0,0 +1,34 @@
package at.petrak.hex.casting.operators
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.SpellDatum
import at.petrak.hex.casting.operators.SpellOperator.Companion.getChecked
import net.minecraft.world.level.ClipContext
import net.minecraft.world.phys.HitResult
import net.minecraft.world.phys.Vec3
object OpBlockAxisRaycast : SpellOperator {
override val argc = 2
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
val origin: Vec3 = args.getChecked(0)
val look: Vec3 = args.getChecked(1)
val blockHitResult = ctx.world.clip(
ClipContext(
origin,
SpellOperator.raycastEnd(origin, look),
ClipContext.Block.COLLIDER,
ClipContext.Fluid.NONE,
ctx.caster
)
)
return SpellOperator.spellListOf(
if (blockHitResult.type == HitResult.Type.BLOCK) {
Vec3(blockHitResult.direction.step())
} else {
Unit
}
)
}
}

View File

@ -0,0 +1,34 @@
package at.petrak.hex.casting.operators
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.SpellDatum
import at.petrak.hex.casting.operators.SpellOperator.Companion.getChecked
import net.minecraft.world.level.ClipContext
import net.minecraft.world.phys.HitResult
import net.minecraft.world.phys.Vec3
object OpBlockRaycast : SpellOperator {
override val argc = 2
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
val origin: Vec3 = args.getChecked(0)
val look: Vec3 = args.getChecked(1)
val blockHitResult = ctx.world.clip(
ClipContext(
origin,
SpellOperator.raycastEnd(origin, look),
ClipContext.Block.COLLIDER,
ClipContext.Fluid.NONE,
ctx.caster
)
)
return SpellOperator.spellListOf(
if (blockHitResult.type == HitResult.Type.BLOCK) {
blockHitResult.location
} else {
Unit
}
)
}
}

View File

@ -0,0 +1,16 @@
package at.petrak.hex.casting.operators
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.SpellDatum
import at.petrak.hex.casting.operators.SpellOperator.Companion.getChecked
import at.petrak.hex.casting.operators.SpellOperator.Companion.spellListOf
import net.minecraft.world.entity.Entity
object OpEntityLook : SpellOperator {
override val argc = 1
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
val e: Entity = args.getChecked(0)
return spellListOf(e.lookAngle)
}
}

View File

@ -0,0 +1,16 @@
package at.petrak.hex.casting.operators
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.SpellDatum
import at.petrak.hex.casting.operators.SpellOperator.Companion.getChecked
import at.petrak.hex.casting.operators.SpellOperator.Companion.spellListOf
import net.minecraft.world.entity.Entity
object OpEntityPos : SpellOperator {
override val argc = 1
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
val e: Entity = args.getChecked(0)
return spellListOf(e.position())
}
}

View File

@ -0,0 +1,34 @@
package at.petrak.hex.casting.operators
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.SpellDatum
import at.petrak.hex.casting.operators.SpellOperator.Companion.getChecked
import net.minecraft.world.entity.projectile.ProjectileUtil
import net.minecraft.world.phys.AABB
import net.minecraft.world.phys.HitResult
import net.minecraft.world.phys.Vec3
object OpEntityRaycast : SpellOperator {
override val argc = 2
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
val origin: Vec3 = args.getChecked(0)
val look: Vec3 = args.getChecked(1)
val endp = SpellOperator.raycastEnd(origin, look)
val entityHitResult = ProjectileUtil.getEntityHitResult(
ctx.caster,
origin,
endp,
AABB(origin, endp),
{ true },
SpellOperator.MAX_DISTANCE
)
return SpellOperator.spellListOf(
if (entityHitResult != null && entityHitResult.type == HitResult.Type.ENTITY) {
entityHitResult.entity
} else {
Unit
}
)
}
}

View File

@ -0,0 +1,12 @@
package at.petrak.hex.casting.operators
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.SpellDatum
import net.minecraft.world.entity.Entity
object OpGetCaster : SpellOperator {
override val argc = 0
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> =
SpellOperator.spellListOf(ctx.caster as Entity)
}

View File

@ -0,0 +1,87 @@
package at.petrak.hex.casting.operators
import at.petrak.hex.casting.CastException
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.SpellDatum
import at.petrak.hex.casting.operators.spells.OpPrint
import at.petrak.hex.hexes.HexPattern
import net.minecraft.world.phys.Vec3
/**
* Manipulates the stack in some way, usually by popping some number of values off the stack
* and pushing one new value.
*
* Implementors MUST NOT mutate the stack or the context.
*/
interface SpellOperator {
val argc: Int
val manaCost: Int
get() = 0
fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>>
companion object {
val PatternMap: Map<String, SpellOperator> = mapOf(
// diamond shape to get the caster
"qaq" to OpGetCaster,
"ede" to OpGetCaster,
// small triangle to get the entity pos
"aa" to OpEntityPos,
"dd" to OpEntityPos,
// Arrow to get the look vector
"wa" to OpEntityLook,
"wd" to OpEntityLook,
// CCW battleaxe for block raycast
"wqaawdd" to OpBlockRaycast,
// and CW for axis raycast
"weddwaa" to OpBlockAxisRaycast,
// CCW diamond mace thing for entity raycast
"weaqa" to OpEntityRaycast,
// ===
// hook for debug
"de" to OpPrint,
"aq" to OpPrint,
)
/**
* May throw CastException
*/
fun fromPattern(pattern: HexPattern): SpellOperator =
PatternMap.getOrElse(pattern.anglesSignature()) {
throw CastException(CastException.Reason.INVALID_PATTERN, pattern)
}
// I see why vzakii did this: you can't raycast out to infinity!
const val MAX_DISTANCE: Double = 32.0
@JvmStatic
fun raycastEnd(origin: Vec3, look: Vec3): Vec3 =
origin.add(look.normalize().scale(MAX_DISTANCE))
/**
* Try to get a value of the given type.
*/
@JvmStatic
inline fun <reified T : Any> List<SpellDatum<*>>.getChecked(idx: Int): T {
val datum = this[idx]
val casted = datum.tryGet<T>()
return if (casted is Double && !casted.isFinite())
0.0 as T
else
casted
}
@JvmStatic
fun spellListOf(vararg vs: Any): List<SpellDatum<*>> {
val out = ArrayList<SpellDatum<*>>(vs.size)
for (v in vs) {
out.add(SpellDatum.make(v))
}
return out
}
}
}

View File

@ -0,0 +1,25 @@
package at.petrak.hex.casting.operators.spells
import at.petrak.hex.casting.CastingContext
import at.petrak.hex.casting.RenderedSpell
import at.petrak.hex.casting.SpellDatum
import at.petrak.hex.casting.operators.SpellOperator
import at.petrak.hex.casting.operators.SpellOperator.Companion.spellListOf
import net.minecraft.Util
import net.minecraft.network.chat.TextComponent
object OpPrint : SpellOperator {
override val argc = 1
override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> {
return spellListOf(Spell(args[0]))
}
class Spell(private val datum: SpellDatum<*>) : RenderedSpell {
override fun cast(ctx: CastingContext) {
ctx.caster.sendMessage(
TextComponent(datum.toString()),
Util.NIL_UUID
)
}
}
}

View File

@ -0,0 +1,87 @@
package at.petrak.hex.client;
import at.petrak.hex.HexUtils;
import at.petrak.hex.casting.CastingHarness;
import at.petrak.hex.items.HexItems;
import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.LongArrayTag;
import net.minecraft.nbt.Tag;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
// https://github.com/gamma-delta/VCC/blob/master/src/main/java/me/gammadelta/client/VCCRenderOverlays.java
public class HexRenderOverlays {
@SubscribeEvent
public static void renderOverlay(RenderGameOverlayEvent e) {
LocalPlayer player = Minecraft.getInstance().player;
ItemStack held = player.getMainHandItem();
if (held.getItem() == HexItems.wand.get()) {
tryRenderCastOverlay(e, player, held);
}
}
private static void tryRenderCastOverlay(RenderGameOverlayEvent e, LocalPlayer player, ItemStack wand) {
if (wand.hasTag() && !wand.getTag().isEmpty()) {
CompoundTag tag = wand.getTag();
if (tag.contains(CastingHarness.TAG_POINTS)) {
PoseStack ps = e.getMatrixStack();
Minecraft mc = Minecraft.getInstance();
MultiBufferSource buffers = mc.renderBuffers().bufferSource();
Vec3 camPos = mc.gameRenderer.getMainCamera().getPosition();
Vec3 eyePos = player.getEyePosition(e.getPartialTicks());
ps.pushPose();
ps.translate(camPos.x, camPos.y, camPos.z);
// comment from when i tried to do this in VCC says I need this
// the chain of trust goes back to eutro
// *shudders*
ps.translate(-eyePos.x, -eyePos.y, -eyePos.z);
ListTag tagPointBlobs = tag.getList(CastingHarness.TAG_POINTS, Tag.TAG_LIST);
for (int patIdx = 0; patIdx < tagPointBlobs.size(); patIdx++) {
ListTag tagPoints = tagPointBlobs.getList(patIdx);
// Start new line
VertexConsumer buf = buffers.getBuffer(RenderType.LINES);
for (int idx = 0; idx < tagPoints.size(); idx++) {
// getLongArray is borken, who knew
Vec3 here = HexUtils.deserializeVec3FromNBT(
((LongArrayTag) tagPoints.get(idx)).getAsLongArray());
addVertex(ps, buf, here);
if (idx == tagPoints.size() - 1 &&
patIdx == tagPointBlobs.size() - 1 &&
tag.contains(CastingHarness.TAG_PDS) &&
!tag.getCompound(CastingHarness.TAG_PDS)
.contains(CastingHarness.PatternDrawState.TAG_BETWEEN_PATTERNS)) {
// Draw the final line to the player cursor
VertexConsumer buf1 = buffers.getBuffer(RenderType.LINES);
addVertex(ps, buf1, player.position().add(player.getLookAngle()));
}
}
}
ps.popPose();
}
}
}
private static void addVertex(PoseStack ps, VertexConsumer buf, Vec3 vert) {
buf.vertex(ps.last().pose(), (float) vert.x, (float) vert.y, (float) vert.z)
.color(128, 128, 255, 255)
.endVertex();
}
}

View File

@ -0,0 +1,8 @@
package at.petrak.hex.hexes
enum class HexAngle {
FORWARD, RIGHT, RIGHT_BACK, BACK, LEFT_BACK, LEFT;
fun rotatedBy(a: HexAngle) = values()[(this.ordinal + a.ordinal) % values().size]
operator fun times(a: HexAngle) = this.rotatedBy(a)
}

View File

@ -0,0 +1,20 @@
package at.petrak.hex.hexes
/**
* Uses axial coordinates as per https://www.redblobgames.com/grids/hexagons/
*/
@JvmRecord
data class HexCoord(val q: Int, val r: Int) {
fun s(): Int = this.q - this.r
fun shiftedBy(x: HexCoord): HexCoord = HexCoord(this.q + x.q, this.r + x.r)
fun shiftedBy(d: HexDir) = this.shiftedBy(d.asDelta())
operator fun plus(x: HexCoord) = this.shiftedBy(x)
operator fun plus(d: HexDir) = this.shiftedBy(d)
companion object {
val Origin = HexCoord(0, 0)
}
}

View File

@ -0,0 +1,25 @@
package at.petrak.hex.hexes
enum class HexDir {
NORTH_EAST, EAST, SOUTH_EAST, SOUTH_WEST, WEST, NORTH_WEST;
fun rotatedBy(a: HexAngle): HexDir =
values()[(this.ordinal + a.ordinal).mod(values().size)]
operator fun times(a: HexAngle) = this.rotatedBy(a)
fun angleFrom(other: HexDir): HexAngle =
HexAngle.values()[(this.ordinal - other.ordinal).mod(HexAngle.values().size)]
operator fun minus(other: HexDir) = this.angleFrom(other)
fun asDelta(): HexCoord =
when (this) {
NORTH_EAST -> HexCoord(1, -1)
EAST -> HexCoord(1, 0)
SOUTH_EAST -> HexCoord(0, 1)
SOUTH_WEST -> HexCoord(-1, 1)
WEST -> HexCoord(-1, 0)
NORTH_WEST -> HexCoord(0, -1)
}
}

View File

@ -0,0 +1,74 @@
package at.petrak.hex.hexes
/**
* Sequence of angles to define a pattern traced.
*/
@JvmRecord
data class HexPattern(val startDir: HexDir, val angles: MutableList<HexAngle> = arrayListOf()) {
/**
* @return True if it successfully appended, false if not.
*/
fun tryAppendDir(newDir: HexDir): Boolean {
// Two restrictions:
// - No adding a pos/dir pair we previously added
// - No backtracking
val linesSeen = mutableSetOf<Pair<HexCoord, HexDir>>()
var compass = this.startDir
var cursor = HexCoord.Origin
for (a in this.angles) {
linesSeen.add(Pair(cursor, compass))
cursor += compass
compass *= a
}
val potentialNewLine = Pair(cursor, newDir)
if (potentialNewLine in linesSeen) return false
val nextAngle = newDir - compass
if (nextAngle == HexAngle.BACK) return false
this.angles.add(nextAngle)
return true
}
@JvmOverloads
fun positions(start: HexCoord = HexCoord.Origin): List<HexCoord> {
val out: ArrayList<HexCoord> = ArrayList(this.angles.size + 2)
out.add(start)
var compass: HexDir = this.startDir
var cursor = start
for (a in this.angles) {
cursor += compass
out.add(cursor)
compass *= a
}
out.add(cursor.shiftedBy(compass))
return out
}
// Terrible shorthand method for easy matching
fun anglesSignature(): String {
return buildString {
for (a in this@HexPattern.angles) {
append(
when (a) {
HexAngle.FORWARD -> "w"
HexAngle.RIGHT -> "e"
HexAngle.RIGHT_BACK -> "d"
HexAngle.BACK -> "s"
HexAngle.LEFT_BACK -> "a"
HexAngle.LEFT -> "q"
}
)
}
}
}
override fun toString(): String = buildString {
append("[HexPattern ")
append(this@HexPattern.startDir)
append(", ")
append(this@HexPattern.anglesSignature())
append("]")
}
}

View File

@ -0,0 +1,23 @@
package at.petrak.hex.items;
import at.petrak.hex.HexMod;
import at.petrak.hex.lib.LibItemNames;
import net.minecraft.world.item.Item;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;
public class HexItems {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, HexMod.MOD_ID);
public static final RegistryObject<Item> wand = ITEMS.register(LibItemNames.WAND,
() -> new ItemWand(unstackable()));
public static Item.Properties props() {
return new Item.Properties();
}
public static Item.Properties unstackable() {
return props().stacksTo(1);
}
}

View File

@ -0,0 +1,63 @@
package at.petrak.hex.items;
import at.petrak.hex.casting.CastingHarness;
import at.petrak.hex.casting.CastingHarness.CastResult;
import net.minecraft.Util;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.ItemUtils;
import net.minecraft.world.level.Level;
public class ItemWand extends Item {
public ItemWand(Properties pProperties) {
super(pProperties);
}
@Override
public void inventoryTick(ItemStack stack, Level world, Entity entity, int slotId, boolean isSelected) {
super.inventoryTick(stack, world, entity, slotId, isSelected);
if (world.isClientSide() || !isSelected) {
return;
}
ServerPlayer player = (ServerPlayer) entity;
CompoundTag stackTag = stack.getOrCreateTag();
if (!stackTag.isEmpty() || player.isUsingItem()) {
CastingHarness harness = CastingHarness.DeserializeFromNBT(stack.getOrCreateTag(), player);
CastResult res = harness.update();
if (!(res instanceof CastResult.Nothing)) {
if (res instanceof CastResult.Success) {
CastResult.Success success = (CastResult.Success) res;
success.getSpell().cast(harness.getCtx());
} else if (res instanceof CastResult.Error) {
CastResult.Error error = (CastResult.Error) res;
player.sendMessage(new TextComponent(error.toString()), Util.NIL_UUID);
}
// In any case clear the tag, we're through
stack.setTag(new CompoundTag());
} else {
// Save back the context
stack.setTag(harness.serializeToNBT());
}
}
}
@Override
public int getUseDuration(ItemStack pStack) {
return 9001;
}
@Override
public InteractionResultHolder<ItemStack> use(Level pLevel, Player pPlayer, InteractionHand pUsedHand) {
return ItemUtils.startUsingInstantly(pLevel, pPlayer, pUsedHand);
}
}

View File

@ -0,0 +1,5 @@
package at.petrak.hex.lib;
public class LibItemNames {
public static final String WAND = "wand";
}

View File

@ -0,0 +1,23 @@
package at.petrak.hex.lib;
import at.petrak.hex.HexMod;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.registries.IForgeRegistry;
import net.minecraftforge.registries.IForgeRegistryEntry;
public class RegisterHelper {
// yoinked from botnia
public static <V extends IForgeRegistryEntry<V>> void register(IForgeRegistry<V> reg, ResourceLocation name,
IForgeRegistryEntry<V> thing) {
reg.register(thing.setRegistryName(name));
}
public static <V extends IForgeRegistryEntry<V>> void register(IForgeRegistry<V> reg, String name,
IForgeRegistryEntry<V> thing) {
register(reg, prefix(name), thing);
}
public static ResourceLocation prefix(String path) {
return new ResourceLocation(HexMod.MOD_ID, path);
}
}

View File

@ -0,0 +1,62 @@
# This is an example mods.toml file. It contains the data relating to the loading mods.
# There are several mandatory fields (#mandatory), and many more that are optional (#optional).
# The overall format is standard TOML format, v0.5.0.
# Note that there are a couple of TOML lists in this file.
# Find more information on toml format here: https://github.com/toml-lang/toml
# The name of the mod loader type to load - for regular FML @Mod mods it should be javafml
modLoader = "javafml" #mandatory
# A version range to match for said mod loader - for regular FML @Mod it will be the forge version
loaderVersion = "[39,)" #mandatory This is typically bumped every Minecraft version by Forge. See our download page for lists of versions.
# The license for you mod. This is mandatory metadata and allows for easier comprehension of your redistributive properties.
# Review your options at https://choosealicense.com/. All rights reserved is the default copyright stance, and is thus the default here.
license = "MIT"
# A URL to refer people to when problems occur with this mod
#issueTrackerURL="https://change.me.to.your.issue.tracker.example.invalid/" #optional
# A list of mods - how many allowed here is determined by the individual mod loader
[[mods]] #mandatory
# The modid of the mod
modId = "hex" #mandatory
# The version number of the mod - there's a few well known ${} variables useable here or just hardcode it
# ${file.jarVersion} will substitute the value of the Implementation-Version as read from the mod's JAR file metadata
# see the associated build.gradle script for how to populate this completely automatically during a build
version = "${file.jarVersion}" #mandatory
# A display name for the mod
displayName = "Hex" #mandatory
# A URL to query for updates for this mod. See the JSON update specification https://mcforge.readthedocs.io/en/latest/gettingstarted/autoupdate/
#updateJSONURL="https://change.me.example.invalid/updates.json" #optional
# A URL for the "homepage" for this mod, displayed in the mod UI
#displayURL="https://change.me.to.your.mods.homepage.example.invalid/" #optional
# A file name (in the root of the mod JAR) containing a logo for display
logoFile = "examplemod.png" #optional
# A text field displayed in the mod UI
credits = "Thanks for this example mod goes to Java" #optional
# A text field displayed in the mod UI
authors = "Love, Cheese and small house plants" #optional
# The description text for the mod (multi line!) (#mandatory)
description = '''
This is a long form description of the mod. You can write whatever you want here
Have some lorem ipsum.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed mollis lacinia magna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed sagittis luctus odio eu tempus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque volutpat ligula eget lacus auctor sagittis. In hac habitasse platea dictumst. Nunc gravida elit vitae sem vehicula efficitur. Donec mattis ipsum et arcu lobortis, eleifend sagittis sem rutrum. Cras pharetra quam eget posuere fermentum. Sed id tincidunt justo. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
'''
# A dependency - use the . to indicate dependency for a specific modid. Dependencies are optional.
[[dependencies.examplemod]] #optional
# the modid of the dependency
modId = "forge" #mandatory
# Does this dependency have to exist - if not, ordering below must be specified
mandatory = true #mandatory
# The version range of the dependency
versionRange = "[39,)" #mandatory
# An ordering relationship for the dependency - BEFORE or AFTER required if the relationship is not mandatory
ordering = "NONE"
# Side this dependency is applied on - BOTH, CLIENT or SERVER
side = "BOTH"
# Here's another dependency
[[dependencies.examplemod]]
modId = "minecraft"
mandatory = true
# This version range declares a minimum of the current minecraft version up to but not including the next major version
versionRange = "[1.18.1,1.19)"
ordering = "NONE"
side = "BOTH"

View File

@ -0,0 +1,6 @@
{
"pack": {
"description": "examplemod resources",
"pack_format": 8
}
}