diff --git a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml b/.github/ISSUE_TEMPLATE/BUG_REPORT.yml deleted file mode 100644 index 667c315f..00000000 --- a/.github/ISSUE_TEMPLATE/BUG_REPORT.yml +++ /dev/null @@ -1,76 +0,0 @@ -name: Report a Bug -description: File a bug report -title: "[Bug] " -labels: [ "bug" ] -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to report a Bug in BCLib! - - type: textarea - id: what-happened - attributes: - label: What happened? - description: Also tell us, what did you expect to happen? - placeholder: Tell us what you see! - value: "A bug happened!" - validations: - required: true - - type: markdown - attributes: - value: | - ## Versions - - type: input - id: bn_version - attributes: - label: BCLib - description: What version of BCLib are you running? - placeholder: 2.x.x - validations: - required: true - - type: input - id: fabric_api_version - attributes: - label: Fabric API - description: What version of Fabric API is installed - placeholder: 0.5x.x - validations: - required: false - - type: input - id: fabric_loader_version - attributes: - label: Fabric Loader - description: What version of Fabric Loader do you use - placeholder: 0.14.x - validations: - required: false - - type: dropdown - id: mc_version - attributes: - label: Minecraft - description: What version of Minecraft is installed? - options: - - 1.19.1 - - 1.19 - - 1.18.2 - - 1.18.1 - - 1.18 - - Older - validations: - required: true - - type: markdown - attributes: - value: | - ## Additional Information - - type: textarea - id: logs - attributes: - label: Relevant log output - description: Please copy and paste any relevant log output. This will be automatically formatted into code, so no need for backticks. - render: shell - - type: textarea - id: other_mods - attributes: - label: Other Mods - description: If you can, please supply a list of installed Mods (besides BetterNether and BCLib). This information may already be included in the log above. - render: shell diff --git a/.github/ISSUE_TEMPLATE/SUGGEST_FROM.yml b/.github/ISSUE_TEMPLATE/SUGGEST_FROM.yml deleted file mode 100644 index 8b40a8bb..00000000 --- a/.github/ISSUE_TEMPLATE/SUGGEST_FROM.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Suggest a Feature or Change -description: Have a new Idea, then suggest a Feature here. -title: "[Suggestion] " -labels: ["suggestion"] -body: - - type: markdown - attributes: - value: | - Thanks for taking the time to suggest a new Feature for BCLib. We appreciate your time! - - type: textarea - id: describe - attributes: - label: Description - description: Tell us your idea - placeholder: - value: - validations: - required: true \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index a49eab2f..00000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1 +0,0 @@ -blank_issues_enabled: true \ No newline at end of file diff --git a/.gitignore b/.gitignore index 2a6f330a..6019df58 100644 --- a/.gitignore +++ b/.gitignore @@ -27,7 +27,5 @@ bin/ # fabric run/ -run-client/ -run-server/ output/ *.log diff --git a/BetterX_CodeFormat.xml b/BetterX_CodeFormat.xml deleted file mode 100644 index ee85f79d..00000000 --- a/BetterX_CodeFormat.xml +++ /dev/null @@ -1,40 +0,0 @@ - - \ No newline at end of file diff --git a/LICENSE b/LICENSE index 9caa064f..419a3b02 100644 --- a/LICENSE +++ b/LICENSE @@ -19,7 +19,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -___________________________ -Some of our Assets (see LICENSE.ASSETS for a Listing) is licensed under CC BY-NC-SA 4.0 -See https://creativecommons.org/licenses/by-nc-sa/4.0/ for Details. diff --git a/LICENSE.ASSETS b/LICENSE.ASSETS deleted file mode 100644 index f2ef219a..00000000 --- a/LICENSE.ASSETS +++ /dev/null @@ -1,14 +0,0 @@ -Some of our Assets (see List below) is licensed under CC BY-NC-SA 4.0 -See https://creativecommons.org/licenses/by-nc-sa/4.0/ for Details. - -Please use the Attribution "Team BetterX". - -The following Files are distributed under this License: - * src/main/resources/assets/bclib/lang/de_de.json - * src/main/resources/assets/bclib/textures/* - * src/main/resources/assets/bclib/betterx.png - * src/main/resources/assets/bclib/header.jpg - * src/main/resources/assets/bclib/icon_betterend.png - * src/main/resources/assets/bclib/icon_betternether.png - * src/main/resources/assets/bclib/icon_bright.png - * src/main/resources/assets/bclib/icon_updater.png \ No newline at end of file diff --git a/README.md b/README.md index 1afe21c6..814d89b5 100644 --- a/README.md +++ b/README.md @@ -1,146 +1,41 @@ -[![](https://jitpack.io/v/quiqueck/BCLib.svg)](https://jitpack.io/#quiqueck/BCLib) - +[![](https://jitpack.io/v/paulevsGitch/BCLib.svg)](https://jitpack.io/#paulevsGitch/BCLib) # BCLib - -BCLib is a library mod for BetterX team mods, developed for Fabric, MC 1.19 - -## Importing: - -You can easily include BCLib into your own mod by adding the following to your `build.gradle`: - -``` -repositories { - ... - maven { url 'https://jitpack.io' } -} -``` - -``` -dependencies { - ... - modImplementation "com.github.quiqueck:BCLib:${project.bclib_version}" -} -``` - -You should also add a dependency to `fabirc.mod.json`. BCLib uses Semantic versioning, so adding the dependcy as follows -should respect that and ensure that your mod is not loaded with an incompatible version of BCLib: - -``` -"depends": { - ... - "bclib": "2.0.x" -}, -"breaks": { - "bclib": "<2.0.6" -} -``` - -In this example `2.0.6` is the BCLIb Version you are building against. +BCLib is a library mod for BetterX team mods, developed for Fabric, MC 1.16.5 ## Features: - -### Rendering - -* Emissive textures (with _e suffix) - * Can be applied to Solid and Transparent blocks; - * Can be changed/added with resourcepacks; - * Incompatible with Sodium and Canvas (just will be not rendered); - * Incompatible with Iris shaders (Iris without shaders works fine). -* Procedural block and item models (from paterns or from code); -* Block render interfaces. - ### API: - -* Simple Mod Integration API: - * Get mod inner methods, classes and objects on runtime. -* Structure Features API: - * Sructure Features with automatical registration, Helpers and math stuff. -* World Data API: - * World fixers for comfortable migration between mod versions when content was removed; - * Support for Block name changes and Tile Entities (WIP). -* Bonemeal API: - * Add custom spreadable blocks; - * Add custom plants grow with weight, biomes and other checks; - * Custom underwater plants. -* Features API: - * Features with automatical registration, Helpers and math. -* Biome API: - * Biome wrapper around MC biomes; - * Custom biome data storage; - * Custom fog density. -* Tag API: - * Pre-builded set of tags; - * Dynamical tag registration with code; - * Adding blocks and items into tags at runtime. +* Simple Mod Integration API; +* Structure Features API; +* World Data API; +* Bonemeal API; +* Features API; +* Biome API; +* Tag API. ### Libs: - -* Spline library (simple): - * Helper to create simple splines as set of points; - * Some basic operation with splines; - * Converting splines to SDF. -* Recipe manager: - * Register recipes from code with configs and ingredients check. -* Noise library: - * Voronoi noise and Open Simplex Noise. -* Math library: - * Many basic math functions that are missing in MC. -* SDF library: - * Implementation of Signed Distance Functions; - * Different SDF Operations and Primitives; - * Different materials for SDF Primitives; - * Block post-processing; - * Feature generation using SDF. +* Spline library (simple); +* Recipe manager; +* Noise library; +* Math library; +* SDF library. ### Helpers And Utils: +* Custom surface builders; +* Translation helper; +* Weighted list; +* Block helper. -* Custom surface builders. -* Translation helper: - * Generates translation template. -* Weighted list: - * A list of objects by weight; -* Weighted Tree: - * Fast approach for big weight structures; -* Block helper: - * Some useful functions to operate with blocks; +### Rendering: +* Procedural block models (from paterns or from code); +* Block render layer interface. -### Complex Materials - -* Utility classes used for mass content generation (wooden blocks, stone blocks, etc.); -* Contains a set of defined blocks, items, recipes and tags; -* Can be modified before mods startup (will add new block type for all instances in all mods); -* All inner blocks and items are Patterned (will have auto-generated models with ability to override them with resource - packs or mod resources). - -### Pre-Defined Blocks and Items: - -* Most basic blocks from MC; -* Automatic item & block model generation; - -### Configs: - -* Custom config system based on Json; -* Hierarchical configs; -* Different entry types; -* Only-changes saves. - -### Interfaces: - -* BlockModelProvider: - * Allows block to return custom model and blockstate. -* ItemModelProvider: - * Allows block to return custom item model. -* CustomColorProvider: - * Make available to add block and item color provider. -* RenderLayerProvider: - * Determine block render layer (Transparent and Translucent). -* PostInitable: - * Allows block to init something after all mods are loaded. -* CustomItemProvider: - * Allows block to change its registered item (example - signs, water lilies). +## Importing: +* Clone repo +* Edit gradle.properties if necessary +* Run command line in folder: gradlew genSources eclipse (or Another-IDE-Name) +* Import project to IDE ## Building: - * Clone repo * Run command line in folder: gradlew build * Mod .jar will be in ./build/libs diff --git a/bclib-composit.gradle b/bclib-composit.gradle deleted file mode 100644 index 3d9f10e6..00000000 --- a/bclib-composit.gradle +++ /dev/null @@ -1,8 +0,0 @@ -plugins { - id 'idea' - id 'eclipse' - id 'fabric-loom' - id 'maven-publish' -} - -apply from: "bclib.gradle" \ No newline at end of file diff --git a/bclib.gradle b/bclib.gradle deleted file mode 100644 index 042875ca..00000000 --- a/bclib.gradle +++ /dev/null @@ -1,149 +0,0 @@ -buildscript { - dependencies { - classpath 'org.kohsuke:github-api:1.114' - } - - repositories { - gradlePluginPortal() - } -} -sourceCompatibility = JavaVersion.VERSION_17 -targetCompatibility = JavaVersion.VERSION_17 - -archivesBaseName = project.archives_base_name -version = project.mod_version -group = project.maven_group - -repositories { - maven { url "https://maven.dblsaiko.net/" } - maven { url "https://maven.fabricmc.net/" } - maven { url "https://maven.shedaniel.me/" } - maven { url 'https://maven.blamejared.com' } - maven { url 'https://jitpack.io' } - maven { url 'https://maven.terraformersmc.com/releases' } - maven { url 'https://maven.terraformersmc.com' } -} - -loom { - accessWidenerPath = file("src/main/resources/bclib.accesswidener") -} - -dependencies { - minecraft "com.mojang:minecraft:${project.minecraft_version}" - mappings loom.officialMojangMappings() - modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" - modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" - modCompileOnly "com.terraformersmc:modmenu:${project.modmenu_version}" - - modCompileOnly "dev.emi:emi:${emi_version}" - //modImplementation "dev.emi:emi:${emi_version}" -} - -processResources { - println "Version: ${project.mod_version}" - inputs.property "version", project.mod_version - - filesMatching("fabric.mod.json") { - expand "version": project.mod_version - } -} - -// ensure that the encoding is set to UTF-8, no matter what the system default is -// this fixes some edge cases with special characters not displaying correctly -// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html -tasks.withType(JavaCompile) { - options.encoding = "UTF-8" - it.options.release = 17 -} - -javadoc { - options.tags = ["reason"] - options.stylesheetFile = new File(projectDir, "javadoc.css"); -} - -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir -} - -// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task -// if it is present. -// If you remove this task, sources will not be generated. -task sourcesJar(type: Jar, dependsOn: classes) { - classifier = 'sources' - from sourceSets.main.allSource -} - -jar { - from "LICENSE" - from "LICENSE.ASSETS" -} - -artifacts { - archives sourcesJar - archives javadocJar -} - -def env = System.getenv() - -import org.kohsuke.github.GHReleaseBuilder -import org.kohsuke.github.GitHub - -task release(dependsOn: [remapJar, sourcesJar, javadocJar]) { - onlyIf { - env.GITHUB_TOKEN - } - - doLast { - def github = GitHub.connectUsingOAuth(env.GITHUB_TOKEN as String) - def repository = github.getRepository("quiqueck/BCLib") - - def releaseBuilder = new GHReleaseBuilder(repository, version as String) - releaseBuilder.name("${archivesBaseName}-${version}") - releaseBuilder.body("A changelog can be found at https://github.com/quiqueck/BCLib/commits") - releaseBuilder.commitish("main") - - def ghRelease = releaseBuilder.create() - ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}.jar"), "application/java-archive"); - ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-sources.jar"), "application/java-archive"); - ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-javadoc.jar"), "application/java-archive"); - } -} - -// configure the maven publication -publishing { - publications { - gpr(MavenPublication) { - artifactId archivesBaseName - artifact(remapJar) { - builtBy remapJar - } - artifact(sourcesJar) { - builtBy remapSourcesJar - } - } - } - - // select the repositories you want to publish to - repositories { - maven { - name = "GitHubPackages" - url = uri("https://maven.pkg.github.com/quiqueck/bclib") - credentials { - username = env.GITHUB_USER - password = env.GITHUB_TOKEN - } - } - } -} - -configurations { - dev { - canBeResolved = false - canBeConsumed = true - } -} - -artifacts { - dev jar -} diff --git a/build.gradle b/build.gradle index e1d0a7ff..9d232758 100644 --- a/build.gradle +++ b/build.gradle @@ -1,8 +1,164 @@ +buildscript { + dependencies { + classpath 'org.kohsuke:github-api:1.114' + } +} + plugins { id 'idea' id 'eclipse' - id 'fabric-loom' version "${loom_version}" + id 'fabric-loom' version '0.8-SNAPSHOT' id 'maven-publish' } -apply from: "bclib.gradle" \ No newline at end of file +sourceCompatibility = JavaVersion.VERSION_16 +targetCompatibility = JavaVersion.VERSION_16 + +archivesBaseName = project.archives_base_name +version = project.mod_version +group = project.maven_group + +repositories { + maven { url "https://maven.dblsaiko.net/" } + maven { url "https://server.bbkr.space:8081/artifactory/libs-release/" } + maven { url "https://maven.fabricmc.net/" } + maven { url 'https://maven.blamejared.com' } + maven { url "https://maven.shedaniel.me/" } + maven { url 'https://jitpack.io' } +} + +dependencies { + minecraft "com.mojang:minecraft:${project.minecraft_version}" + mappings minecraft.officialMojangMappings() + modImplementation "net.fabricmc:fabric-loader:${project.loader_version}" + modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}" + + //useApi "vazkii.patchouli:Patchouli:1.16.4-${project.patchouli_version}" +} + +def useOptional(String dep) { + dependencies.modRuntime (dep) { + exclude group: "net.fabricmc.fabric-api" + exclude group: "net.fabricmc" + if (!dep.contains("me.shedaniel")) { + exclude group: "me.shedaniel" + } + } + dependencies.modCompileOnly (dep) { + exclude group: "net.fabricmc.fabric-api" + exclude group: "net.fabricmc" + if (!dep.contains("me.shedaniel")) { + exclude group: "me.shedaniel" + } + } +} + +def useApi(String dep) { + dependencies.modApi (dep) { + exclude group: "net.fabricmc.fabric-api" + exclude group: "net.fabricmc" + if (!dep.contains("me.shedaniel")) { + exclude group: "me.shedaniel" + } + } +} + +processResources { + inputs.property "version", project.version + duplicatesStrategy = 'EXCLUDE' + + from(sourceSets.main.resources.srcDirs) { + include "fabric.mod.json" + expand "version": project.version + } + + from(sourceSets.main.resources.srcDirs) { + exclude "fabric.mod.json" + } +} + +// ensure that the encoding is set to UTF-8, no matter what the system default is +// this fixes some edge cases with special characters not displaying correctly +// see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html +tasks.withType(JavaCompile) { + options.encoding = "UTF-8" +} + +javadoc { + options.tags = [ "reason" ] +} + +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} + +// Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task +// if it is present. +// If you remove this task, sources will not be generated. +task sourcesJar(type: Jar, dependsOn: classes) { + classifier = 'sources' + from sourceSets.main.allSource +} + +jar { + from "LICENSE" +} + +artifacts { + archives sourcesJar + archives javadocJar +} + +def env = System.getenv() + +import org.kohsuke.github.GHReleaseBuilder +import org.kohsuke.github.GitHub + +task release(dependsOn: [remapJar, sourcesJar, javadocJar]) { + onlyIf { + env.GITHUB_TOKEN + } + + doLast { + def github = GitHub.connectUsingOAuth(env.GITHUB_TOKEN as String) + def repository = github.getRepository("paulevsGitch/BCLib") + + def releaseBuilder = new GHReleaseBuilder(repository, version as String) + releaseBuilder.name("${archivesBaseName}-${version}") + releaseBuilder.body("A changelog can be found at https://github.com/paulevsGitch/BCLib/commits") + releaseBuilder.commitish("main") + + def ghRelease = releaseBuilder.create() + ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}.jar"), "application/java-archive"); + ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-sources.jar"), "application/java-archive"); + ghRelease.uploadAsset(file("${project.buildDir}/libs/${archivesBaseName}-${version}-javadoc.jar"), "application/java-archive"); + } +} + +// configure the maven publication +publishing { + publications { + gpr(MavenPublication) { + artifactId archivesBaseName + artifact(remapJar) { + builtBy remapJar + } + artifact(sourcesJar) { + builtBy remapSourcesJar + } + } + } + + // select the repositories you want to publish to + repositories { + maven { + name = "GitHubPackages" + url = uri("https://maven.pkg.github.com/paulevsgitch/bclib") + credentials { + username = env.GITHUB_USER + password = env.GITHUB_TOKEN + } + } + } +} diff --git a/gradle.properties b/gradle.properties index 29084562..f0252152 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,16 +1,18 @@ # Done to increase the memory available to gradle. -org.gradle.jvmargs=-Xmx8G -#Loom -loom_version=0.12-SNAPSHOT +org.gradle.jvmargs=-Xmx2G + # Fabric Properties -# check these on https://fabricmc.net/versions.html -minecraft_version=1.19.2 -loader_version=0.14.9 -fabric_version=0.60.0+1.19.2 +# check these on https://fabricmc.net/use +minecraft_version= 1.17 +yarn_mappings= 6 +loader_version= 0.11.6 + # Mod Properties -mod_version=2.1.0 -maven_group=org.betterx.bclib -archives_base_name=bclib +mod_version = 0.2.0 +maven_group = ru.bclib +archives_base_name = bclib + # Dependencies -modmenu_version=4.0.5 -emi_version=0.3.0+1.19 \ No newline at end of file +# currently not on the main fabric site, check on the maven: https://maven.fabricmc.net/net/fabricmc/fabric-api/fabric-api +patchouli_version = 50-FABRIC +fabric_version = 0.36.0+1.17 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180f..490fda85 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index e750102e..f371643e 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-7.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew old mode 100755 new mode 100644 index 1b6c7873..2fe81a7d --- a/gradlew +++ b/gradlew @@ -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"); # 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. -# -# 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/. -# +## +## Gradle start up script for UN*X +## ############################################################################## # 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 +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi done - -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null APP_NAME="Gradle" -APP_BASE_NAME=${0##*/} +APP_BASE_NAME=`basename "$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 +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 ;; +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + 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 + JAVACMD="$JAVA_HOME/jre/sh/java" else - JAVACMD=$JAVA_HOME/bin/java + JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then 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." fi 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. Please set the JAVA_HOME variable in your environment to match the @@ -140,95 +105,79 @@ 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 +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi 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 Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi # 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" ) +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` - 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 + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" 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=`expr $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 -# 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. +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` -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' ' ' - )" '"$@"' +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat index ac1b06f9..9109989e 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -40,7 +40,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -54,7 +54,7 @@ goto fail set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe -if exist "%JAVA_EXE%" goto execute +if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% @@ -64,14 +64,28 @@ echo location of your Java installation. 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 @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 %* +"%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 @rem End local scope for the variables with windows NT shell diff --git a/javadoc.css b/javadoc.css deleted file mode 100644 index e393f777..00000000 --- a/javadoc.css +++ /dev/null @@ -1,903 +0,0 @@ -/* - * Javadoc style sheet - */ - -@import url("resources/fonts/dejavu.css"); - -/* - * Styles for individual HTML elements. - * - * These are styles that are specific to individual HTML elements. Changing them affects the style of a particular - * HTML element throughout the page. - */ - -body { - background-color: #ffffff; - color: #353833; - font-family: "DejaVu Sans", Arial, Helvetica, sans-serif; - font-size: 14px; - margin: 0; - padding: 0; - height: 100%; - width: 100%; -} -iframe { - margin: 0; - padding: 0; - height: 100%; - width: 100%; - overflow-y: scroll; - border: none; -} -a:link, -a:visited { - text-decoration: none; - color: #4a6782; -} -a[href]:hover, -a[href]:focus { - text-decoration: none; - color: #bb7a2a; -} -a[name] { - color: #353833; -} -pre { - font-family: "DejaVu Sans Mono", monospace; - font-size: 16px; - background-color: #fffadb; - border-radius: 5px; -} -h1 { - font-size: 20px; -} -h2 { - font-size: 18px; -} -h3 { - font-size: 16px; -} -h4 { - font-size: 13px; -} -h5 { - font-size: 12px; -} -h6 { - font-size: 11px; -} -ul { - list-style-type: disc; -} -code, -tt { - font-family: "DejaVu Sans Mono", monospace; - font-size: 14px; - padding-top: 4px; - margin-top: 8px; - line-height: 1.4em; -} -dt code { - font-family: "DejaVu Sans Mono", monospace; - font-size: 14px; - padding-top: 4px; -} -.summary-table dt code { - font-family: "DejaVu Sans Mono", monospace; - font-size: 14px; - vertical-align: top; - padding-top: 4px; -} -sup { - font-size: 8px; -} -button { - font-family: "DejaVu Sans", Arial, Helvetica, sans-serif; - font-size: 14px; -} -/* - * Styles for HTML generated by javadoc. - * - * These are style classes that are used by the standard doclet to generate HTML documentation. - */ - -/* - * Styles for document title and copyright. - */ -.clear { - clear: both; - height: 0; - overflow: hidden; -} -.about-language { - float: right; - padding: 0 21px 8px 8px; - font-size: 11px; - margin-top: -9px; - height: 2.9em; -} -.legal-copy { - margin-left: 0.5em; -} -.tab { - background-color: #0066ff; - color: #ffffff; - padding: 8px; - width: 5em; - font-weight: bold; -} -/* - * Styles for navigation bar. - */ -@media screen { - .flex-box { - position: fixed; - display: flex; - flex-direction: column; - height: 100%; - width: 100%; - } - .flex-header { - flex: 0 0 auto; - } - .flex-content { - flex: 1 1 auto; - overflow-y: auto; - } -} -.top-nav { - background-color: #4d7a97; - color: #ffffff; - float: left; - padding: 0; - width: 100%; - clear: right; - min-height: 2.8em; - padding-top: 10px; - overflow: hidden; - font-size: 12px; -} -.sub-nav { - background-color: #dee3e9; - float: left; - width: 100%; - overflow: hidden; - font-size: 12px; -} -.sub-nav div { - clear: left; - float: left; - padding: 0 0 5px 6px; - text-transform: uppercase; -} -.sub-nav .nav-list { - padding-top: 5px; -} -ul.nav-list { - display: block; - margin: 0 25px 0 0; - padding: 0; -} -ul.sub-nav-list { - float: left; - margin: 0 25px 0 0; - padding: 0; -} -ul.nav-list li { - list-style: none; - float: left; - padding: 5px 6px; - text-transform: uppercase; -} -.sub-nav .nav-list-search { - float: right; - margin: 0 0 0 0; - padding: 5px 6px; - clear: none; -} -.nav-list-search label { - position: relative; - right: -16px; -} -ul.sub-nav-list li { - list-style: none; - float: left; - padding-top: 10px; -} -.top-nav a:link, -.top-nav a:active, -.top-nav a:visited { - color: #ffffff; - text-decoration: none; - text-transform: uppercase; -} -.top-nav a:hover { - text-decoration: none; - color: #bb7a2a; - text-transform: uppercase; -} -.nav-bar-cell1-rev { - background-color: #f8981d; - color: #253441; - margin: auto 5px; -} -.skip-nav { - position: absolute; - top: auto; - left: -9999px; - overflow: hidden; -} -/* - * Hide navigation links and search box in print layout - */ -@media print { - ul.nav-list, - div.sub-nav { - display: none; - } -} -/* - * Styles for page header and footer. - */ -.title { - color: #2c4557; - margin: 10px 0; -} -.sub-title { - margin: 5px 0 0 0; -} -.header ul { - margin: 0 0 15px 0; - padding: 0; -} -.header ul li, -.footer ul li { - list-style: none; - font-size: 13px; -} -/* - * Styles for headings. - */ -body.class-declaration-page .summary h2, -body.class-declaration-page .details h2, -body.class-use-page h2, -body.module-declaration-page .block-list h2 { - font-style: italic; - padding: 0; - margin: 15px 0; -} -body.class-declaration-page .summary h3, -body.class-declaration-page .details h3, -body.class-declaration-page .summary .inherited-list h2 { - background-color: #dee3e9; - border: 1px solid #d0d9e0; - margin: 0 0 6px -8px; - padding: 7px 5px; -} -/* - * Styles for page layout containers. - */ -main { - clear: both; - padding: 10px 20px; - position: relative; -} -dl.notes > dt { - font-family: "DejaVu Sans", Arial, Helvetica, sans-serif; - font-size: 12px; - font-weight: bold; - margin: 10px 0 0 0; - color: #4e4e4e; -} -dl.notes > dd { - margin: 5px 0 10px 0; - font-size: 15px; - font-family: "Roboto", "DejaVu Sans", "Helvetica Neue", Arial, Helvetica, sans-serif; -} -dl.name-value > dt { - margin-left: 1px; - font-size: 1.1em; - display: inline; - font-weight: bold; -} -dl.name-value > dd { - margin: 0 0 0 1px; - font-size: 1.1em; - display: inline; -} -/* - * Styles for lists. - */ -li.circle { - list-style: circle; -} -ul.horizontal li { - display: inline; - font-size: 0.9em; -} -div.inheritance { - margin: 0; - padding: 0; -} -div.inheritance div.inheritance { - margin-left: 2em; -} -ul.block-list, -ul.details-list, -ul.member-list, -ul.summary-list { - margin: 10px 0 10px 0; - padding: 0; -} -ul.block-list > li, -ul.details-list > li, -ul.member-list > li, -ul.summary-list > li { - list-style: none; - margin-bottom: 15px; - line-height: 1.4; -} -.summary-table dl, -.summary-table dl dt, -.summary-table dl dd { - margin-top: 0; - margin-bottom: 1px; -} -/* - * Styles for tables. - */ -.summary-table { - width: 100%; - border-spacing: 0; - border-left: 1px solid #eee; - border-right: 1px solid #eee; - border-bottom: 1px solid #eee; -} -.summary-table { - padding: 0; -} -.caption { - position: relative; - text-align: left; - background-repeat: no-repeat; - color: #253441; - font-weight: bold; - clear: none; - overflow: hidden; - padding: 0px; - padding-top: 10px; - padding-left: 1px; - margin: 0px; - white-space: pre; -} -.caption a:link, -.caption a:visited { - color: #1f389c; -} -.caption a:hover, -.caption a:active { - color: #ffffff; -} -.caption span { - white-space: nowrap; - padding-top: 5px; - padding-left: 12px; - padding-right: 12px; - padding-bottom: 7px; - display: inline-block; - float: left; - background-color: #f8981d; - border: none; - height: 16px; -} - -div.table-tabs > button { - border: none; - cursor: pointer; - padding: 5px 12px 7px 12px; - font-weight: bold; - margin-right: 3px; -} -div.table-tabs > button.active-table-tab { - background: #f8981d; - color: #253441; -} -div.table-tabs > button.table-tab { - background: #4d7a97; - color: #ffffff; -} -.two-column-summary { - display: grid; - grid-template-columns: minmax(15%, max-content) minmax(15%, auto); -} -.three-column-summary { - display: grid; - grid-template-columns: minmax(10%, max-content) minmax(15%, max-content) minmax(15%, auto); -} -.four-column-summary { - display: grid; - grid-template-columns: minmax(10%, max-content) minmax(10%, max-content) minmax(10%, max-content) minmax(10%, auto); -} -@media screen and (max-width: 600px) { - .two-column-summary { - display: grid; - grid-template-columns: 1fr; - } -} -@media screen and (max-width: 800px) { - .three-column-summary { - display: grid; - grid-template-columns: minmax(10%, max-content) minmax(25%, auto); - } - .three-column-summary .col-last { - grid-column-end: span 2; - } -} -@media screen and (max-width: 1000px) { - .four-column-summary { - display: grid; - grid-template-columns: minmax(15%, max-content) minmax(15%, auto); - } -} -.summary-table > div { - text-align: left; - padding: 8px 3px 3px 7px; -} -.col-first, -.col-second, -.col-last, -.col-constructor-name, -.col-deprecated-item-name { - vertical-align: top; - padding-right: 0; - padding-top: 8px; - padding-bottom: 3px; -} -.table-header { - background: #dee3e9; - font-weight: bold; -} -.col-first, -.col-first { - font-size: 13px; -} -.col-second, -.col-second, -.col-last, -.col-constructor-name, -.col-deprecated-item-name, -.col-last { - font-size: 13px; -} -.col-first, -.col-second, -.col-constructor-name { - vertical-align: top; - overflow: auto; -} -.col-last { - white-space: normal; -} -.col-first a:link, -.col-first a:visited, -.col-second a:link, -.col-second a:visited, -.col-first a:link, -.col-first a:visited, -.col-second a:link, -.col-second a:visited, -.col-constructor-name a:link, -.col-constructor-name a:visited, -.col-deprecated-item-name a:link, -.col-deprecated-item-name a:visited, -.constant-values-container a:link, -.constant-values-container a:visited, -.all-classes-container a:link, -.all-classes-container a:visited, -.all-packages-container a:link, -.all-packages-container a:visited { - font-weight: bold; -} -.table-sub-heading-color { - background-color: #eeeeff; -} -.even-row-color, -.even-row-color .table-header { - background-color: #ffffff; -} -.odd-row-color, -.odd-row-color .table-header { - background-color: #eeeeef; -} -/* - * Styles for contents. - */ -.deprecated-content { - margin: 0; - padding: 10px 0; -} -div.block { - font-size: 15px; - font-family: "Roboto", "DejaVu Sans", "Helvetica Neue", Arial, Helvetica, sans-serif; -} -.col-last div { - padding-top: 0; -} -.col-last a { - padding-bottom: 3px; -} -.module-signature, -.package-signature, -.type-signature, -.member-signature { - font-family: "DejaVu Sans Mono", monospace; - font-size: 14px; - margin: 14px 0; - white-space: pre-wrap; -} -.module-signature, -.package-signature, -.type-signature { - margin-top: 0; -} -.member-signature .type-parameters-long, -.member-signature .parameters, -.member-signature .exceptions { - display: inline-block; - vertical-align: top; - white-space: pre; -} -.member-signature .type-parameters { - white-space: normal; -} -/* - * Styles for formatting effect. - */ -.source-line-no { - color: green; - padding: 0 30px 0 0; -} -h1.hidden { - visibility: hidden; - overflow: hidden; - font-size: 10px; -} -.block { - display: block; - margin: 0 10px 5px 0; - color: #474747; -} -.deprecated-label, -.descfrm-type-label, -.implementation-label, -.member-name-label, -.member-name-link, -.module-label-in-package, -.module-label-in-type, -.override-specify-label, -.package-label-in-type, -.package-hierarchy-label, -.type-name-label, -.type-name-link, -.search-tag-link { - font-weight: bold; -} -.deprecation-comment, -.help-footnote, -.interface-name { - font-style: italic; -} -.deprecation-block { - font-size: 14px; - font-family: "DejaVu Serif", Georgia, "Times New Roman", Times, serif; - border-style: solid; - border-width: thin; - border-radius: 10px; - padding: 10px; - margin-bottom: 10px; - margin-right: 10px; - display: inline-block; -} -div.block div.deprecation-comment, -div.block div.block span.emphasized-phrase, -div.block div.block span.interface-name { - font-style: normal; -} -/* - * Styles specific to HTML5 elements. - */ -main, -nav, -header, -footer, -section { - display: block; -} -/* - * Styles for javadoc search. - */ -.ui-autocomplete-category { - font-weight: bold; - font-size: 15px; - padding: 7px 0 7px 3px; - background-color: #4d7a97; - color: #ffffff; -} -.result-item { - font-size: 13px; -} -.ui-autocomplete { - max-height: 85%; - max-width: 65%; - overflow-y: scroll; - overflow-x: scroll; - white-space: nowrap; - box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16), 0 3px 6px rgba(0, 0, 0, 0.23); -} -ul.ui-autocomplete { - position: fixed; - z-index: 999999; -} -ul.ui-autocomplete li { - float: left; - clear: both; - width: 100%; -} -.result-highlight { - font-weight: bold; -} -#search { - background-image: url("resources/glass.png"); - background-size: 13px; - background-repeat: no-repeat; - background-position: 2px 3px; - padding-left: 20px; - position: relative; - right: -18px; - width: 400px; -} -#reset { - background-color: rgb(255, 255, 255); - background-image: url("resources/x.png"); - background-position: center; - background-repeat: no-repeat; - background-size: 12px; - border: 0 none; - width: 16px; - height: 16px; - position: relative; - left: -4px; - top: -4px; - font-size: 0px; -} -.watermark { - color: #545454; -} -.search-tag-desc-result { - font-style: italic; - font-size: 11px; -} -.search-tag-holder-result { - font-style: italic; - font-size: 12px; -} -.search-tag-result:target { - background-color: yellow; -} -.module-graph span { - display: none; - position: absolute; -} -.module-graph:hover span { - display: block; - margin: -100px 0 0 100px; - z-index: 1; -} -.inherited-list { - margin: 10px 0 10px 0; -} -section.description { - line-height: 1.4; -} -.summary section[class$="-summary"], -.details section[class$="-details"], -.class-uses .detail, -.serialized-class-details { - padding: 0px 20px 5px 10px; - border: 1px solid #ededed; - background-color: #f8f8f8; -} -.inherited-list, -section[class$="-details"] .detail { - padding: 0 0 5px 8px; - background-color: #ffffff; - border: none; -} -.vertical-separator { - padding: 0 5px; -} -ul.help-section-list { - margin: 0; -} -/* - * Indicator icon for external links. - */ -main a[href*="://"]::after -{ - content: ""; - display: inline-block; - background-image: url('data:image/svg+xml; utf8, \ - \ - \ - '); - background-size: 100% 100%; - width: 7px; - height: 7px; - margin-left: 2px; - margin-bottom: 4px; -} -main a[href*="://"]:hover::after, -main a[href*="://"]:focus::after -{ - background-image: url('data:image/svg+xml; utf8, \ - \ - \ - '); -} - -/* - * Styles for user-provided tables. - * - * borderless: - * No borders, vertical margins, styled caption. - * This style is provided for use with existing doc comments. - * In general, borderless tables should not be used for layout purposes. - * - * plain: - * Plain borders around table and cells, vertical margins, styled caption. - * Best for small tables or for complex tables for tables with cells that span - * rows and columns, when the "striped" style does not work well. - * - * striped: - * Borders around the table and vertical borders between cells, striped rows, - * vertical margins, styled caption. - * Best for tables that have a header row, and a body containing a series of simple rows. - */ - -table.borderless, -table.plain, -table.striped { - margin-top: 10px; - margin-bottom: 10px; -} -table.borderless > caption, -table.plain > caption, -table.striped > caption { - font-weight: bold; - font-size: smaller; -} -table.borderless th, -table.borderless td, -table.plain th, -table.plain td, -table.striped th, -table.striped td { - padding: 2px 5px; -} -table.borderless, -table.borderless > thead > tr > th, -table.borderless > tbody > tr > th, -table.borderless > tr > th, -table.borderless > thead > tr > td, -table.borderless > tbody > tr > td, -table.borderless > tr > td { - border: none; -} -table.borderless > thead > tr, -table.borderless > tbody > tr, -table.borderless > tr { - background-color: transparent; -} -table.plain { - border-collapse: collapse; - border: 1px solid black; -} -table.plain > thead > tr, -table.plain > tbody tr, -table.plain > tr { - background-color: transparent; -} -table.plain > thead > tr > th, -table.plain > tbody > tr > th, -table.plain > tr > th, -table.plain > thead > tr > td, -table.plain > tbody > tr > td, -table.plain > tr > td { - border: 1px solid black; -} -table.striped { - border-collapse: collapse; - border: 1px solid black; -} -table.striped > thead { - background-color: #e3e3e3; -} -table.striped > thead > tr > th, -table.striped > thead > tr > td { - border: 1px solid black; -} -table.striped > tbody > tr:nth-child(even) { - background-color: #eee; -} -table.striped > tbody > tr:nth-child(odd) { - background-color: #fff; -} -table.striped > tbody > tr > th, -table.striped > tbody > tr > td { - border-left: 1px solid black; - border-right: 1px solid black; -} -table.striped > tbody > tr > th { - font-weight: normal; -} -/** - * Tweak font sizes and paddings for small screens. - */ -@media screen and (max-width: 1050px) { - #search { - width: 300px; - } -} -@media screen and (max-width: 800px) { - #search { - width: 200px; - } - .top-nav, - .bottom-nav { - font-size: 11px; - padding-top: 6px; - } - .sub-nav { - font-size: 11px; - } - .about-language { - padding-right: 16px; - } - ul.nav-list li, - .sub-nav .nav-list-search { - padding: 6px; - } - ul.sub-nav-list li { - padding-top: 5px; - } - main { - padding: 10px; - } - .summary section[class$="-summary"], - .details section[class$="-details"], - .class-uses .detail, - .serialized-class-details { - padding: 0 8px 5px 8px; - } - body { - -webkit-text-size-adjust: none; - } -} -@media screen and (max-width: 500px) { - #search { - width: 150px; - } - .top-nav, - .bottom-nav { - font-size: 10px; - } - .sub-nav { - font-size: 10px; - } - .about-language { - font-size: 10px; - padding-right: 12px; - } -} diff --git a/jitpack.yml b/jitpack.yml deleted file mode 100644 index e8af8cfd..00000000 --- a/jitpack.yml +++ /dev/null @@ -1,6 +0,0 @@ -# From https://github.com/jitpack/jitpack.io/issues/4506#issuecomment-864562270 -before_install: - - source "$HOME/.sdkman/bin/sdkman-init.sh" - - sdk update - - sdk install java 17.0.1-tem - - sdk use java 17.0.1-tem \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 027b233d..f91a4fe7 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1,9 +1,9 @@ pluginManagement { - repositories { - maven { - name = 'Fabric' - url = 'https://maven.fabricmc.net/' - } - gradlePluginPortal() - } + repositories { + maven { + name = 'Fabric' + url = 'https://maven.fabricmc.net/' + } + gradlePluginPortal() + } } diff --git a/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java b/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java deleted file mode 100644 index fdf56631..00000000 --- a/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.anti_ad.mc.ipn.api; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -// Included from "Inventory Profiles Next" (https://github.com/blackd/Inventory-Profiles) -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) -public @interface IPNIgnore { -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/BCLib.java b/src/main/java/org/betterx/bclib/BCLib.java deleted file mode 100644 index de1bf196..00000000 --- a/src/main/java/org/betterx/bclib/BCLib.java +++ /dev/null @@ -1,168 +0,0 @@ -package org.betterx.bclib; - -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.*; -import org.betterx.bclib.api.v2.generator.BCLibEndBiomeSource; -import org.betterx.bclib.api.v2.generator.BCLibNetherBiomeSource; -import org.betterx.bclib.api.v2.generator.GeneratorOptions; -import org.betterx.bclib.api.v2.levelgen.LevelGenEvents; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeBuilder; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.bclib.api.v2.levelgen.structures.TemplatePiece; -import org.betterx.bclib.api.v2.levelgen.surface.rules.Conditions; -import org.betterx.bclib.api.v2.poi.PoiManager; -import org.betterx.bclib.api.v3.levelgen.features.blockpredicates.BlockPredicates; -import org.betterx.bclib.api.v3.levelgen.features.placement.PlacementModifiers; -import org.betterx.bclib.commands.CommandRegistry; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.networking.VersionChecker; -import org.betterx.bclib.recipes.AnvilRecipe; -import org.betterx.bclib.recipes.CraftingRecipes; -import org.betterx.bclib.registry.BaseBlockEntities; -import org.betterx.bclib.registry.BaseRegistry; -import org.betterx.worlds.together.WorldsTogether; -import org.betterx.worlds.together.util.Logger; -import org.betterx.worlds.together.world.WorldConfig; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.Blocks; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.ModInitializer; -import net.fabricmc.loader.api.FabricLoader; - -import java.util.List; - -public class BCLib implements ModInitializer { - public static final String MOD_ID = "bclib"; - public static final Logger LOGGER = new Logger(MOD_ID); - - public static final boolean RUNS_NULLSCAPE = FabricLoader.getInstance() - .getModContainer("nullscape") - .isPresent(); - - @Override - public void onInitialize() { - WorldsTogether.onInitialize(); - LevelGenEvents.register(); - BlockPredicates.ensureStaticInitialization(); - BCLBiomeRegistry.ensureStaticallyLoaded(); - BaseRegistry.register(); - GeneratorOptions.init(); - BaseBlockEntities.register(); - BCLibEndBiomeSource.register(); - BCLibNetherBiomeSource.register(); - CraftingRecipes.init(); - WorldConfig.registerModCache(MOD_ID); - DataExchangeAPI.registerMod(MOD_ID); - AnvilRecipe.register(); - Conditions.registerAll(); - CommandRegistry.register(); - PoiManager.registerAll(); - - DataExchangeAPI.registerDescriptors(List.of( - HelloClient.DESCRIPTOR, - HelloServer.DESCRIPTOR, - RequestFiles.DESCRIPTOR, - SendFiles.DESCRIPTOR, - Chunker.DESCRIPTOR - ) - ); - - BCLibPatch.register(); - TemplatePiece.ensureStaticInitialization(); - PlacementModifiers.ensureStaticInitialization(); - Configs.save(); - - WorldsTogether.FORCE_SERVER_TO_BETTERX_PRESET = Configs.SERVER_CONFIG.forceBetterXPreset(); - VersionChecker.registerMod(MOD_ID); - - - if (false && isDevEnvironment()) { - BCLBiome theYellow = BCLBiomeBuilder - .start(makeID("the_yellow")) - .precipitation(Biome.Precipitation.NONE) - .temperature(1.0f) - .wetness(1.0f) - .fogColor(0xFFFF00) - .waterColor(0x777700) - .waterFogColor(0xFFFF00) - .skyColor(0xAAAA00) - .addNetherClimateParamater(-1, 1) - .surface(Blocks.YELLOW_CONCRETE) - .build(); - BiomeAPI.registerEndLandBiome(theYellow); - - BCLBiome theBlue = BCLBiomeBuilder - .start(makeID("the_blue")) - .precipitation(Biome.Precipitation.NONE) - .temperature(1.0f) - .wetness(1.0f) - .fogColor(0x0000FF) - .waterColor(0x000077) - .waterFogColor(0x0000FF) - .skyColor(0x0000AA) - .addNetherClimateParamater(-1, 1) - .surface(Blocks.LIGHT_BLUE_CONCRETE) - .build(); - BiomeAPI.registerEndLandBiome(theBlue); - - BCLBiome theGray = BCLBiomeBuilder - .start(makeID("the_gray")) - .precipitation(Biome.Precipitation.NONE) - .temperature(1.0f) - .wetness(1.0f) - .fogColor(0xFFFFFF) - .waterColor(0x777777) - .waterFogColor(0xFFFFFF) - .skyColor(0xAAAAAA) - .addNetherClimateParamater(-1, 1) - .surface(Blocks.GRAY_CONCRETE) - .build(); - BiomeAPI.registerEndVoidBiome(theGray); - - BCLBiome theOrange = BCLBiomeBuilder - .start(makeID("the_orange")) - .precipitation(Biome.Precipitation.NONE) - .temperature(1.0f) - .wetness(1.0f) - .fogColor(0xFF7700) - .waterColor(0x773300) - .waterFogColor(0xFF7700) - .skyColor(0xAA7700) - .addNetherClimateParamater(-1, 1.1f) - .surface(Blocks.ORANGE_CONCRETE) - .build(); - BiomeAPI.registerNetherBiome(theOrange); - - BCLBiome thePurple = BCLBiomeBuilder - .start(makeID("the_purple")) - .precipitation(Biome.Precipitation.NONE) - .temperature(1.0f) - .wetness(1.0f) - .fogColor(0xFF00FF) - .waterColor(0x770077) - .waterFogColor(0xFF00FF) - .skyColor(0xAA00AA) - .addNetherClimateParamater(-1.1f, 1) - .surface(Blocks.PURPLE_CONCRETE) - .build(); - BiomeAPI.registerNetherBiome(thePurple); - } - } - - public static boolean isDevEnvironment() { - return FabricLoader.getInstance().isDevelopmentEnvironment(); - } - - public static boolean isClient() { - return FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT; - } - - public static ResourceLocation makeID(String path) { - return new ResourceLocation(MOD_ID, path); - } -} diff --git a/src/main/java/org/betterx/bclib/BCLibPatch.java b/src/main/java/org/betterx/bclib/BCLibPatch.java deleted file mode 100644 index 3f211530..00000000 --- a/src/main/java/org/betterx/bclib/BCLibPatch.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.betterx.bclib; - -import org.betterx.bclib.api.v2.datafixer.DataFixerAPI; -import org.betterx.bclib.api.v2.datafixer.ForcedLevelPatch; -import org.betterx.bclib.api.v2.datafixer.MigrationProfile; -import org.betterx.bclib.api.v2.generator.GeneratorOptions; -import org.betterx.bclib.api.v2.levelgen.LevelGenUtil; -import org.betterx.bclib.config.Configs; - -import net.minecraft.core.RegistryAccess; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtOps; -import net.minecraft.nbt.Tag; -import net.minecraft.resources.RegistryOps; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.dimension.LevelStem; - -public final class BCLibPatch { - public static void register() { - // TODO separate values in config on client side (config screen) - if (Configs.MAIN_CONFIG.repairBiomes() && (GeneratorOptions.fixEndBiomeSource() || GeneratorOptions.fixNetherBiomeSource())) { - DataFixerAPI.registerPatch(BiomeSourcePatch::new); - } - } -} - -final class BiomeSourcePatch extends ForcedLevelPatch { - private static final String NETHER_BIOME_SOURCE = "bclib:nether_biome_source"; - private static final String END_BIOME_SOURCE = "bclib:end_biome_source"; - private static final String MC_NETHER = "minecraft:the_nether"; - private static final String MC_END = "minecraft:the_end"; - - protected BiomeSourcePatch() { - super(BCLib.MOD_ID, "1.2.1"); - } - - - @Override - protected Boolean runLevelDatPatch(CompoundTag root, MigrationProfile profile) { - //make sure we have a working generators file before attempting to patch - LevelGenUtil.migrateGeneratorSettings(); - - final CompoundTag worldGenSettings = root.getCompound("Data").getCompound("WorldGenSettings"); - final CompoundTag dimensions = worldGenSettings.getCompound("dimensions"); - final RegistryAccess registryAccess = RegistryAccess.builtinCopy(); - final RegistryOps registryOps = RegistryOps.create(NbtOps.INSTANCE, registryAccess); - - - boolean result = false; - - result |= checkDimension(worldGenSettings, dimensions, registryAccess, registryOps, LevelStem.NETHER); - result |= checkDimension(worldGenSettings, dimensions, registryAccess, registryOps, LevelStem.END); - - System.out.println("Dimensions:" + dimensions); - return result; -// if (root != null) return false; -// -// boolean result = false; -// -// if (GeneratorOptions.fixNetherBiomeSource()) { -// if (!dimensions.contains(MC_NETHER) || !isBCLibEntry(dimensions.getCompound(MC_NETHER))) { -// CompoundTag dimRoot = new CompoundTag(); -// dimRoot.put("generator", makeNetherGenerator(seed)); -// dimRoot.putString("type", MC_NETHER); -// dimensions.put(MC_NETHER, dimRoot); -// result = true; -// } -// } -// -// if (GeneratorOptions.fixEndBiomeSource()) { -// if (!dimensions.contains(MC_END) || !isBCLibEntry(dimensions.getCompound(MC_END))) { -// CompoundTag dimRoot = new CompoundTag(); -// dimRoot.put("generator", makeEndGenerator(seed)); -// dimRoot.putString("type", MC_END); -// dimensions.put(MC_END, dimRoot); -// result = true; -// } -// } -// -// return result; - } - - private boolean checkDimension( - CompoundTag worldGenSettings, - CompoundTag dimensions, - RegistryAccess registryAccess, - RegistryOps registryOps, - ResourceKey dimensionKey - ) { - boolean result = false; -// final long seed = worldGenSettings.contains("seed") -// ? worldGenSettings.getLong("seed") -// : MHelper.RANDOM.nextLong(); -// -// final boolean genStructures = !worldGenSettings.contains("generate_features") || worldGenSettings.getBoolean( -// "generate_features"); -// -// final boolean genBonusChest = worldGenSettings.contains("bonus_chest") && worldGenSettings.getBoolean( -// "bonus_chest"); -// -// -// CompoundTag dimensionTag = dimensions.getCompound(dimensionKey.location().toString()); -// Optional oWorldGen = WorldGenSettings.CODEC -// .parse(new Dynamic<>(registryOps, worldGenSettings)) -// .result(); -// -// Optional oLevelStem = LevelStem.CODEC -// .parse(new Dynamic<>(registryOps, dimensionTag)) -// .resultOrPartial(BCLib.LOGGER::error); -// -// Optional netherGenerator = oLevelStem.map(l -> l.generator()); -// int biomeSourceVersion = LevelGenUtil.getBiomeVersionForGenerator(netherGenerator.orElse(null)); -// int targetVersion = LevelGenUtil.getBiomeVersionForCurrentWorld(dimensionKey); -// if (biomeSourceVersion != targetVersion) { -// Optional> refLevelStem = LevelGenUtil.referenceStemForVersion( -// dimensionKey, -// targetVersion, -// registryAccess, -// oWorldGen.map(g -> g.seed()).orElse(seed), -// oWorldGen.map(g -> g.generateStructures()).orElse(genStructures), -// oWorldGen.map(g -> g.generateBonusChest()).orElse(genBonusChest) -// ); -// -// BCLib.LOGGER.warning("The world uses the BiomeSource Version " + biomeSourceVersion + " but should have " + targetVersion + "."); -// BCLib.LOGGER.warning("Dimension: " + dimensionKey); -// BCLib.LOGGER.warning("Found: " + netherGenerator); -// BCLib.LOGGER.warning("Should: " + refLevelStem.map(l -> l.value().generator())); -// -// if (refLevelStem.isPresent()) { -// var levelStem = refLevelStem.get(); -// BCLib.LOGGER.warning("Repairing level.dat in order to ensure world continuity."); -// var codec = LevelStem.CODEC.orElse(levelStem.value()); -// var encodeResult = codec.encodeStart(registryOps, levelStem.value()); -// if (encodeResult.result().isPresent()) { -// dimensions.put(dimensionKey.location().toString(), encodeResult.result().get()); -// result = true; -// } else { -// BCLib.LOGGER.error("Unable to encode '" + dimensionKey + "' generator for level.dat."); -// } -// } else { -// BCLib.LOGGER.error("Unable to update '" + dimensionKey + "' generator in level.dat."); -// } -// } - - return result; - } - - private boolean isBCLibEntry(CompoundTag dimRoot) { - String type = dimRoot.getCompound("generator").getCompound("biome_source").getString("type"); - if (type.isEmpty() || type.length() < 5) { - return false; - } - return type.startsWith("bclib"); - } - - public static CompoundTag makeNetherGenerator(long seed) { - CompoundTag generator = new CompoundTag(); - generator.putString("type", "minecraft:noise"); - generator.putString("settings", "minecraft:nether"); - generator.putLong("seed", seed); - - CompoundTag biomeSource = new CompoundTag(); - biomeSource.putString("type", NETHER_BIOME_SOURCE); - biomeSource.putLong("seed", seed); - generator.put("biome_source", biomeSource); - - return generator; - } - - public static CompoundTag makeEndGenerator(long seed) { - CompoundTag generator = new CompoundTag(); - generator.putString("type", "minecraft:noise"); - generator.putString("settings", "minecraft:end"); - generator.putLong("seed", seed); - - CompoundTag biomeSource = new CompoundTag(); - biomeSource.putString("type", END_BIOME_SOURCE); - biomeSource.putLong("seed", seed); - generator.put("biome_source", biomeSource); - - return generator; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/BonemealAPI.java b/src/main/java/org/betterx/bclib/api/v2/BonemealAPI.java deleted file mode 100644 index 3a18607c..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/BonemealAPI.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.betterx.bclib.api.v2; - -import org.betterx.bclib.util.BlocksHelper; -import org.betterx.bclib.util.WeightedList; - -import net.minecraft.core.BlockPos; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import java.util.Map; -import java.util.Set; -import java.util.function.BiConsumer; - -public class BonemealAPI { - private static final Map>>> WATER_GRASS_BIOMES = Maps.newHashMap(); - private static final Map>>> LAND_GRASS_BIOMES = Maps.newHashMap(); - private static final Map>> WATER_GRASS_TYPES = Maps.newHashMap(); - private static final Map>> LAND_GRASS_TYPES = Maps.newHashMap(); - private static final Map SPREADABLE_BLOCKS = Maps.newHashMap(); - private static final Set TERRAIN_TO_SPREAD = Sets.newHashSet(); - private static final Set TERRAIN = Sets.newHashSet(); - - public static void addSpreadableBlock(Block spreadableBlock, Block surfaceForSpread) { - SPREADABLE_BLOCKS.put(spreadableBlock, surfaceForSpread); - TERRAIN_TO_SPREAD.add(surfaceForSpread); - TERRAIN.add(surfaceForSpread); - } - - public static boolean isTerrain(Block block) { - return TERRAIN.contains(block); - } - - public static boolean isSpreadableTerrain(Block block) { - return TERRAIN_TO_SPREAD.contains(block); - } - - public static Block getSpreadable(Block block) { - return SPREADABLE_BLOCKS.get(block); - } - - public static void addLandGrass(Block plant, Block... terrain) { - addLandGrass(makeConsumer(plant), terrain); - } - - public static void addLandGrass(BiConsumer plant, Block... terrain) { - for (Block block : terrain) { - addLandGrass(plant, block, 1F); - } - } - - public static void addLandGrass(ResourceLocation biome, Block plant, Block... terrain) { - addLandGrass(biome, makeConsumer(plant), terrain); - } - - public static void addLandGrass(ResourceLocation biome, BiConsumer plant, Block... terrain) { - for (Block block : terrain) { - addLandGrass(biome, plant, block, 1F); - } - } - - public static void addLandGrass(Block plant, Block terrain, float chance) { - addLandGrass(makeConsumer(plant), terrain, chance); - } - - public static void addLandGrass(BiConsumer plant, Block terrain, float chance) { - WeightedList> list = LAND_GRASS_TYPES.get(terrain); - if (list == null) { - list = new WeightedList<>(); - LAND_GRASS_TYPES.put(terrain, list); - } - TERRAIN.add(terrain); - list.add(plant, chance); - } - - public static void addLandGrass(ResourceLocation biome, Block plant, Block terrain, float chance) { - addLandGrass(biome, makeConsumer(plant), terrain, chance); - } - - public static void addLandGrass( - ResourceLocation biome, - BiConsumer plant, - Block terrain, - float chance - ) { - Map>> map = LAND_GRASS_BIOMES.get(biome); - if (map == null) { - map = Maps.newHashMap(); - LAND_GRASS_BIOMES.put(biome, map); - } - WeightedList> list = map.get(terrain); - if (list == null) { - list = new WeightedList<>(); - map.put(terrain, list); - } - TERRAIN.add(terrain); - list.add(plant, chance); - } - - public static void addWaterGrass(Block plant, Block... terrain) { - addWaterGrass(makeConsumer(plant), terrain); - } - - public static void addWaterGrass(BiConsumer plant, Block... terrain) { - for (Block block : terrain) { - addWaterGrass(plant, block, 1F); - } - } - - public static void addWaterGrass(ResourceLocation biome, Block plant, Block... terrain) { - addWaterGrass(biome, makeConsumer(plant), terrain); - } - - public static void addWaterGrass(ResourceLocation biome, BiConsumer plant, Block... terrain) { - for (Block block : terrain) { - addWaterGrass(biome, plant, block, 1F); - } - } - - public static void addWaterGrass(Block plant, Block terrain, float chance) { - addWaterGrass(makeConsumer(plant), terrain, chance); - } - - public static void addWaterGrass(BiConsumer plant, Block terrain, float chance) { - WeightedList> list = WATER_GRASS_TYPES.get(terrain); - if (list == null) { - list = new WeightedList<>(); - WATER_GRASS_TYPES.put(terrain, list); - } - TERRAIN.add(terrain); - list.add(plant, chance); - } - - public static void addWaterGrass(ResourceLocation biome, Block plant, Block terrain, float chance) { - addWaterGrass(biome, makeConsumer(plant), terrain, chance); - } - - public static void addWaterGrass( - ResourceLocation biome, - BiConsumer plant, - Block terrain, - float chance - ) { - Map>> map = WATER_GRASS_BIOMES.get(biome); - if (map == null) { - map = Maps.newHashMap(); - WATER_GRASS_BIOMES.put(biome, map); - } - WeightedList> list = map.get(terrain); - if (list == null) { - list = new WeightedList<>(); - map.put(terrain, list); - } - TERRAIN.add(terrain); - list.add(plant, chance); - } - - public static BiConsumer getLandGrass( - ResourceLocation biomeID, - Block terrain, - RandomSource random - ) { - Map>> map = LAND_GRASS_BIOMES.get(biomeID); - WeightedList> list; - if (map != null) { - list = map.get(terrain); - if (list == null) { - list = LAND_GRASS_TYPES.get(terrain); - } - } else { - list = LAND_GRASS_TYPES.get(terrain); - } - return list == null ? null : list.get(random); - } - - public static BiConsumer getWaterGrass( - ResourceLocation biomeID, - Block terrain, - RandomSource random - ) { - Map>> map = WATER_GRASS_BIOMES.get(biomeID); - WeightedList> list; - if (map != null) { - list = map.get(terrain); - if (list == null) { - list = WATER_GRASS_TYPES.get(terrain); - } - } else { - list = WATER_GRASS_TYPES.get(terrain); - } - return list == null ? null : list.get(random); - } - - private static BiConsumer makeConsumer(Block block) { - return (level, pos) -> BlocksHelper.setWithoutUpdate(level, pos, block); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/ComposterAPI.java b/src/main/java/org/betterx/bclib/api/v2/ComposterAPI.java deleted file mode 100644 index 96a4f5c0..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/ComposterAPI.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.betterx.bclib.api.v2; - -import org.betterx.bclib.mixin.common.ComposterBlockAccessor; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Block; - -public class ComposterAPI { - public static Block allowCompost(float chance, Block block) { - if (block != null) { - allowCompost(chance, block.asItem()); - } - return block; - } - - public static Item allowCompost(float chance, Item item) { - if (item != null && item != Items.AIR) { - ComposterBlockAccessor.callAdd(chance, item); - } - return item; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/DiggerItemSpeed.java b/src/main/java/org/betterx/bclib/api/v2/DiggerItemSpeed.java deleted file mode 100644 index c469d76c..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/DiggerItemSpeed.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.api.v2; - -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; - -public class DiggerItemSpeed { - public static final List modifiers = new LinkedList<>(); - - @FunctionalInterface - public interface SpeedModifier { - Optional calculateSpeed(ItemStack stack, BlockState state, float initialSpeed, float currentSpeed); - } - - public static void addModifier(SpeedModifier mod) { - modifiers.add(mod); - } - - public static Optional getModifiedSpeed(ItemStack stack, BlockState state, float initialSpeed) { - float currentSpeed = initialSpeed; - Optional speed = Optional.empty(); - for (SpeedModifier mod : modifiers) { - Optional res = mod.calculateSpeed(stack, state, initialSpeed, currentSpeed); - if (res.isPresent()) { - currentSpeed = res.get(); - speed = res; - } - } - - return speed; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/LifeCycleAPI.java b/src/main/java/org/betterx/bclib/api/v2/LifeCycleAPI.java deleted file mode 100644 index 0cd78a48..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/LifeCycleAPI.java +++ /dev/null @@ -1,145 +0,0 @@ -package org.betterx.bclib.api.v2; - -import org.betterx.bclib.api.v2.datafixer.DataFixerAPI; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.progress.ChunkProgressListener; -import net.minecraft.world.level.CustomSpawner; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.storage.LevelStorageSource; -import net.minecraft.world.level.storage.ServerLevelData; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Executor; - -/** - * provides some lifetime hooks for a Minecraft instance - */ -public class LifeCycleAPI { - private final static List onLoadLevelBiomes = new ArrayList<>(2); - private final static List onLoadLevel = new ArrayList<>(2); - private final static List beforeLoadLevel = new ArrayList<>(2); - - - /** - * Register a callback that is called before a level is loaded or created, - * but after the {@link org.betterx.worlds.together.world.WorldConfig} was initialized and patches from - * the {@link DataFixerAPI} were applied. - * - * @param call The callback Method - */ - public static void beforeLevelLoad(BeforeLevelLoadCall call) { - beforeLoadLevel.add(call); - } - - /** - * Register a callback that is called when a new {@code ServerLevel is instantiated}. - * This callback will receive the world seed as well as it's biome registry. - * - * @param call The calbback Method - */ - public static void onLevelLoad(LevelLoadBiomesCall call) { - onLoadLevelBiomes.add(call); - } - - /** - * Register a callback that is called when a new {@code ServerLevel is instantiated}. - * This callbacl will receiv all parameters that were passed to the ServerLevel's constructor - * - * @param call The calbback Method - */ - public static void onLevelLoad(LevelLoadCall call) { - onLoadLevel.add(call); - } - - /** - * For internal use, You should not call this method! - */ - public static void _runBeforeLevelLoad() { - beforeLoadLevel.forEach(c -> c.beforeLoad()); - } - - /** - * For internal use, You should not call this method! - * - * @param minecraftServer - * @param executor - * @param levelStorageAccess - * @param serverLevelData - * @param resourceKey - * @param chunkProgressListener - * @param bl - * @param l - * @param list - * @param bl2 - */ - public static void _runLevelLoad( - ServerLevel world, - MinecraftServer minecraftServer, - Executor executor, - LevelStorageSource.LevelStorageAccess levelStorageAccess, - ServerLevelData serverLevelData, - ResourceKey resourceKey, - ChunkProgressListener chunkProgressListener, - boolean bl, - long l, - List list, - boolean bl2 - ) { - onLoadLevel.forEach(c -> c.onLoad( - world, - minecraftServer, - executor, - levelStorageAccess, - serverLevelData, - resourceKey, - chunkProgressListener, - bl, - l, - list, - bl2 - )); - - final long seed = world.getSeed(); - final Registry biomeRegistry = world.registryAccess().registryOrThrow(Registry.BIOME_REGISTRY); - onLoadLevelBiomes.forEach(c -> c.onLoad(world, seed, biomeRegistry)); - } - - /** - * A callback function that is used for each new ServerLevel instance - */ - public interface BeforeLevelLoadCall { - void beforeLoad(); - } - - /** - * A callback function that is used for each new ServerLevel instance - */ - public interface LevelLoadBiomesCall { - void onLoad(ServerLevel world, long seed, Registry registry); - } - - /** - * A callback function that is used for each new ServerLevel instance - */ - public interface LevelLoadCall { - void onLoad( - ServerLevel world, - MinecraftServer minecraftServer, - Executor executor, - LevelStorageSource.LevelStorageAccess levelStorageAccess, - ServerLevelData serverLevelData, - ResourceKey resourceKey, - ChunkProgressListener chunkProgressListener, - boolean bl, - long l, - List list, - boolean bl2 - ); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/ModIntegrationAPI.java b/src/main/java/org/betterx/bclib/api/v2/ModIntegrationAPI.java deleted file mode 100644 index a4982abe..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/ModIntegrationAPI.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.betterx.bclib.api.v2; - -import org.betterx.bclib.integration.ModIntegration; - -import net.fabricmc.loader.api.FabricLoader; - -import com.google.common.collect.Lists; - -import java.util.List; - -public class ModIntegrationAPI { - private static final List INTEGRATIONS = Lists.newArrayList(); - private static final boolean HAS_CANVAS = FabricLoader.getInstance().isModLoaded("canvas"); - - /** - * Registers mod integration - * - * @param integration - * @return - */ - public static ModIntegration register(ModIntegration integration) { - INTEGRATIONS.add(integration); - return integration; - } - - /** - * Get all registered mod integrations. - * - * @return {@link List} of {@link ModIntegration}. - */ - public static List getIntegrations() { - return INTEGRATIONS; - } - - /** - * Initialize all integrations, only for internal usage. - */ - public static void registerAll() { - INTEGRATIONS.forEach(integration -> { - if (integration.modIsInstalled()) { - integration.init(); - } - }); - } - - public static boolean hasCanvas() { - return HAS_CANVAS; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/PostInitAPI.java b/src/main/java/org/betterx/bclib/api/v2/PostInitAPI.java deleted file mode 100644 index 35364550..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/PostInitAPI.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.betterx.bclib.api.v2; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; -import org.betterx.bclib.blocks.BaseBarrelBlock; -import org.betterx.bclib.blocks.BaseChestBlock; -import org.betterx.bclib.blocks.BaseFurnaceBlock; -import org.betterx.bclib.blocks.BaseSignBlock; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.client.render.BaseChestBlockEntityRenderer; -import org.betterx.bclib.client.render.BaseSignBlockEntityRenderer; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.interfaces.Fuel; -import org.betterx.bclib.interfaces.PostInitable; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.interfaces.TagProvider; -import org.betterx.bclib.interfaces.tools.*; -import org.betterx.bclib.networking.VersionChecker; -import org.betterx.bclib.registry.BaseBlockEntities; -import org.betterx.worlds.together.tag.v3.MineableTags; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.client.renderer.RenderType; -import net.minecraft.core.Registry; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; -import net.fabricmc.fabric.api.registry.FuelRegistry; - -import com.google.common.collect.Lists; - -import java.util.List; -import java.util.function.Consumer; - -public class PostInitAPI { - private static List> postInitFunctions = Lists.newArrayList(); - private static List> blockTags = Lists.newArrayList(); - private static List> itemTags = Lists.newArrayList(); - - /** - * Register a new function which will be called after all mods are initiated. Will be called on both client and server. - * - * @param function {@link Consumer} with {@code boolean} parameter ({@code true} for client, {@code false} for server). - */ - public static void register(Consumer function) { - postInitFunctions.add(function); - } - - /** - * Called in proper BCLib entry points, for internal usage only. - * - * @param isClient {@code boolean}, {@code true} for client, {@code false} for server. - */ - public static void postInit(boolean isClient) { - Registry.BLOCK.forEach(block -> { - processBlockCommon(block); - if (isClient) { - processBlockClient(block); - } - }); - - - Registry.ITEM.forEach(item -> { - processItemCommon(item); - }); - - if (postInitFunctions != null) { - postInitFunctions.forEach(function -> function.accept(isClient)); - postInitFunctions = null; - } - blockTags = null; - itemTags = null; - InternalBiomeAPI.loadFabricAPIBiomes(); - Configs.BIOMES_CONFIG.saveChanges(); - - VersionChecker.startCheck(isClient); - } - - @Environment(EnvType.CLIENT) - private static void processBlockClient(Block block) { - if (block instanceof RenderLayerProvider) { - BCLRenderLayer layer = ((RenderLayerProvider) block).getRenderLayer(); - if (layer == BCLRenderLayer.CUTOUT) BlockRenderLayerMap.INSTANCE.putBlock(block, RenderType.cutout()); - else if (layer == BCLRenderLayer.TRANSLUCENT) - BlockRenderLayerMap.INSTANCE.putBlock(block, RenderType.translucent()); - } - if (block instanceof BaseChestBlock) { - BaseChestBlockEntityRenderer.registerRenderLayer(block); - } else if (block instanceof BaseSignBlock) { - BaseSignBlockEntityRenderer.registerRenderLayer(block); - } - } - - private static void processItemCommon(Item item) { - if (item instanceof TagProvider provider) { - try { - provider.addTags(null, itemTags); - } catch (NullPointerException ex) { - BCLib.LOGGER.error(item + " probably tried to access blockTags.", ex); - } - itemTags.forEach(tag -> TagManager.ITEMS.add(tag, item)); - itemTags.clear(); - } - } - - private static void processBlockCommon(Block block) { - if (block instanceof PostInitable) { - ((PostInitable) block).postInit(); - } - if (block instanceof BaseChestBlock) { - BaseBlockEntities.CHEST.registerBlock(block); - } else if (block instanceof BaseSignBlock) { - BaseBlockEntities.SIGN.registerBlock(block); - } else if (block instanceof BaseBarrelBlock) { - BaseBlockEntities.BARREL.registerBlock(block); - } else if (block instanceof BaseFurnaceBlock) { - BaseBlockEntities.FURNACE.registerBlock(block); - } - if (!(block instanceof PreventMineableAdd)) { - if (block instanceof AddMineableShears) { - TagManager.BLOCKS.add(block, MineableTags.SHEARS); - } - if (block instanceof AddMineableAxe) { - TagManager.BLOCKS.add(block, MineableTags.AXE); - } - if (block instanceof AddMineablePickaxe) { - TagManager.BLOCKS.add(block, MineableTags.PICKAXE); - } - if (block instanceof AddMineableShovel) { - TagManager.BLOCKS.add(block, MineableTags.SHOVEL); - } - if (block instanceof AddMineableHoe) { - TagManager.BLOCKS.add(block, MineableTags.HOE); - } - if (block instanceof AddMineableSword) { - TagManager.BLOCKS.add(block, MineableTags.SWORD); - } - if (block instanceof AddMineableHammer) { - TagManager.BLOCKS.add(block, MineableTags.HAMMER); - } - } - if (block instanceof TagProvider) { - ((TagProvider) block).addTags(blockTags, itemTags); - blockTags.forEach(tag -> TagManager.BLOCKS.add(tag, block)); - itemTags.forEach(tag -> TagManager.ITEMS.add(tag, block.asItem())); - blockTags.clear(); - itemTags.clear(); - } - - if (block instanceof Fuel fl) { - FuelRegistry.INSTANCE.add(block, fl.getFuelTime()); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/ShovelAPI.java b/src/main/java/org/betterx/bclib/api/v2/ShovelAPI.java deleted file mode 100644 index bdbc0351..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/ShovelAPI.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.betterx.bclib.api.v2; - -import org.betterx.bclib.mixin.common.ShovelItemAccessor; - -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.Map; - -public class ShovelAPI { - /** - * Will add left-click behaviour to shovel: when it is targeting cetrain {@link Block} it will be converting to new - * {@link BlockState} on usage. Example: grass converting to path. - * - * @param target {@link Block} that will be converted. - * @param convert {@link BlockState} to convert block into. - */ - public static void addShovelBehaviour(Block target, BlockState convert) { - Map map = ShovelItemAccessor.bclib_getFlattenables(); - map.put(target, convert); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/advancement/AdvancementBuilderElements.java b/src/main/java/org/betterx/bclib/api/v2/advancement/AdvancementBuilderElements.java deleted file mode 100644 index e692ad77..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/advancement/AdvancementBuilderElements.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.betterx.bclib.api.v2.advancement; - -import net.minecraft.advancements.DisplayInfo; -import net.minecraft.advancements.FrameType; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; - -import org.jetbrains.annotations.Nullable; - -class Display { - ItemStack icon; - Component title; - net.minecraft.network.chat.Component description; - @Nullable ResourceLocation background; - FrameType frame; - boolean showToast; - boolean announceChat; - boolean hidden; - - Display() { - } - - Display reset() { - this.icon = null; - this.title = null; - this.description = null; - frame = FrameType.TASK; - background = null; - showToast = true; - announceChat = true; - hidden = false; - return this; - } - - DisplayInfo build() { - return new DisplayInfo( - icon, title, description, - background, frame, showToast, announceChat, hidden - ); - } -} - diff --git a/src/main/java/org/betterx/bclib/api/v2/advancement/AdvancementManager.java b/src/main/java/org/betterx/bclib/api/v2/advancement/AdvancementManager.java deleted file mode 100644 index 92a03afa..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/advancement/AdvancementManager.java +++ /dev/null @@ -1,466 +0,0 @@ -package org.betterx.bclib.api.v2.advancement; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.levelgen.structures.BCLStructure; -import org.betterx.bclib.complexmaterials.WoodenComplexMaterial; -import org.betterx.bclib.items.complex.EquipmentSet; - -import net.minecraft.advancements.*; -import net.minecraft.advancements.critereon.*; -import net.minecraft.core.Registry; -import net.minecraft.data.recipes.RecipeBuilder; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.Container; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.levelgen.structure.Structure; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import org.jetbrains.annotations.ApiStatus; - -public class AdvancementManager { - private static final Map ADVANCEMENTS = new HashMap<>(); - - public static void register(ResourceLocation id, Advancement.Builder builder) { - ADVANCEMENTS.put(id, builder); - } - - @ApiStatus.Internal - public static void addAdvancements(Map map) { - for (var entry : ADVANCEMENTS.entrySet()) { - if (!map.containsKey(entry.getKey())) { - map.put(entry.getKey(), entry.getValue()); - } - } - } - - public static class RewardsBuilder { - private final Builder calle; - private final AdvancementRewards.Builder builder = new AdvancementRewards.Builder(); - - private RewardsBuilder(Builder calle) { - this.calle = calle; - } - - public RewardsBuilder addExperience(int i) { - builder.addExperience(i); - return this; - } - - - public RewardsBuilder addLootTable(ResourceLocation resourceLocation) { - builder.addLootTable(resourceLocation); - return this; - } - - - public RewardsBuilder addRecipe(ResourceLocation resourceLocation) { - builder.addRecipe(resourceLocation); - return this; - } - - - public RewardsBuilder runs(ResourceLocation resourceLocation) { - builder.runs(resourceLocation); - return this; - } - - public Builder endReward() { - calle.rewards(builder.build()); - return calle; - } - } - - public enum AdvancementType { - REGULAR, - RECIPE_DECORATIONS, - RECIPE_TOOL - } - - public static class Builder { - private static final ThreadLocal DISPLAY_BUILDER = ThreadLocal.withInitial(DisplayBuilder::new); - private static final ResourceLocation RECIPES_ROOT = RecipeBuilder.ROOT_RECIPE_ADVANCEMENT; - - private final Advancement.Builder builder = Advancement.Builder.advancement(); - private final ResourceLocation id; - private final AdvancementType type; - private boolean canBuild = true; - - private Builder(ResourceLocation id, AdvancementType type) { - ResourceLocation ID; - if (type == AdvancementType.RECIPE_DECORATIONS) { - ID = new ResourceLocation(id.getNamespace(), "recipes/decorations/" + id.getPath()); - builder.parent(RECIPES_ROOT); - } else if (type == AdvancementType.RECIPE_TOOL) { - ID = new ResourceLocation(id.getNamespace(), "recipes/tools/" + id.getPath()); - builder.parent(RECIPES_ROOT); - } else { - ID = id; - } - this.id = ID; - this.type = type; - } - - public static Builder createEmptyCopy(Builder builder) { - return new Builder(builder.id, builder.type); - } - - public static Builder create(ResourceLocation id) { - return new Builder(id, AdvancementType.REGULAR); - } - - public static Builder create(ResourceLocation id, AdvancementType type) { - return new Builder(id, type); - } - - public static Builder create(Item icon) { - return create(icon, AdvancementType.REGULAR); - } - - public static Builder create(ItemStack icon) { - return create(icon, AdvancementType.REGULAR); - } - - public static Builder create(ItemLike icon, AdvancementType type) { - return create(new ItemStack(icon), type); - } - - public static Builder create(ItemStack icon, AdvancementType type) { - return create(icon, type, (displayBuilder) -> { - }); - } - - public static Builder create(Item icon, AdvancementType type, Consumer displayAdapter) { - return create(new ItemStack(icon), type, displayAdapter); - } - - public static Builder create(ItemStack icon, AdvancementType type, Consumer displayAdapter) { - var id = Registry.ITEM.getKey(icon.getItem()); - boolean canBuild = true; - if (id == null || icon.is(Items.AIR)) { - canBuild = false; - id = Registry.ITEM.getDefaultKey(); - } - - String baseName = "advancements." + id.getNamespace() + "." + id.getPath() + "."; - Builder b = new Builder(id, type); - var displayBuilder = b.startDisplay( - icon, - Component.translatable(baseName + "title"), - Component.translatable(baseName + "description") - ); - if (displayAdapter != null) displayAdapter.accept(displayBuilder); - b = displayBuilder.endDisplay(); - b.canBuild = canBuild; - return b; - } - - public static > Builder createRecipe(T recipe, AdvancementType type) { - Item item = recipe.getResultItem().getItem(); - return create(item, type, displayBuilder -> displayBuilder.hideToast().hideFromChat()) - //.awardRecipe(item) - .addRecipeUnlockCriterion("has_the_recipe", recipe) - .startReward() - .addRecipe(recipe.getId()) - .endReward() - .requirements(RequirementsStrategy.OR); - } - - public Builder parent(Advancement advancement) { - builder.parent(advancement); - return this; - } - - public Builder parent(ResourceLocation resourceLocation) { - builder.parent(resourceLocation); - return this; - } - - public DisplayBuilder startDisplay(ItemLike icon) { - String baseName = "advancements." + id.getNamespace() + "." + id.getPath() + "."; - return startDisplay( - icon, - Component.translatable(baseName + "title"), - Component.translatable(baseName + "description") - ); - } - - public DisplayBuilder startDisplay( - ItemLike icon, - Component title, - Component description - ) { - return startDisplay(new ItemStack(icon), title, description); - } - - public DisplayBuilder startDisplay( - ItemStack icon, - Component title, - Component description - ) { - if (icon == null) { - canBuild = false; - } else { - var id = Registry.ITEM.getKey(icon.getItem()); - if (id == null) { - canBuild = false; - } - } - DisplayBuilder dp = DISPLAY_BUILDER.get().reset(this); - return dp.icon(icon).title(title).description(description); - } - - Builder display(DisplayInfo displayInfo) { - builder.display(displayInfo); - return this; - } - - public Builder awardRecipe(ItemLike... items) { - var rewardBuilder = startReward(); - for (ItemLike item : items) { - var id = Registry.ITEM.getKey(item.asItem()); - if (id == null) continue; - rewardBuilder.addRecipe(id); - } - return rewardBuilder.endReward(); - } - - public RewardsBuilder startReward() { - return new RewardsBuilder(this); - } - - public Builder rewards(AdvancementRewards advancementRewards) { - builder.rewards(advancementRewards); - return this; - } - - public Builder rewardXP(int xp) { - return rewards(AdvancementRewards.Builder.experience(500).build()); - } - - public Builder addCriterion(String string, CriterionTriggerInstance criterionTriggerInstance) { - builder.addCriterion(string, new Criterion(criterionTriggerInstance)); - return this; - } - - public Builder addCriterion(String string, Criterion criterion) { - builder.addCriterion(string, criterion); - return this; - } - - public Builder addAtStructureCriterion(String name, BCLStructure structure) { - return addAtStructureCriterion(name, structure.structureKey); - } - - public Builder addAtStructureCriterion(String name, ResourceKey structure) { - return addCriterion( - name, - PlayerTrigger - .TriggerInstance - .located( - LocationPredicate.inStructure(structure) - ) - ); - } - - public > Builder addRecipeUnlockCriterion(String name, T recipe) { - return addCriterion( - name, - RecipeUnlockedTrigger.unlocked(recipe.getId()) - ); - } - - public Builder addInventoryChangedCriterion(String name, ItemLike... items) { - return addCriterion( - name, - InventoryChangeTrigger.TriggerInstance.hasItems(items) - ); - } - - public Builder addInventoryChangedCriterion(String name, TagKey tag) { - return addCriterion( - name, - InventoryChangeTrigger.TriggerInstance.hasItems(new ItemPredicate( - tag, - null, - MinMaxBounds.Ints.ANY, - MinMaxBounds.Ints.ANY, - EnchantmentPredicate.NONE, - EnchantmentPredicate.NONE, - null, - NbtPredicate.ANY - )) - ); - } - - // - - public Builder addEquipmentSetSlotCriterion(EquipmentSet set, String slot) { - return addInventoryChangedCriterion( - set.baseName + "_" + slot, - set.getSlot(slot) - ); - } - - public Builder addArmorSetCriterion(EquipmentSet set) { - return addEquipmentSetSlotCriterion(set, EquipmentSet.HELMET_SLOT) - .addEquipmentSetSlotCriterion(set, EquipmentSet.CHESTPLATE_SLOT) - .addEquipmentSetSlotCriterion(set, EquipmentSet.LEGGINGS_SLOT) - .addEquipmentSetSlotCriterion(set, EquipmentSet.BOOTS_SLOT); - } - - public Builder addToolSetCriterion(EquipmentSet set) { - return addEquipmentSetSlotCriterion(set, EquipmentSet.PICKAXE_SLOT) - .addEquipmentSetSlotCriterion(set, EquipmentSet.AXE_SLOT) - .addEquipmentSetSlotCriterion(set, EquipmentSet.SHOVEL_SLOT) - .addEquipmentSetSlotCriterion(set, EquipmentSet.SWORD_SLOT) - .addEquipmentSetSlotCriterion(set, EquipmentSet.HOE_SLOT); - } - - public Builder addWoodCriterion(WoodenComplexMaterial mat) { - return addInventoryChangedCriterion( - mat.getBaseName(), - mat.getBlock(WoodenComplexMaterial.BLOCK_LOG), - mat.getBlock(WoodenComplexMaterial.BLOCK_BARK), - mat.getBlock(WoodenComplexMaterial.BLOCK_PLANKS) - ); - } - - public Builder addVisitBiomesCriterion(List> list) { - for (ResourceKey resourceKey : list) { - addCriterion( - resourceKey.location().toString(), - PlayerTrigger.TriggerInstance.located(LocationPredicate.inBiome(resourceKey)) - ); - } - return this; - } - - public Builder requirements(RequirementsStrategy requirementsStrategy) { - builder.requirements(requirementsStrategy); - return this; - } - - public Builder requirements(String[][] strings) { - builder.requirements(strings); - return this; - } - - public Builder printDebugJson() { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - BCLib.LOGGER.info(gson.toJson(builder.serializeToJson())); - return this; - } - - public ResourceLocation buildAndRegister() { - AdvancementManager.register(id, this.builder); - return this.id; - } - - public ResourceLocation buildAndRegister(Map map) { - map.put(id, this.builder); - return this.id; - } - } - - public static class DisplayBuilder { - Builder base; - final Display display = new Display(); - - DisplayBuilder reset(Builder base) { - this.base = base; - this.display.reset(); - return this; - } - - public DisplayBuilder background(ResourceLocation value) { - display.background = value; - return this; - } - - public DisplayBuilder icon(ItemLike value) { - display.icon = new ItemStack(value); - return this; - } - - public DisplayBuilder icon(ItemStack value) { - display.icon = value; - return this; - } - - public DisplayBuilder title(Component value) { - display.title = value; - return this; - } - - public DisplayBuilder description(Component value) { - display.description = value; - return this; - } - - public DisplayBuilder showToast() { - display.showToast = true; - return this; - } - - public DisplayBuilder hideToast() { - display.showToast = false; - return this; - } - - public DisplayBuilder hidden() { - display.hidden = true; - return this; - } - - public DisplayBuilder visible() { - display.hidden = false; - return this; - } - - public DisplayBuilder announceToChat() { - display.announceChat = true; - return this; - } - - public DisplayBuilder hideFromChat() { - display.announceChat = false; - return this; - } - - public DisplayBuilder frame(FrameType type) { - display.frame = type; - return this; - } - - public DisplayBuilder challenge() { - return frame(FrameType.CHALLENGE); - } - - public DisplayBuilder task() { - return frame(FrameType.TASK); - } - - public DisplayBuilder goal() { - return frame(FrameType.GOAL); - } - - public Builder endDisplay() { - base.display(display.build()); - return base; - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/BaseDataHandler.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/BaseDataHandler.java deleted file mode 100644 index ae35daea..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/BaseDataHandler.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; - -import java.nio.charset.StandardCharsets; -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -public abstract class BaseDataHandler { - private final boolean originatesOnServer; - @NotNull - private final ResourceLocation identifier; - - protected BaseDataHandler(ResourceLocation identifier, boolean originatesOnServer) { - this.originatesOnServer = originatesOnServer; - this.identifier = identifier; - } - - final public boolean getOriginatesOnServer() { - return originatesOnServer; - } - - final public ResourceLocation getIdentifier() { - return identifier; - } - - @Environment(EnvType.CLIENT) - abstract void receiveFromServer( - Minecraft client, - ClientPacketListener handler, - FriendlyByteBuf buf, - PacketSender responseSender - ); - - private ServerPlayer lastMessageSender; - - void receiveFromClient( - MinecraftServer server, - ServerPlayer player, - ServerGamePacketListenerImpl handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - lastMessageSender = player; - } - - final protected boolean reply(BaseDataHandler message, MinecraftServer server) { - if (lastMessageSender == null) return false; - message.sendToClient(server, lastMessageSender); - return true; - } - - abstract void sendToClient(MinecraftServer server); - - abstract void sendToClient(MinecraftServer server, ServerPlayer player); - - @Environment(EnvType.CLIENT) - abstract void sendToServer(Minecraft client); - - protected boolean isBlocking() { - return false; - } - - @Override - public String toString() { - return "BasDataHandler{" + "originatesOnServer=" + originatesOnServer + ", identifier=" + identifier + '}'; - } - - /** - * Write a String to a buffer (Convenience Method) - * - * @param buf The buffer to write to - * @param s The String you want to write - */ - public static void writeString(FriendlyByteBuf buf, String s) { - buf.writeByteArray(s.getBytes(StandardCharsets.UTF_8)); - } - - /** - * Read a string from a buffer (Convenience Method) - * - * @param buf Thea buffer to read from - * @return The received String - */ - public static String readString(FriendlyByteBuf buf) { - byte[] data = buf.readByteArray(); - return new String(data, StandardCharsets.UTF_8); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BaseDataHandler)) return false; - BaseDataHandler that = (BaseDataHandler) o; - return originatesOnServer == that.originatesOnServer && identifier.equals(that.identifier); - } - - @Override - public int hashCode() { - return Objects.hash(originatesOnServer, identifier); - } -} - diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/Connector.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/Connector.java deleted file mode 100644 index d0d818d8..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/Connector.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange; - -import java.util.Set; - -abstract class Connector { - protected final DataExchange api; - - Connector(DataExchange api) { - this.api = api; - } - - public abstract boolean onClient(); - - protected Set getDescriptors() { - return api.getDescriptors(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/ConnectorClientside.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/ConnectorClientside.java deleted file mode 100644 index 3a3b728e..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/ConnectorClientside.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.FriendlyByteBuf; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; -import net.fabricmc.fabric.api.networking.v1.PacketSender; - -/** - * This is an internal class that handles a Clienetside players Connection to a Server - */ -@Environment(EnvType.CLIENT) -public class ConnectorClientside extends Connector { - private Minecraft client; - - ConnectorClientside(DataExchange api) { - super(api); - this.client = null; - } - - - @Override - public boolean onClient() { - return true; - } - - public void onPlayInit(ClientPacketListener handler, Minecraft client) { - if (this.client != null && this.client != client) { - BCLib.LOGGER.warning("Client changed!"); - } - this.client = client; - for (DataHandlerDescriptor desc : getDescriptors()) { - ClientPlayNetworking.registerReceiver(desc.IDENTIFIER, (_client, _handler, _buf, _responseSender) -> { - receiveFromServer(desc, _client, _handler, _buf, _responseSender); - }); - } - } - - public void onPlayReady(ClientPacketListener handler, PacketSender sender, Minecraft client) { - for (DataHandlerDescriptor desc : getDescriptors()) { - if (desc.sendOnJoin) { - BaseDataHandler h = desc.JOIN_INSTANCE.get(); - if (!h.getOriginatesOnServer()) { - h.sendToServer(client); - } - } - } - } - - public void onPlayDisconnect(ClientPacketListener handler, Minecraft client) { - for (DataHandlerDescriptor desc : getDescriptors()) { - ClientPlayNetworking.unregisterReceiver(desc.IDENTIFIER); - } - } - - void receiveFromServer( - DataHandlerDescriptor desc, - Minecraft client, - ClientPacketListener handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - BaseDataHandler h = desc.INSTANCE.get(); - h.receiveFromServer(client, handler, buf, responseSender); - } - - public void sendToServer(BaseDataHandler h) { - if (client == null) { - throw new RuntimeException("[internal error] Client not initialized yet!"); - } - h.sendToServer(this.client); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/ConnectorServerside.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/ConnectorServerside.java deleted file mode 100644 index e0bcd935..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/ConnectorServerside.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange; - -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; - -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; - -/** - * This is an internal class that handles a Serverside Connection to a Client-Player - */ -public class ConnectorServerside extends Connector { - private MinecraftServer server; - - ConnectorServerside(DataExchange api) { - super(api); - server = null; - } - - @Override - public boolean onClient() { - return false; - } - - public void onPlayInit(ServerGamePacketListenerImpl handler, MinecraftServer server) { - if (this.server != null && this.server != server) { - BCLib.LOGGER.warning("Server changed!"); - } - this.server = server; - for (DataHandlerDescriptor desc : getDescriptors()) { - ServerPlayNetworking.registerReceiver( - handler, - desc.IDENTIFIER, - (_server, _player, _handler, _buf, _responseSender) -> { - receiveFromClient( - desc, - _server, - _player, - _handler, - _buf, - _responseSender - ); - } - ); - } - } - - public void onPlayReady(ServerGamePacketListenerImpl handler, PacketSender sender, MinecraftServer server) { - for (DataHandlerDescriptor desc : getDescriptors()) { - if (desc.sendOnJoin) { - BaseDataHandler h = desc.JOIN_INSTANCE.get(); - if (h.getOriginatesOnServer()) { - h.sendToClient(server, handler.player); - } - } - } - } - - public void onPlayDisconnect(ServerGamePacketListenerImpl handler, MinecraftServer server) { - for (DataHandlerDescriptor desc : getDescriptors()) { - ServerPlayNetworking.unregisterReceiver(handler, desc.IDENTIFIER); - } - } - - void receiveFromClient( - DataHandlerDescriptor desc, - MinecraftServer server, - ServerPlayer player, - ServerGamePacketListenerImpl handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - BaseDataHandler h = desc.INSTANCE.get(); - h.receiveFromClient(server, player, handler, buf, responseSender); - } - - public void sendToClient(BaseDataHandler h) { - if (server == null) { - throw new RuntimeException("[internal error] Server not initialized yet!"); - } - h.sendToClient(this.server); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataExchangeAPI.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataExchangeAPI.java deleted file mode 100644 index 120267dd..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataExchangeAPI.java +++ /dev/null @@ -1,217 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID; -import org.betterx.bclib.config.Config; -import org.betterx.worlds.together.util.ModUtil; - -import net.minecraft.network.FriendlyByteBuf; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; - -import java.io.File; -import java.util.List; -import java.util.function.BiConsumer; - -public class DataExchangeAPI extends DataExchange { - private final static List MODS = Lists.newArrayList(); - - /** - * You should never need to create a custom instance of this Object. - */ - public DataExchangeAPI() { - super(); - } - - @Environment(EnvType.CLIENT) - protected ConnectorClientside clientSupplier(DataExchange api) { - return new ConnectorClientside(api); - } - - protected ConnectorServerside serverSupplier(DataExchange api) { - return new ConnectorServerside(api); - } - - /** - * Register a mod to participate in the DataExchange. - * - * @param modID - {@link String} modID. - */ - public static void registerMod(String modID) { - if (!MODS.contains(modID)) MODS.add(modID); - } - - /** - * Register a mod dependency to participate in the DataExchange. - * - * @param modID - {@link String} modID. - */ - public static void registerModDependency(String modID) { - if (ModUtil.getModInfo(modID, false) != null && !"0.0.0".equals(ModUtil.getModVersion(modID))) { - registerMod(modID); - } else { - BCLib.LOGGER.info("Mod Dependency '" + modID + "' not found. This is probably OK."); - } - } - - /** - * Returns the IDs of all registered Mods. - * - * @return List of modIDs - */ - public static List registeredMods() { - return MODS; - } - - /** - * Add a new Descriptor for a {@link DataHandler}. - * - * @param desc The Descriptor you want to add. - */ - public static void registerDescriptor(DataHandlerDescriptor desc) { - DataExchange api = DataExchange.getInstance(); - api.getDescriptors() - .add(desc); - } - - /** - * Bulk-Add a Descriptors for your {@link DataHandler}-Objects. - * - * @param desc The Descriptors you want to add. - */ - public static void registerDescriptors(List desc) { - DataExchange api = DataExchange.getInstance(); - api.getDescriptors() - .addAll(desc); - } - - /** - * Sends the Handler. - *

- * Depending on what the result of {@link DataHandler#getOriginatesOnServer()}, the Data is sent from the server - * to the client (if {@code true}) or the other way around. - *

- * The method {@link DataHandler#serializeData(FriendlyByteBuf, boolean)} is called just before the data is sent. You should - * use this method to add the Data you need to the communication. - * - * @param h The Data that you want to send - */ - public static void send(BaseDataHandler h) { - if (h.getOriginatesOnServer()) { - DataExchangeAPI.getInstance().server.sendToClient(h); - } else { - DataExchangeAPI.getInstance().client.sendToServer(h); - } - } - - /** - * Registers a File for automatic client syncing. - * - * @param modID The ID of the calling Mod - * @param fileName The name of the File - */ - public static void addAutoSyncFile(String modID, File fileName) { - AutoSync.addAutoSyncFileData(modID, fileName, false, SyncFileHash.NEED_TRANSFER); - } - - /** - * Registers a File for automatic client syncing. - *

- * The file is synced of the {@link SyncFileHash} on client and server are not equal. This method will not copy the - * configs content from the client to the server. - * - * @param modID The ID of the calling Mod - * @param uniqueID A unique Identifier for the File. (see {@link SyncFileHash#uniqueID} for - * Details - * @param fileName The name of the File - */ - public static void addAutoSyncFile(String modID, String uniqueID, File fileName) { - AutoSync.addAutoSyncFileData(modID, uniqueID, fileName, false, SyncFileHash.NEED_TRANSFER); - } - - /** - * Registers a File for automatic client syncing. - *

- * The content of the file is requested for comparison. This will copy the - * entire file from the client to the server. - *

- * You should only use this option, if you need to compare parts of the file in order to decide - * if the File needs to be copied. Normally using the {@link SyncFileHash} - * for comparison is sufficient. - * - * @param modID The ID of the calling Mod - * @param fileName The name of the File - * @param needTransfer If the predicate returns true, the file needs to get copied to the server. - */ - public static void addAutoSyncFile(String modID, File fileName, AutoSync.NeedTransferPredicate needTransfer) { - AutoSync.addAutoSyncFileData(modID, fileName, true, needTransfer); - } - - /** - * Registers a File for automatic client syncing. - *

- * The content of the file is requested for comparison. This will copy the - * entire file from the client to the server. - *

- * You should only use this option, if you need to compare parts of the file in order to decide - * if the File needs to be copied. Normally using the {@link SyncFileHash} - * for comparison is sufficient. - * - * @param modID The ID of the calling Mod - * @param uniqueID A unique Identifier for the File. (see {@link SyncFileHash#uniqueID} for - * Details - * @param fileName The name of the File - * @param needTransfer If the predicate returns true, the file needs to get copied to the server. - */ - public static void addAutoSyncFile( - String modID, - String uniqueID, - File fileName, - AutoSync.NeedTransferPredicate needTransfer - ) { - AutoSync.addAutoSyncFileData(modID, uniqueID, fileName, true, needTransfer); - } - - /** - * Register a function that is called whenever the client receives a file from the server and replaced toe local - * file with the new content. - *

- * This callback is usefull if you need to reload the new content before the game is quit. - * - * @param callback A Function that receives the AutoSyncID as well as the Filename. - */ - public static void addOnWriteCallback(BiConsumer callback) { - AutoSync.addOnWriteCallback(callback); - } - - /** - * Returns the sync-folder for a given Mod. - *

- * BCLib will ensure that the contents of sync-folder on the client is the same as the one on the server. - * - * @param modID ID of the Mod - * @return The path to the sync-folder - */ - public static File getModSyncFolder(String modID) { - File fl = AutoSync.SYNC_FOLDER.localFolder.resolve(modID.replace(".", "-") - .replace(":", "-") - .replace("\\", "-") - .replace("/", "-")) - .normalize() - .toFile(); - - if (!fl.exists()) { - fl.mkdirs(); - } - return fl; - } - - static { - addOnWriteCallback(Config::reloadSyncedConfig); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataHandler.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataHandler.java deleted file mode 100644 index 649956af..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataHandler.java +++ /dev/null @@ -1,332 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.Chunker; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import net.minecraft.world.entity.player.Player; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; -import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.fabricmc.fabric.api.networking.v1.PlayerLookup; -import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; - -import java.util.Collection; -import java.util.List; - -public abstract class DataHandler extends BaseDataHandler { - public abstract static class WithoutPayload extends DataHandler { - protected WithoutPayload(ResourceLocation identifier, boolean originatesOnServer) { - super(identifier, originatesOnServer); - } - - @Override - protected boolean prepareData(boolean isClient) { - return true; - } - - @Override - protected void serializeData(FriendlyByteBuf buf, boolean isClient) { - } - - @Override - protected void deserializeIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean isClient) { - } - } - - protected DataHandler(ResourceLocation identifier, boolean originatesOnServer) { - super(identifier, originatesOnServer); - } - - protected boolean prepareData(boolean isClient) { - return true; - } - - abstract protected void serializeData(FriendlyByteBuf buf, boolean isClient); - - abstract protected void deserializeIncomingData(FriendlyByteBuf buf, PacketSender responseSender, boolean isClient); - - abstract protected void runOnGameThread(Minecraft client, MinecraftServer server, boolean isClient); - - - @Environment(EnvType.CLIENT) - @Override - void receiveFromServer( - Minecraft client, - ClientPacketListener handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - deserializeIncomingData(buf, responseSender, true); - final Runnable runner = () -> runOnGameThread(client, null, true); - - if (isBlocking()) client.executeBlocking(runner); - else client.execute(runner); - } - - @Override - void receiveFromClient( - MinecraftServer server, - ServerPlayer player, - ServerGamePacketListenerImpl handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - super.receiveFromClient(server, player, handler, buf, responseSender); - - deserializeIncomingData(buf, responseSender, false); - final Runnable runner = () -> runOnGameThread(null, server, false); - - if (isBlocking()) server.executeBlocking(runner); - else server.execute(runner); - } - - @Override - void sendToClient(MinecraftServer server) { - if (prepareData(false)) { - FriendlyByteBuf buf = PacketByteBufs.create(); - serializeData(buf, false); - - _sendToClient(getIdentifier(), server, PlayerLookup.all(server), buf); - } - } - - @Override - void sendToClient(MinecraftServer server, ServerPlayer player) { - if (prepareData(false)) { - FriendlyByteBuf buf = PacketByteBufs.create(); - serializeData(buf, false); - - _sendToClient(getIdentifier(), server, List.of(player), buf); - } - } - - - public static void _sendToClient( - ResourceLocation identifier, - MinecraftServer server, - Collection players, - FriendlyByteBuf buf - ) { - if (buf.readableBytes() > Chunker.MAX_PACKET_SIZE) { - final Chunker.PacketChunkSender sender = new Chunker.PacketChunkSender(buf, identifier); - sender.sendChunks(players); - } else { - for (ServerPlayer player : players) { - ServerPlayNetworking.send(player, identifier, buf); - } - } - } - - @Environment(EnvType.CLIENT) - @Override - void sendToServer(Minecraft client) { - if (prepareData(true)) { - FriendlyByteBuf buf = PacketByteBufs.create(); - serializeData(buf, true); - ClientPlayNetworking.send(getIdentifier(), buf); - } - } - - /** - * A Message that always originates on the Client - */ - public abstract static class FromClient extends BaseDataHandler { - public abstract static class WithoutPayload extends FromClient { - protected WithoutPayload(ResourceLocation identifier) { - super(identifier); - } - - @Override - protected boolean prepareDataOnClient() { - return true; - } - - @Override - protected void serializeDataOnClient(FriendlyByteBuf buf) { - } - - @Override - protected void deserializeIncomingDataOnServer( - FriendlyByteBuf buf, - Player player, - PacketSender responseSender - ) { - } - } - - protected FromClient(ResourceLocation identifier) { - super(identifier, false); - } - - @Environment(EnvType.CLIENT) - protected boolean prepareDataOnClient() { - return true; - } - - @Environment(EnvType.CLIENT) - abstract protected void serializeDataOnClient(FriendlyByteBuf buf); - - protected abstract void deserializeIncomingDataOnServer( - FriendlyByteBuf buf, - Player player, - PacketSender responseSender - ); - protected abstract void runOnServerGameThread(MinecraftServer server, Player player); - - @Environment(EnvType.CLIENT) - @Override - void receiveFromServer( - Minecraft client, - ClientPacketListener handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the client!"); - } - - @Override - void receiveFromClient( - MinecraftServer server, - ServerPlayer player, - ServerGamePacketListenerImpl handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - super.receiveFromClient(server, player, handler, buf, responseSender); - - deserializeIncomingDataOnServer(buf, player, responseSender); - final Runnable runner = () -> runOnServerGameThread(server, player); - - if (isBlocking()) server.executeBlocking(runner); - else server.execute(runner); - } - - @Override - void sendToClient(MinecraftServer server) { - BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the client!"); - } - - @Override - void sendToClient(MinecraftServer server, ServerPlayer player) { - BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the client!"); - } - - @Environment(EnvType.CLIENT) - @Override - void sendToServer(Minecraft client) { - if (prepareDataOnClient()) { - FriendlyByteBuf buf = PacketByteBufs.create(); - serializeDataOnClient(buf); - ClientPlayNetworking.send(getIdentifier(), buf); - } - } - } - - /** - * A Message that always originates on the Server - */ - public abstract static class FromServer extends BaseDataHandler { - public abstract static class WithoutPayload extends FromServer { - protected WithoutPayload(ResourceLocation identifier) { - super(identifier); - } - - @Override - protected boolean prepareDataOnServer() { - return true; - } - - @Override - protected void serializeDataOnServer(FriendlyByteBuf buf) { - } - - @Override - protected void deserializeIncomingDataOnClient(FriendlyByteBuf buf, PacketSender responseSender) { - } - } - - protected FromServer(ResourceLocation identifier) { - super(identifier, true); - } - - protected boolean prepareDataOnServer() { - return true; - } - - abstract protected void serializeDataOnServer(FriendlyByteBuf buf); - - @Environment(EnvType.CLIENT) - abstract protected void deserializeIncomingDataOnClient(FriendlyByteBuf buf, PacketSender responseSender); - - @Environment(EnvType.CLIENT) - abstract protected void runOnClientGameThread(Minecraft client); - - - @Environment(EnvType.CLIENT) - @Override - final void receiveFromServer( - Minecraft client, - ClientPacketListener handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - deserializeIncomingDataOnClient(buf, responseSender); - final Runnable runner = () -> runOnClientGameThread(client); - - if (isBlocking()) client.executeBlocking(runner); - else client.execute(runner); - } - - @Override - final void receiveFromClient( - MinecraftServer server, - ServerPlayer player, - ServerGamePacketListenerImpl handler, - FriendlyByteBuf buf, - PacketSender responseSender - ) { - super.receiveFromClient(server, player, handler, buf, responseSender); - BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the server!"); - } - - public void receiveFromMemory(FriendlyByteBuf buf) { - receiveFromServer(Minecraft.getInstance(), null, buf, null); - } - - @Override - final void sendToClient(MinecraftServer server) { - if (prepareDataOnServer()) { - FriendlyByteBuf buf = PacketByteBufs.create(); - serializeDataOnServer(buf); - - _sendToClient(getIdentifier(), server, PlayerLookup.all(server), buf); - } - } - - @Override - final void sendToClient(MinecraftServer server, ServerPlayer player) { - if (prepareDataOnServer()) { - FriendlyByteBuf buf = PacketByteBufs.create(); - serializeDataOnServer(buf); - - _sendToClient(getIdentifier(), server, List.of(player), buf); - } - } - - @Environment(EnvType.CLIENT) - @Override - final void sendToServer(Minecraft client) { - BCLib.LOGGER.error("[Internal Error] The message '" + getIdentifier() + "' must originate from the server!"); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataHandlerDescriptor.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataHandlerDescriptor.java deleted file mode 100644 index b572bc31..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/DataHandlerDescriptor.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import net.minecraft.resources.ResourceLocation; - -import java.util.Objects; -import java.util.function.Supplier; -import org.jetbrains.annotations.NotNull; - -public class DataHandlerDescriptor { - public DataHandlerDescriptor(@NotNull ResourceLocation identifier, @NotNull Supplier instancer) { - this(identifier, instancer, instancer, false, false); - } - - public DataHandlerDescriptor( - @NotNull ResourceLocation identifier, - @NotNull Supplier instancer, - boolean sendOnJoin, - boolean sendBeforeEnter - ) { - this(identifier, instancer, instancer, sendOnJoin, sendBeforeEnter); - } - - public DataHandlerDescriptor( - @NotNull ResourceLocation identifier, - @NotNull Supplier receiv_instancer, - @NotNull Supplier join_instancer, - boolean sendOnJoin, - boolean sendBeforeEnter - ) { - this.INSTANCE = receiv_instancer; - this.JOIN_INSTANCE = join_instancer; - this.IDENTIFIER = identifier; - - this.sendOnJoin = sendOnJoin; - this.sendBeforeEnter = sendBeforeEnter; - } - - public final boolean sendOnJoin; - public final boolean sendBeforeEnter; - @NotNull - public final ResourceLocation IDENTIFIER; - @NotNull - public final Supplier INSTANCE; - @NotNull - public final Supplier JOIN_INSTANCE; - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o instanceof ResourceLocation) { - return o.equals(IDENTIFIER); - } - if (!(o instanceof DataHandlerDescriptor that)) return false; - return IDENTIFIER.equals(that.IDENTIFIER); - } - - @Override - public int hashCode() { - return Objects.hash(IDENTIFIER); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/FileHash.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/FileHash.java deleted file mode 100644 index dcbef098..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/FileHash.java +++ /dev/null @@ -1,160 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import org.betterx.bclib.BCLib; - -import net.minecraft.network.FriendlyByteBuf; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Arrays; -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -public class FileHash { - private static final int ERR_DOES_NOT_EXIST = -10; - private static final int ERR_IO_ERROR = -20; - - /** - * The md5-hash of the file - */ - @NotNull - public final byte[] md5; - - /** - * The size (in bytes) of the input. - */ - public final int size; - - /** - * a value that is directly calculated from defined byte positions. - */ - public final int value; - - FileHash(byte[] md5, int size, int value) { - Objects.nonNull(md5); - - this.md5 = md5; - this.size = size; - this.value = value; - } - - static FileHash createForEmpty(int errCode) { - return new FileHash(new byte[0], 0, errCode); - } - - public boolean noFile() { - return md5.length == 0; - } - - /** - * Serializes the Object to a buffer - * - * @param buf The buffer to write to - */ - public void serialize(FriendlyByteBuf buf) { - buf.writeInt(size); - buf.writeInt(value); - buf.writeByteArray(md5); - } - - /** - * Deserialize a Buffer to a new {@link SyncFileHash}-Object - * - * @param buf Thea buffer to read from - * @return The received String - */ - public static FileHash deserialize(FriendlyByteBuf buf) { - final int size = buf.readInt(); - final int value = buf.readInt(); - final byte[] md5 = buf.readByteArray(); - - return new FileHash(md5, size, value); - } - - /** - * Convert the md5-hash to a human readable string - * - * @return The converted String - */ - public String getMd5String() { - return toHexString(md5); - } - - /** - * Converts a byte-array to a hex-string representation - * - * @param bytes The source array - * @return The resulting string, or an empty String if the input was {@code null} - */ - public static String toHexString(byte[] bytes) { - if (bytes == null) return ""; - - StringBuilder sb = new StringBuilder(); - for (byte b : bytes) { - sb.append(String.format("%02x", b)); - } - return sb.toString(); - } - - /** - * Create a new {@link FileHash}. - * - * @param file The input file - * @return A new Instance. You can compare instances using {@link #equals(Object)} to determine if two files are - * identical. Will return {@code null} when an error occurs or the File does not exist - */ - public static FileHash create(File file) { - if (!file.exists()) return createForEmpty(ERR_DOES_NOT_EXIST); - final Path path = file.toPath(); - - int size = 0; - byte[] md5 = new byte[0]; - int value = 0; - - try { - byte[] data = Files.readAllBytes(path); - - size = data.length; - - value = size > 0 ? (data[size / 3] | (data[size / 2] << 8) | (data[size / 5] << 16)) : -1; - if (size > 20) value |= data[20] << 24; - - MessageDigest md = MessageDigest.getInstance("MD5"); - md.update(data); - md5 = md.digest(); - - return new FileHash(md5, size, value); - } catch (IOException e) { - BCLib.LOGGER.error("Failed to read file: " + file); - return null; - } catch (NoSuchAlgorithmException e) { - BCLib.LOGGER.error("Unable to build hash for file: " + file); - } - - return createForEmpty(ERR_IO_ERROR); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof FileHash)) return false; - FileHash fileHash = (FileHash) o; - return size == fileHash.size && value == fileHash.value && Arrays.equals(md5, fileHash.md5); - } - - @Override - public int hashCode() { - int result = Objects.hash(size, value); - result = 31 * result + Arrays.hashCode(md5); - return result; - } - - @Override - public String toString() { - return String.format("%08x", size) + "-" + String.format("%08x", value) + "-" + getMd5String(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/SyncFileHash.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/SyncFileHash.java deleted file mode 100644 index da416911..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/SyncFileHash.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange; - -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID; - -import net.minecraft.network.FriendlyByteBuf; - -import java.io.File; -import java.util.Objects; - -/** - * Calculates a hash based on the contents of a File. - *

- * A File-Hash contains the md5-sum of the File, as well as its size and byte-values from defined positions - *

- * You can compare instances using {@link #equals(Object)} to determine if two files are - * identical. - */ -public class SyncFileHash extends AutoSyncID { - public final FileHash hash; - - SyncFileHash(String modID, File file, byte[] md5, int size, int value) { - this(modID, file.getName(), md5, size, value); - } - - SyncFileHash(String modID, String uniqueID, byte[] md5, int size, int value) { - this(modID, uniqueID, new FileHash(md5, size, value)); - } - - SyncFileHash(String modID, File file, FileHash hash) { - this(modID, file.getName(), hash); - } - - SyncFileHash(String modID, String uniqueID, FileHash hash) { - super(modID, uniqueID); - this.hash = hash; - } - - - final static AutoSync.NeedTransferPredicate NEED_TRANSFER = (clientHash, serverHash, content) -> !clientHash.equals( - serverHash); - - @Override - public String toString() { - return super.toString() + ": " + hash.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof SyncFileHash)) return false; - if (!super.equals(o)) return false; - SyncFileHash that = (SyncFileHash) o; - return hash.equals(that.hash); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), hash); - } - - /** - * Serializes the Object to a buffer - * - * @param buf The buffer to write to - */ - public void serialize(FriendlyByteBuf buf) { - hash.serialize(buf); - DataHandler.writeString(buf, modID); - DataHandler.writeString(buf, uniqueID); - } - - /** - * Deserialize a Buffer to a new {@link SyncFileHash}-Object - * - * @param buf Thea buffer to read from - * @return The received String - */ - public static SyncFileHash deserialize(FriendlyByteBuf buf) { - final FileHash hash = FileHash.deserialize(buf); - final String modID = DataHandler.readString(buf); - final String uniqueID = DataHandler.readString(buf); - - return new SyncFileHash(modID, uniqueID, hash); - } - - /** - * Create a new {@link SyncFileHash}. - *

- * Will call {@link #create(String, File, String)} using the name of the File as {@code uniqueID}. - * - * @param modID ID of the calling Mod - * @param file The input file - * @return A new Instance. You can compare instances using {@link #equals(Object)} to determine if two files are - * identical. Will return {@code null} when an error occurs or the File does not exist - */ - public static SyncFileHash create(String modID, File file) { - return create(modID, file, file.getName()); - } - - /** - * Create a new {@link SyncFileHash}. - * - * @param modID ID of the calling Mod - * @param file The input file - * @param uniqueID The unique ID that is used for this File (see {@link SyncFileHash#uniqueID} for Details. - * @return A new Instance. You can compare instances using {@link #equals(Object)} to determine if two files are - * identical. Will return {@code null} when an error occurs or the File does not exist - */ - public static SyncFileHash create(String modID, File file, String uniqueID) { - return new SyncFileHash(modID, uniqueID, FileHash.create(file)); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/DataExchange.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/DataExchange.java deleted file mode 100644 index 255b994b..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/DataExchange.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler; - -import org.betterx.bclib.api.v2.dataexchange.*; - -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.client.networking.v1.ClientPlayConnectionEvents; -import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents; - -import java.util.HashSet; -import java.util.Set; - -abstract public class DataExchange { - - - private static DataExchangeAPI instance; - - protected static DataExchangeAPI getInstance() { - if (instance == null) { - instance = new DataExchangeAPI(); - } - return instance; - } - - protected ConnectorServerside server; - protected ConnectorClientside client; - protected final Set descriptors; - - - private final boolean didLoadSyncFolder = false; - - abstract protected ConnectorClientside clientSupplier(DataExchange api); - - abstract protected ConnectorServerside serverSupplier(DataExchange api); - - protected DataExchange() { - descriptors = new HashSet<>(); - } - - public Set getDescriptors() { - return descriptors; - } - - public static DataHandlerDescriptor getDescriptor(ResourceLocation identifier) { - return getInstance().descriptors.stream().filter(d -> d.equals(identifier)).findFirst().orElse(null); - } - - @Environment(EnvType.CLIENT) - protected void initClientside() { - if (client != null) return; - client = clientSupplier(this); - - ClientPlayConnectionEvents.INIT.register(client::onPlayInit); - ClientPlayConnectionEvents.JOIN.register(client::onPlayReady); - ClientPlayConnectionEvents.DISCONNECT.register(client::onPlayDisconnect); - } - - protected void initServerSide() { - if (server != null) return; - server = serverSupplier(this); - - ServerPlayConnectionEvents.INIT.register(server::onPlayInit); - ServerPlayConnectionEvents.JOIN.register(server::onPlayReady); - ServerPlayConnectionEvents.DISCONNECT.register(server::onPlayDisconnect); - } - - /** - * Initializes all datastructures that need to exist in the client component. - *

- * This is automatically called by BCLib. You can register {@link DataHandler}-Objects before this Method is called - */ - @Environment(EnvType.CLIENT) - public static void prepareClientside() { - DataExchange api = DataExchange.getInstance(); - api.initClientside(); - - } - - /** - * Initializes all datastructures that need to exist in the server component. - *

- * This is automatically called by BCLib. You can register {@link DataHandler}-Objects before this Method is called - */ - public static void prepareServerside() { - DataExchange api = DataExchange.getInstance(); - api.initServerSide(); - } - - - /** - * Automatically called before the player enters the world. - *

- * This is automatically called by BCLib. It will send all {@link DataHandler}-Objects that have {@link DataHandlerDescriptor#sendBeforeEnter} set to* - * {@code true}, - */ - @Environment(EnvType.CLIENT) - public static void sendOnEnter() { - getInstance().descriptors.forEach((desc) -> { - if (desc.sendBeforeEnter) { - BaseDataHandler h = desc.JOIN_INSTANCE.get(); - if (!h.getOriginatesOnServer()) { - getInstance().client.sendToServer(h); - } - } - }); - } - - -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoFileSyncEntry.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoFileSyncEntry.java deleted file mode 100644 index 17a3920f..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoFileSyncEntry.java +++ /dev/null @@ -1,262 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.api.v2.dataexchange.SyncFileHash; -import org.betterx.bclib.util.Pair; -import org.betterx.bclib.util.Triple; -import org.betterx.worlds.together.util.ModUtil; -import org.betterx.worlds.together.util.ModUtil.ModInfo; -import org.betterx.worlds.together.util.PathUtil; - -import net.minecraft.network.FriendlyByteBuf; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - -class AutoFileSyncEntry extends AutoSyncID { - static class ForDirectFileRequest extends AutoFileSyncEntry { - final File relFile; - - ForDirectFileRequest(String syncID, File relFile, File absFile) { - super(AutoSyncID.ForDirectFileRequest.MOD_ID, syncID, absFile, false, (a, b, c) -> false); - this.relFile = relFile; - } - - @Override - public int serializeContent(FriendlyByteBuf buf) { - int res = super.serializeContent(buf); - DataHandler.writeString(buf, relFile.toString()); - - return res; - } - - static AutoFileSyncEntry.ForDirectFileRequest finishDeserializeContent(String syncID, FriendlyByteBuf buf) { - final String relFile = DataHandler.readString(buf); - SyncFolderDescriptor desc = AutoSync.getSyncFolderDescriptor(syncID); - if (desc != null) { - //ensures that the file is not above the base-folder - if (desc.acceptChildElements(desc.mapAbsolute(relFile))) { - return new AutoFileSyncEntry.ForDirectFileRequest( - syncID, - new File(relFile), - desc.localFolder.resolve(relFile) - .normalize() - .toFile() - ); - } - } - return null; - } - - @Override - public String toString() { - return uniqueID + " - " + relFile; - } - } - - static class ForModFileRequest extends AutoFileSyncEntry { - public static File getLocalPathForID(String modID, boolean matchLocalVersion) { - ModInfo mi = ModUtil.getModInfo(modID, matchLocalVersion); - if (mi != null) { - return mi.jarPath.toFile(); - } - return null; - } - - public final String version; - - ForModFileRequest(String modID, boolean matchLocalVersion, String version) { - super( - modID, - AutoSyncID.ForModFileRequest.UNIQUE_ID, - getLocalPathForID(modID, matchLocalVersion), - false, - (a, b, c) -> false - ); - if (this.fileName == null && matchLocalVersion) { - BCLib.LOGGER.error("Unknown mod '" + modID + "'."); - } - if (version == null) - this.version = ModUtil.getModVersion(modID); - else - this.version = version; - } - - @Override - public int serializeContent(FriendlyByteBuf buf) { - final int res = super.serializeContent(buf); - buf.writeInt(ModUtil.convertModVersion(version)); - return res; - } - - static AutoFileSyncEntry.ForModFileRequest finishDeserializeContent(String modID, FriendlyByteBuf buf) { - final String version = ModUtil.convertModVersion(buf.readInt()); - return new AutoFileSyncEntry.ForModFileRequest(modID, false, version); - } - - @Override - public String toString() { - return "Mod " + modID + " (v" + version + ")"; - } - } - - public final AutoSync.NeedTransferPredicate needTransfer; - public final File fileName; - public final boolean requestContent; - private SyncFileHash hash; - - AutoFileSyncEntry( - String modID, - File fileName, - boolean requestContent, - AutoSync.NeedTransferPredicate needTransfer - ) { - this(modID, fileName.getName(), fileName, requestContent, needTransfer); - } - - AutoFileSyncEntry( - String modID, - String uniqueID, - File fileName, - boolean requestContent, - AutoSync.NeedTransferPredicate needTransfer - ) { - super(modID, uniqueID); - this.needTransfer = needTransfer; - this.fileName = fileName; - this.requestContent = requestContent; - } - - - public SyncFileHash getFileHash() { - if (hash == null) { - hash = SyncFileHash.create(modID, fileName, uniqueID); - } - return hash; - } - - public byte[] getContent() { - if (!fileName.exists()) return new byte[0]; - final Path path = fileName.toPath(); - - try { - return Files.readAllBytes(path); - } catch (IOException e) { - - } - return new byte[0]; - } - - public int serializeContent(FriendlyByteBuf buf) { - DataHandler.writeString(buf, modID); - DataHandler.writeString(buf, uniqueID); - return serializeFileContent(buf); - } - - public static Triple deserializeContent(FriendlyByteBuf buf) { - final String modID = DataHandler.readString(buf); - final String uniqueID = DataHandler.readString(buf); - byte[] data = deserializeFileContent(buf); - - AutoFileSyncEntry entry; - if (AutoSyncID.ForDirectFileRequest.MOD_ID.equals(modID)) { - entry = AutoFileSyncEntry.ForDirectFileRequest.finishDeserializeContent(uniqueID, buf); - } else if (AutoSyncID.ForModFileRequest.UNIQUE_ID.equals(uniqueID)) { - entry = AutoFileSyncEntry.ForModFileRequest.finishDeserializeContent(modID, buf); - } else { - entry = AutoFileSyncEntry.findMatching(modID, uniqueID); - } - return new Triple<>(entry, data, new AutoSyncID(modID, uniqueID)); - } - - - public void serialize(FriendlyByteBuf buf) { - getFileHash().serialize(buf); - buf.writeBoolean(requestContent); - - if (requestContent) { - serializeFileContent(buf); - } - } - - public static AutoSync.AutoSyncTriple deserializeAndMatch(FriendlyByteBuf buf) { - Pair e = deserialize(buf); - AutoFileSyncEntry match = findMatching(e.first); - return new AutoSync.AutoSyncTriple(e.first, e.second, match); - } - - public static Pair deserialize(FriendlyByteBuf buf) { - SyncFileHash hash = SyncFileHash.deserialize(buf); - boolean withContent = buf.readBoolean(); - byte[] data = null; - if (withContent) { - data = deserializeFileContent(buf); - } - - return new Pair(hash, data); - } - - private int serializeFileContent(FriendlyByteBuf buf) { - if (!org.betterx.worlds.together.util.PathUtil.isChildOf( - org.betterx.worlds.together.util.PathUtil.GAME_FOLDER, - fileName.toPath() - )) { - BCLib.LOGGER.error(fileName + " is not within game folder " + PathUtil.GAME_FOLDER + ". Pretending it does not exist."); - buf.writeInt(0); - return 0; - } - - byte[] content = getContent(); - buf.writeInt(content.length); - buf.writeByteArray(content); - return content.length; - } - - private static byte[] deserializeFileContent(FriendlyByteBuf buf) { - byte[] data; - int size = buf.readInt(); - data = buf.readByteArray(size); - return data; - } - - - public static AutoFileSyncEntry findMatching(SyncFileHash hash) { - return findMatching(hash.modID, hash.uniqueID); - } - - public static AutoFileSyncEntry findMatching(AutoSyncID aid) { - if (aid instanceof AutoSyncID.ForDirectFileRequest) { - AutoSyncID.ForDirectFileRequest freq = (AutoSyncID.ForDirectFileRequest) aid; - SyncFolderDescriptor desc = AutoSync.getSyncFolderDescriptor(freq.uniqueID); - if (desc != null) { - SyncFolderDescriptor.SubFile subFile = desc.getLocalSubFile(freq.relFile.toString()); - if (subFile != null) { - final File absPath = desc.localFolder.resolve(subFile.relPath) - .normalize() - .toFile(); - return new AutoFileSyncEntry.ForDirectFileRequest( - freq.uniqueID, - new File(subFile.relPath), - absPath - ); - } - } - return null; - } else if (aid instanceof AutoSyncID.ForModFileRequest) { - AutoSyncID.ForModFileRequest mreq = (AutoSyncID.ForModFileRequest) aid; - return new AutoFileSyncEntry.ForModFileRequest(mreq.modID, true, null); - } - return findMatching(aid.modID, aid.uniqueID); - } - - public static AutoFileSyncEntry findMatching(String modID, String uniqueID) { - return AutoSync.getAutoSyncFiles() - .stream() - .filter(asf -> asf.modID.equals(modID) && asf.uniqueID.equals(uniqueID)) - .findFirst() - .orElse(null); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoSync.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoSync.java deleted file mode 100644 index 64a3811d..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoSync.java +++ /dev/null @@ -1,207 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; -import org.betterx.bclib.api.v2.dataexchange.SyncFileHash; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.config.ServerConfig; -import org.betterx.worlds.together.util.PathUtil; - -import net.fabricmc.loader.api.FabricLoader; - -import java.io.File; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.function.BiConsumer; - -public class AutoSync { - public static final String SYNC_CATEGORY = "auto_sync"; - public final static SyncFolderDescriptor SYNC_FOLDER = new SyncFolderDescriptor( - "BCLIB-SYNC", - FabricLoader.getInstance() - .getGameDir() - .resolve("bclib-sync") - .normalize() - .toAbsolutePath(), - true - ); - - @FunctionalInterface - public interface NeedTransferPredicate { - boolean test(SyncFileHash clientHash, SyncFileHash serverHash, FileContentWrapper content); - } - - final static class AutoSyncTriple { - public final SyncFileHash serverHash; - public final byte[] serverContent; - public final AutoFileSyncEntry localMatch; - - public AutoSyncTriple(SyncFileHash serverHash, byte[] serverContent, AutoFileSyncEntry localMatch) { - this.serverHash = serverHash; - this.serverContent = serverContent; - this.localMatch = localMatch; - } - - @Override - public String toString() { - return serverHash.modID + "." + serverHash.uniqueID; - } - } - - - // ##### File Syncing - protected final static List> onWriteCallbacks = new ArrayList<>(2); - - /** - * Register a function that is called whenever the client receives a file from the server and replaced toe local - * file with the new content. - *

- * This callback is usefull if you need to reload the new content before the game is quit. - * - * @param callback A Function that receives the AutoSyncID as well as the Filename. - */ - public static void addOnWriteCallback(BiConsumer callback) { - onWriteCallbacks.add(callback); - } - - private static final List autoSyncFiles = new ArrayList<>(4); - - public static List getAutoSyncFiles() { - return autoSyncFiles; - } - - /** - * Registers a File for automatic client syncing. - * - * @param modID The ID of the calling Mod - * @param needTransfer If the predicate returns true, the file needs to get copied to the server. - * @param fileName The name of the File - * @param requestContent When {@code true} the content of the file is requested for comparison. This will copy the - * entire file from the client to the server. - *

- * You should only use this option, if you need to compare parts of the file in order to decide - * If the File needs to be copied. Normally using the {@link SyncFileHash} - * for comparison is sufficient. - */ - public static void addAutoSyncFileData( - String modID, - File fileName, - boolean requestContent, - NeedTransferPredicate needTransfer - ) { - if (!PathUtil.isChildOf(PathUtil.GAME_FOLDER, fileName.toPath())) { - BCLib.LOGGER.error(fileName + " is outside of Game Folder " + PathUtil.GAME_FOLDER); - } else { - autoSyncFiles.add(new AutoFileSyncEntry(modID, fileName, requestContent, needTransfer)); - } - } - - /** - * Registers a File for automatic client syncing. - * - * @param modID The ID of the calling Mod - * @param uniqueID A unique Identifier for the File. (see {@link SyncFileHash#uniqueID} for - * Details - * @param needTransfer If the predicate returns true, the file needs to get copied to the server. - * @param fileName The name of the File - * @param requestContent When {@code true} the content of the file is requested for comparison. This will copy the - * entire file from the client to the server. - *

- * You should only use this option, if you need to compare parts of the file in order to decide - * If the File needs to be copied. Normally using the {@link SyncFileHash} - * for comparison is sufficient. - */ - public static void addAutoSyncFileData( - String modID, - String uniqueID, - File fileName, - boolean requestContent, - NeedTransferPredicate needTransfer - ) { - if (!PathUtil.isChildOf(PathUtil.GAME_FOLDER, fileName.toPath())) { - BCLib.LOGGER.error(fileName + " is outside of Game Folder " + PathUtil.GAME_FOLDER); - } else { - autoSyncFiles.add(new AutoFileSyncEntry(modID, uniqueID, fileName, requestContent, needTransfer)); - } - } - - /** - * Called when {@code SendFiles} received a File on the Client and wrote it to the FileSystem. - *

- * This is the place where reload Code should go. - * - * @param aid The ID of the received File - * @param file The location of the FIle on the client - */ - static void didReceiveFile(AutoSyncID aid, File file) { - onWriteCallbacks.forEach(fkt -> fkt.accept(aid, file)); - } - - - // ##### Folder Syncing - static final List syncFolderDescriptions = Arrays.asList(SYNC_FOLDER); - - private List syncFolderContent; - - protected List getSyncFolderContent() { - if (syncFolderContent == null) { - return new ArrayList<>(0); - } - return syncFolderContent; - } - - private static boolean didRegisterAdditionalMods = false; - - //we call this from HelloClient on the Server to prepare transfer - protected static void loadSyncFolder() { - if (Configs.SERVER_CONFIG.isOfferingFiles()) { - syncFolderDescriptions.forEach(desc -> desc.loadCache()); - } - - if (!didRegisterAdditionalMods && Configs.SERVER_CONFIG.isOfferingMods()) { - didRegisterAdditionalMods = true; - List modIDs = Configs.SERVER_CONFIG.get(ServerConfig.ADDITIONAL_MODS); - if (modIDs != null) { - modIDs.stream().forEach(modID -> DataExchangeAPI.registerModDependency(modID)); - } - } - - } - - protected static SyncFolderDescriptor getSyncFolderDescriptor(String folderID) { - return syncFolderDescriptions.stream() - .filter(d -> d.equals(folderID)) - .findFirst() - .orElse(null); - } - - protected static Path localBasePathForFolderID(String folderID) { - final SyncFolderDescriptor desc = getSyncFolderDescriptor(folderID); - if (desc != null) { - return desc.localFolder; - } else { - BCLib.LOGGER.warning("Unknown Sync-Folder ID '" + folderID + "'"); - return null; - } - } - - public static void registerSyncFolder(String folderID, Path localBaseFolder, boolean removeAdditionalFiles) { - localBaseFolder = localBaseFolder.normalize(); - if (PathUtil.isChildOf(PathUtil.GAME_FOLDER, localBaseFolder)) { - final SyncFolderDescriptor desc = new SyncFolderDescriptor( - folderID, - localBaseFolder, - removeAdditionalFiles - ); - if (syncFolderDescriptions.contains(desc)) { - BCLib.LOGGER.warning("Tried to override Folder Sync '" + folderID + "' again."); - } else { - syncFolderDescriptions.add(desc); - } - } else { - BCLib.LOGGER.error(localBaseFolder + " (from " + folderID + ") is outside the game directory " + PathUtil.GAME_FOLDER + ". Sync is not allowed."); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoSyncID.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoSyncID.java deleted file mode 100644 index b8ace9bc..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/AutoSyncID.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.config.Config; -import org.betterx.worlds.together.util.ModUtil; - -import net.minecraft.network.FriendlyByteBuf; - -import java.io.File; -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -public class AutoSyncID { - static class WithContentOverride extends AutoSyncID { - final FileContentWrapper contentWrapper; - final File localFile; - - WithContentOverride(String modID, String uniqueID, FileContentWrapper contentWrapper, File localFile) { - super(modID, uniqueID); - this.contentWrapper = contentWrapper; - this.localFile = localFile; - } - - @Override - public String toString() { - return super.toString() + " (Content override)"; - } - } - - static class ForDirectFileRequest extends AutoSyncID { - public final static String MOD_ID = "bclib::FILE"; - final File relFile; - - ForDirectFileRequest(String syncID, File relFile) { - super(ForDirectFileRequest.MOD_ID, syncID); - this.relFile = relFile; - } - - @Override - void serializeData(FriendlyByteBuf buf) { - super.serializeData(buf); - DataHandler.writeString(buf, relFile.toString()); - } - - static ForDirectFileRequest finishDeserialize(String modID, String uniqueID, FriendlyByteBuf buf) { - final File fl = new File(DataHandler.readString(buf)); - return new ForDirectFileRequest(uniqueID, fl); - } - - @Override - public String toString() { - return super.uniqueID + " (" + this.relFile + ")"; - } - } - - static class ForModFileRequest extends AutoSyncID { - public final static String UNIQUE_ID = "bclib::MOD"; - private final String version; - - ForModFileRequest(String modID, String version) { - super(modID, ForModFileRequest.UNIQUE_ID); - this.version = version; - } - - @Override - void serializeData(FriendlyByteBuf buf) { - super.serializeData(buf); - buf.writeInt(ModUtil.convertModVersion(version)); - } - - static ForModFileRequest finishDeserialize(String modID, String uniqueID, FriendlyByteBuf buf) { - final String version = ModUtil.convertModVersion(buf.readInt()); - return new ForModFileRequest(modID, version); - } - - @Override - public String toString() { - return super.modID + " (v" + this.version + ")"; - } - } - - /** - * A Unique ID for the referenced File. - *

- * Files with the same {@link #modID} need to have a unique IDs. Normally the filename from FileHash(String, File, byte[], int, int) - * is used to generated that ID, but you can directly specify one using FileHash(String, String, byte[], int, int). - */ - @NotNull - public final String uniqueID; - - /** - * The ID of the Mod that is registering the File - */ - @NotNull - public final String modID; - - public AutoSyncID(String modID, String uniqueID) { - Objects.nonNull(modID); - Objects.nonNull(uniqueID); - - this.modID = modID; - this.uniqueID = uniqueID; - } - - @Override - public String toString() { - return modID + "." + uniqueID; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof AutoSyncID)) return false; - AutoSyncID that = (AutoSyncID) o; - return uniqueID.equals(that.uniqueID) && modID.equals(that.modID); - } - - @Override - public int hashCode() { - return Objects.hash(uniqueID, modID); - } - - void serializeData(FriendlyByteBuf buf) { - DataHandler.writeString(buf, modID); - DataHandler.writeString(buf, uniqueID); - } - - static AutoSyncID deserializeData(FriendlyByteBuf buf) { - String modID = DataHandler.readString(buf); - String uID = DataHandler.readString(buf); - - if (ForDirectFileRequest.MOD_ID.equals(modID)) { - return ForDirectFileRequest.finishDeserialize(modID, uID, buf); - } else if (ForModFileRequest.UNIQUE_ID.equals(uID)) { - return ForModFileRequest.finishDeserialize(modID, uID, buf); - } else { - return new AutoSyncID(modID, uID); - } - } - - public boolean isConfigFile() { - return this.uniqueID.startsWith(Config.CONFIG_SYNC_PREFIX); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/Chunker.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/Chunker.java deleted file mode 100644 index d9eab98e..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/Chunker.java +++ /dev/null @@ -1,280 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.BaseDataHandler; -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor; -import org.betterx.bclib.api.v2.dataexchange.handler.DataExchange; - -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.ProgressListener; - -import net.fabricmc.fabric.api.networking.v1.PacketByteBufs; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; - -import java.util.*; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Used to seperate large data transfers into multiple smaller messages. - *

- * {@link DataHandler} will automatically convert larger messages into Chunks on the Server - * and assemble the original message from those chunks on the client. - */ -public class Chunker extends DataHandler.FromServer { - - /** - * Responsible for assembling the original ByteBuffer created by {@link PacketChunkSender} on the - * receiving end. Automatically created from the header {@link Chunker}-Message (where the serialNo==-1) - */ - static class PacketChunkReceiver { - @NotNull - public final UUID uuid; - public final int chunkCount; - @NotNull - private final FriendlyByteBuf networkedBuf; - @Nullable - private final DataHandlerDescriptor descriptor; - - private static final List active = new ArrayList<>(1); - - private static PacketChunkReceiver newReceiver(@NotNull UUID uuid, int chunkCount, ResourceLocation origin) { - DataHandlerDescriptor desc = DataExchange.getDescriptor(origin); - final PacketChunkReceiver r = new PacketChunkReceiver(uuid, chunkCount, desc); - active.add(r); - return r; - } - - private static PacketChunkReceiver getOrCreate(@NotNull UUID uuid, int chunkCount, ResourceLocation origin) { - return active.stream() - .filter(r -> r.uuid.equals(uuid)) - .findFirst() - .orElse(newReceiver(uuid, chunkCount, origin)); - } - - public static PacketChunkReceiver get(@NotNull UUID uuid) { - return active.stream().filter(r -> r.uuid.equals(uuid)).findFirst().orElse(null); - } - - private PacketChunkReceiver(@NotNull UUID uuid, int chunkCount, @Nullable DataHandlerDescriptor descriptor) { - this.uuid = uuid; - this.chunkCount = chunkCount; - networkedBuf = PacketByteBufs.create(); - this.descriptor = descriptor; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof PacketChunkReceiver)) return false; - PacketChunkReceiver that = (PacketChunkReceiver) o; - return uuid.equals(that.uuid); - } - - @Override - public int hashCode() { - return Objects.hash(uuid); - } - - public boolean testFinished() { - ProgressListener listener = ChunkerProgress.getProgressListener(); - if (listener != null) { - listener.progressStagePercentage((100 * receivedCount) / chunkCount); - } - if (incomingBuffer == null) { - return true; - } - if (lastReadSerial >= chunkCount - 1) { - onFinish(); - return true; - } - return false; - } - - private void addBuffer(FriendlyByteBuf input) { - final int size = input.readableBytes(); - final int cap = networkedBuf.capacity() - networkedBuf.writerIndex(); - - if (cap < size) { - networkedBuf.capacity(networkedBuf.writerIndex() + size); - } - input.readBytes(networkedBuf, size); - input.clear(); - } - - protected void onFinish() { - incomingBuffer.clear(); - incomingBuffer = null; - - final BaseDataHandler baseHandler = descriptor.INSTANCE.get(); - if (baseHandler instanceof DataHandler.FromServer handler) { - handler.receiveFromMemory(networkedBuf); - } - } - - Map incomingBuffer = new HashMap<>(); - int lastReadSerial = -1; - int receivedCount = 0; - - public void processReceived(FriendlyByteBuf buf, int serialNo, int size) { - receivedCount++; - - if (lastReadSerial == serialNo - 1) { - addBuffer(buf); - lastReadSerial = serialNo; - } else { - //not sure if order is guaranteed by the underlying system! - boolean haveAll = true; - for (int nr = lastReadSerial + 1; nr < serialNo - 1; nr++) { - if (incomingBuffer.get(nr) == null) { - haveAll = false; - break; - } - } - - if (haveAll) { - for (int nr = lastReadSerial + 1; nr < serialNo - 1; nr++) { - addBuffer(incomingBuffer.get(nr)); - incomingBuffer.put(nr, null); - } - addBuffer(buf); - lastReadSerial = serialNo; - } else { - incomingBuffer.put(serialNo, buf); - } - } - } - } - - /** - * Responsible for splitting an outgoing ByteBuffer into several smaller Chunks and - * send them as seperate messages to the {@link Chunker}-Channel - */ - public static class PacketChunkSender { - private final FriendlyByteBuf networkedBuf; - public final UUID uuid; - public final int chunkCount; - public final int size; - public final ResourceLocation origin; - - public PacketChunkSender(FriendlyByteBuf buf, ResourceLocation origin) { - networkedBuf = buf; - - size = buf.readableBytes(); - chunkCount = (int) Math.ceil((double) size / MAX_PAYLOAD_SIZE); - uuid = UUID.randomUUID(); - this.origin = origin; - } - - public void sendChunks(Collection players) { - BCLib.LOGGER.info("Sending Request in " + chunkCount + " Packet-Chunks"); - for (int i = -1; i < chunkCount; i++) { - Chunker c = new Chunker(i, uuid, networkedBuf, chunkCount, origin); - FriendlyByteBuf buf = PacketByteBufs.create(); - c.serializeDataOnServer(buf); - - for (ServerPlayer player : players) { - ServerPlayNetworking.send(player, DESCRIPTOR.IDENTIFIER, buf); - } - } - } - } - - //header = version + UUID + serialNo + size, see serializeDataOnServer - private static final int HEADER_SIZE = 1 + 16 + 4 + 4; - - public static final int MAX_PACKET_SIZE = 1024 * 1024; - private static final int MAX_PAYLOAD_SIZE = MAX_PACKET_SIZE - HEADER_SIZE; - - public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor( - new ResourceLocation( - BCLib.MOD_ID, - "chunker" - ), - Chunker::new, - false, - false - ); - - private int serialNo; - private UUID uuid; - private int chunkCount; - private FriendlyByteBuf networkedBuf; - private ResourceLocation origin; - - protected Chunker(int serialNo, UUID uuid, FriendlyByteBuf networkedBuf, int chunkCount, ResourceLocation origin) { - super(DESCRIPTOR.IDENTIFIER); - this.serialNo = serialNo; - this.uuid = uuid; - this.networkedBuf = networkedBuf; - this.chunkCount = chunkCount; - this.origin = origin; - } - - protected Chunker() { - super(DESCRIPTOR.IDENTIFIER); - } - - - @Override - protected void serializeDataOnServer(FriendlyByteBuf buf) { - //Sending Header. Make sure to change HEADER_SIZE if you change this! - buf.writeByte(0); - buf.writeLong(uuid.getMostSignificantBits()); - buf.writeLong(uuid.getLeastSignificantBits()); - buf.writeInt(serialNo); - - //sending Payload - if (serialNo == -1) { - //this is our header-Chunk that transports status information - buf.writeInt(chunkCount); - writeString(buf, origin.getNamespace()); - writeString(buf, origin.getPath()); - } else { - //this is an actual payload chunk - buf.capacity(MAX_PACKET_SIZE); - final int size = Math.min(MAX_PAYLOAD_SIZE, networkedBuf.readableBytes()); - buf.writeInt(size); - networkedBuf.readBytes(buf, size); - } - } - - private PacketChunkReceiver receiver; - - @Override - protected void deserializeIncomingDataOnClient(FriendlyByteBuf buf, PacketSender responseSender) { - final int version = buf.readByte(); - uuid = new UUID(buf.readLong(), buf.readLong()); - serialNo = buf.readInt(); - - if (serialNo == -1) { - chunkCount = buf.readInt(); - final String namespace = readString(buf); - final String path = readString(buf); - ResourceLocation ident = new ResourceLocation(namespace, path); - BCLib.LOGGER.info("Receiving " + chunkCount + " + Packet-Chunks for " + ident); - - receiver = PacketChunkReceiver.getOrCreate(uuid, chunkCount, ident); - } else { - receiver = PacketChunkReceiver.get(uuid); - if (receiver != null) { - final int size = buf.readInt(); - receiver.processReceived(buf, serialNo, size); - } else { - BCLib.LOGGER.error("Unknown Packet-Chunk Transfer for " + uuid); - } - } - } - - @Override - protected void runOnClientGameThread(Minecraft client) { - if (receiver != null) { - receiver.testFinished(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/ChunkerProgress.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/ChunkerProgress.java deleted file mode 100644 index ae82fc38..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/ChunkerProgress.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.client.gui.screens.ProgressScreen; - -import net.minecraft.util.ProgressListener; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class ChunkerProgress { - private static ProgressScreen progressScreen; - - @Environment(EnvType.CLIENT) - public static void setProgressScreen(ProgressScreen scr) { - progressScreen = scr; - } - - @Environment(EnvType.CLIENT) - public static ProgressScreen getProgressScreen() { - return progressScreen; - } - - @Environment(EnvType.CLIENT) - public static ProgressListener getProgressListener() { - return progressScreen; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/FileContentWrapper.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/FileContentWrapper.java deleted file mode 100644 index 669fc955..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/FileContentWrapper.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; - -public class FileContentWrapper { - private byte[] rawContent; - private ByteArrayOutputStream outputStream; - - FileContentWrapper(byte[] content) { - this.rawContent = content; - this.outputStream = null; - } - - public byte[] getOriginalContent() { - return rawContent; - } - - public byte[] getRawContent() { - if (outputStream != null) { - return outputStream.toByteArray(); - } - return rawContent; - } - - private void invalidateOutputStream() { - if (this.outputStream != null) { - try { - this.outputStream.close(); - } catch (IOException e) { - BCLib.LOGGER.debug(e); - } - } - this.outputStream = null; - } - - public void setRawContent(byte[] rawContent) { - this.rawContent = rawContent; - invalidateOutputStream(); - } - - public void syncWithOutputStream() { - if (outputStream != null) { - try { - outputStream.flush(); - } catch (IOException e) { - BCLib.LOGGER.error(e.getMessage()); - e.printStackTrace(); - } - setRawContent(getRawContent()); - invalidateOutputStream(); - } - } - - public ByteArrayInputStream getInputStream() { - if (rawContent == null) return new ByteArrayInputStream(new byte[0]); - return new ByteArrayInputStream(rawContent); - } - - public ByteArrayOutputStream getOrCreateOutputStream() { - if (this.outputStream == null) { - return this.getEmptyOutputStream(); - } - return this.outputStream; - } - - public ByteArrayOutputStream getEmptyOutputStream() { - invalidateOutputStream(); - this.outputStream = new ByteArrayOutputStream(this.rawContent.length); - return this.outputStream; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/HelloClient.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/HelloClient.java deleted file mode 100644 index 31e883f6..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/HelloClient.java +++ /dev/null @@ -1,530 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor; -import org.betterx.bclib.client.gui.screens.ModListScreen; -import org.betterx.bclib.client.gui.screens.ProgressScreen; -import org.betterx.bclib.client.gui.screens.SyncFilesScreen; -import org.betterx.bclib.client.gui.screens.WarnBCLibVersionMismatch; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.config.ServerConfig; -import org.betterx.worlds.together.util.ModUtil; -import org.betterx.worlds.together.util.ModUtil.ModInfo; -import org.betterx.worlds.together.util.PathUtil; - -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.fabricmc.loader.api.metadata.ModEnvironment; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.*; -import java.util.Map.Entry; -import java.util.stream.Collectors; - -/** - * Sent from the Server to the Client. - *

- * For Details refer to {@link HelloServer} - */ -public class HelloClient extends DataHandler.FromServer { - public record OfferedModInfo(String version, int size, boolean canDownload) { - } - - public interface IServerModMap extends Map { - } - - public static class ServerModMap extends HashMap implements IServerModMap { - } - - public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor( - new ResourceLocation( - BCLib.MOD_ID, - "hello_client" - ), - HelloClient::new, - false, - false - ); - - public HelloClient() { - super(DESCRIPTOR.IDENTIFIER); - } - - static String getBCLibVersion() { - return ModUtil.getModVersion(BCLib.MOD_ID); - } - - @Override - protected boolean prepareDataOnServer() { - if (!Configs.SERVER_CONFIG.isAllowingAutoSync()) { - BCLib.LOGGER.info("Auto-Sync was disabled on the server."); - return false; - } - - AutoSync.loadSyncFolder(); - return true; - } - - @Override - protected void serializeDataOnServer(FriendlyByteBuf buf) { - final String vbclib = getBCLibVersion(); - BCLib.LOGGER.info("Sending Hello to Client. (server=" + vbclib + ")"); - - //write BCLibVersion (=protocol version) - buf.writeInt(ModUtil.convertModVersion(vbclib)); - - if (Configs.SERVER_CONFIG.isOfferingMods() || Configs.SERVER_CONFIG.isOfferingInfosForMods()) { - List mods = DataExchangeAPI.registeredMods(); - final List inmods = mods; - if (Configs.SERVER_CONFIG.isOfferingAllMods() || Configs.SERVER_CONFIG.isOfferingInfosForMods()) { - mods = new ArrayList<>(inmods.size()); - mods.addAll(inmods); - mods.addAll(ModUtil - .getMods() - .entrySet() - .stream() - .filter(entry -> entry.getValue().metadata.getEnvironment() != ModEnvironment.SERVER && !inmods.contains( - entry.getKey())) - .map(entry -> entry.getKey()) - .collect(Collectors.toList()) - ); - } - - mods = mods - .stream() - .filter(entry -> !Configs.SERVER_CONFIG.get(ServerConfig.EXCLUDED_MODS).contains(entry)) - .collect(Collectors.toList()); - - //write Plugin Versions - buf.writeInt(mods.size()); - for (String modID : mods) { - final String ver = ModUtil.getModVersion(modID); - int size = 0; - - final ModInfo mi = ModUtil.getModInfo(modID); - if (mi != null) { - try { - size = (int) Files.size(mi.jarPath); - } catch (IOException e) { - BCLib.LOGGER.error("Unable to get File Size: " + e.getMessage()); - } - } - - - writeString(buf, modID); - buf.writeInt(ModUtil.convertModVersion(ver)); - buf.writeInt(size); - final boolean canDownload = size > 0 && Configs.SERVER_CONFIG.isOfferingMods() && (Configs.SERVER_CONFIG.isOfferingAllMods() || inmods.contains( - modID)); - buf.writeBoolean(canDownload); - - BCLib.LOGGER.info(" - Listing Mod " + modID + " v" + ver + " (size: " + PathUtil.humanReadableFileSize( - size) + ", download=" + canDownload + ")"); - } - } else { - BCLib.LOGGER.info("Server will not list Mods."); - buf.writeInt(0); - } - - if (Configs.SERVER_CONFIG.isOfferingFiles() || Configs.SERVER_CONFIG.isOfferingConfigs()) { - //do only include files that exist on the server - final List existingAutoSyncFiles = AutoSync.getAutoSyncFiles() - .stream() - .filter(e -> e.fileName.exists()) - .filter(e -> (e.isConfigFile() && Configs.SERVER_CONFIG.isOfferingConfigs()) || (e instanceof AutoFileSyncEntry.ForDirectFileRequest && Configs.SERVER_CONFIG.isOfferingFiles())) - .collect(Collectors.toList()); - - //send config Data - buf.writeInt(existingAutoSyncFiles.size()); - for (AutoFileSyncEntry entry : existingAutoSyncFiles) { - entry.serialize(buf); - BCLib.LOGGER.info(" - Offering " + (entry.isConfigFile() ? "Config " : "File ") + entry); - } - } else { - BCLib.LOGGER.info("Server will neither offer Files nor Configs."); - buf.writeInt(0); - } - - if (Configs.SERVER_CONFIG.isOfferingFiles()) { - buf.writeInt(AutoSync.syncFolderDescriptions.size()); - AutoSync.syncFolderDescriptions.forEach(desc -> { - BCLib.LOGGER.info(" - Offering Folder " + desc.localFolder + " (allowDelete=" + desc.removeAdditionalFiles + ")"); - desc.serialize(buf); - }); - } else { - BCLib.LOGGER.info("Server will not offer Sync Folders."); - buf.writeInt(0); - } - - buf.writeBoolean(Configs.SERVER_CONFIG.isOfferingInfosForMods()); - } - - String bclibVersion = "0.0.0"; - - - IServerModMap modVersion = new ServerModMap(); - List autoSyncedFiles = null; - List autoSynFolders = null; - boolean serverPublishedModInfo = false; - - @Environment(EnvType.CLIENT) - @Override - protected void deserializeIncomingDataOnClient(FriendlyByteBuf buf, PacketSender responseSender) { - //read BCLibVersion (=protocol version) - bclibVersion = ModUtil.convertModVersion(buf.readInt()); - - //read Plugin Versions - modVersion = new ServerModMap(); - int count = buf.readInt(); - for (int i = 0; i < count; i++) { - final String id = readString(buf); - final String version = ModUtil.convertModVersion(buf.readInt()); - final int size; - final boolean canDownload; - //since v0.4.1 we also send the size of the mod-File - size = buf.readInt(); - canDownload = buf.readBoolean(); - modVersion.put(id, new OfferedModInfo(version, size, canDownload)); - } - - //read config Data - count = buf.readInt(); - autoSyncedFiles = new ArrayList<>(count); - for (int i = 0; i < count; i++) { - //System.out.println("Deserializing "); - AutoSync.AutoSyncTriple t = AutoFileSyncEntry.deserializeAndMatch(buf); - autoSyncedFiles.add(t); - //System.out.println(t.first); - } - - - autoSynFolders = new ArrayList<>(1); - //since v0.4.1 we also send the sync folders - final int folderCount = buf.readInt(); - for (int i = 0; i < folderCount; i++) { - SyncFolderDescriptor desc = SyncFolderDescriptor.deserialize(buf); - autoSynFolders.add(desc); - } - - serverPublishedModInfo = buf.readBoolean(); - } - - @Environment(EnvType.CLIENT) - private void processAutoSyncFolder( - final List filesToRequest, - final List filesToRemove - ) { - if (!Configs.CLIENT_CONFIG.isAcceptingFiles()) { - return; - } - - if (autoSynFolders.size() > 0) { - BCLib.LOGGER.info("Folders offered by Server:"); - } - - autoSynFolders.forEach(desc -> { - //desc contains the fileCache sent from the server, load the local version to get hold of the actual file cache on the client - SyncFolderDescriptor localDescriptor = AutoSync.getSyncFolderDescriptor(desc.folderID); - if (localDescriptor != null) { - BCLib.LOGGER.info(" - " + desc.folderID + " (" + desc.localFolder + ", allowRemove=" + desc.removeAdditionalFiles + ")"); - localDescriptor.invalidateCache(); - - desc.relativeFilesStream() - .filter(desc::discardChildElements) - .forEach(subFile -> { - BCLib.LOGGER.warning(" * " + subFile.relPath + " (REJECTED)"); - }); - - - if (desc.removeAdditionalFiles) { - List additionalFiles = localDescriptor.relativeFilesStream() - .filter(subFile -> !desc.hasRelativeFile( - subFile)) - .map(desc::mapAbsolute) - .filter(desc::acceptChildElements) - .map(absPath -> new AutoSyncID.ForDirectFileRequest( - desc.folderID, - absPath.toFile() - )) - .collect(Collectors.toList()); - - additionalFiles.forEach(aid -> BCLib.LOGGER.info(" * " + desc.localFolder.relativize(aid.relFile.toPath()) + " (missing on server)")); - filesToRemove.addAll(additionalFiles); - } - - desc.relativeFilesStream() - .filter(desc::acceptChildElements) - .forEach(subFile -> { - SyncFolderDescriptor.SubFile localSubFile = localDescriptor.getLocalSubFile(subFile.relPath); - if (localSubFile != null) { - //the file exists locally, check if the hashes match - if (!localSubFile.hash.equals(subFile.hash)) { - BCLib.LOGGER.info(" * " + subFile.relPath + " (changed)"); - filesToRequest.add(new AutoSyncID.ForDirectFileRequest( - desc.folderID, - new File(subFile.relPath) - )); - } else { - BCLib.LOGGER.info(" * " + subFile.relPath); - } - } else { - //the file is missing locally - BCLib.LOGGER.info(" * " + subFile.relPath + " (missing on client)"); - filesToRequest.add(new AutoSyncID.ForDirectFileRequest( - desc.folderID, - new File(subFile.relPath) - )); - } - }); - - //free some memory - localDescriptor.invalidateCache(); - } else { - BCLib.LOGGER.info(" - " + desc.folderID + " (Failed to find)"); - } - }); - } - - @Environment(EnvType.CLIENT) - private void processSingleFileSync(final List filesToRequest) { - final boolean debugHashes = Configs.CLIENT_CONFIG.shouldPrintDebugHashes(); - - if (autoSyncedFiles.size() > 0) { - BCLib.LOGGER.info("Files offered by Server:"); - } - - //Handle single sync files - //Single files need to be registered for sync on both client and server - //There are no restrictions to the target folder, but the client decides the final - //location. - for (AutoSync.AutoSyncTriple e : autoSyncedFiles) { - String actionString = ""; - FileContentWrapper contentWrapper = new FileContentWrapper(e.serverContent); - if (e.localMatch == null) { - actionString = "(unknown source -> omitting)"; - //filesToRequest.add(new AutoSyncID(e.serverHash.modID, e.serverHash.uniqueID)); - } else if (e.localMatch.needTransfer.test(e.localMatch.getFileHash(), e.serverHash, contentWrapper)) { - actionString = "(prepare update)"; - //we did not yet receive the new content - if (contentWrapper.getRawContent() == null) { - filesToRequest.add(new AutoSyncID(e.serverHash.modID, e.serverHash.uniqueID)); - } else { - filesToRequest.add(new AutoSyncID.WithContentOverride( - e.serverHash.modID, - e.serverHash.uniqueID, - contentWrapper, - e.localMatch.fileName - )); - } - } - - BCLib.LOGGER.info(" - " + e + ": " + actionString); - if (debugHashes) { - BCLib.LOGGER.info(" * " + e.serverHash + " (Server)"); - BCLib.LOGGER.info(" * " + e.localMatch.getFileHash() + " (Client)"); - BCLib.LOGGER.info(" * local Content " + (contentWrapper.getRawContent() == null)); - } - } - } - - - @Environment(EnvType.CLIENT) - private void processModFileSync(final List filesToRequest, final Set mismatchingMods) { - for (Entry e : modVersion.entrySet()) { - final String localVersion = ModUtil.convertModVersion(ModUtil.convertModVersion(ModUtil.getModVersion(e.getKey()))); - final OfferedModInfo serverInfo = e.getValue(); - - ModInfo nfo = ModUtil.getModInfo(e.getKey()); - final boolean clientOnly = nfo != null && nfo.metadata.getEnvironment() == ModEnvironment.CLIENT; - final boolean requestMod = !clientOnly && !serverInfo.version.equals(localVersion) && serverInfo.size > 0 && serverInfo.canDownload; - - BCLib.LOGGER.info(" - " + e.getKey() + " (client=" + localVersion + ", server=" + serverInfo.version + ", size=" + PathUtil.humanReadableFileSize( - serverInfo.size) + (requestMod ? ", requesting" : "") + (serverInfo.canDownload - ? "" - : ", not offered") + (clientOnly ? ", client only" : "") + ")"); - if (requestMod) { - filesToRequest.add(new AutoSyncID.ForModFileRequest(e.getKey(), serverInfo.version)); - } - if (!serverInfo.version.equals(localVersion)) { - mismatchingMods.add(e.getKey()); - } - } - - mismatchingMods.addAll(ModListScreen.localMissing(modVersion)); - mismatchingMods.addAll(ModListScreen.serverMissing(modVersion)); - } - - @Override - protected boolean isBlocking() { - return true; - } - - @Environment(EnvType.CLIENT) - @Override - protected void runOnClientGameThread(Minecraft client) { - if (!Configs.CLIENT_CONFIG.isAllowingAutoSync()) { - BCLib.LOGGER.info("Auto-Sync was disabled on the client."); - return; - } - final String localBclibVersion = getBCLibVersion(); - BCLib.LOGGER.info("Received Hello from Server. (client=" + localBclibVersion + ", server=" + bclibVersion + ")"); - - if (ModUtil.convertModVersion(localBclibVersion) != ModUtil.convertModVersion(bclibVersion)) { - showBCLibError(client); - return; - } - - final List filesToRequest = new ArrayList<>(2); - final List filesToRemove = new ArrayList<>(2); - final Set mismatchingMods = new HashSet<>(2); - - - processModFileSync(filesToRequest, mismatchingMods); - processSingleFileSync(filesToRequest); - processAutoSyncFolder(filesToRequest, filesToRemove); - - //Handle folder sync - //Both client and server need to know about the folder you want to sync - //Files can only get placed within that folder - - if ((filesToRequest.size() > 0 || filesToRemove.size() > 0) && (Configs.CLIENT_CONFIG.isAcceptingMods() || Configs.CLIENT_CONFIG.isAcceptingConfigs() || Configs.CLIENT_CONFIG.isAcceptingFiles())) { - showSyncFilesScreen(client, filesToRequest, filesToRemove); - return; - } else if (serverPublishedModInfo && mismatchingMods.size() > 0 && Configs.CLIENT_CONFIG.isShowingModInfo()) { - client.setScreen(new ModListScreen( - client.screen, - Component.translatable("title.bclib.modmissmatch"), - Component.translatable("message.bclib.modmissmatch"), - CommonComponents.GUI_PROCEED, - ModUtil.getMods(), - modVersion - )); - return; - } - } - - @Environment(EnvType.CLIENT) - protected void showBCLibError(Minecraft client) { - BCLib.LOGGER.error("BCLib differs on client and server."); - client.setScreen(new WarnBCLibVersionMismatch((download) -> { - if (download) { - requestBCLibDownload(); - - this.onCloseSyncFilesScreen(); - } else { - Minecraft.getInstance() - .setScreen(null); - } - })); - } - - @Environment(EnvType.CLIENT) - protected void showSyncFilesScreen( - Minecraft client, - List files, - final List filesToRemove - ) { - int configFiles = 0; - int singleFiles = 0; - int folderFiles = 0; - int modFiles = 0; - - for (AutoSyncID aid : files) { - if (aid.isConfigFile()) { - configFiles++; - } else if (aid instanceof AutoSyncID.ForModFileRequest) { - modFiles++; - } else if (aid instanceof AutoSyncID.ForDirectFileRequest) { - folderFiles++; - } else { - singleFiles++; - } - } - - client.setScreen(new SyncFilesScreen( - modFiles, - configFiles, - singleFiles, - folderFiles, - filesToRemove.size(), - modVersion, - (downloadMods, downloadConfigs, downloadFiles, removeFiles) -> { - if (downloadMods || downloadConfigs || downloadFiles) { - BCLib.LOGGER.info("Updating local Files:"); - List localChanges = new ArrayList<>( - files.toArray().length); - List requestFiles = new ArrayList<>(files.toArray().length); - - files.forEach(aid -> { - if (aid.isConfigFile() && downloadConfigs) { - processOfferedFile(requestFiles, aid); - } else if (aid instanceof AutoSyncID.ForModFileRequest && downloadMods) { - processOfferedFile(requestFiles, aid); - } else if (downloadFiles) { - processOfferedFile(requestFiles, aid); - } - }); - - requestFileDownloads(requestFiles); - } - if (removeFiles) { - filesToRemove.forEach(aid -> { - BCLib.LOGGER.info(" - " + aid.relFile + " (removing)"); - aid.relFile.delete(); - }); - } - - this.onCloseSyncFilesScreen(); - } - )); - } - - @Environment(EnvType.CLIENT) - private void onCloseSyncFilesScreen() { - Minecraft.getInstance() - .setScreen(ChunkerProgress.getProgressScreen()); - } - - private void processOfferedFile(List requestFiles, AutoSyncID aid) { - if (aid instanceof AutoSyncID.WithContentOverride) { - final AutoSyncID.WithContentOverride aidc = (AutoSyncID.WithContentOverride) aid; - BCLib.LOGGER.info(" - " + aid + " (updating Content)"); - - SendFiles.writeSyncedFile(aid, aidc.contentWrapper.getRawContent(), aidc.localFile); - } else { - requestFiles.add(aid); - BCLib.LOGGER.info(" - " + aid + " (requesting)"); - } - } - - private void requestBCLibDownload() { - BCLib.LOGGER.warning("Starting download of BCLib"); - requestFileDownloads(List.of(new AutoSyncID.ForModFileRequest(BCLib.MOD_ID, bclibVersion))); - } - - @Environment(EnvType.CLIENT) - private void requestFileDownloads(List files) { - BCLib.LOGGER.info("Starting download of Files:" + files.size()); - - final ProgressScreen progress = new ProgressScreen( - null, - Component.translatable("title.bclib.filesync.progress"), - Component.translatable("message.bclib.filesync.progress") - ); - progress.progressStart(Component.translatable("message.bclib.filesync.progress.stage.empty")); - ChunkerProgress.setProgressScreen(progress); - - DataExchangeAPI.send(new RequestFiles(files)); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/HelloServer.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/HelloServer.java deleted file mode 100644 index df1994fa..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/HelloServer.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor; -import org.betterx.bclib.config.Configs; -import org.betterx.worlds.together.util.ModUtil; - -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.entity.player.Player; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; - -import java.io.File; - -/** - * This message is sent once a player enters the world. It initiates a sequence of Messages that will sync files between both - * client and server. - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Description
ServerClient
Player enters World
<--{@link HelloServer}Sends the current BLib-Version installed on the Client
{@link HelloClient}-->Sends the current BClIb-Version, the Version of all Plugins and data for all AutpoSync-Files - * ({@link DataExchangeAPI#addAutoSyncFile(String, File)} on the Server
<--{@link RequestFiles}Request missing or out of sync Files from the Server
{@link SendFiles}-->Send Files from the Server to the Client
- */ -public class HelloServer extends DataHandler.FromClient { - public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor( - new ResourceLocation( - BCLib.MOD_ID, - "hello_server" - ), - HelloServer::new, - true, - false - ); - - protected String bclibVersion = "0.0.0"; - - public HelloServer() { - super(DESCRIPTOR.IDENTIFIER); - } - - @Environment(EnvType.CLIENT) - @Override - protected boolean prepareDataOnClient() { - if (!Configs.CLIENT_CONFIG.isAllowingAutoSync()) { - BCLib.LOGGER.info("Auto-Sync was disabled on the client."); - return false; - } - - return true; - } - - @Environment(EnvType.CLIENT) - @Override - protected void serializeDataOnClient(FriendlyByteBuf buf) { - BCLib.LOGGER.info("Sending hello to server."); - buf.writeInt(ModUtil.convertModVersion(HelloClient.getBCLibVersion())); - } - - @Override - protected void deserializeIncomingDataOnServer(FriendlyByteBuf buf, Player player, PacketSender responseSender) { - bclibVersion = ModUtil.convertModVersion(buf.readInt()); - } - - @Override - protected void runOnServerGameThread(MinecraftServer server, Player player) { - if (!Configs.SERVER_CONFIG.isAllowingAutoSync()) { - BCLib.LOGGER.info("Auto-Sync was disabled on the server."); - return; - } - - String localBclibVersion = HelloClient.getBCLibVersion(); - BCLib.LOGGER.info("Received Hello from Client. (server=" + localBclibVersion + ", client=" + bclibVersion + ")"); - - if (!server.isPublished()) { - BCLib.LOGGER.info("Auto-Sync is disabled for Singleplayer worlds."); - return; - } - - reply(new HelloClient(), server); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/RequestFiles.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/RequestFiles.java deleted file mode 100644 index 35c4ecbe..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/RequestFiles.java +++ /dev/null @@ -1,109 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor; -import org.betterx.bclib.config.Configs; - -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.world.entity.player.Player; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.util.stream.Collectors; - -public class RequestFiles extends DataHandler.FromClient { - public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor( - new ResourceLocation( - BCLib.MOD_ID, - "request_files" - ), - RequestFiles::new, - false, - false - ); - static String currentToken = ""; - - protected List files; - - private RequestFiles() { - this(null); - } - - public RequestFiles(List files) { - super(DESCRIPTOR.IDENTIFIER); - this.files = files; - } - - @Environment(EnvType.CLIENT) - @Override - protected boolean prepareDataOnClient() { - if (!Configs.CLIENT_CONFIG.isAllowingAutoSync()) { - BCLib.LOGGER.info("Auto-Sync was disabled on the client."); - return false; - } - return true; - } - - @Environment(EnvType.CLIENT) - @Override - protected void serializeDataOnClient(FriendlyByteBuf buf) { - newToken(); - writeString(buf, currentToken); - - buf.writeInt(files.size()); - - for (AutoSyncID a : files) { - a.serializeData(buf); - } - } - - String receivedToken = ""; - - @Override - protected void deserializeIncomingDataOnServer(FriendlyByteBuf buf, Player player, PacketSender responseSender) { - receivedToken = readString(buf); - int size = buf.readInt(); - files = new ArrayList<>(size); - - BCLib.LOGGER.info("Client requested " + size + " Files:"); - for (int i = 0; i < size; i++) { - AutoSyncID asid = AutoSyncID.deserializeData(buf); - files.add(asid); - BCLib.LOGGER.info(" - " + asid); - } - - - } - - @Override - protected void runOnServerGameThread(MinecraftServer server, Player player) { - if (!Configs.SERVER_CONFIG.isAllowingAutoSync()) { - BCLib.LOGGER.info("Auto-Sync was disabled on the server."); - return; - } - - List syncEntries = files.stream() - .map(asid -> AutoFileSyncEntry.findMatching(asid)) - .filter(e -> e != null) - .collect(Collectors.toList()); - - reply(new SendFiles(syncEntries, receivedToken), server); - } - - public static void newToken() { - currentToken = UUID.randomUUID() - .toString(); - } - - static { - newToken(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/SendFiles.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/SendFiles.java deleted file mode 100644 index 5d16a6f5..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/SendFiles.java +++ /dev/null @@ -1,225 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.api.v2.dataexchange.DataHandlerDescriptor; -import org.betterx.bclib.client.gui.screens.ConfirmRestartScreen; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.util.Pair; -import org.betterx.bclib.util.Triple; -import org.betterx.worlds.together.util.PathUtil; - -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -public class SendFiles extends DataHandler.FromServer { - public static final DataHandlerDescriptor DESCRIPTOR = new DataHandlerDescriptor( - new ResourceLocation( - BCLib.MOD_ID, - "send_files" - ), - SendFiles::new, - false, - false - ); - - protected List files; - private String token; - - public SendFiles() { - this(null, ""); - } - - public SendFiles(List files, String token) { - super(DESCRIPTOR.IDENTIFIER); - this.files = files; - this.token = token; - } - - @Override - protected boolean prepareDataOnServer() { - if (!Configs.SERVER_CONFIG.isAllowingAutoSync()) { - BCLib.LOGGER.info("Auto-Sync was disabled on the server."); - return false; - } - - return true; - } - - @Override - protected void serializeDataOnServer(FriendlyByteBuf buf) { - List existingFiles = files.stream() - .filter(e -> e != null && e.fileName != null && e.fileName.exists()) - .collect(Collectors.toList()); - /* - //this will try to send a file that was not registered or requested by the client - existingFiles.add(new AutoFileSyncEntry("none", new File("D:\\MinecraftPlugins\\BetterNether\\run\\server.properties"),true,(a, b, content) -> { - System.out.println("Got Content:" + content.length); - return true; - }));*/ - - /*//this will try to send a folder-file that was not registered or requested by the client - existingFiles.add(new AutoFileSyncEntry.ForDirectFileRequest(DataExchange.SYNC_FOLDER.folderID, new File("test.json"), DataExchange.SYNC_FOLDER.mapAbsolute("test.json").toFile()));*/ - - /*//this will try to send a folder-file that was not registered or requested by the client and is outside the base-folder - existingFiles.add(new AutoFileSyncEntry.ForDirectFileRequest(DataExchange.SYNC_FOLDER.folderID, new File("../breakout.json"), DataExchange.SYNC_FOLDER.mapAbsolute("../breakout.json").toFile()));*/ - - - writeString(buf, token); - buf.writeInt(existingFiles.size()); - - BCLib.LOGGER.info("Sending " + existingFiles.size() + " Files to Client:"); - for (AutoFileSyncEntry entry : existingFiles) { - int length = entry.serializeContent(buf); - BCLib.LOGGER.info(" - " + entry + " (" + PathUtil.humanReadableFileSize(length) + ")"); - } - } - - private List> receivedFiles; - - @Environment(EnvType.CLIENT) - @Override - protected void deserializeIncomingDataOnClient(FriendlyByteBuf buf, PacketSender responseSender) { - if (Configs.CLIENT_CONFIG.isAcceptingConfigs() || Configs.CLIENT_CONFIG.isAcceptingFiles() || Configs.CLIENT_CONFIG.isAcceptingMods()) { - token = readString(buf); - if (!token.equals(RequestFiles.currentToken)) { - RequestFiles.newToken(); - BCLib.LOGGER.error("Unrequested File Transfer!"); - receivedFiles = new ArrayList<>(0); - return; - } - RequestFiles.newToken(); - - int size = buf.readInt(); - receivedFiles = new ArrayList<>(size); - BCLib.LOGGER.info("Server sent " + size + " Files:"); - for (int i = 0; i < size; i++) { - Triple p = AutoFileSyncEntry.deserializeContent(buf); - if (p.first != null) { - final String type; - if (p.first.isConfigFile() && Configs.CLIENT_CONFIG.isAcceptingConfigs()) { - receivedFiles.add(p); - type = "Accepted Config "; - } else if (p.first instanceof AutoFileSyncEntry.ForModFileRequest && Configs.CLIENT_CONFIG.isAcceptingMods()) { - receivedFiles.add(p); - type = "Accepted Mod "; - } else if (Configs.CLIENT_CONFIG.isAcceptingFiles()) { - receivedFiles.add(p); - type = "Accepted File "; - } else { - type = "Ignoring "; - } - BCLib.LOGGER.info(" - " + type + p.first + " (" + PathUtil.humanReadableFileSize(p.second.length) + ")"); - } else { - BCLib.LOGGER.error(" - Failed to receive File " + p.third + ", possibly sent from a Mod that is not installed on the client."); - } - } - } - } - - @Environment(EnvType.CLIENT) - @Override - protected void runOnClientGameThread(Minecraft client) { - if (Configs.CLIENT_CONFIG.isAcceptingConfigs() || Configs.CLIENT_CONFIG.isAcceptingFiles() || Configs.CLIENT_CONFIG.isAcceptingMods()) { - BCLib.LOGGER.info("Writing Files:"); - - for (Pair entry : receivedFiles) { - final AutoFileSyncEntry e = entry.first; - final byte[] data = entry.second; - - writeSyncedFile(e, data, e.fileName); - } - - showConfirmRestart(client); - } - } - - - @Environment(EnvType.CLIENT) - static void writeSyncedFile(AutoSyncID e, byte[] data, File fileName) { - if (fileName != null && !PathUtil.isChildOf(PathUtil.GAME_FOLDER, fileName.toPath())) { - BCLib.LOGGER.error(fileName + " is not within game folder " + PathUtil.GAME_FOLDER); - return; - } - - if (!PathUtil.MOD_BAK_FOLDER.toFile().exists()) { - PathUtil.MOD_BAK_FOLDER.toFile().mkdirs(); - } - - Path path = fileName != null ? fileName.toPath() : null; - Path removeAfter = null; - if (e instanceof AutoFileSyncEntry.ForModFileRequest mase) { - removeAfter = path; - int count = 0; - final String prefix = "_bclib_synced_"; - String name = prefix + mase.modID + "_" + mase.version.replace(".", "_") + ".jar"; - do { - if (path != null) { - //move to the same directory as the existing Mod - path = path.getParent() - .resolve(name); - } else { - //move to the default mode location - path = PathUtil.MOD_FOLDER.resolve(name); - } - count++; - name = prefix + mase.modID + "_" + mase.version.replace(".", "_") + "__" + String.format( - "%03d", - count - ) + ".jar"; - } while (path.toFile().exists()); - } - - BCLib.LOGGER.info(" - Writing " + path + " (" + PathUtil.humanReadableFileSize(data.length) + ")"); - try { - final File parentFile = path.getParent() - .toFile(); - if (!parentFile.exists()) { - parentFile.mkdirs(); - } - Files.write(path, data); - if (removeAfter != null) { - final String bakFileName = removeAfter.toFile().getName(); - String collisionFreeName = bakFileName; - Path targetPath; - int count = 0; - do { - targetPath = PathUtil.MOD_BAK_FOLDER.resolve(collisionFreeName); - count++; - collisionFreeName = String.format("%03d", count) + "_" + bakFileName; - } while (targetPath.toFile().exists()); - - BCLib.LOGGER.info(" - Moving " + removeAfter + " to " + targetPath); - removeAfter.toFile().renameTo(targetPath.toFile()); - } - AutoSync.didReceiveFile(e, fileName); - - - } catch (IOException ioException) { - BCLib.LOGGER.error(" --> Writing " + fileName + " failed: " + ioException); - } - } - - @Environment(EnvType.CLIENT) - protected void showConfirmRestart(Minecraft client) { - client.setScreen(new ConfirmRestartScreen(() -> { - Minecraft.getInstance() - .setScreen(null); - client.stop(); - })); - - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/SyncFolderDescriptor.java b/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/SyncFolderDescriptor.java deleted file mode 100644 index b214047b..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/dataexchange/handler/autosync/SyncFolderDescriptor.java +++ /dev/null @@ -1,218 +0,0 @@ -package org.betterx.bclib.api.v2.dataexchange.handler.autosync; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataHandler; -import org.betterx.bclib.api.v2.dataexchange.FileHash; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID.ForDirectFileRequest; -import org.betterx.bclib.config.Configs; -import org.betterx.worlds.together.util.PathUtil; - -import net.minecraft.network.FriendlyByteBuf; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; -import org.jetbrains.annotations.NotNull; - -public class SyncFolderDescriptor { - static class SubFile { - public final String relPath; - public final FileHash hash; - - - SubFile(String relPath, FileHash hash) { - this.relPath = relPath; - this.hash = hash; - } - - @Override - public String toString() { - return relPath; - } - - public void serialize(FriendlyByteBuf buf) { - DataHandler.writeString(buf, relPath); - hash.serialize(buf); - } - - public static SubFile deserialize(FriendlyByteBuf buf) { - final String relPath = DataHandler.readString(buf); - FileHash hash = FileHash.deserialize(buf); - return new SubFile(relPath, hash); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o instanceof String) return relPath.equals(o); - if (!(o instanceof SubFile)) return false; - SubFile subFile = (SubFile) o; - return relPath.equals(subFile.relPath); - } - - @Override - public int hashCode() { - return relPath.hashCode(); - } - } - - @NotNull - public final String folderID; - public final boolean removeAdditionalFiles; - @NotNull - public final Path localFolder; - - private List fileCache; - - public SyncFolderDescriptor(String folderID, Path localFolder, boolean removeAdditionalFiles) { - this.removeAdditionalFiles = removeAdditionalFiles; - this.folderID = folderID; - this.localFolder = localFolder; - fileCache = null; - } - - @Override - public String toString() { - return "SyncFolderDescriptor{" + "folderID='" + folderID + '\'' + ", removeAdditionalFiles=" + removeAdditionalFiles + ", localFolder=" + localFolder + ", files=" + ( - fileCache == null - ? "?" - : fileCache.size()) + "}"; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o instanceof String) { - return folderID.equals(o); - } - if (o instanceof ForDirectFileRequest) { - return folderID.equals(((ForDirectFileRequest) o).uniqueID); - } - if (!(o instanceof SyncFolderDescriptor)) return false; - SyncFolderDescriptor that = (SyncFolderDescriptor) o; - return folderID.equals(that.folderID); - } - - @Override - public int hashCode() { - return folderID.hashCode(); - } - - public int fileCount() { - return fileCache == null ? 0 : fileCache.size(); - } - - public void invalidateCache() { - fileCache = null; - } - - public void loadCache() { - if (fileCache == null) { - fileCache = new ArrayList<>(8); - PathUtil.fileWalker(localFolder.toFile(), p -> fileCache.add(new SubFile( - localFolder.relativize(p) - .toString(), - FileHash.create(p.toFile()) - ))); - - /*//this tests if we can trick the system to load files that are not beneath the base-folder - if (!BCLib.isClient()) { - fileCache.add(new SubFile("../breakout.json", FileHash.create(mapAbsolute("../breakout.json").toFile()))); - }*/ - } - } - - public void serialize(FriendlyByteBuf buf) { - final boolean debugHashes = Configs.CLIENT_CONFIG.getBoolean(AutoSync.SYNC_CATEGORY, "debugHashes", false); - loadCache(); - - DataHandler.writeString(buf, folderID); - buf.writeBoolean(removeAdditionalFiles); - buf.writeInt(fileCache.size()); - fileCache.forEach(fl -> { - BCLib.LOGGER.info(" - " + fl.relPath); - if (debugHashes) { - BCLib.LOGGER.info(" " + fl.hash); - } - fl.serialize(buf); - }); - } - - public static SyncFolderDescriptor deserialize(FriendlyByteBuf buf) { - final String folderID = DataHandler.readString(buf); - final boolean remAddFiles = buf.readBoolean(); - final int count = buf.readInt(); - SyncFolderDescriptor localDescriptor = AutoSync.getSyncFolderDescriptor(folderID); - - final SyncFolderDescriptor desc; - if (localDescriptor != null) { - desc = new SyncFolderDescriptor( - folderID, - localDescriptor.localFolder, - localDescriptor.removeAdditionalFiles && remAddFiles - ); - desc.fileCache = new ArrayList<>(count); - } else { - BCLib.LOGGER.warning(BCLib.isClient() - ? "Client" - : "Server" + " does not know Sync-Folder ID '" + folderID + "'"); - desc = null; - } - - for (int i = 0; i < count; i++) { - SubFile relPath = SubFile.deserialize(buf); - if (desc != null) desc.fileCache.add(relPath); - } - - return desc; - } - - //Note: make sure loadCache was called before using this - boolean hasRelativeFile(String relFile) { - return fileCache.stream() - .filter(sf -> sf.equals(relFile)) - .findFirst() - .isPresent(); - } - - //Note: make sure loadCache was called before using this - boolean hasRelativeFile(SubFile subFile) { - return hasRelativeFile(subFile.relPath); - } - - //Note: make sure loadCache was called before using this - SubFile getLocalSubFile(String relPath) { - return fileCache.stream() - .filter(sf -> sf.relPath.equals(relPath)) - .findFirst() - .orElse(null); - } - - Stream relativeFilesStream() { - loadCache(); - return fileCache.stream(); - } - - public Path mapAbsolute(String relPath) { - return this.localFolder.resolve(relPath) - .normalize(); - } - - public Path mapAbsolute(SubFile subFile) { - return this.localFolder.resolve(subFile.relPath) - .normalize(); - } - - public boolean acceptChildElements(Path absPath) { - return PathUtil.isChildOf(this.localFolder, absPath); - } - - public boolean acceptChildElements(SubFile subFile) { - return acceptChildElements(mapAbsolute(subFile)); - } - - public boolean discardChildElements(SubFile subFile) { - return !acceptChildElements(subFile); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/datafixer/DataFixerAPI.java b/src/main/java/org/betterx/bclib/api/v2/datafixer/DataFixerAPI.java deleted file mode 100644 index 07a9cf20..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/datafixer/DataFixerAPI.java +++ /dev/null @@ -1,598 +0,0 @@ -package org.betterx.bclib.api.v2.datafixer; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.client.gui.screens.AtomicProgressListener; -import org.betterx.bclib.client.gui.screens.ConfirmFixScreen; -import org.betterx.bclib.client.gui.screens.LevelFixErrorScreen; -import org.betterx.bclib.client.gui.screens.LevelFixErrorScreen.Listener; -import org.betterx.bclib.client.gui.screens.ProgressScreen; -import org.betterx.bclib.config.Configs; -import org.betterx.worlds.together.util.Logger; -import org.betterx.worlds.together.world.WorldConfig; - -import net.minecraft.Util; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.toasts.SystemToast; -import net.minecraft.client.gui.screens.worldselection.EditWorldScreen; -import net.minecraft.nbt.*; -import net.minecraft.network.chat.Component; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.chunk.storage.RegionFile; -import net.minecraft.world.level.storage.LevelResource; -import net.minecraft.world.level.storage.LevelStorageSource; -import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.io.*; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.zip.ZipException; -import org.jetbrains.annotations.NotNull; - -/** - * API to manage Patches that need to get applied to a world - */ -public class DataFixerAPI { - static final Logger LOGGER = new Logger("DataFixerAPI"); - - static class State { - public boolean didFail = false; - protected ArrayList errors = new ArrayList<>(); - - public void addError(String s) { - errors.add(s); - } - - public boolean hasError() { - return errors.size() > 0; - } - - public String getErrorMessage() { - return errors.stream().reduce("", (a, b) -> a + " - " + b + "\n"); - } - - public String[] getErrorMessages() { - String[] res = new String[errors.size()]; - return errors.toArray(res); - } - } - - @FunctionalInterface - public interface Callback { - void call(); - } - - private static boolean wrapCall( - LevelStorageSource levelSource, - String levelID, - Function runWithLevel - ) { - LevelStorageSource.LevelStorageAccess levelStorageAccess; - try { - levelStorageAccess = levelSource.createAccess(levelID); - } catch (IOException e) { - BCLib.LOGGER.warning("Failed to read level {} data", levelID, e); - SystemToast.onWorldAccessFailure(Minecraft.getInstance(), levelID); - Minecraft.getInstance().setScreen(null); - return true; - } - - boolean returnValue = runWithLevel.apply(levelStorageAccess); - - try { - levelStorageAccess.close(); - } catch (IOException e) { - BCLib.LOGGER.warning("Failed to unlock access to level {}", levelID, e); - } - - return returnValue; - } - - /** - * Will apply necessary Patches to the world. - * - * @param levelSource The SourceStorage for this Minecraft instance, You can get this using - * {@code Minecraft.getInstance().getLevelSource()} - * @param levelID The ID of the Level you want to patch - * @param showUI {@code true}, if you want to present the user with a Screen that offers to backup the world - * before applying the patches - * @param onResume When this method retursn {@code true}, this function will be called when the world is ready - * @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and - * patches were enabled in the config and the Guardian did find any patches that need to be applied to the world. - */ - public static boolean fixData( - LevelStorageSource levelSource, - String levelID, - boolean showUI, - Consumer onResume - ) { - return wrapCall(levelSource, levelID, (levelStorageAccess) -> fixData(levelStorageAccess, showUI, onResume)); - } - - /** - * Will apply necessary Patches to the world. - * - * @param levelStorageAccess The access class of the level you want to patch - * @param showUI {@code true}, if you want to present the user with a Screen that offers to backup the world - * before applying the patches - * @param onResume When this method retursn {@code true}, this function will be called when the world is ready - * @return {@code true} if the UI was displayed. The UI is only displayed if {@code showUI} was {@code true} and - * patches were enabled in the config and the Guardian did find any patches that need to be applied to the world. - */ - public static boolean fixData( - LevelStorageSource.LevelStorageAccess levelStorageAccess, - boolean showUI, - Consumer onResume - ) { - File levelPath = levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile(); - return fixData(levelPath, levelStorageAccess.getLevelId(), showUI, onResume); - } - - /** - * Creates the patch level file for new worlds - */ - public static void initializePatchData() { - getMigrationProfile().markApplied(); - WorldConfig.saveFile(BCLib.MOD_ID); - } - - - @Environment(EnvType.CLIENT) - private static AtomicProgressListener showProgressScreen() { - ProgressScreen ps = new ProgressScreen( - Minecraft.getInstance().screen, - Component.translatable("title.bclib.datafixer.progress"), - Component.translatable("message.bclib.datafixer.progress") - ); - Minecraft.getInstance().setScreen(ps); - return ps; - } - - private static boolean fixData(File dir, String levelID, boolean showUI, Consumer onResume) { - MigrationProfile profile = loadProfileIfNeeded(dir); - - BiConsumer runFixes = (createBackup, applyFixes) -> { - final AtomicProgressListener progress; - if (applyFixes) { - if (showUI) { - progress = showProgressScreen(); - } else { - progress = new AtomicProgressListener() { - private long timeStamp = Util.getMillis(); - private AtomicInteger counter = new AtomicInteger(0); - - @Override - public void incAtomic(int maxProgress) { - int percentage = (100 * counter.incrementAndGet()) / maxProgress; - if (Util.getMillis() - this.timeStamp >= 1000L) { - this.timeStamp = Util.getMillis(); - BCLib.LOGGER.info("Patching... {}%", percentage); - } - } - - @Override - public void resetAtomic() { - counter = new AtomicInteger(0); - } - - public void stop() { - } - - public void progressStage(Component component) { - BCLib.LOGGER.info("Patcher Stage... {}%", component.getString()); - } - }; - } - } else { - progress = null; - } - - Supplier runner = () -> { - if (createBackup) { - progress.progressStage(Component.translatable("message.bclib.datafixer.progress.waitbackup")); - EditWorldScreen.makeBackupAndShowToast(Minecraft.getInstance().getLevelSource(), levelID); - } - - if (applyFixes) { - return runDataFixes(dir, profile, progress); - } - - return new State(); - }; - - if (showUI) { - Thread fixerThread = new Thread(() -> { - final State state = runner.get(); - - Minecraft.getInstance() - .execute(() -> { - if (profile != null && showUI) { - //something went wrong, show the user our error - if (state.didFail || state.hasError()) { - showLevelFixErrorScreen(state, (markFixed) -> { - if (markFixed) { - profile.markApplied(); - } - onResume.accept(applyFixes); - }); - } else { - onResume.accept(applyFixes); - } - } - }); - - }); - fixerThread.start(); - } else { - State state = runner.get(); - if (state.hasError()) { - LOGGER.error("There were Errors while fixing the Level:"); - LOGGER.error(state.getErrorMessage()); - } - } - }; - - //we have some migrations - if (profile != null) { - //display the confirm UI. - if (showUI) { - showBackupWarning(levelID, runFixes); - return true; - } else { - BCLib.LOGGER.warning("Applying Fixes on Level"); - runFixes.accept(false, true); - } - } - return false; - } - - @Environment(EnvType.CLIENT) - private static void showLevelFixErrorScreen(State state, Listener onContinue) { - Minecraft.getInstance() - .setScreen(new LevelFixErrorScreen( - Minecraft.getInstance().screen, - state.getErrorMessages(), - onContinue - )); - } - - private static MigrationProfile loadProfileIfNeeded(File levelBaseDir) { - if (!Configs.MAIN_CONFIG.applyPatches()) { - LOGGER.info("World Patches are disabled"); - return null; - } - - MigrationProfile profile = getMigrationProfile(); - profile.runPrePatches(levelBaseDir); - - if (!profile.hasAnyFixes()) { - LOGGER.info("Everything up to date"); - return null; - } - - return profile; - } - - @NotNull - private static MigrationProfile getMigrationProfile() { - final CompoundTag patchConfig = WorldConfig.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY); - MigrationProfile profile = Patch.createMigrationData(patchConfig); - return profile; - } - - @Environment(EnvType.CLIENT) - static void showBackupWarning(String levelID, BiConsumer whenFinished) { - Minecraft.getInstance().setScreen(new ConfirmFixScreen(null, whenFinished::accept)); - } - - private static State runDataFixes(File dir, MigrationProfile profile, AtomicProgressListener progress) { - State state = new State(); - progress.resetAtomic(); - - progress.progressStage(Component.translatable("message.bclib.datafixer.progress.reading")); - List players = getAllPlayers(dir); - List regions = getAllRegions(dir, null); - final int maxProgress = players.size() + regions.size() + 4; - progress.incAtomic(maxProgress); - - progress.progressStage(Component.translatable("message.bclib.datafixer.progress.players")); - players.parallelStream().forEach((file) -> { - fixPlayer(profile, state, file); - progress.incAtomic(maxProgress); - }); - - progress.progressStage(Component.translatable("message.bclib.datafixer.progress.level")); - fixLevel(profile, state, dir); - progress.incAtomic(maxProgress); - - progress.progressStage(Component.translatable("message.bclib.datafixer.progress.worlddata")); - try { - profile.patchWorldData(); - } catch (PatchDidiFailException e) { - state.didFail = true; - state.addError("Failed fixing worldconfig (" + e.getMessage() + ")"); - BCLib.LOGGER.error(e.getMessage()); - } - progress.incAtomic(maxProgress); - - progress.progressStage(Component.translatable("message.bclib.datafixer.progress.regions")); - regions.parallelStream().forEach((file) -> { - fixRegion(profile, state, file); - progress.incAtomic(maxProgress); - }); - - if (!state.didFail) { - progress.progressStage(Component.translatable("message.bclib.datafixer.progress.saving")); - profile.markApplied(); - WorldConfig.saveFile(BCLib.MOD_ID); - } - progress.incAtomic(maxProgress); - - progress.stop(); - - return state; - } - - private static void fixLevel(MigrationProfile profile, State state, File levelBaseDir) { - try { - LOGGER.info("Inspecting level.dat in " + levelBaseDir); - - //load the level (could already contain patches applied by patchLevelDat) - CompoundTag level = profile.getLevelDat(levelBaseDir); - boolean[] changed = {profile.isLevelDatChanged()}; - - if (profile.getPrePatchException() != null) { - throw profile.getPrePatchException(); - } - - if (level.contains("Data")) { - CompoundTag dataTag = (CompoundTag) level.get("Data"); - if (dataTag.contains("Player")) { - CompoundTag player = (CompoundTag) dataTag.get("Player"); - fixPlayerNbt(player, changed, profile); - } - } - - if (changed[0]) { - LOGGER.warning("Writing '{}'", profile.getLevelDatFile()); - NbtIo.writeCompressed(level, profile.getLevelDatFile()); - } - } catch (Exception e) { - BCLib.LOGGER.error("Failed fixing Level-Data."); - state.addError("Failed fixing Level-Data in level.dat (" + e.getMessage() + ")"); - state.didFail = true; - e.printStackTrace(); - } - } - - private static void fixPlayer(MigrationProfile data, State state, File file) { - try { - LOGGER.info("Inspecting " + file); - - CompoundTag player = readNbt(file); - boolean[] changed = {false}; - fixPlayerNbt(player, changed, data); - - if (changed[0]) { - LOGGER.warning("Writing '{}'", file); - NbtIo.writeCompressed(player, file); - } - } catch (Exception e) { - BCLib.LOGGER.error("Failed fixing Player-Data."); - state.addError("Failed fixing Player-Data in " + file.getName() + " (" + e.getMessage() + ")"); - state.didFail = true; - e.printStackTrace(); - } - } - - private static void fixPlayerNbt(CompoundTag player, boolean[] changed, MigrationProfile data) { - //Checking Inventory - ListTag inventory = player.getList("Inventory", Tag.TAG_COMPOUND); - fixItemArrayWithID(inventory, changed, data, true); - - //Checking EnderChest - ListTag enderitems = player.getList("EnderItems", Tag.TAG_COMPOUND); - fixItemArrayWithID(enderitems, changed, data, true); - - //Checking ReceipBook - if (player.contains("recipeBook")) { - CompoundTag recipeBook = player.getCompound("recipeBook"); - changed[0] |= fixStringIDList(recipeBook, "recipes", data); - changed[0] |= fixStringIDList(recipeBook, "toBeDisplayed", data); - } - } - - static boolean fixStringIDList(CompoundTag root, String name, MigrationProfile data) { - boolean _changed = false; - if (root.contains(name)) { - ListTag items = root.getList(name, Tag.TAG_STRING); - ListTag newItems = new ListTag(); - - for (Tag tag : items) { - final StringTag str = (StringTag) tag; - final String replace = data.replaceStringFromIDs(str.getAsString()); - if (replace != null) { - _changed = true; - newItems.add(StringTag.valueOf(replace)); - } else { - newItems.add(tag); - } - } - if (_changed) { - root.put(name, newItems); - } - } - return _changed; - } - - private static void fixRegion(MigrationProfile data, State state, File file) { - try { - Path path = file.toPath(); - LOGGER.info("Inspecting " + path); - boolean[] changed = new boolean[1]; - RegionFile region = new RegionFile(path, path.getParent(), true); - - for (int x = 0; x < 32; x++) { - for (int z = 0; z < 32; z++) { - ChunkPos pos = new ChunkPos(x, z); - changed[0] = false; - if (region.hasChunk(pos) && !state.didFail) { - DataInputStream input = region.getChunkDataInputStream(pos); - CompoundTag root = NbtIo.read(input); - // if ((root.toString().contains("betternether:chest") || root.toString().contains("bclib:chest"))) { - // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + ".nbt")); - // } - input.close(); - - //Checking TileEntities - ListTag tileEntities = root.getCompound("Level") - .getList("TileEntities", Tag.TAG_COMPOUND); - fixItemArrayWithID(tileEntities, changed, data, true); - - //Checking Entities - ListTag entities = root.getList("Entities", Tag.TAG_COMPOUND); - fixItemArrayWithID(entities, changed, data, true); - - //Checking Block Palette - ListTag sections = root.getCompound("Level") - .getList("Sections", Tag.TAG_COMPOUND); - sections.forEach((tag) -> { - ListTag palette = ((CompoundTag) tag).getList("Palette", Tag.TAG_COMPOUND); - palette.forEach((blockTag) -> { - CompoundTag blockTagCompound = ((CompoundTag) blockTag); - changed[0] |= data.replaceStringFromIDs(blockTagCompound, "Name"); - }); - - try { - changed[0] |= data.patchBlockState( - palette, - ((CompoundTag) tag).getList( - "BlockStates", - Tag.TAG_LONG - ) - ); - } catch (PatchDidiFailException e) { - BCLib.LOGGER.error("Failed fixing BlockState in " + pos); - state.addError("Failed fixing BlockState in " + pos + " (" + e.getMessage() + ")"); - state.didFail = true; - changed[0] = false; - e.printStackTrace(); - } - }); - - if (changed[0]) { - LOGGER.warning("Writing '{}': {}/{}", file, x, z); - // NbtIo.write(root, new File(file.toString() + "-" + x + "-" + z + "-changed.nbt")); - DataOutputStream output = region.getChunkDataOutputStream(pos); - NbtIo.write(root, output); - output.close(); - } - } - } - } - region.close(); - } catch (Exception e) { - BCLib.LOGGER.error("Failed fixing Region."); - state.addError("Failed fixing Region in " + file.getName() + " (" + e.getMessage() + ")"); - state.didFail = true; - e.printStackTrace(); - } - } - - static CompoundTag patchConfTag = null; - - static CompoundTag getPatchData() { - if (patchConfTag == null) { - patchConfTag = WorldConfig.getCompoundTag(BCLib.MOD_ID, Configs.MAIN_PATCH_CATEGORY); - } - return patchConfTag; - } - - static void fixItemArrayWithID(ListTag items, boolean[] changed, MigrationProfile data, boolean recursive) { - items.forEach(inTag -> { - fixID((CompoundTag) inTag, changed, data, recursive); - }); - } - - - static void fixID(CompoundTag inTag, boolean[] changed, MigrationProfile data, boolean recursive) { - final CompoundTag tag = inTag; - - changed[0] |= data.replaceStringFromIDs(tag, "id"); - if (tag.contains("Item")) { - CompoundTag item = (CompoundTag) tag.get("Item"); - fixID(item, changed, data, recursive); - } - - if (recursive && tag.contains("Items")) { - fixItemArrayWithID(tag.getList("Items", Tag.TAG_COMPOUND), changed, data, true); - } - if (recursive && tag.contains("Inventory")) { - ListTag inventory = tag.getList("Inventory", Tag.TAG_COMPOUND); - fixItemArrayWithID(inventory, changed, data, true); - } - if (tag.contains("tag")) { - CompoundTag entityTag = (CompoundTag) tag.get("tag"); - if (entityTag.contains("BlockEntityTag")) { - CompoundTag blockEntityTag = (CompoundTag) entityTag.get("BlockEntityTag"); - fixID(blockEntityTag, changed, data, recursive); - /*ListTag items = blockEntityTag.getList("Items", Tag.TAG_COMPOUND); - fixItemArrayWithID(items, changed, data, recursive);*/ - } - } - } - - private static List getAllPlayers(File dir) { - List list = new ArrayList<>(); - dir = new File(dir, "playerdata"); - if (!dir.exists() || !dir.isDirectory()) { - return list; - } - for (File file : dir.listFiles()) { - if (file.isFile() && file.getName().endsWith(".dat")) { - list.add(file); - } - } - return list; - } - - private static List getAllRegions(File dir, List list) { - if (list == null) { - list = new ArrayList<>(); - } - for (File file : dir.listFiles()) { - if (file.isDirectory()) { - getAllRegions(file, list); - } else if (file.isFile() && file.getName().endsWith(".mca")) { - list.add(file); - } - } - return list; - } - - /** - * register a new Patch - * - * @param patch A #Supplier that will instantiate the new Patch Object - */ - public static void registerPatch(Supplier patch) { - Patch.getALL().add(patch.get()); - } - - private static CompoundTag readNbt(File file) throws IOException { - try { - return NbtIo.readCompressed(file); - } catch (ZipException | EOFException e) { - return NbtIo.read(file); - } - } - -} diff --git a/src/main/java/org/betterx/bclib/api/v2/datafixer/ForcedLevelPatch.java b/src/main/java/org/betterx/bclib/api/v2/datafixer/ForcedLevelPatch.java deleted file mode 100644 index 0d18a7e0..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/datafixer/ForcedLevelPatch.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.betterx.bclib.api.v2.datafixer; - -import org.betterx.bclib.interfaces.PatchBiFunction; -import org.betterx.bclib.interfaces.PatchFunction; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.jetbrains.annotations.NotNull; - - -/** - * A Patch for level.dat that is always executed no matter what Patchlevel is set in a world. - */ -public abstract class ForcedLevelPatch extends Patch { - protected ForcedLevelPatch(@NotNull String modID, String version) { - super(modID, version, true); - } - - @Override - public final Map getIDReplacements() { - return new HashMap(); - } - - @Override - public final PatchFunction getWorldDataPatcher() { - return null; - } - - @Override - public final PatchBiFunction getBlockStatePatcher() { - return null; - } - - @Override - public final List getWorldDataIDPaths() { - return null; - } - - @Override - public PatchFunction getLevelDatPatcher() { - return this::runLevelDatPatch; - } - - /** - * Called with the contents of level.dat in {@code root} - * - * @param root The contents of level.dat - * @param profile The active migration profile - * @return true, if the run did change the contents of root - */ - abstract protected Boolean runLevelDatPatch(CompoundTag root, MigrationProfile profile); -} - diff --git a/src/main/java/org/betterx/bclib/api/v2/datafixer/MigrationProfile.java b/src/main/java/org/betterx/bclib/api/v2/datafixer/MigrationProfile.java deleted file mode 100644 index 931773ca..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/datafixer/MigrationProfile.java +++ /dev/null @@ -1,374 +0,0 @@ -package org.betterx.bclib.api.v2.datafixer; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.interfaces.PatchBiFunction; -import org.betterx.bclib.interfaces.PatchFunction; -import org.betterx.worlds.together.util.ModUtil; -import org.betterx.worlds.together.world.WorldConfig; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.nbt.Tag; - -import java.io.File; -import java.io.IOException; -import java.util.*; -import java.util.stream.Collectors; -import org.jetbrains.annotations.NotNull; - -public class MigrationProfile { - final Set mods; - final Map idReplacements; - final List> levelPatchers; - final List> statePatchers; - final List worldDataPatchers; - final Map> worldDataIDPaths; - - private final CompoundTag config; - private CompoundTag level; - private File levelBaseDir; - private boolean prePatchChangedLevelDat; - private boolean didRunPrePatch; - private Exception prePatchException; - - MigrationProfile(CompoundTag config, boolean applyAll) { - this.config = config; - - this.mods = Collections.unmodifiableSet(Patch.getALL() - .stream() - .map(p -> p.modID) - .collect(Collectors.toSet())); - - HashMap replacements = new HashMap(); - List> levelPatches = new LinkedList<>(); - List worldDataPatches = new LinkedList<>(); - List> statePatches = new LinkedList<>(); - HashMap> worldDataIDPaths = new HashMap<>(); - for (String modID : mods) { - - Patch.getALL() - .stream() - .filter(p -> p.modID.equals(modID)) - .forEach(patch -> { - List paths = patch.getWorldDataIDPaths(); - if (paths != null) worldDataIDPaths.put(modID, paths); - - if (applyAll || currentPatchLevel(modID) < patch.level || patch.alwaysApply) { - replacements.putAll(patch.getIDReplacements()); - if (patch.getLevelDatPatcher() != null) - levelPatches.add(patch.getLevelDatPatcher()); - if (patch.getWorldDataPatcher() != null) - worldDataPatches.add(patch); - if (patch.getBlockStatePatcher() != null) - statePatches.add(patch.getBlockStatePatcher()); - DataFixerAPI.LOGGER.info("Applying " + patch); - } else { - DataFixerAPI.LOGGER.info("Ignoring " + patch); - } - }); - } - - this.worldDataIDPaths = Collections.unmodifiableMap(worldDataIDPaths); - this.idReplacements = Collections.unmodifiableMap(replacements); - this.levelPatchers = Collections.unmodifiableList(levelPatches); - this.worldDataPatchers = Collections.unmodifiableList(worldDataPatches); - this.statePatchers = Collections.unmodifiableList(statePatches); - } - - /** - * This method is supposed to be used by developers to apply id-patches to custom nbt structures. It is only - * available in Developer-Mode - */ - public static void fixCustomFolder(File dir) { - if (!BCLib.isDevEnvironment()) return; - MigrationProfile profile = Patch.createMigrationData(); - List nbts = getAllNbts(dir, null); - nbts.parallelStream().forEach((file) -> { - DataFixerAPI.LOGGER.info("Loading NBT " + file); - try { - CompoundTag root = NbtIo.readCompressed(file); - boolean[] changed = {false}; - int spawnerIdx = -1; - if (root.contains("palette")) { - ListTag items = root.getList("palette", Tag.TAG_COMPOUND); - for (int idx = 0; idx < items.size(); idx++) { - final CompoundTag tag = (CompoundTag) items.get(idx); - if (tag.contains("Name") && tag.getString("Name").equals("minecraft:spawner")) - spawnerIdx = idx; - if (tag.contains("Name") && (tag.getString("Name").equals("minecraft:") || tag.getString("Name") - .equals(""))) { - System.out.println("Empty Name"); - } - if (tag.contains("id") && (tag.getString("id").equals("minecraft:") || tag.getString("id") - .equals(""))) { - System.out.println("Empty ID"); - } - changed[0] |= profile.replaceStringFromIDs(tag, "Name"); - } - } - - if (spawnerIdx >= 0 && root.contains("blocks")) { - ListTag items = root.getList("blocks", Tag.TAG_COMPOUND); - for (int idx = 0; idx < items.size(); idx++) { - final CompoundTag blockTag = (CompoundTag) items.get(idx); - if (blockTag.contains("state") && blockTag.getInt("state") == spawnerIdx && blockTag.contains( - "nbt")) { - CompoundTag nbt = blockTag.getCompound("nbt"); - if (nbt.contains("SpawnData")) { - final CompoundTag entity = nbt.getCompound("SpawnData"); - if (!entity.contains("entity")) { - CompoundTag data = new CompoundTag(); - data.put("entity", entity); - nbt.put("SpawnData", data); - - changed[0] = true; - } - } - if (nbt.contains("SpawnPotentials")) { - ListTag pots = nbt.getList("SpawnPotentials", Tag.TAG_COMPOUND); - for (Tag potItemIn : pots) { - final CompoundTag potItem = (CompoundTag) potItemIn; - if (potItem.contains("Weight")) { - int weight = potItem.getInt("Weight"); - potItem.putInt("weight", weight); - potItem.remove("Weight"); - - changed[0] = true; - } - - if (potItem.contains("Entity")) { - CompoundTag entity = potItem.getCompound("Entity"); - CompoundTag data = new CompoundTag(); - data.put("entity", entity); - - potItem.put("data", data); - potItem.remove("Entity"); - - changed[0] = true; - } - } - } - } - } - } - - if (changed[0]) { - DataFixerAPI.LOGGER.info("Writing NBT " + file); - NbtIo.writeCompressed(root, file); - } - } catch (IOException e) { - e.printStackTrace(); - } - }); - } - - private static List getAllNbts(File dir, List list) { - if (list == null) { - list = new ArrayList<>(); - } - for (File file : dir.listFiles()) { - if (file.isDirectory()) { - getAllNbts(file, list); - } else if (file.isFile() && file.getName().endsWith(".nbt")) { - list.add(file); - } - } - return list; - } - - final public CompoundTag getLevelDat(File levelBaseDir) { - if (level == null || this.levelBaseDir == null || !this.levelBaseDir.equals(levelBaseDir)) { - runPrePatches(levelBaseDir); - } - return level; - } - - final public boolean isLevelDatChanged() { - return prePatchChangedLevelDat; - } - - final public File getLevelDatFile() { - return new File(levelBaseDir, "level.dat"); - } - - final public Exception getPrePatchException() { - return prePatchException; - } - - - final public void runPrePatches(File levelBaseDir) { - if (didRunPrePatch) { - BCLib.LOGGER.warning("Already did run PrePatches for " + this.levelBaseDir + "."); - } - BCLib.LOGGER.info("Running Pre Patchers on " + levelBaseDir); - - this.levelBaseDir = levelBaseDir; - this.level = null; - this.prePatchException = null; - didRunPrePatch = true; - - this.prePatchChangedLevelDat = runPreLevelPatches(getLevelDatFile()); - } - - private boolean runPreLevelPatches(File levelDat) { - try { - level = NbtIo.readCompressed(levelDat); - - boolean changed = patchLevelDat(level); - return changed; - } catch (IOException | PatchDidiFailException e) { - prePatchException = e; - return false; - } - } - - final public void markApplied() { - for (String modID : mods) { - DataFixerAPI.LOGGER.info( - "Updating Patch-Level for '{}' from {} to {}", - modID, - ModUtil.convertModVersion(currentPatchLevel(modID)), - ModUtil.convertModVersion(Patch.maxPatchLevel(modID)) - ); - if (config != null) - config.putString(modID, Patch.maxPatchVersion(modID)); - } - } - - public String currentPatchVersion(@NotNull String modID) { - if (config == null || !config.contains(modID)) return "0.0.0"; - return config.getString(modID); - } - - public int currentPatchLevel(@NotNull String modID) { - return ModUtil.convertModVersion(currentPatchVersion(modID)); - } - - public boolean hasAnyFixes() { - boolean hasLevelDatPatches; - if (didRunPrePatch != false) { - hasLevelDatPatches = prePatchChangedLevelDat; - } else { - hasLevelDatPatches = levelPatchers.size() > 0; - } - - return idReplacements.size() > 0 || hasLevelDatPatches || worldDataPatchers.size() > 0; - } - - public String replaceStringFromIDs(@NotNull String val) { - final String replace = idReplacements.get(val); - return replace; - } - - public boolean replaceStringFromIDs(@NotNull CompoundTag tag, @NotNull String key) { - if (!tag.contains(key)) return false; - - final String val = tag.getString(key); - final String replace = idReplacements.get(val); - - if (replace != null) { - DataFixerAPI.LOGGER.warning("Replacing ID '{}' with '{}'.", val, replace); - tag.putString(key, replace); - return true; - } - - return false; - } - - private boolean replaceIDatPath(@NotNull ListTag list, @NotNull String[] parts, int level) { - boolean[] changed = {false}; - if (level == parts.length - 1) { - DataFixerAPI.fixItemArrayWithID(list, changed, this, true); - } else { - list.forEach(inTag -> changed[0] |= replaceIDatPath((CompoundTag) inTag, parts, level + 1)); - } - return changed[0]; - } - - private boolean replaceIDatPath(@NotNull CompoundTag tag, @NotNull String[] parts, int level) { - boolean changed = false; - for (int i = level; i < parts.length - 1; i++) { - final String part = parts[i]; - if (tag.contains(part)) { - final byte type = tag.getTagType(part); - if (type == Tag.TAG_LIST) { - ListTag list = tag.getList(part, Tag.TAG_COMPOUND); - return replaceIDatPath(list, parts, i); - } else if (type == Tag.TAG_COMPOUND) { - tag = tag.getCompound(part); - } - } else { - return false; - } - } - - if (tag != null && parts.length > 0) { - final String key = parts[parts.length - 1]; - final byte type = tag.getTagType(key); - if (type == Tag.TAG_LIST) { - final ListTag list = tag.getList(key, Tag.TAG_COMPOUND); - final boolean[] _changed = {false}; - if (list.size() == 0) { - _changed[0] = DataFixerAPI.fixStringIDList(tag, key, this); - } else { - DataFixerAPI.fixItemArrayWithID(list, _changed, this, true); - } - return _changed[0]; - } else if (type == Tag.TAG_STRING) { - return replaceStringFromIDs(tag, key); - } else if (type == Tag.TAG_COMPOUND) { - final CompoundTag cTag = tag.getCompound(key); - boolean[] _changed = {false}; - DataFixerAPI.fixID(cTag, _changed, this, true); - return _changed[0]; - } - } - - - return false; - } - - public boolean replaceIDatPath(@NotNull CompoundTag root, @NotNull String path) { - String[] parts = path.split("\\."); - return replaceIDatPath(root, parts, 0); - } - - public boolean patchLevelDat(@NotNull CompoundTag level) throws PatchDidiFailException { - boolean changed = false; - for (PatchFunction f : levelPatchers) { - changed |= f.apply(level, this); - } - return changed; - } - - public void patchWorldData() throws PatchDidiFailException { - for (Patch patch : worldDataPatchers) { - CompoundTag root = WorldConfig.getRootTag(patch.modID); - boolean changed = patch.getWorldDataPatcher().apply(root, this); - if (changed) { - WorldConfig.saveFile(patch.modID); - } - } - - for (Map.Entry> entry : worldDataIDPaths.entrySet()) { - CompoundTag root = WorldConfig.getRootTag(entry.getKey()); - boolean[] changed = {false}; - entry.getValue().forEach(path -> { - changed[0] |= replaceIDatPath(root, path); - }); - - if (changed[0]) { - WorldConfig.saveFile(entry.getKey()); - } - } - } - - public boolean patchBlockState(ListTag palette, ListTag states) throws PatchDidiFailException { - boolean changed = false; - for (PatchBiFunction f : statePatchers) { - changed |= f.apply(palette, states, this); - } - return changed; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/datafixer/Patch.java b/src/main/java/org/betterx/bclib/api/v2/datafixer/Patch.java deleted file mode 100644 index cadf2ec3..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/datafixer/Patch.java +++ /dev/null @@ -1,237 +0,0 @@ -package org.betterx.bclib.api.v2.datafixer; - -import org.betterx.bclib.interfaces.PatchBiFunction; -import org.betterx.bclib.interfaces.PatchFunction; -import org.betterx.worlds.together.util.ModUtil; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.jetbrains.annotations.NotNull; - -public abstract class Patch { - private static final List ALL = new ArrayList<>(10); - - /** - * The Patch-Level derived from {@link #version} - */ - public final int level; - - /** - * The Patch-Version string - */ - public final String version; - - /** - * The Mod-ID that registered this Patch - */ - - @NotNull - public final String modID; - - /** - * This Mod is tested for each level start - */ - public final boolean alwaysApply; - - static List getALL() { - return ALL; - } - - /** - * Returns the highest Patch-Version that is available for the given mod. If no patches were - * registerd for the mod, this will return 0.0.0 - * - * @param modID The ID of the mod you want to query - * @return The highest Patch-Version that was found - */ - public static String maxPatchVersion(@NotNull String modID) { - return ALL.stream().filter(p -> p.modID.equals(modID)).map(p -> p.version).reduce((p, c) -> c).orElse("0.0.0"); - } - - /** - * Returns the highest patch-level that is available for the given mod. If no patches were - * registerd for the mod, this will return 0 - * - * @param modID The ID of the mod you want to query - * @return The highest Patch-Level that was found - */ - public static int maxPatchLevel(@NotNull String modID) { - return ALL.stream().filter(p -> p.modID.equals(modID)).mapToInt(p -> p.level).max().orElse(0); - } - - /** - * Called by inheriting classes. - *

- * Performs some sanity checks on the values and might throw a #RuntimeException if any - * inconsistencies are found. - * - * @param modID The ID of the Mod you want to register a patch for. This should be your - * ModID only. The ModID can not be {@code null} or an empty String. - * @param version The mod-version that introduces the patch. This needs Semantic-Version String - * like x.x.x. Developers are responsible for registering their patches in the correct - * order (with increasing versions). You are not allowed to register a new - * Patch with a version lower or equal than - * {@link Patch#maxPatchVersion(String)} - */ - protected Patch(@NotNull String modID, String version) { - this(modID, version, false); - } - - /** - * Internal Constructor used to create patches that can allways run (no matter what patchlevel a level has) - * - * @param modID The ID of the Mod - * @param version The mod-version that introduces the patch. When {@Code runAllways} is set, this version will - * determine the patchlevel that is written to the level - * @param alwaysApply When true, this patch is always active, no matter the patchlevel of the world. - * This should be used sparingly and just for patches that apply to level.dat (as they only take - * effect when changes are detected). Use {@link ForcedLevelPatch} to instatiate. - */ - Patch(@NotNull String modID, String version, boolean alwaysApply) { - //Patchlevels need to be unique and registered in ascending order - if (modID == null || modID.isEmpty()) { - throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); - } - - if (version == null || version.isEmpty()) { - throw new RuntimeException("Invalid Mod-Version"); - } - - this.version = version; - this.alwaysApply = alwaysApply; - this.level = ModUtil.convertModVersion(version); - if (!ALL.stream().filter(p -> p.modID.equals(modID)).noneMatch(p -> p.level >= this.level) || this.level <= 0) { - throw new RuntimeException( - "[INTERNAL ERROR] Patch-levels need to be created in ascending order beginning with 1."); - } - - this.modID = modID; - } - - @Override - public String toString() { - return "Patch{" + modID + ':' + version + ':' + level + '}'; - } - - - /** - * Return block data fixes. Fixes will be applied on world load if current patch-level for - * the linked mod is lower than the {@link #level}. - *

- * The default implementation of this method returns an empty map. - * - * @return The returned Map should contain the replacements. All occurences of the - * {@code KeySet} are replaced with the associated value. - */ - public Map getIDReplacements() { - return new HashMap(); - } - - /** - * Return a {@link PatchFunction} that is called with the content of level.dat. - *

- * The function needs to return {@code true}, if changes were made to the data. - * If an error occurs, the method should throw a {@link PatchDidiFailException} - *

- * The default implementation of this method returns null. - * - * @return {@code true} if changes were applied and we need to save the data - */ - public PatchFunction getLevelDatPatcher() { - return null; - } - - /** - * Return a {@link PatchFunction} that is called with the content from the - * {@link org.betterx.worlds.together.world.WorldConfig} for this Mod. - * The function needs to return {@code true}, if changes were made to the data. - * If an error occurs, the method should throw a {@link PatchDidiFailException} - *

- * The default implementation of this method returns null. - * - * @return {@code true} if changes were applied and we need to save the data - */ - public PatchFunction getWorldDataPatcher() { - return null; - } - - /** - * Return a {@link PatchBiFunction} that is called with pallette and blockstate of - * each chunk in every region. This method is called AFTER all ID replacements - * from {@link #getIDReplacements()} were applied to the pallete. - *

- * The first parameter is the palette and the second is the blockstate. - *

- * The function needs to return {@code true}, if changes were made to the data. - * If an error occurs, the method should throw a {@link PatchDidiFailException} - *

- * The default implementation of this method returns null. - * - * @return {@code true} if changes were applied and we need to save the data - */ - public PatchBiFunction getBlockStatePatcher() { - return null; - } - - /** - * Generates ready to use data for all currently registered patches. The list of - * patches is selected by the current patch-level of the world. - *

- * A {@link #Patch} with a given {@link #level} is only included if the patch-level of the - * world is less - * - * @param config The current patch-level configuration* - * @return a new {@link MigrationProfile} Object. - */ - static MigrationProfile createMigrationData(CompoundTag config) { - return new MigrationProfile(config, false); - } - - /** - * This method is supposed to be used by developers to apply id-patches to custom nbt structures. It is only - * available in Developer-Mode - */ - static MigrationProfile createMigrationData() { - return new MigrationProfile(null, true); - } - - /** - * Returns a list of paths where your mod stores IDs in your {@link org.betterx.worlds.together.world.WorldConfig}-File. - *

- * {@link DataFixerAPI} will use information from the latest patch that returns a non-null-result. This list is used - * to automatically fix changed IDs from all active patches (see {@link Patch#getIDReplacements()} - *

- * The end of the path can either be a {@link net.minecraft.nbt.StringTag}, a {@link net.minecraft.nbt.ListTag} or - * a {@link CompoundTag}. If the Path contains a non-leaf {@link net.minecraft.nbt.ListTag}, all members of that - * list will be processed. For example: - *

-     * 	 - global +
-     * 			  | - key (String)
-     * 			  | - items (List) +
-     * 							   | - { id (String) }
-     * 							   | - { id (String) }
-     * 
- * The path global.items.id will fix all id-entries in the items-list, while the path - * global.key will only fix the key-entry. - *

- * if the leaf-entry (= the last part of the path, which would be items in global.items) is a - * {@link CompoundTag}, the system will fix any id entry. If the {@link CompoundTag} contains an item - * or tag.BlockEntityTag entry, the system will recursivley continue with those. If an items - * or inventory-{@link net.minecraft.nbt.ListTag} was found, the system will continue recursivley with - * every item of that list. - *

- * if the leaf-entry is a {@link net.minecraft.nbt.ListTag}, it is handle the same as a child items entry - * of a {@link CompoundTag}. - * - * @return {@code null} if nothing changes or a list of Paths in your {@link org.betterx.worlds.together.world.WorldConfig}-File. - * Paths are dot-seperated (see {@link org.betterx.worlds.together.world.WorldConfig#getCompoundTag(String, String)}). - */ - public List getWorldDataIDPaths() { - return null; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/datafixer/PatchDidiFailException.java b/src/main/java/org/betterx/bclib/api/v2/datafixer/PatchDidiFailException.java deleted file mode 100644 index 053d29fe..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/datafixer/PatchDidiFailException.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.betterx.bclib.api.v2.datafixer; - -public class PatchDidiFailException extends Exception { - public PatchDidiFailException() { - super(); - } - - public PatchDidiFailException(Exception e) { - super(e); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/BCLBiomeSource.java b/src/main/java/org/betterx/bclib/api/v2/generator/BCLBiomeSource.java deleted file mode 100644 index 305e0cd5..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/BCLBiomeSource.java +++ /dev/null @@ -1,137 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; -import org.betterx.worlds.together.biomesource.BiomeSourceFromRegistry; -import org.betterx.worlds.together.biomesource.BiomeSourceHelper; -import org.betterx.worlds.together.biomesource.MergeableBiomeSource; -import org.betterx.worlds.together.world.BiomeSourceWithNoiseRelatedSettings; -import org.betterx.worlds.together.world.BiomeSourceWithSeed; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; - -import com.google.common.collect.Sets; - -import java.util.Comparator; -import java.util.List; -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -public abstract class BCLBiomeSource extends BiomeSource implements BiomeSourceWithSeed, MergeableBiomeSource, BiomeSourceWithNoiseRelatedSettings, BiomeSourceFromRegistry { - protected final Registry biomeRegistry; - private int registryModificationCounter; - protected long currentSeed; - protected int maxHeight; - - private static List> preInit(Registry biomeRegistry, List> biomes) { - biomes = biomes.stream().sorted(Comparator.comparing(holder -> holder.unwrapKey() - .get() - .location() - .toString())) - .toList(); - return biomes; - } - - protected BCLBiomeSource( - Registry biomeRegistry, - List> list, - long seed - ) { - super(preInit(biomeRegistry, list)); - this.registryModificationCounter = InternalBiomeAPI.getBiomeRegistryModificationCount(biomeRegistry); - this.biomeRegistry = biomeRegistry; - this.currentSeed = seed; - } - - @Override - public boolean didBiomeRegistryChange() { - return this.registryModificationCounter != InternalBiomeAPI.getBiomeRegistryModificationCount(biomeRegistry); - } - - final public void setSeed(long seed) { - if (seed != currentSeed) { - BCLib.LOGGER.debug(this + "\n --> new seed = " + seed); - this.currentSeed = seed; - initMap(seed); - } - } - - /** - * Set world height - * - * @param maxHeight height of the World. - */ - final public void setMaxHeight(int maxHeight) { - if (this.maxHeight != maxHeight) { - BCLib.LOGGER.debug(this + "\n --> new height = " + maxHeight); - this.maxHeight = maxHeight; - onHeightChange(maxHeight); - } - } - - protected final void initMap(long seed) { - BCLib.LOGGER.debug(this + "\n --> Map Update"); - onInitMap(seed); - } - - protected abstract void onInitMap(long newSeed); - protected abstract void onHeightChange(int newHeight); - - public BCLBiomeSource createCopyForDatapack(Set> datapackBiomes) { - Set> mutableSet = Sets.newHashSet(); - mutableSet.addAll(datapackBiomes); - return cloneForDatapack(mutableSet); - } - - protected abstract BCLBiomeSource cloneForDatapack(Set> datapackBiomes); - - @NotNull - protected String getNamespaces() { - return BiomeSourceHelper.getNamespaces(possibleBiomes()); - } - - public interface ValidBiomePredicate { - boolean isValid(Holder biome, ResourceLocation location); - } - - protected static List> getBiomes( - Registry biomeRegistry, - List exclude, - List include, - BCLibNetherBiomeSource.ValidBiomePredicate test - ) { - return biomeRegistry.stream() - .filter(biome -> biomeRegistry.getResourceKey(biome).isPresent()) - - .map(biome -> biomeRegistry.getOrCreateHolderOrThrow(biomeRegistry.getResourceKey(biome) - .get())) - .filter(biome -> { - ResourceLocation location = biome.unwrapKey().orElseThrow().location(); - final String strLocation = location.toString(); - if (exclude.contains(strLocation)) return false; - if (include.contains(strLocation)) return true; - - return test.isValid(biome, location); - }) - .toList(); - } - - @Override - public BCLBiomeSource mergeWithBiomeSource(BiomeSource inputBiomeSource) { - final Set> datapackBiomes = inputBiomeSource.possibleBiomes(); - return this.createCopyForDatapack(datapackBiomes); - } - - public void onLoadGeneratorSettings(NoiseGeneratorSettings generator) { - this.setMaxHeight(generator.noiseSettings().height()); - } - - public Registry getBiomeRegistry() { - return biomeRegistry; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/BCLChunkGenerator.java b/src/main/java/org/betterx/bclib/api/v2/generator/BCLChunkGenerator.java deleted file mode 100644 index 39114b70..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/BCLChunkGenerator.java +++ /dev/null @@ -1,229 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.levelgen.LevelGenUtil; -import org.betterx.bclib.interfaces.NoiseGeneratorSettingsProvider; -import org.betterx.bclib.mixin.common.ChunkGeneratorAccessor; -import org.betterx.worlds.together.WorldsTogether; -import org.betterx.worlds.together.biomesource.MergeableBiomeSource; -import org.betterx.worlds.together.biomesource.ReloadableBiomeSource; -import org.betterx.worlds.together.chunkgenerator.EnforceableChunkGenerator; -import org.betterx.worlds.together.chunkgenerator.InjectableSurfaceRules; -import org.betterx.worlds.together.chunkgenerator.RestorableBiomeSource; -import org.betterx.worlds.together.world.BiomeSourceWithNoiseRelatedSettings; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.resources.RegistryOps; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.FeatureSorter; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; -import net.minecraft.world.level.levelgen.RandomState; -import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.levelgen.structure.StructureSet; -import net.minecraft.world.level.levelgen.synth.NormalNoise; - -import com.google.common.base.Suppliers; - -import java.util.List; -import java.util.function.Function; - -public class BCLChunkGenerator extends NoiseBasedChunkGenerator implements RestorableBiomeSource, InjectableSurfaceRules, EnforceableChunkGenerator { - - public static final Codec CODEC = RecordCodecBuilder - .create((RecordCodecBuilder.Instance builderInstance) -> { - final RecordCodecBuilder> noiseGetter = RegistryOps - .retrieveRegistry( - Registry.NOISE_REGISTRY) - .forGetter( - BCLChunkGenerator::getNoises); - - RecordCodecBuilder biomeSourceCodec = BiomeSource.CODEC - .fieldOf("biome_source") - .forGetter((BCLChunkGenerator generator) -> generator.biomeSource); - - RecordCodecBuilder> settingsCodec = NoiseGeneratorSettings.CODEC - .fieldOf("settings") - .forGetter((BCLChunkGenerator generator) -> generator.settings); - - - return NoiseBasedChunkGenerator - .commonCodec(builderInstance) - .and(builderInstance.group(noiseGetter, biomeSourceCodec, settingsCodec)) - .apply(builderInstance, builderInstance.stable(BCLChunkGenerator::new)); - }); - public final BiomeSource initialBiomeSource; - - public BCLChunkGenerator( - Registry registry, - Registry registry2, - BiomeSource biomeSource, - Holder holder - ) { - super(registry, registry2, biomeSource, holder); - initialBiomeSource = biomeSource; - if (biomeSource instanceof BiomeSourceWithNoiseRelatedSettings bcl) { - bcl.onLoadGeneratorSettings(holder.value()); - } - - if (WorldsTogether.RUNS_TERRABLENDER) { - BCLib.LOGGER.info("Make sure features are loaded from terrablender" + biomeSource); - - //terrablender is invalidating the feature initialization - //we redo it at this point, otherwise we will get blank biomes - rebuildFeaturesPerStep(biomeSource); - } - } - - private void rebuildFeaturesPerStep(BiomeSource biomeSource) { - if (this instanceof ChunkGeneratorAccessor acc) { - Function, BiomeGenerationSettings> function = (Holder hh) -> hh.value() - .getGenerationSettings(); - - acc.bcl_setFeaturesPerStep(Suppliers.memoize(() -> FeatureSorter.buildFeaturesPerStep( - List.copyOf(biomeSource.possibleBiomes()), - (hh) -> function.apply(hh).features(), - true - ))); - } - } - - /** - * Other Mods like TerraBlender might inject new BiomeSources. We und that change after the world setup did run. - * - * @param dimensionKey The Dimension where this ChunkGenerator is used from - */ - @Override - public void restoreInitialBiomeSource(ResourceKey dimensionKey) { - if (initialBiomeSource != getBiomeSource()) { - if (this instanceof ChunkGeneratorAccessor acc) { - if (initialBiomeSource instanceof MergeableBiomeSource bs) { - acc.bcl_setBiomeSource(bs.mergeWithBiomeSource(getBiomeSource())); - } else if (initialBiomeSource instanceof ReloadableBiomeSource bs) { - bs.reloadBiomes(); - } - - rebuildFeaturesPerStep(getBiomeSource()); - } - } - } - - - @Override - protected Codec codec() { - return CODEC; - } - - - private Registry getNoises() { - if (this instanceof NoiseGeneratorSettingsProvider p) { - return p.bclib_getNoises(); - } - return null; - } - - @Override - public String toString() { - return "BCLib - Chunk Generator (" + Integer.toHexString(hashCode()) + ")"; - } - - // This method is injected by Terrablender. - // We make sure terrablender does not rewrite the feature-set for our ChunkGenerator by overwriting the - // Mixin-Method with an empty implementation - public void appendFeaturesPerStep() { - } - - public static RandomState createRandomState(ServerLevel level, ChunkGenerator generator) { - if (generator instanceof NoiseBasedChunkGenerator noiseBasedChunkGenerator) { - return RandomState.create( - noiseBasedChunkGenerator.generatorSettings().value(), - level.registryAccess().registryOrThrow(Registry.NOISE_REGISTRY), - level.getSeed() - ); - } else { - return RandomState.create(level.registryAccess(), NoiseGeneratorSettings.OVERWORLD, level.getSeed()); - } - } - - @Override - public WorldGenSettings enforceGeneratorInWorldGenSettings( - RegistryAccess access, - ResourceKey dimensionKey, - ResourceKey dimensionTypeKey, - ChunkGenerator loadedChunkGenerator, - WorldGenSettings settings - ) { - BCLib.LOGGER.info("Enforcing Correct Generator for " + dimensionKey.location().toString() + "."); - - ChunkGenerator referenceGenerator = this; - if (loadedChunkGenerator instanceof org.betterx.bclib.interfaces.ChunkGeneratorAccessor generator) { - if (loadedChunkGenerator instanceof NoiseGeneratorSettingsProvider noiseProvider) { - if (referenceGenerator instanceof NoiseGeneratorSettingsProvider referenceProvider) { - final BiomeSource bs; - if (referenceGenerator.getBiomeSource() instanceof MergeableBiomeSource mbs) { - bs = mbs.mergeWithBiomeSource(loadedChunkGenerator.getBiomeSource()); - } else { - bs = referenceGenerator.getBiomeSource(); - } - - referenceGenerator = new BCLChunkGenerator( - generator.bclib_getStructureSetsRegistry(), - noiseProvider.bclib_getNoises(), - bs, - buildGeneratorSettings( - referenceProvider.bclib_getNoiseGeneratorSettingHolders(), - noiseProvider.bclib_getNoiseGeneratorSettingHolders(), - bs - ) - ); - } - } - } - - return LevelGenUtil.replaceGenerator( - dimensionKey, - dimensionTypeKey, - access, - settings, - referenceGenerator - ); - - } - - private static Holder buildGeneratorSettings( - Holder reference, - Holder settings, - BiomeSource biomeSource - ) { - return settings; -// NoiseGeneratorSettings old = settings.value(); -// NoiseGeneratorSettings noise = new NoiseGeneratorSettings( -// old.noiseSettings(), -// old.defaultBlock(), -// old.defaultFluid(), -// old.noiseRouter(), -// SurfaceRuleRegistry.mergeSurfaceRulesFromBiomes(old.surfaceRule(), biomeSource), -// //SurfaceRuleUtil.addRulesForBiomeSource(old.surfaceRule(), biomeSource), -// old.spawnTarget(), -// old.seaLevel(), -// old.disableMobGeneration(), -// old.aquifersEnabled(), -// old.oreVeinsEnabled(), -// old.useLegacyRandomSource() -// ); -// -// -// return Holder.direct(noise); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/BCLibEndBiomeSource.java b/src/main/java/org/betterx/bclib/api/v2/generator/BCLibEndBiomeSource.java deleted file mode 100644 index 1e232700..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/BCLibEndBiomeSource.java +++ /dev/null @@ -1,438 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.generator.config.BCLEndBiomeSourceConfig; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.interfaces.BiomeMap; -import org.betterx.worlds.together.biomesource.BiomeSourceWithConfig; -import org.betterx.worlds.together.biomesource.ReloadableBiomeSource; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Holder; -import net.minecraft.core.QuartPos; -import net.minecraft.core.Registry; -import net.minecraft.core.SectionPos; -import net.minecraft.resources.RegistryOps; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BiomeTags; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.Biomes; -import net.minecraft.world.level.biome.Climate; -import net.minecraft.world.level.levelgen.DensityFunction; - -import java.awt.*; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.jetbrains.annotations.NotNull; - -public class BCLibEndBiomeSource extends BCLBiomeSource implements BiomeSourceWithConfig, ReloadableBiomeSource { - public static Codec CODEC - = RecordCodecBuilder.create((instance) -> instance.group( - RegistryOps - .retrieveRegistry(Registry.BIOME_REGISTRY) - .forGetter((theEndBiomeSource) -> theEndBiomeSource.biomeRegistry), - Codec - .LONG - .fieldOf("seed") - .stable() - .forGetter(source -> source.currentSeed), - BCLEndBiomeSourceConfig - .CODEC - .fieldOf("config") - .orElse(BCLEndBiomeSourceConfig.DEFAULT) - .forGetter(o -> o.config) - ) - .apply( - instance, - instance.stable(BCLibEndBiomeSource::new) - ) - ); - private final Point pos; - private BiomeMap mapLand; - private BiomeMap mapVoid; - private BiomeMap mapCenter; - private BiomeMap mapBarrens; - - private BiomePicker endLandBiomePicker; - private BiomePicker endVoidBiomePicker; - private BiomePicker endCenterBiomePicker; - private BiomePicker endBarrensBiomePicker; - private List deciders; - - private BCLEndBiomeSourceConfig config; - - public BCLibEndBiomeSource(Registry biomeRegistry, long seed, BCLEndBiomeSourceConfig config) { - this(biomeRegistry, seed, config, true); - } - - public BCLibEndBiomeSource(Registry biomeRegistry, BCLEndBiomeSourceConfig config) { - this(biomeRegistry, 0, config, false); - } - - private BCLibEndBiomeSource( - Registry biomeRegistry, - long seed, - BCLEndBiomeSourceConfig config, - boolean initMaps - ) { - this(biomeRegistry, getBiomes(biomeRegistry), seed, config, initMaps); - } - - private BCLibEndBiomeSource( - Registry biomeRegistry, - List> list, - long seed, - BCLEndBiomeSourceConfig config, - boolean initMaps - ) { - super(biomeRegistry, list, seed); - this.config = config; - rebuildBiomePickers(); - - this.pos = new Point(); - - if (initMaps) { - initMap(seed); - } - } - - @NotNull - private void rebuildBiomePickers() { - var includeMap = Configs.BIOMES_CONFIG.getBiomeIncludeMap(); - var excludeList = Configs.BIOMES_CONFIG.getExcludeMatching(BiomeAPI.BiomeType.END); - - this.deciders = BiomeDecider.DECIDERS.stream() - .filter(d -> d.canProvideFor(this)) - .map(d -> d.createInstance(this)) - .toList(); - - this.endLandBiomePicker = new BiomePicker(biomeRegistry); - this.endVoidBiomePicker = new BiomePicker(biomeRegistry); - this.endCenterBiomePicker = new BiomePicker(biomeRegistry); - this.endBarrensBiomePicker = new BiomePicker(biomeRegistry); - Map pickerMap = new HashMap<>(); - pickerMap.put(BiomeAPI.BiomeType.END_LAND, endLandBiomePicker); - pickerMap.put(BiomeAPI.BiomeType.END_VOID, endVoidBiomePicker); - pickerMap.put(BiomeAPI.BiomeType.END_CENTER, endCenterBiomePicker); - pickerMap.put(BiomeAPI.BiomeType.END_BARRENS, endBarrensBiomePicker); - - - this.possibleBiomes().forEach(biome -> { - ResourceKey key = biome.unwrapKey().orElseThrow(); - ResourceLocation biomeID = key.location(); - String biomeStr = biomeID.toString(); - //exclude everything that was listed - if (excludeList != null && excludeList.contains(biomeStr)) return; - if (!biome.isBound()) { - BCLib.LOGGER.warning("Biome " + biomeStr + " is requested but not yet bound."); - return; - } - final BCLBiome bclBiome; - if (!BiomeAPI.hasBiome(biomeID)) { - bclBiome = new BCLBiome(biomeID, biome.value(), BiomeAPI.BiomeType.END_LAND); - InternalBiomeAPI.registerBCLBiomeData(bclBiome); - } else { - bclBiome = BiomeAPI.getBiome(biomeID); - } - - - if (bclBiome != null || bclBiome != BCLBiomeRegistry.EMPTY_BIOME) { - if (bclBiome.getParentBiome() == null) { - //ignore small islands when void biomes are disabled - if (!config.withVoidBiomes) { - if (biomeID.equals(Biomes.SMALL_END_ISLANDS.location())) { - return; - } - } - - //force include biomes - boolean didForceAdd = false; - for (var entry : pickerMap.entrySet()) { - var includeList = includeMap == null ? null : includeMap.get(entry.getKey()); - if (includeList != null && includeList.contains(biomeStr)) { - entry.getValue().addBiome(bclBiome); - didForceAdd = true; - } - } - - if (!didForceAdd) { - if (biomeID.equals(BCLBiomeRegistry.EMPTY_BIOME.getID()) - || bclBiome.getIntendedType().is(BiomeAPI.BiomeType.END_IGNORE)) { - //we should not add this biome anywhere, so just ignore it - } else { - didForceAdd = false; - for (BiomeDecider decider : deciders) { - if (decider.addToPicker(bclBiome)) { - didForceAdd = true; - break; - } - } - if (!didForceAdd) { - if (bclBiome.getIntendedType().is(BiomeAPI.BiomeType.END_CENTER) - || TheEndBiomesHelper.canGenerateAsMainIslandBiome(key)) { - endCenterBiomePicker.addBiome(bclBiome); - } else if (bclBiome.getIntendedType().is(BiomeAPI.BiomeType.END_LAND) - || TheEndBiomesHelper.canGenerateAsHighlandsBiome(key)) { - if (!config.withVoidBiomes) endVoidBiomePicker.addBiome(bclBiome); - endLandBiomePicker.addBiome(bclBiome); - } else if (bclBiome.getIntendedType().is(BiomeAPI.BiomeType.END_BARRENS) - || TheEndBiomesHelper.canGenerateAsEndBarrens(key)) { - endBarrensBiomePicker.addBiome(bclBiome); - } else if (bclBiome.getIntendedType().is(BiomeAPI.BiomeType.END_VOID) - || TheEndBiomesHelper.canGenerateAsSmallIslandsBiome(key)) { - endVoidBiomePicker.addBiome(bclBiome); - } else { - BCLib.LOGGER.info("Found End Biome " + biomeStr + " that was not registers with fabric or bclib. Assuming end-land Biome..."); - endLandBiomePicker.addBiome(bclBiome); - } - } - } - } - } - } - }); - - endLandBiomePicker.rebuild(); - endVoidBiomePicker.rebuild(); - endBarrensBiomePicker.rebuild(); - endCenterBiomePicker.rebuild(); - - for (BiomeDecider decider : deciders) { - decider.rebuild(); - } - - if (endVoidBiomePicker.isEmpty()) { - BCLib.LOGGER.info("No Void Biomes found. Disabling by using barrens"); - endVoidBiomePicker = endBarrensBiomePicker; - } - if (endBarrensBiomePicker.isEmpty()) { - BCLib.LOGGER.info("No Barrens Biomes found. Disabling by using land Biomes"); - endBarrensBiomePicker = endLandBiomePicker; - endVoidBiomePicker = endLandBiomePicker; - } - if (endCenterBiomePicker.isEmpty()) { - BCLib.LOGGER.warning("No Center Island Biomes found. Forcing use of vanilla center."); - endCenterBiomePicker.addBiome(BiomeAPI.THE_END); - endCenterBiomePicker.rebuild(); - if (endCenterBiomePicker.isEmpty()) { - BCLib.LOGGER.error("Unable to force vanilla central Island. Falling back to land Biomes..."); - endCenterBiomePicker = endLandBiomePicker; - } - } - } - - protected BCLBiomeSource cloneForDatapack(Set> datapackBiomes) { - datapackBiomes.addAll(getNonVanillaBiomes(this.biomeRegistry)); - datapackBiomes.addAll(possibleBiomes().stream() - .filter(h -> !h.unwrapKey() - .orElseThrow() - .location() - .getNamespace() - .equals("minecraft")) - .toList()); - - return new BCLibEndBiomeSource( - this.biomeRegistry, - datapackBiomes.stream() - .filter(b -> b.isValidInRegistry(biomeRegistry) && b.unwrapKey() - .orElse(null) != BCLBiomeRegistry.EMPTY_BIOME.getBiomeKey()) - .toList(), - this.currentSeed, - this.config, - true - ); - } - - private static List> getNonVanillaBiomes(Registry biomeRegistry) { - return getBiomes( - biomeRegistry, - Configs.BIOMES_CONFIG.getExcludeMatching(BiomeAPI.BiomeType.END), - Configs.BIOMES_CONFIG.getIncludeMatching(BiomeAPI.BiomeType.END), - BCLibEndBiomeSource::isValidNonVanillaEndBiome - ); - } - - private static List> getBiomes(Registry biomeRegistry) { - return getBiomes( - biomeRegistry, - Configs.BIOMES_CONFIG.getExcludeMatching(BiomeAPI.BiomeType.END), - Configs.BIOMES_CONFIG.getIncludeMatching(BiomeAPI.BiomeType.END), - BCLibEndBiomeSource::isValidEndBiome - ); - } - - - private static boolean isValidEndBiome(Holder biome, ResourceLocation location) { - if (BiomeAPI.wasRegisteredAs(location, BiomeAPI.BiomeType.END_IGNORE)) return false; - - return biome.is(BiomeTags.IS_END) || - BiomeAPI.wasRegisteredAsEndBiome(location) || - TheEndBiomesHelper.canGenerateInEnd(biome.unwrapKey().orElse(null)); - } - - private static boolean isValidNonVanillaEndBiome(Holder biome, ResourceLocation location) { - if (BiomeAPI.wasRegisteredAs(location, BiomeAPI.BiomeType.END_IGNORE) || biome.unwrapKey() - .orElseThrow() - .location() - .getNamespace() - .equals("minecraft")) - return false; - - return biome.is(BiomeTags.IS_END) || - BiomeAPI.wasRegisteredAsEndBiome(location) || - TheEndBiomesHelper.canGenerateInEnd(biome.unwrapKey().orElse(null)); - } - - public static void register() { - Registry.register(Registry.BIOME_SOURCE, BCLib.makeID("end_biome_source"), CODEC); - } - - @Override - protected void onInitMap(long seed) { - for (BiomeDecider decider : deciders) { - decider.createMap((picker, size) -> config.mapVersion.mapBuilder.create( - seed, - size <= 0 ? config.landBiomesSize : size, - picker - )); - } - this.mapLand = config.mapVersion.mapBuilder.create( - seed, - config.landBiomesSize, - endLandBiomePicker - ); - - this.mapVoid = config.mapVersion.mapBuilder.create( - seed, - config.voidBiomesSize, - endVoidBiomePicker - ); - - this.mapCenter = config.mapVersion.mapBuilder.create( - seed, - config.centerBiomesSize, - endCenterBiomePicker - ); - - this.mapBarrens = config.mapVersion.mapBuilder.create( - seed, - config.barrensBiomesSize, - endBarrensBiomePicker - ); - } - - @Override - protected void onHeightChange(int newHeight) { - - } - - @Override - public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ, Climate.@NotNull Sampler sampler) { - if (mapLand == null || mapVoid == null || mapCenter == null || mapBarrens == null) - return this.possibleBiomes().stream().findFirst().orElseThrow(); - - int posX = QuartPos.toBlock(biomeX); - int posY = QuartPos.toBlock(biomeY); - int posZ = QuartPos.toBlock(biomeZ); - - long dist = Math.abs(posX) + Math.abs(posZ) > (long) config.innerVoidRadiusSquared - ? ((long) config.innerVoidRadiusSquared + 1) - : (long) posX * (long) posX + (long) posZ * (long) posZ; - - - if ((biomeX & 63) == 0 || (biomeZ & 63) == 0) { - mapLand.clearCache(); - mapVoid.clearCache(); - mapCenter.clearCache(); - mapVoid.clearCache(); - for (BiomeDecider decider : deciders) { - decider.clearMapCache(); - } - } - - BiomeAPI.BiomeType suggestedType; - - - int x = (SectionPos.blockToSectionCoord(posX) * 2 + 1) * 8; - int z = (SectionPos.blockToSectionCoord(posZ) * 2 + 1) * 8; - double d = sampler.erosion().compute(new DensityFunction.SinglePointContext(x, posY, z)); - if (dist <= (long) config.innerVoidRadiusSquared) { - suggestedType = BiomeAPI.BiomeType.END_CENTER; - } else { - if (d > 0.25) { - suggestedType = BiomeAPI.BiomeType.END_LAND; //highlands - } else if (d >= -0.0625) { - suggestedType = BiomeAPI.BiomeType.END_LAND; //midlands - } else { - suggestedType = d < -0.21875 - ? BiomeAPI.BiomeType.END_VOID //small islands - : (config.withVoidBiomes - ? BiomeAPI.BiomeType.END_BARRENS - : BiomeAPI.BiomeType.END_LAND); //barrens - } - } - - final BiomeAPI.BiomeType originalType = suggestedType; - for (BiomeDecider decider : deciders) { - suggestedType = decider - .suggestType(originalType, suggestedType, d, maxHeight, posX, posY, posZ, biomeX, biomeY, biomeZ); - } - - - BiomePicker.ActualBiome result; - for (BiomeDecider decider : deciders) { - if (decider.canProvideBiome(suggestedType)) { - result = decider.provideBiome(suggestedType, posX, posY, posZ); - if (result != null) return result.biome; - } - } - - if (suggestedType.is(BiomeAPI.BiomeType.END_CENTER)) return mapCenter.getBiome(posX, posY, posZ).biome; - if (suggestedType.is(BiomeAPI.BiomeType.END_VOID)) return mapVoid.getBiome(posX, posY, posZ).biome; - if (suggestedType.is(BiomeAPI.BiomeType.END_BARRENS)) return mapBarrens.getBiome(posX, posY, posZ).biome; - return mapLand.getBiome(posX, posY, posZ).biome; - } - - - @Override - protected Codec codec() { - return CODEC; - } - - @Override - public String toString() { - return "\nBCLib - The End BiomeSource (" + Integer.toHexString(hashCode()) + ")" + - "\n biomes = " + possibleBiomes().size() + - "\n namespaces = " + getNamespaces() + - "\n seed = " + currentSeed + - "\n height = " + maxHeight + - "\n deciders = " + deciders.size() + - "\n config = " + config; - } - - @Override - public BCLEndBiomeSourceConfig getTogetherConfig() { - return config; - } - - @Override - public void setTogetherConfig(BCLEndBiomeSourceConfig newConfig) { - this.config = newConfig; - this.initMap(currentSeed); - } - - @Override - public void reloadBiomes() { - rebuildBiomePickers(); - this.initMap(currentSeed); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/BCLibNetherBiomeSource.java b/src/main/java/org/betterx/bclib/api/v2/generator/BCLibNetherBiomeSource.java deleted file mode 100644 index 80693f1d..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/BCLibNetherBiomeSource.java +++ /dev/null @@ -1,246 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.generator.config.BCLNetherBiomeSourceConfig; -import org.betterx.bclib.api.v2.generator.config.MapBuilderFunction; -import org.betterx.bclib.api.v2.generator.map.MapStack; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.interfaces.BiomeMap; -import org.betterx.worlds.together.biomesource.BiomeSourceWithConfig; -import org.betterx.worlds.together.biomesource.ReloadableBiomeSource; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.resources.RegistryOps; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BiomeTags; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.Climate; - -import net.fabricmc.fabric.api.biome.v1.NetherBiomes; - -import java.util.List; -import java.util.Set; - -public class BCLibNetherBiomeSource extends BCLBiomeSource implements BiomeSourceWithConfig, ReloadableBiomeSource { - public static final Codec CODEC = RecordCodecBuilder - .create(instance -> instance - .group( - RegistryOps - .retrieveRegistry(Registry.BIOME_REGISTRY) - .forGetter(source -> source.biomeRegistry), - Codec - .LONG - .fieldOf("seed") - .stable() - .forGetter(source -> { - return source.currentSeed; - }), - BCLNetherBiomeSourceConfig - .CODEC - .fieldOf("config") - .orElse(BCLNetherBiomeSourceConfig.DEFAULT) - .forGetter(o -> o.config) - ) - .apply(instance, instance.stable(BCLibNetherBiomeSource::new)) - ); - private BiomeMap biomeMap; - private BiomePicker biomePicker; - private BCLNetherBiomeSourceConfig config; - - public BCLibNetherBiomeSource(Registry biomeRegistry, BCLNetherBiomeSourceConfig config) { - this(biomeRegistry, 0, config, false); - } - - public BCLibNetherBiomeSource(Registry biomeRegistry, long seed, BCLNetherBiomeSourceConfig config) { - this(biomeRegistry, seed, config, true); - } - - private BCLibNetherBiomeSource( - Registry biomeRegistry, - long seed, - BCLNetherBiomeSourceConfig config, - boolean initMaps - ) { - this(biomeRegistry, getBiomes(biomeRegistry), seed, config, initMaps); - } - - private BCLibNetherBiomeSource( - Registry biomeRegistry, - List> list, - long seed, - BCLNetherBiomeSourceConfig config, - boolean initMaps - ) { - super(biomeRegistry, list, seed); - this.config = config; - rebuildBiomePicker(); - if (initMaps) { - initMap(seed); - } - } - - private void rebuildBiomePicker() { - biomePicker = new BiomePicker(biomeRegistry); - - this.possibleBiomes().forEach(biome -> { - ResourceLocation biomeID = biome.unwrapKey().orElseThrow().location(); - if (!biome.isBound()) { - BCLib.LOGGER.warning("Biome " + biomeID.toString() + " is requested but not yet bound."); - return; - } - if (!BiomeAPI.hasBiome(biomeID)) { - BCLBiome bclBiome = new BCLBiome(biomeID, biome.value(), BiomeAPI.BiomeType.NETHER); - InternalBiomeAPI.registerBCLBiomeData(bclBiome); - biomePicker.addBiome(bclBiome); - } else { - BCLBiome bclBiome = BiomeAPI.getBiome(biomeID); - - if (bclBiome != BCLBiomeRegistry.EMPTY_BIOME) { - if (bclBiome.getParentBiome() == null) { - biomePicker.addBiome(bclBiome); - } - } - } - }); - - biomePicker.rebuild(); - } - - protected BCLBiomeSource cloneForDatapack(Set> datapackBiomes) { - datapackBiomes.addAll(getNonVanillaBiomes(this.biomeRegistry)); - datapackBiomes.addAll(possibleBiomes().stream() - .filter(h -> !h.unwrapKey() - .orElseThrow() - .location() - .getNamespace() - .equals("minecraft")) - .toList()); - return new BCLibNetherBiomeSource( - this.biomeRegistry, - datapackBiomes.stream() - .filter(b -> b.isValidInRegistry(biomeRegistry) && b.unwrapKey() - .orElse(null) != BCLBiomeRegistry.EMPTY_BIOME.getBiomeKey()) - .toList(), - this.currentSeed, - config, - true - ); - } - - private static List> getNonVanillaBiomes(Registry biomeRegistry) { - List include = Configs.BIOMES_CONFIG.getIncludeMatching(BiomeAPI.BiomeType.NETHER); - List exclude = Configs.BIOMES_CONFIG.getExcludeMatching(BiomeAPI.BiomeType.NETHER); - - return getBiomes(biomeRegistry, exclude, include, BCLibNetherBiomeSource::isValidNonVanillaNetherBiome); - } - - - private static List> getBiomes(Registry biomeRegistry) { - List include = Configs.BIOMES_CONFIG.getIncludeMatching(BiomeAPI.BiomeType.NETHER); - List exclude = Configs.BIOMES_CONFIG.getExcludeMatching(BiomeAPI.BiomeType.NETHER); - - return getBiomes(biomeRegistry, exclude, include, BCLibNetherBiomeSource::isValidNetherBiome); - } - - - private static boolean isValidNetherBiome(Holder biome, ResourceLocation location) { - return NetherBiomes.canGenerateInNether(biome.unwrapKey().get()) || - biome.is(BiomeTags.IS_NETHER) || - BiomeAPI.wasRegisteredAsNetherBiome(location); - } - - private static boolean isValidNonVanillaNetherBiome(Holder biome, ResourceLocation location) { - if (BiomeAPI.wasRegisteredAs(location, BiomeAPI.BiomeType.END_IGNORE) || biome.unwrapKey() - .orElseThrow() - .location() - .getNamespace() - .equals("minecraft")) - return false; - - return NetherBiomes.canGenerateInNether(biome.unwrapKey().get()) || - BiomeAPI.wasRegisteredAsNetherBiome(location); - } - - public static void register() { - Registry.register(Registry.BIOME_SOURCE, BCLib.makeID("nether_biome_source"), CODEC); - } - - - @Override - public Holder getNoiseBiome(int biomeX, int biomeY, int biomeZ, Climate.Sampler var4) { - if (biomeMap == null) - return this.possibleBiomes().stream().findFirst().get(); - - if ((biomeX & 63) == 0 && (biomeZ & 63) == 0) { - biomeMap.clearCache(); - } - BiomePicker.ActualBiome bb = biomeMap.getBiome(biomeX << 2, biomeY << 2, biomeZ << 2); - return bb.biome; - } - - @Override - protected Codec codec() { - return CODEC; - } - - @Override - protected void onInitMap(long seed) { - MapBuilderFunction mapConstructor = config.mapVersion.mapBuilder; - if (maxHeight > config.biomeSizeVertical * 1.5 && config.useVerticalBiomes) { - this.biomeMap = new MapStack( - seed, - config.biomeSize, - biomePicker, - config.biomeSizeVertical, - maxHeight, - mapConstructor - ); - } else { - this.biomeMap = mapConstructor.create( - seed, - config.biomeSize, - biomePicker - ); - } - } - - @Override - protected void onHeightChange(int newHeight) { - initMap(currentSeed); - } - - @Override - public String toString() { - return "\nBCLib - Nether BiomeSource (" + Integer.toHexString(hashCode()) + ")" + - "\n biomes = " + possibleBiomes().size() + - "\n namespaces = " + getNamespaces() + - "\n seed = " + currentSeed + - "\n height = " + maxHeight + - "\n config = " + config; - } - - @Override - public BCLNetherBiomeSourceConfig getTogetherConfig() { - return config; - } - - @Override - public void setTogetherConfig(BCLNetherBiomeSourceConfig newConfig) { - this.config = newConfig; - initMap(currentSeed); - } - - @Override - public void reloadBiomes() { - rebuildBiomePicker(); - initMap(currentSeed); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/BiomeDecider.java b/src/main/java/org/betterx/bclib/api/v2/generator/BiomeDecider.java deleted file mode 100644 index 37255815..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/BiomeDecider.java +++ /dev/null @@ -1,264 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.bclib.interfaces.BiomeMap; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; - -import java.util.LinkedList; -import java.util.List; - - -/** - * Used to extend the BiomePlacement in the {@link BCLBiomeSource} - */ -public abstract class BiomeDecider { - - /** - * used to create new {@link BiomeMap} instances - */ - @FunctionalInterface - public interface BiomeMapBuilderFunction { - /** - * Constructs a new {@link BiomeMap} - * - * @param picker The picker the BiomeMap should use - * @param biomeSize The biomeSize the map will use or -1 for the default size - * @return a new {@link BiomeMap} instance - */ - BiomeMap create(BiomePicker picker, int biomeSize); - } - - /** - * used to determine wether or not a decider can provide this biome - */ - @FunctionalInterface - public interface BiomePredicate { - boolean test(BCLBiome biome); - } - - protected BiomePicker picker; - protected BiomeMap map; - private final BiomePredicate predicate; - - static List DECIDERS = new LinkedList<>(); - - /** - * Register a high priority Decider for the {@link BCLibEndBiomeSource}. - * Normally you should not need to register a high priority decider and instead use - * {@link BiomeDecider#registerDecider(ResourceLocation, BiomeDecider)}. - * BetterEnd (for example) will add - * - * @param location The {@link ResourceLocation} for the decider - * @param decider The initial decider Instance. Each Instance of the {@link BCLibEndBiomeSource} - * will call {@link BiomeDecider#createInstance(BCLBiomeSource)} to build a - * new instance of this decider - */ - public static void registerHighPriorityDecider(ResourceLocation location, BiomeDecider decider) { - if (DECIDERS.size() == 0) DECIDERS.add(decider); - else DECIDERS.add(0, decider); - } - - /** - * Register a new Decider for the {@link BCLibEndBiomeSource} - * - * @param location The {@link ResourceLocation} for the decider - * @param decider The initial decider Instance. Each Instance of the {@link BCLibEndBiomeSource} - * will call {@link BiomeDecider#createInstance(BCLBiomeSource)} to build a - * new instance of this decider - */ - public static void registerDecider(ResourceLocation location, BiomeDecider decider) { - DECIDERS.add(decider); - } - - protected BiomeDecider(BiomePredicate predicate) { - this(null, predicate); - } - - /** - * @param biomeRegistry The biome registry assigned to the creating BiomeSource - * @param predicate A predicate that decides if a given Biome can be provided by this decider - */ - protected BiomeDecider( - Registry biomeRegistry, BiomePredicate predicate - ) { - this.predicate = predicate; - this.map = null; - if (biomeRegistry == null) { - this.picker = null; - } else { - this.picker = new BiomePicker(biomeRegistry); - } - } - - /** - * Called to test, if a decider is suitable for the given BiomeSource. - * - * @param source The BiomeSource that wants to use the decider - * @return true, if this decider is usable by that source - */ - public abstract boolean canProvideFor(BiomeSource source); - - /** - * Called from the BiomeSource whenever it needs to create a new instance of this decider. - *

- * Inheriting classes should overwrite this method and return Instances of the class. For - * the base {@link BiomeDecider} you would return new BiomeDecider(biomeSource.biomeRegistry, this.predicate); - * - * @param biomeSource The biome source this decider is used from - * @return A new instance - */ - public abstract BiomeDecider createInstance(BCLBiomeSource biomeSource); - - /** - * Called when the BiomeSources needs to construct a new {@link BiomeMap} for the picker. - *

- * The default implementation creates a new map with the instances picker and a default biome size - * - * @param mapBuilder A function you can use to create a new {@link BiomeMap} that conforms to the settings - * of the current BiomeSource. - */ - public void createMap(BiomeMapBuilderFunction mapBuilder) { - this.map = mapBuilder.create(picker, -1); - } - - /** - * called whenever the BiomeSource needs to clear caches - */ - public void clearMapCache() { - map.clearCache(); - } - - /** - * This method get's called whenever the BiomeSource populates the Biome Pickers. You need to - * determine if the passed Biome is valid for your picker. - *

- * If this method returns false, the Biome wil not get added to any other Deciders/Pickers. - *

- * The default implementation will use the instances {@link BiomeDecider#predicate} to determine if - * a biome should get added and return true if it was added. - * - * @param biome The biome that should get added if it matches the criteria of the picker - * @return false, if other pickers/deciders are allowed to use the biome as well - */ - public boolean addToPicker(BCLBiome biome) { - if (predicate.test(biome)) { - picker.addBiome(biome); - return true; - } - - return false; - } - - /** - * Called whenever the picker needs to rebuild it's contents - */ - public void rebuild() { - picker.rebuild(); - } - - /** - * Called from the BiomeSource to determine the type of Biome it needs to place. - * - * @param originalType The original biome type the source did select - * @param suggestedType The currently suggested type. This will differ from originalType if other - * {@link BiomeDecider} instances already had a new suggestion. You implementation should return the - * suggestedType if it does not want to provide the Biome for this location - * @param maxHeight The maximum terrain height for this world - * @param blockX The block coordinate where we are at - * @param blockY The block coordinate where we are at - * @param blockZ The block coordinate where we are at - * @param quarterX The quarter Block Coordinate (which is blockX/4) - * @param quarterY The quarter Block Coordinate (which is blockY/4) - * @param quarterZ The quarter Block Coordinate (which is blockZ/4) - * @return The suggestedType if this decider does not plan to provide a Biome, or a unique BiomeType. - * The Biome Source will call {@link BiomeDecider#canProvideBiome(BiomeAPI.BiomeType)} with the finally chosen type - * for all available Deciders. - */ - public BiomeAPI.BiomeType suggestType( - BiomeAPI.BiomeType originalType, - BiomeAPI.BiomeType suggestedType, - int maxHeight, - int blockX, - int blockY, - int blockZ, - int quarterX, - int quarterY, - int quarterZ - ) { - return suggestType( - originalType, - suggestedType, - 0, - maxHeight, - blockX, - blockY, - blockZ, - quarterX, - quarterY, - quarterZ - ); - } - - /** - * Called from the BiomeSource to determine the type of Biome it needs to place. - * - * @param originalType The original biome type the source did select - * @param suggestedType The currently suggested type. This will differ from originalType if other - * {@link BiomeDecider} instances already had a new suggestion. You implementation should return the - * suggestedType if it does not want to provide the Biome for this location - * @param density The terrain density at this location. Currently only valid if for {@link BCLibEndBiomeSource} - * that use the {@link org.betterx.bclib.api.v2.generator.config.BCLEndBiomeSourceConfig.EndBiomeGeneratorType#VANILLA} - * @param maxHeight The maximum terrain height for this world - * @param blockX The block coordinate where we are at - * @param blockY The block coordinate where we are at - * @param blockZ The block coordinate where we are at - * @param quarterX The quarter Block Coordinate (which is blockX/4) - * @param quarterY The quarter Block Coordinate (which is blockY/4) - * @param quarterZ The quarter Block Coordinate (which is blockZ/4) - * @param maxHeight - * @return The suggestedType if this decider does not plan to provide a Biome, or a unique BiomeType. - * The Biome Source will call {@link BiomeDecider#canProvideBiome(BiomeAPI.BiomeType)} with the finally chosen type - * for all available Deciders. - */ - public abstract BiomeAPI.BiomeType suggestType( - BiomeAPI.BiomeType originalType, - BiomeAPI.BiomeType suggestedType, - double density, - int maxHeight, - int blockX, - int blockY, - int blockZ, - int quarterX, - int quarterY, - int quarterZ - ); - - - /** - * Called to check if this decider can place a biome for the specified type - * - * @param suggestedType The type of biome we need to place - * @return true, if this type of biome can be provided by the current picker. If true - * is returned, the BiomeSource will call {@link BiomeDecider#provideBiome(BiomeAPI.BiomeType, int, int, int)} - * next - */ - public abstract boolean canProvideBiome(BiomeAPI.BiomeType suggestedType); - - /** - * Called to check if this decider can place a biome for the specified type - *

- * The default implementation will return map.getBiome(posX, posY, posZ) - * - * @param suggestedType The type of biome we need to place - * @return The methode should return a Biome from its {@link BiomeMap}. If null is returned, the next - * decider (or the default map) will provide the biome - */ - public BiomePicker.ActualBiome provideBiome(BiomeAPI.BiomeType suggestedType, int posX, int posY, int posZ) { - return map.getBiome(posX, posY, posZ); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/BiomePicker.java b/src/main/java/org/betterx/bclib/api/v2/generator/BiomePicker.java deleted file mode 100644 index 550d467e..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/BiomePicker.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; -import org.betterx.bclib.util.WeighTree; -import org.betterx.bclib.util.WeightedList; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.levelgen.WorldgenRandom; - -import com.google.common.collect.Lists; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public class BiomePicker { - private final Map all = new HashMap<>(); - public final Registry biomeRegistry; - private final List biomes = Lists.newArrayList(); - private final List allowedBiomes; - public final ActualBiome fallbackBiome; - private WeighTree tree; - - public BiomePicker(Registry biomeRegistry) { - this(biomeRegistry, null); - } - - public BiomePicker(Registry biomeRegistry, List> allowedBiomes) { - this.biomeRegistry = biomeRegistry; - this.allowedBiomes = allowedBiomes != null ? allowedBiomes - .stream() - .map(h -> h.unwrapKey()) - .filter(o -> o.isPresent()) - .map(o -> o.get().location().toString()).toList() : null; - this.fallbackBiome = create(BCLBiomeRegistry.EMPTY_BIOME); - } - - private boolean isAllowed(BCLBiome b) { - if (allowedBiomes == null) return true; - return allowedBiomes.contains(b.getID().toString()); - } - - private ActualBiome create(BCLBiome bclBiome) { - ActualBiome e = all.get(bclBiome); - if (e != null) return e; - return new ActualBiome(bclBiome); - } - - public void addBiome(BCLBiome biome) { - biomes.add(create(biome)); - } - - public ActualBiome getBiome(WorldgenRandom random) { - return biomes.isEmpty() ? fallbackBiome : tree.get(random); - } - - public boolean isEmpty() { - return biomes.isEmpty(); - } - - public void rebuild() { - WeightedList list = new WeightedList<>(); - - biomes.forEach(biome -> { - if (biome.isValid) - list.add(biome, biome.bclBiome.getGenChance()); - }); - //only a single biome, we need to add the edges as well - if (list.size() == 1) { - ActualBiome biome = list.get(0); - - if (biome.getEdge() != null) { - float defaultBiomeSize = 128; - float edgeSize = (biome.bclBiome.getEdgeSize() * list.getWeight(0)) / defaultBiomeSize; - list.add(biome.getEdge(), edgeSize); - } - } - - //no Biome, make sure we add at least one, otherwise bad things will happen - if (list.isEmpty()) { - list.add(create(BCLBiomeRegistry.EMPTY_BIOME), 1); - } - - - tree = new WeighTree<>(list); - } - - public class ActualBiome { - public final BCLBiome bclBiome; - public final Holder biome; - public final ResourceKey key; - - private final WeightedList subbiomes = new WeightedList<>(); - private final ActualBiome edge; - private final ActualBiome parent; - public final boolean isValid; - - private ActualBiome(BCLBiome bclBiome) { - all.put(bclBiome, this); - this.bclBiome = bclBiome; - - this.key = biomeRegistry.getResourceKey(biomeRegistry.get(bclBiome.getID())).orElse(null); - this.biome = key != null ? biomeRegistry.getOrCreateHolderOrThrow(key) : null; - this.isValid = key != null && biome != null && biome.isBound(); - bclBiome.forEachSubBiome((b, w) -> { - if (isAllowed(b)) - subbiomes.add(create(b), w); - }); - - if (bclBiome.getEdge() != null && isAllowed(bclBiome.getEdge())) { - edge = create(bclBiome.getEdge()); - } else { - edge = null; - } - - parent = bclBiome.getParentBiome() != null ? create(bclBiome.getParentBiome()) : null; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ActualBiome entry = (ActualBiome) o; - return bclBiome.equals(entry.bclBiome); - } - - @Override - public int hashCode() { - return Objects.hash(bclBiome); - } - - public ActualBiome getSubBiome(WorldgenRandom random) { - return subbiomes.get(random); - } - - public ActualBiome getEdge() { - return edge; - } - - public ActualBiome getParentBiome() { - return parent; - } - - public boolean isSame(ActualBiome e) { - return bclBiome.isSame(e.bclBiome); - } - - @Override - public String toString() { - return "ActualBiome{" + - "key=" + key.location() + - ", subbiomes=" + subbiomes.size() + - ", edge=" + (edge != null ? edge.key.location() : "null") + - ", parent=" + (parent != null ? parent.key.location() : "null") + - ", isValid=" + isValid + - '}'; - } - } - - @Override - public String toString() { - return "BiomePicker{" + - "biomes=" + biomes.size() + " (" + all.size() + ")" + - ", biomeRegistry=" + biomeRegistry + - ", type=" + super.toString() + - '}'; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/BiomeType.java b/src/main/java/org/betterx/bclib/api/v2/generator/BiomeType.java deleted file mode 100644 index 8bfb3789..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/BiomeType.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -public enum BiomeType { - LAND, VOID -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/GeneratorOptions.java b/src/main/java/org/betterx/bclib/api/v2/generator/GeneratorOptions.java deleted file mode 100644 index 2c68c7ae..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/GeneratorOptions.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.config.Configs; - -public class GeneratorOptions { - //private static BiFunction endLandFunction; - private static boolean fixEndBiomeSource = true; - private static boolean fixNetherBiomeSource = true; - - public static void init() { - fixEndBiomeSource = Configs.GENERATOR_CONFIG.getBoolean("options.biomeSource", "fixEndBiomeSource", true); - fixNetherBiomeSource = Configs.GENERATOR_CONFIG.getBoolean("options.biomeSource", "fixNetherBiomeSource", true); - } - - public static boolean fixEndBiomeSource() { - return fixEndBiomeSource; - } - - public static boolean fixNetherBiomeSource() { - return fixNetherBiomeSource; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/TheEndBiomesHelper.java b/src/main/java/org/betterx/bclib/api/v2/generator/TheEndBiomesHelper.java deleted file mode 100644 index 93fe1d91..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/TheEndBiomesHelper.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; - -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; -import org.jetbrains.annotations.ApiStatus; - - -/** - * Helper class until FAPI integrates this PR - */ -public class TheEndBiomesHelper { - @ApiStatus.Internal - private static Map>> END_BIOMES = new HashMap<>(); - - @ApiStatus.Internal - public static void add(BiomeAPI.BiomeType type, ResourceKey biome) { - if (biome == null) return; - END_BIOMES.computeIfAbsent(type, t -> new HashSet<>()).add(biome); - } - - private static boolean has(BiomeAPI.BiomeType type, ResourceKey biome) { - if (biome == null) return false; - Set> set = END_BIOMES.get(type); - if (set == null) return false; - return set.contains(biome); - } - - /** - * Returns true if the given biome was added as a main end Biome in the end, considering the Vanilla end biomes, - * and any biomes added to the End by mods. - * - * @param biome The biome to search for - */ - public static boolean canGenerateAsMainIslandBiome(ResourceKey biome) { - return has(BiomeAPI.BiomeType.END_CENTER, biome); - } - - /** - * Returns true if the given biome was added as a small end islands Biome in the end, considering the Vanilla end biomes, - * and any biomes added to the End by mods. - * - * @param biome The biome to search for - */ - public static boolean canGenerateAsSmallIslandsBiome(ResourceKey biome) { - return has(BiomeAPI.BiomeType.END_VOID, biome); - } - - /** - * Returns true if the given biome was added as a Highland Biome in the end, considering the Vanilla end biomes, - * and any biomes added to the End by mods. - * - * @param biome The biome to search for - */ - public static boolean canGenerateAsHighlandsBiome(ResourceKey biome) { - return has(BiomeAPI.BiomeType.END_LAND, biome); - } - - /** - * Returns true if the given biome was added as midland biome in the end, considering the Vanilla end biomes, - * and any biomes added to the End as midland biome by mods. - * - * @param biome The biome to search for - */ - public static boolean canGenerateAsEndMidlands(ResourceKey biome) { - return false; - } - - /** - * Returns true if the given biome was added as barrens biome in the end, considering the Vanilla end biomes, - * and any biomes added to the End as barrens biome by mods. - * - * @param biome The biome to search for - */ - public static boolean canGenerateAsEndBarrens(ResourceKey biome) { - return has(BiomeAPI.BiomeType.END_BARRENS, biome); - } - - public static boolean canGenerateInEnd(ResourceKey biome) { - return canGenerateAsHighlandsBiome(biome) - || canGenerateAsEndBarrens(biome) - || canGenerateAsEndMidlands(biome) - || canGenerateAsSmallIslandsBiome(biome) - || canGenerateAsMainIslandBiome(biome); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/TypeBiomeDecider.java b/src/main/java/org/betterx/bclib/api/v2/generator/TypeBiomeDecider.java deleted file mode 100644 index 559de7d2..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/TypeBiomeDecider.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.api.v2.generator; - -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; - -import net.minecraft.core.Registry; -import net.minecraft.world.level.biome.Biome; - -public abstract class TypeBiomeDecider extends BiomeDecider { - protected final BiomeAPI.BiomeType assignedType; - - public TypeBiomeDecider(BiomeAPI.BiomeType assignedType) { - this(null, assignedType); - } - - protected TypeBiomeDecider(Registry biomeRegistry, BiomeAPI.BiomeType assignedType) { - super(biomeRegistry, (biome) -> biome.getIntendedType().is(assignedType)); - this.assignedType = assignedType; - } - - @Override - public boolean canProvideBiome(BiomeAPI.BiomeType suggestedType) { - return suggestedType.equals(assignedType); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/config/BCLEndBiomeSourceConfig.java b/src/main/java/org/betterx/bclib/api/v2/generator/config/BCLEndBiomeSourceConfig.java deleted file mode 100644 index 0a76e88d..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/config/BCLEndBiomeSourceConfig.java +++ /dev/null @@ -1,213 +0,0 @@ -package org.betterx.bclib.api.v2.generator.config; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.generator.BCLibEndBiomeSource; -import org.betterx.bclib.api.v2.generator.map.hex.HexBiomeMap; -import org.betterx.bclib.api.v2.generator.map.square.SquareBiomeMap; -import org.betterx.worlds.together.biomesource.config.BiomeSourceConfig; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.util.Mth; -import net.minecraft.util.StringRepresentable; - -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -public class BCLEndBiomeSourceConfig implements BiomeSourceConfig { - public static final BCLEndBiomeSourceConfig VANILLA = new BCLEndBiomeSourceConfig( - EndBiomeMapType.VANILLA, - EndBiomeGeneratorType.VANILLA, - true, - 4096, - 128, - 128, - 128, - 128 - ); - public static final BCLEndBiomeSourceConfig MINECRAFT_17 = new BCLEndBiomeSourceConfig( - EndBiomeMapType.SQUARE, - EndBiomeGeneratorType.PAULEVS, - true, - VANILLA.innerVoidRadiusSquared * 16 * 16, - 256, - 256, - 256, - 256 - ); - public static final BCLEndBiomeSourceConfig MINECRAFT_18 = new BCLEndBiomeSourceConfig( - EndBiomeMapType.HEX, - BCLib.RUNS_NULLSCAPE ? EndBiomeGeneratorType.VANILLA : EndBiomeGeneratorType.PAULEVS, - BCLib.RUNS_NULLSCAPE ? false : true, - MINECRAFT_17.innerVoidRadiusSquared, - MINECRAFT_17.centerBiomesSize, - MINECRAFT_17.voidBiomesSize, - MINECRAFT_17.landBiomesSize, - MINECRAFT_17.barrensBiomesSize - ); - public static final BCLEndBiomeSourceConfig DEFAULT = MINECRAFT_18; - - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - EndBiomeMapType.CODEC - .fieldOf("map_type") - .orElse(DEFAULT.mapVersion) - .forGetter(o -> o.mapVersion), - EndBiomeGeneratorType.CODEC - .fieldOf("generator_version") - .orElse(DEFAULT.generatorVersion) - .forGetter(o -> o.generatorVersion), - Codec.BOOL - .fieldOf("with_void_biomes") - .orElse(DEFAULT.withVoidBiomes) - .forGetter(o -> o.withVoidBiomes), - Codec.INT - .fieldOf("inner_void_radius_squared") - .orElse(DEFAULT.innerVoidRadiusSquared) - .forGetter(o -> o.innerVoidRadiusSquared), - Codec.INT - .fieldOf("center_biomes_size") - .orElse(DEFAULT.centerBiomesSize) - .forGetter(o -> o.centerBiomesSize), - Codec.INT - .fieldOf("void_biomes_size") - .orElse(DEFAULT.voidBiomesSize) - .forGetter(o -> o.voidBiomesSize), - Codec.INT - .fieldOf("land_biomes_size") - .orElse(DEFAULT.landBiomesSize) - .forGetter(o -> o.landBiomesSize), - Codec.INT - .fieldOf("barrens_biomes_size") - .orElse(DEFAULT.barrensBiomesSize) - .forGetter(o -> o.barrensBiomesSize) - ) - .apply(instance, BCLEndBiomeSourceConfig::new)); - - public BCLEndBiomeSourceConfig( - @NotNull EndBiomeMapType mapVersion, - @NotNull EndBiomeGeneratorType generatorVersion, - boolean withVoidBiomes, - int innerVoidRadiusSquared, - int centerBiomesSize, - int voidBiomesSize, - int landBiomesSize, - int barrensBiomesSize - ) { - this.mapVersion = mapVersion; - this.generatorVersion = generatorVersion; - this.withVoidBiomes = withVoidBiomes; - this.innerVoidRadiusSquared = innerVoidRadiusSquared; - this.barrensBiomesSize = Mth.clamp(barrensBiomesSize, 1, 8192); - this.voidBiomesSize = Mth.clamp(voidBiomesSize, 1, 8192); - this.centerBiomesSize = Mth.clamp(centerBiomesSize, 1, 8192); - this.landBiomesSize = Mth.clamp(landBiomesSize, 1, 8192); - } - - public enum EndBiomeMapType implements StringRepresentable { - VANILLA("vanilla", (seed, biomeSize, picker) -> new HexBiomeMap(seed, biomeSize, picker)), - SQUARE("square", (seed, biomeSize, picker) -> new SquareBiomeMap(seed, biomeSize, picker)), - HEX("hex", (seed, biomeSize, picker) -> new HexBiomeMap(seed, biomeSize, picker)); - - public static final Codec CODEC = StringRepresentable.fromEnum(EndBiomeMapType::values); - public final String name; - public final @NotNull MapBuilderFunction mapBuilder; - - EndBiomeMapType(String name, @NotNull MapBuilderFunction mapBuilder) { - this.name = name; - this.mapBuilder = mapBuilder; - } - - @Override - public String getSerializedName() { - return name; - } - - @Override - public String toString() { - return name; - } - } - - public enum EndBiomeGeneratorType implements StringRepresentable { - VANILLA("vanilla"), - PAULEVS("paulevs"); - - public static final Codec CODEC = StringRepresentable.fromEnum(EndBiomeGeneratorType::values); - public final String name; - - EndBiomeGeneratorType(String name) { - this.name = name; - } - - @Override - public String getSerializedName() { - return name; - } - - @Override - public String toString() { - return name; - } - } - - - public final @NotNull EndBiomeMapType mapVersion; - public final @NotNull EndBiomeGeneratorType generatorVersion; - public final boolean withVoidBiomes; - public final int innerVoidRadiusSquared; - - public final int voidBiomesSize; - public final int centerBiomesSize; - public final int landBiomesSize; - public final int barrensBiomesSize; - - @Override - public String toString() { - return "BCLEndBiomeSourceConfig{" + - "mapVersion=" + mapVersion + - ", generatorVersion=" + generatorVersion + - ", withVoidBiomes=" + withVoidBiomes + - ", innerVoidRadiusSquared=" + innerVoidRadiusSquared + - ", voidBiomesSize=" + voidBiomesSize + - ", centerBiomesSize=" + centerBiomesSize + - ", landBiomesSize=" + landBiomesSize + - ", barrensBiomesSize=" + barrensBiomesSize + - '}'; - } - - @Override - public boolean couldSetWithoutRepair(BiomeSourceConfig input) { - if (input instanceof BCLEndBiomeSourceConfig cfg) { - return withVoidBiomes == cfg.withVoidBiomes && mapVersion == cfg.mapVersion && generatorVersion == cfg.generatorVersion; - } - return false; - } - - @Override - public boolean sameConfig(BiomeSourceConfig input) { - return this.equals(input); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - BCLEndBiomeSourceConfig that = (BCLEndBiomeSourceConfig) o; - return withVoidBiomes == that.withVoidBiomes && innerVoidRadiusSquared == that.innerVoidRadiusSquared && voidBiomesSize == that.voidBiomesSize && centerBiomesSize == that.centerBiomesSize && landBiomesSize == that.landBiomesSize && barrensBiomesSize == that.barrensBiomesSize && mapVersion == that.mapVersion && generatorVersion == that.generatorVersion; - } - - @Override - public int hashCode() { - return Objects.hash( - mapVersion, - generatorVersion, - withVoidBiomes, - innerVoidRadiusSquared, - voidBiomesSize, - centerBiomesSize, - landBiomesSize, - barrensBiomesSize - ); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/config/BCLNetherBiomeSourceConfig.java b/src/main/java/org/betterx/bclib/api/v2/generator/config/BCLNetherBiomeSourceConfig.java deleted file mode 100644 index 4d8c5249..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/config/BCLNetherBiomeSourceConfig.java +++ /dev/null @@ -1,127 +0,0 @@ -package org.betterx.bclib.api.v2.generator.config; - -import org.betterx.bclib.api.v2.generator.BCLibNetherBiomeSource; -import org.betterx.bclib.api.v2.generator.map.hex.HexBiomeMap; -import org.betterx.bclib.api.v2.generator.map.square.SquareBiomeMap; -import org.betterx.worlds.together.biomesource.config.BiomeSourceConfig; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.util.Mth; -import net.minecraft.util.StringRepresentable; - -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -public class BCLNetherBiomeSourceConfig implements BiomeSourceConfig { - public static final BCLNetherBiomeSourceConfig VANILLA = new BCLNetherBiomeSourceConfig( - NetherBiomeMapType.VANILLA, - 256, - 86, - false - ); - public static final BCLNetherBiomeSourceConfig MINECRAFT_17 = new BCLNetherBiomeSourceConfig( - NetherBiomeMapType.SQUARE, - 256, - 86, - true - ); - public static final BCLNetherBiomeSourceConfig MINECRAFT_18 = new BCLNetherBiomeSourceConfig( - NetherBiomeMapType.HEX, - MINECRAFT_17.biomeSize, - MINECRAFT_17.biomeSizeVertical, - MINECRAFT_17.useVerticalBiomes - ); - public static final BCLNetherBiomeSourceConfig DEFAULT = MINECRAFT_18; - - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - BCLNetherBiomeSourceConfig.NetherBiomeMapType.CODEC - .fieldOf("map_type") - .orElse(DEFAULT.mapVersion) - .forGetter(o -> o.mapVersion), - Codec.INT.fieldOf("biome_size").orElse(DEFAULT.biomeSize).forGetter(o -> o.biomeSize), - Codec.INT.fieldOf("biome_size_vertical") - .orElse(DEFAULT.biomeSizeVertical) - .forGetter(o -> o.biomeSizeVertical), - Codec.BOOL.fieldOf("use_vertical_biomes") - .orElse(DEFAULT.useVerticalBiomes) - .forGetter(o -> o.useVerticalBiomes) - ) - .apply(instance, BCLNetherBiomeSourceConfig::new)); - public final @NotNull NetherBiomeMapType mapVersion; - public final int biomeSize; - public final int biomeSizeVertical; - - public final boolean useVerticalBiomes; - - public BCLNetherBiomeSourceConfig( - @NotNull NetherBiomeMapType mapVersion, - int biomeSize, - int biomeSizeVertical, - boolean useVerticalBiomes - ) { - this.mapVersion = mapVersion; - this.biomeSize = Mth.clamp(biomeSize, 1, 8192); - this.biomeSizeVertical = Mth.clamp(biomeSizeVertical, 1, 8192); - this.useVerticalBiomes = useVerticalBiomes; - } - - @Override - public String toString() { - return "BCLibNetherBiomeSourceConfig{" + - "mapVersion=" + mapVersion + - '}'; - } - - @Override - public boolean couldSetWithoutRepair(BiomeSourceConfig input) { - if (input instanceof BCLNetherBiomeSourceConfig cfg) { - return mapVersion == cfg.mapVersion; - } - return false; - } - - @Override - public boolean sameConfig(BiomeSourceConfig input) { - return this.equals(input); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof BCLNetherBiomeSourceConfig)) return false; - BCLNetherBiomeSourceConfig that = (BCLNetherBiomeSourceConfig) o; - return mapVersion == that.mapVersion; - } - - @Override - public int hashCode() { - return Objects.hash(mapVersion); - } - - public enum NetherBiomeMapType implements StringRepresentable { - VANILLA("vanilla", (seed, biomeSize, picker) -> new HexBiomeMap(seed, biomeSize, picker)), - SQUARE("square", (seed, biomeSize, picker) -> new SquareBiomeMap(seed, biomeSize, picker)), - HEX("hex", (seed, biomeSize, picker) -> new HexBiomeMap(seed, biomeSize, picker)); - - public static final Codec CODEC = StringRepresentable.fromEnum(NetherBiomeMapType::values); - public final String name; - public final MapBuilderFunction mapBuilder; - - NetherBiomeMapType(String name, MapBuilderFunction mapBuilder) { - this.name = name; - this.mapBuilder = mapBuilder; - } - - @Override - public String getSerializedName() { - return name; - } - - @Override - public String toString() { - return name; - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/config/MapBuilderFunction.java b/src/main/java/org/betterx/bclib/api/v2/generator/config/MapBuilderFunction.java deleted file mode 100644 index cfb9e206..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/config/MapBuilderFunction.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.api.v2.generator.config; - -import org.betterx.bclib.api.v2.generator.BiomePicker; -import org.betterx.bclib.interfaces.BiomeMap; - -@FunctionalInterface -public interface MapBuilderFunction { - BiomeMap create(long seed, int biomeSize, BiomePicker picker); -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/map/MapStack.java b/src/main/java/org/betterx/bclib/api/v2/generator/map/MapStack.java deleted file mode 100644 index 74dbb00f..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/map/MapStack.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.betterx.bclib.api.v2.generator.map; - -import org.betterx.bclib.api.v2.generator.BiomePicker; -import org.betterx.bclib.api.v2.generator.config.MapBuilderFunction; -import org.betterx.bclib.interfaces.BiomeChunk; -import org.betterx.bclib.interfaces.BiomeMap; -import org.betterx.bclib.interfaces.TriConsumer; -import org.betterx.bclib.noise.OpenSimplexNoise; - -import net.minecraft.util.Mth; - -import java.util.Random; - -public class MapStack implements BiomeMap { - private final OpenSimplexNoise noise; - private final BiomeMap[] maps; - private final double layerDistortion; - private final int worldHeight; - private final int minValue; - private final int maxValue; - private final int maxIndex; - - public MapStack( - long seed, - int size, - BiomePicker picker, - int mapHeight, - int worldHeight, - MapBuilderFunction mapConstructor - ) { - final int mapCount = Mth.ceil((float) worldHeight / mapHeight); - this.maxIndex = mapCount - 1; - this.worldHeight = worldHeight; - this.layerDistortion = mapHeight * 0.1; - minValue = Mth.floor(mapHeight * 0.5F + 0.5F); - maxValue = Mth.floor(worldHeight - mapHeight * 0.5F + 0.5F); - maps = new BiomeMap[mapCount]; - Random random = new Random(seed); - for (int i = 0; i < mapCount; i++) { - maps[i] = mapConstructor.create(random.nextLong(), size, picker); - maps[i].setChunkProcessor(this::onChunkCreation); - } - noise = new OpenSimplexNoise(random.nextInt()); - } - - @Override - public void clearCache() { - for (BiomeMap map : maps) { - map.clearCache(); - } - } - - @Override - public void setChunkProcessor(TriConsumer processor) { - } - - @Override - public BiomeChunk getChunk(int cx, int cz, boolean update) { - return null; - } - - @Override - public BiomePicker.ActualBiome getBiome(double x, double y, double z) { - int mapIndex; - - if (y < minValue) { - mapIndex = 0; - } else if (y > maxValue) { - mapIndex = maxIndex; - } else { - mapIndex = Mth.floor((y + noise.eval( - x * 0.03, - z * 0.03 - ) * layerDistortion) / worldHeight * maxIndex + 0.5F); - mapIndex = Mth.clamp(mapIndex, 0, maxIndex); - } - - return maps[mapIndex].getBiome(x, y, z); - } - - private void onChunkCreation(int cx, int cz, int side) { - BiomePicker.ActualBiome[][] biomeMap = new BiomePicker.ActualBiome[side][side]; - BiomeChunk[] chunks = new BiomeChunk[maps.length]; - - boolean isNoEmpty = false; - for (int i = 0; i < maps.length; i++) { - chunks[i] = maps[i].getChunk(cx, cz, false); - for (int x = 0; x < side; x++) { - for (int z = 0; z < side; z++) { - if (biomeMap[x][z] == null) { - BiomePicker.ActualBiome biome = chunks[i].getBiome(x, z); - if (biome.bclBiome.isVertical()) { - biomeMap[x][z] = biome; - isNoEmpty = true; - } - } - } - } - } - - if (isNoEmpty) { - for (int i = 0; i < maps.length; i++) { - for (int x = 0; x < side; x++) { - for (int z = 0; z < side; z++) { - if (biomeMap[x][z] != null) { - chunks[i].setBiome(x, z, biomeMap[x][z]); - } - } - } - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/map/hex/HexBiomeChunk.java b/src/main/java/org/betterx/bclib/api/v2/generator/map/hex/HexBiomeChunk.java deleted file mode 100644 index 5332c128..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/map/hex/HexBiomeChunk.java +++ /dev/null @@ -1,160 +0,0 @@ -package org.betterx.bclib.api.v2.generator.map.hex; - -import org.betterx.bclib.api.v2.generator.BiomePicker; -import org.betterx.bclib.interfaces.BiomeChunk; - -import net.minecraft.world.level.levelgen.WorldgenRandom; - -import java.util.Arrays; - -public class HexBiomeChunk implements BiomeChunk { - private static final short SIDE = 32; - private static final byte SIDE_PRE = 4; - private static final short SIZE = SIDE * SIDE; - private static final short MAX_SIDE = SIZE - SIDE; - private static final byte SCALE_PRE = SIDE / SIDE_PRE; - private static final byte SIZE_PRE = SIDE_PRE * SIDE_PRE; - private static final byte SIDE_MASK = SIDE - 1; - private static final byte SIDE_PRE_MASK = SIDE_PRE - 1; - private static final byte SIDE_OFFSET = (byte) Math.round(Math.log(SIDE) / Math.log(2)); - private static final byte SIDE_PRE_OFFSET = (byte) Math.round(Math.log(SIDE_PRE) / Math.log(2)); - private static final short[][] NEIGHBOURS; - - private final BiomePicker.ActualBiome[] biomes = new BiomePicker.ActualBiome[SIZE]; - - public HexBiomeChunk(WorldgenRandom random, BiomePicker picker) { - BiomePicker.ActualBiome[][] buffers = new BiomePicker.ActualBiome[2][SIZE]; - - for (BiomePicker.ActualBiome[] buffer : buffers) { - Arrays.fill(buffer, null); - } - - for (byte index = 0; index < SIZE_PRE; index++) { - byte px = (byte) (index >> SIDE_PRE_OFFSET); - byte pz = (byte) (index & SIDE_PRE_MASK); - px = (byte) (px * SCALE_PRE + random.nextInt(SCALE_PRE)); - pz = (byte) (pz * SCALE_PRE + random.nextInt(SCALE_PRE)); - circle(buffers[0], getIndex(px, pz), picker.getBiome(random), null); - } - - boolean hasEmptyCells = true; - byte bufferIndex = 0; - while (hasEmptyCells) { - BiomePicker.ActualBiome[] inBuffer = buffers[bufferIndex]; - bufferIndex = (byte) ((bufferIndex + 1) & 1); - BiomePicker.ActualBiome[] outBuffer = buffers[bufferIndex]; - hasEmptyCells = false; - - for (short index = SIDE; index < MAX_SIDE; index++) { - byte z = (byte) (index & SIDE_MASK); - if (z == 0 || z == SIDE_MASK) { - continue; - } - if (inBuffer[index] != null) { - outBuffer[index] = inBuffer[index]; - short[] neighbours = getNeighbours(index & SIDE_MASK); - short indexSide = (short) (index + neighbours[random.nextInt(6)]); - if (indexSide >= 0 && indexSide < SIZE && outBuffer[indexSide] == null) { - outBuffer[indexSide] = inBuffer[index]; - } - } else { - hasEmptyCells = true; - } - } - } - - BiomePicker.ActualBiome[] outBuffer = buffers[bufferIndex]; - byte preN = (byte) (SIDE_MASK - 2); - for (byte index = 0; index < SIDE; index++) { - outBuffer[getIndex(index, (byte) 0)] = outBuffer[getIndex(index, (byte) 2)]; - outBuffer[getIndex((byte) 0, index)] = outBuffer[getIndex((byte) 2, index)]; - outBuffer[getIndex(index, SIDE_MASK)] = outBuffer[getIndex(index, preN)]; - outBuffer[getIndex(SIDE_MASK, index)] = outBuffer[getIndex(preN, index)]; - } - - for (short index = 0; index < SIZE; index++) { - if (outBuffer[index] == null) { - outBuffer[index] = picker.getBiome(random); - } else if (random.nextInt(4) == 0) { - circle(outBuffer, index, outBuffer[index].getSubBiome(random), outBuffer[index]); - } - } - - System.arraycopy(outBuffer, 0, this.biomes, 0, SIZE); - } - - private void circle( - BiomePicker.ActualBiome[] buffer, - short center, - BiomePicker.ActualBiome biome, - BiomePicker.ActualBiome mask - ) { - if (buffer[center] == mask) { - buffer[center] = biome; - } - short[] neighbours = getNeighbours(center & SIDE_MASK); - for (short i : neighbours) { - short index = (short) (center + i); - if (index >= 0 && index < SIZE && buffer[index] == mask) { - buffer[index] = biome; - } - } - } - - private static byte wrap(int value) { - return (byte) (value & SIDE_MASK); - } - - private short getIndex(byte x, byte z) { - return (short) ((short) x << SIDE_OFFSET | z); - } - - @Override - public BiomePicker.ActualBiome getBiome(int x, int z) { - return biomes[getIndex(wrap(x), wrap(z))]; - } - - @Override - public void setBiome(int x, int z, BiomePicker.ActualBiome biome) { - biomes[getIndex(wrap(x), wrap(z))] = biome; - } - - @Override - public int getSide() { - return SIDE; - } - - public static int scaleCoordinate(int value) { - return value >> SIDE_OFFSET; - } - - public static boolean isBorder(int value) { - return wrap(value) == SIDE_MASK; - } - - private short[] getNeighbours(int z) { - return NEIGHBOURS[z & 1]; - } - - public static float scaleMap(float size) { - return size / (SIDE >> 2); - } - - static { - NEIGHBOURS = new short[2][6]; - - NEIGHBOURS[0][0] = 1; - NEIGHBOURS[0][1] = -1; - NEIGHBOURS[0][2] = SIDE; - NEIGHBOURS[0][3] = -SIDE; - NEIGHBOURS[0][4] = SIDE + 1; - NEIGHBOURS[0][5] = SIDE - 1; - - NEIGHBOURS[1][0] = 1; - NEIGHBOURS[1][1] = -1; - NEIGHBOURS[1][2] = SIDE; - NEIGHBOURS[1][3] = -SIDE; - NEIGHBOURS[1][4] = -SIDE + 1; - NEIGHBOURS[1][5] = -SIDE - 1; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/map/hex/HexBiomeMap.java b/src/main/java/org/betterx/bclib/api/v2/generator/map/hex/HexBiomeMap.java deleted file mode 100644 index 713f7fe2..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/map/hex/HexBiomeMap.java +++ /dev/null @@ -1,187 +0,0 @@ -package org.betterx.bclib.api.v2.generator.map.hex; - -import org.betterx.bclib.api.v2.generator.BiomePicker; -import org.betterx.bclib.interfaces.BiomeChunk; -import org.betterx.bclib.interfaces.BiomeMap; -import org.betterx.bclib.interfaces.TriConsumer; -import org.betterx.bclib.noise.OpenSimplexNoise; -import org.betterx.bclib.util.MHelper; - -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.levelgen.WorldgenRandom; - -import com.google.common.collect.Maps; - -import java.util.Map; -import java.util.Random; - -public class HexBiomeMap implements BiomeMap { - private static final float RAD_INNER = (float) Math.sqrt(3.0) * 0.5F; - private static final float COEF = 0.25F * (float) Math.sqrt(3.0); - private static final float COEF_HALF = COEF * 0.5F; - private static final float SIN = (float) Math.sin(0.4); - private static final float COS = (float) Math.cos(0.4); - private static final float[] EDGE_CIRCLE_X; - private static final float[] EDGE_CIRCLE_Z; - - private final Map chunks = Maps.newConcurrentMap(); - private final BiomePicker picker; - - private final OpenSimplexNoise[] noises = new OpenSimplexNoise[2]; - private TriConsumer processor; - private final byte noiseIterations; - private final float scale; - private final int seed; - - public HexBiomeMap(long seed, int size, BiomePicker picker) { - this.picker = picker; - this.scale = HexBiomeChunk.scaleMap(size); - Random random = new Random(seed); - - noises[0] = new OpenSimplexNoise(random.nextInt()); - noises[1] = new OpenSimplexNoise(random.nextInt()); - noiseIterations = (byte) Math.min(Math.ceil(Math.log(scale) / Math.log(2)), 5); - this.seed = random.nextInt(); - } - - @Override - public void clearCache() { - if (chunks.size() > 127) { - chunks.clear(); - } - } - - @Override - public BiomePicker.ActualBiome getBiome(double x, double y, double z) { - BiomePicker.ActualBiome biome = getRawBiome(x, z); - BiomePicker.ActualBiome edge = biome.getEdge(); - int size = biome.bclBiome.getEdgeSize(); - - if (edge == null && biome.getParentBiome() != null) { - edge = biome.getParentBiome().getEdge(); - size = biome.getParentBiome().bclBiome.getEdgeSize(); - } - - if (edge == null) { - return biome; - } - - for (byte i = 0; i < 8; i++) { - if (!getRawBiome(x + size * EDGE_CIRCLE_X[i], z + size * EDGE_CIRCLE_Z[i]).isSame(biome)) { - return edge; - } - } - - return biome; - } - - @Override - public BiomeChunk getChunk(final int cx, final int cz, final boolean update) { - final ChunkPos pos = new ChunkPos(cx, cz); - HexBiomeChunk chunk = chunks.get(pos); - if (chunk == null) { - WorldgenRandom random = new WorldgenRandom(RandomSource.create(MHelper.getSeed(seed, cx, cz))); - chunk = new HexBiomeChunk(random, picker); - if (update && processor != null) { - processor.accept(cx, cz, chunk.getSide()); - } - chunks.put(pos, chunk); - } - return chunk; - } - - @Override - public void setChunkProcessor(TriConsumer processor) { - this.processor = processor; - } - - private BiomePicker.ActualBiome getRawBiome(double x, double z) { - double px = x / scale * RAD_INNER; - double pz = z / scale; - double dx = rotateX(px, pz); - double dz = rotateZ(px, pz); - px = dx; - pz = dz; - - dx = getNoise(px, pz, (byte) 0) * 0.2F; - dz = getNoise(pz, px, (byte) 1) * 0.2F; - px += dx; - pz += dz; - - int cellZ = (int) Math.floor(pz); - boolean offset = (cellZ & 1) == 1; - - if (offset) { - px += 0.5; - } - - int cellX = (int) Math.floor(px); - - float pointX = (float) (px - cellX - 0.5); - float pointZ = (float) (pz - cellZ - 0.5); - - if (Math.abs(pointZ) < 0.3333F) { - return getChunkBiome(cellX, cellZ); - } - - if (insideHexagon(0, 0, 1.1555F, pointZ * RAD_INNER, pointX)) { - return getChunkBiome(cellX, cellZ); - } - - cellX = pointX < 0 ? (offset ? cellX - 1 : cellX) : (offset ? cellX : cellX + 1); - cellZ = pointZ < 0 ? cellZ - 1 : cellZ + 1; - - return getChunkBiome(cellX, cellZ); - } - - private BiomePicker.ActualBiome getChunkBiome(int x, int z) { - int cx = HexBiomeChunk.scaleCoordinate(x); - int cz = HexBiomeChunk.scaleCoordinate(z); - - if (((z >> 2) & 1) == 0 && HexBiomeChunk.isBorder(x)) { - x = 0; - cx += 1; - } else if (((x >> 2) & 1) == 0 && HexBiomeChunk.isBorder(z)) { - z = 0; - cz += 1; - } - - return getChunk(cx, cz, true).getBiome(x, z); - } - - private boolean insideHexagon(float centerX, float centerZ, float radius, float x, float z) { - double dx = Math.abs(x - centerX) / radius; - double dy = Math.abs(z - centerZ) / radius; - return (dy <= COEF) && (COEF * dx + 0.25F * dy <= COEF_HALF); - } - - private double getNoise(double x, double z, byte state) { - double result = 0; - for (byte i = 1; i <= noiseIterations; i++) { - OpenSimplexNoise noise = noises[state]; - state = (byte) ((state + 1) & 1); - result += noise.eval(x * i, z * i) / i; - } - return result; - } - - private double rotateX(double x, double z) { - return x * COS - z * SIN; - } - - private double rotateZ(double x, double z) { - return x * SIN + z * COS; - } - - static { - EDGE_CIRCLE_X = new float[8]; - EDGE_CIRCLE_Z = new float[8]; - - for (byte i = 0; i < 8; i++) { - float angle = i / 4F * (float) Math.PI; - EDGE_CIRCLE_X[i] = (float) Math.sin(angle); - EDGE_CIRCLE_Z[i] = (float) Math.cos(angle); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/map/square/SquareBiomeChunk.java b/src/main/java/org/betterx/bclib/api/v2/generator/map/square/SquareBiomeChunk.java deleted file mode 100644 index a9df57a3..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/map/square/SquareBiomeChunk.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.betterx.bclib.api.v2.generator.map.square; - -import org.betterx.bclib.api.v2.generator.BiomePicker; -import org.betterx.bclib.interfaces.BiomeChunk; - -import net.minecraft.world.level.levelgen.WorldgenRandom; - -public class SquareBiomeChunk implements BiomeChunk { - private static final int BIT_OFFSET = 4; - protected static final int WIDTH = 1 << BIT_OFFSET; - private static final int SM_WIDTH = WIDTH >> 1; - private static final int SM_BIT_OFFSET = BIT_OFFSET >> 1; - private static final int MASK_OFFSET = SM_WIDTH - 1; - protected static final int MASK_WIDTH = WIDTH - 1; - - private static final int SM_CAPACITY = SM_WIDTH * SM_WIDTH; - private static final int CAPACITY = WIDTH * WIDTH; - - private final BiomePicker.ActualBiome[] biomes; - - public SquareBiomeChunk(WorldgenRandom random, BiomePicker picker) { - BiomePicker.ActualBiome[] PreBio = new BiomePicker.ActualBiome[SM_CAPACITY]; - biomes = new BiomePicker.ActualBiome[CAPACITY]; - - for (int x = 0; x < SM_WIDTH; x++) { - int offset = x << SM_BIT_OFFSET; - for (int z = 0; z < SM_WIDTH; z++) { - PreBio[offset | z] = picker.getBiome(random); - } - } - - for (int x = 0; x < WIDTH; x++) { - int offset = x << BIT_OFFSET; - for (int z = 0; z < WIDTH; z++) { - biomes[offset | z] = PreBio[getSmIndex(offsetXZ(x, random), offsetXZ(z, random))].getSubBiome(random); - } - } - } - - @Override - public BiomePicker.ActualBiome getBiome(int x, int z) { - return biomes[getIndex(x & MASK_WIDTH, z & MASK_WIDTH)]; - } - - @Override - public void setBiome(int x, int z, BiomePicker.ActualBiome biome) { - biomes[getIndex(x & MASK_WIDTH, z & MASK_WIDTH)] = biome; - } - - @Override - public int getSide() { - return WIDTH; - } - - private int offsetXZ(int x, WorldgenRandom random) { - return ((x + random.nextInt(2)) >> 1) & MASK_OFFSET; - } - - private int getIndex(int x, int z) { - return x << BIT_OFFSET | z; - } - - private int getSmIndex(int x, int z) { - return x << SM_BIT_OFFSET | z; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/generator/map/square/SquareBiomeMap.java b/src/main/java/org/betterx/bclib/api/v2/generator/map/square/SquareBiomeMap.java deleted file mode 100644 index 1ce1d9e0..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/generator/map/square/SquareBiomeMap.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.betterx.bclib.api.v2.generator.map.square; - -import org.betterx.bclib.api.v2.generator.BiomePicker; -import org.betterx.bclib.interfaces.BiomeChunk; -import org.betterx.bclib.interfaces.BiomeMap; -import org.betterx.bclib.interfaces.TriConsumer; -import org.betterx.bclib.noise.OpenSimplexNoise; -import org.betterx.bclib.util.MHelper; - -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.levelgen.LegacyRandomSource; -import net.minecraft.world.level.levelgen.WorldgenRandom; - -import com.google.common.collect.Maps; - -import java.util.Map; - -public class SquareBiomeMap implements BiomeMap { - private final Map maps = Maps.newHashMap(); - private final OpenSimplexNoise noiseX; - private final OpenSimplexNoise noiseZ; - private final WorldgenRandom random; - private final BiomePicker picker; - - private final int sizeXZ; - private final int depth; - private final int size; - - private TriConsumer processor; - - public SquareBiomeMap(long seed, int size, BiomePicker picker) { - random = new WorldgenRandom(new LegacyRandomSource(seed)); - noiseX = new OpenSimplexNoise(random.nextLong()); - noiseZ = new OpenSimplexNoise(random.nextLong()); - this.sizeXZ = size; - depth = (int) Math.ceil(Math.log(size) / Math.log(2)) - 2; - this.size = 1 << depth; - this.picker = picker; - } - - @Override - public void clearCache() { - if (maps.size() > 32) { - maps.clear(); - } - } - - @Override - public BiomePicker.ActualBiome getBiome(double x, double y, double z) { - BiomePicker.ActualBiome biome = getRawBiome(x, z); - - if (biome.getEdge() != null || (biome.getParentBiome() != null && biome.getParentBiome().getEdge() != null)) { - BiomePicker.ActualBiome search = biome; - if (biome.getParentBiome() != null) { - search = biome.getParentBiome(); - } - - int size = search.bclBiome.getEdgeSize(); - boolean edge = !search.isSame(getRawBiome(x + size, z)); - edge = edge || !search.isSame(getRawBiome(x - size, z)); - edge = edge || !search.isSame(getRawBiome(x, z + size)); - edge = edge || !search.isSame(getRawBiome(x, z - size)); - edge = edge || !search.isSame(getRawBiome(x - 1, z - 1)); - edge = edge || !search.isSame(getRawBiome(x - 1, z + 1)); - edge = edge || !search.isSame(getRawBiome(x + 1, z - 1)); - edge = edge || !search.isSame(getRawBiome(x + 1, z + 1)); - - if (edge) { - biome = search.getEdge(); - } - } - - return biome; - } - - @Override - public void setChunkProcessor(TriConsumer processor) { - this.processor = processor; - } - - @Override - public BiomeChunk getChunk(int cx, int cz, boolean update) { - ChunkPos cpos = new ChunkPos(cx, cz); - SquareBiomeChunk chunk = maps.get(cpos); - if (chunk == null) { - synchronized (random) { - random.setLargeFeatureWithSalt(0, cpos.x, cpos.z, 0); - chunk = new SquareBiomeChunk(random, picker); - } - maps.put(cpos, chunk); - - if (update && processor != null) { - processor.accept(cx, cz, chunk.getSide()); - } - } - - return chunk; - } - - private BiomePicker.ActualBiome getRawBiome(double bx, double bz) { - double x = bx * size / sizeXZ; - double z = bz * size / sizeXZ; - - double px = bx * 0.2; - double pz = bz * 0.2; - - for (int i = 0; i < depth; i++) { - double nx = (x + noiseX.eval(px, pz)) / 2F; - double nz = (z + noiseZ.eval(px, pz)) / 2F; - - x = nx; - z = nz; - - px = px / 2 + i; - pz = pz / 2 + i; - } - - int ix = MHelper.floor(x); - int iz = MHelper.floor(z); - - if ((ix & SquareBiomeChunk.MASK_WIDTH) == SquareBiomeChunk.MASK_WIDTH) { - x += (iz / 2) & 1; - } - if ((iz & SquareBiomeChunk.MASK_WIDTH) == SquareBiomeChunk.MASK_WIDTH) { - z += (ix / 2) & 1; - } - - ChunkPos cpos = new ChunkPos( - MHelper.floor(x / SquareBiomeChunk.WIDTH), - MHelper.floor(z / SquareBiomeChunk.WIDTH) - ); - SquareBiomeChunk chunk = maps.get(cpos); - if (chunk == null) { - synchronized (random) { - random.setLargeFeatureWithSalt(0, cpos.x, cpos.z, 0); - chunk = new SquareBiomeChunk(random, picker); - } - maps.put(cpos, chunk); - } - - return chunk.getBiome(MHelper.floor(x), MHelper.floor(z)); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/LevelGenEvents.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/LevelGenEvents.java deleted file mode 100644 index 1028f9d6..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/LevelGenEvents.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.LifeCycleAPI; -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; -import org.betterx.bclib.api.v2.datafixer.DataFixerAPI; -import org.betterx.bclib.api.v2.generator.BCLibEndBiomeSource; -import org.betterx.bclib.api.v2.generator.config.BCLEndBiomeSourceConfig; -import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; -import org.betterx.bclib.api.v2.poi.PoiManager; -import org.betterx.bclib.registry.PresetsRegistry; -import org.betterx.worlds.together.tag.v3.TagManager; -import org.betterx.worlds.together.world.WorldConfig; -import org.betterx.worlds.together.world.event.WorldEvents; -import org.betterx.worlds.together.worldPreset.TogetherWorldPreset; - -import net.minecraft.core.Holder; -import net.minecraft.core.RegistryAccess; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagLoader; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.levelgen.presets.WorldPreset; -import net.minecraft.world.level.storage.LevelStorageSource; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Consumer; - -public class LevelGenEvents { - public static void setupWorld() { - InternalBiomeAPI.prepareNewLevel(); - DataExchangeAPI.prepareServerside(); - } - - public static void register() { - WorldEvents.BEFORE_WORLD_LOAD.on(LevelGenEvents::prepareWorld); - WorldEvents.BEFORE_SERVER_WORLD_LOAD.on(LevelGenEvents::prepareServerWorld); - - WorldEvents.ON_WORLD_LOAD.on(LevelGenEvents::onWorldLoad); - WorldEvents.WORLD_REGISTRY_READY.on(LevelGenEvents::onRegistryReady); - WorldEvents.ON_FINALIZE_LEVEL_STEM.on(LevelGenEvents::finalizeStem); - WorldEvents.ON_FINALIZED_WORLD_LOAD.on(LevelGenEvents::finalizedWorldLoad); - - WorldEvents.PATCH_WORLD.on(LevelGenEvents::patchExistingWorld); - WorldEvents.ADAPT_WORLD_PRESET.on(LevelGenEvents::adaptWorldPresetSettings); - - WorldEvents.BEFORE_ADDING_TAGS.on(LevelGenEvents::appplyTags); - } - - - private static void appplyTags( - String directory, - Map> tagsMap - ) { - if (directory.equals(TagManager.BIOMES.directory)) { - InternalBiomeAPI._runBiomeTagAdders(); - } - } - - - private static boolean patchExistingWorld( - LevelStorageSource.LevelStorageAccess storageAccess, - Consumer allDone - ) { - return DataFixerAPI.fixData(storageAccess, true, allDone); - } - - private static Optional> adaptWorldPresetSettings( - Optional> currentPreset, - WorldGenSettings worldGenSettings - ) { - LevelStem endStem = worldGenSettings.dimensions().get(LevelStem.END); - - //We probably loaded a Datapack for the End - if (!(endStem.generator().getBiomeSource() instanceof BCLibEndBiomeSource)) { - if (currentPreset.isPresent()) { - if (currentPreset.get().value() instanceof TogetherWorldPreset worldPreset) { - ResourceKey worldPresetKey = currentPreset.get().unwrapKey().orElse(null); - - //user did not configure/change the Preset! - if (PresetsRegistry.BCL_WORLD.equals(worldPresetKey) - || PresetsRegistry.BCL_WORLD_17.equals(worldPresetKey)) { - BCLib.LOGGER.info("Detected Datapack for END."); - - LevelStem configuredEndStem = worldPreset.getDimension(LevelStem.END); - if (configuredEndStem.generator().getBiomeSource() instanceof BCLibEndBiomeSource endSource) { - BCLib.LOGGER.info("Changing Default WorldPreset Settings for Datapack use."); - - BCLEndBiomeSourceConfig inputConfig = endSource.getTogetherConfig(); - endSource.setTogetherConfig(new BCLEndBiomeSourceConfig( - inputConfig.mapVersion, - BCLEndBiomeSourceConfig.EndBiomeGeneratorType.VANILLA, - false, - inputConfig.innerVoidRadiusSquared, - inputConfig.centerBiomesSize, - inputConfig.voidBiomesSize, - inputConfig.landBiomesSize, - inputConfig.barrensBiomesSize - )); - } - } - } - } - } - return currentPreset; - } - - private static void onRegistryReady(RegistryAccess a) { - InternalBiomeAPI.initRegistry(a); - } - - private static void prepareWorld( - LevelStorageSource.LevelStorageAccess storageAccess, - Map, ChunkGenerator> dimensions, - boolean isNewWorld - ) { - setupWorld(); - if (isNewWorld) { - WorldConfig.saveFile(BCLib.MOD_ID); - DataFixerAPI.initializePatchData(); - } else { - LevelGenUtil.migrateGeneratorSettings(); - } - } - - private static void prepareServerWorld( - LevelStorageSource.LevelStorageAccess storageAccess, - Map, ChunkGenerator> dimensions, - boolean isNewWorld - ) { - setupWorld(); - - if (isNewWorld) { - WorldConfig.saveFile(BCLib.MOD_ID); - DataFixerAPI.initializePatchData(); - } else { - LevelGenUtil.migrateGeneratorSettings(); - DataFixerAPI.fixData(storageAccess, false, (didFix) -> {/* not called when showUI==false */}); - } - } - - private static void onWorldLoad() { - LifeCycleAPI._runBeforeLevelLoad(); - } - - private static void finalizeStem( - WorldGenSettings settings, - ResourceKey dimension, - LevelStem levelStem - ) { - InternalBiomeAPI.applyModifications(levelStem.generator().getBiomeSource(), dimension); - } - - private static void finalizedWorldLoad(WorldGenSettings worldGenSettings) { - PoiManager.updateStates(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/LevelGenUtil.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/LevelGenUtil.java deleted file mode 100644 index a9b97dda..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/LevelGenUtil.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.generator.BCLChunkGenerator; -import org.betterx.bclib.api.v2.generator.BCLibEndBiomeSource; -import org.betterx.bclib.api.v2.generator.BCLibNetherBiomeSource; -import org.betterx.bclib.api.v2.generator.config.BCLEndBiomeSourceConfig; -import org.betterx.bclib.api.v2.generator.config.BCLNetherBiomeSourceConfig; -import org.betterx.bclib.registry.PresetsRegistry; -import org.betterx.worlds.together.levelgen.WorldGenUtil; -import org.betterx.worlds.together.util.ModUtil; -import org.betterx.worlds.together.world.WorldConfig; -import org.betterx.worlds.together.worldPreset.TogetherWorldPreset; - -import com.mojang.serialization.Lifecycle; -import net.minecraft.core.Holder; -import net.minecraft.core.MappedRegistry; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.levelgen.presets.WorldPreset; -import net.minecraft.world.level.levelgen.presets.WorldPresets; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.jetbrains.annotations.NotNull; - -public class LevelGenUtil { - private static final String TAG_VERSION = "version"; - private static final String TAG_BN_GEN_VERSION = "generator_version"; - - @NotNull - public static LevelStem getBCLNetherLevelStem(WorldGenUtil.Context context, BCLNetherBiomeSourceConfig config) { - BCLibNetherBiomeSource netherSource = new BCLibNetherBiomeSource(context.biomes, config); - - return new LevelStem( - context.dimension, - new BCLChunkGenerator( - context.structureSets, - context.noiseParameters, - netherSource, - context.generatorSettings - ) - ); - } - - public static LevelStem getBCLEndLevelStem(WorldGenUtil.Context context, BCLEndBiomeSourceConfig config) { - BCLibEndBiomeSource endSource = new BCLibEndBiomeSource(context.biomes, config); - return new LevelStem( - context.dimension, - new BCLChunkGenerator( - context.structureSets, - context.noiseParameters, - endSource, - context.generatorSettings - ) - ); - } - - - public static WorldGenSettings replaceGenerator( - ResourceKey dimensionKey, - ResourceKey dimensionTypeKey, - RegistryAccess registryAccess, - WorldGenSettings worldGenSettings, - ChunkGenerator generator - ) { - Registry dimensionTypeRegistry = registryAccess.registryOrThrow(Registry.DIMENSION_TYPE_REGISTRY); - Registry newDimensions = withDimension( - dimensionKey, - dimensionTypeKey, - dimensionTypeRegistry, - worldGenSettings.dimensions(), - generator - ); - return new WorldGenSettings( - worldGenSettings.seed(), - worldGenSettings.generateStructures(), - worldGenSettings.generateBonusChest(), - newDimensions - ); - } - - public static Registry withDimension( - ResourceKey dimensionKey, - ResourceKey dimensionTypeKey, - Registry dimensionTypeRegistry, - Registry inputDimensions, - ChunkGenerator generator - ) { - - LevelStem levelStem = inputDimensions.get(dimensionKey); - Holder dimensionType = levelStem == null - ? dimensionTypeRegistry.getOrCreateHolderOrThrow(dimensionTypeKey) - : levelStem.typeHolder(); - return withDimension(dimensionKey, inputDimensions, new LevelStem(dimensionType, generator)); - } - - public static Registry withDimension( - ResourceKey dimensionKey, - Registry inputDimensions, - LevelStem levelStem - ) { - MappedRegistry writableRegistry = new MappedRegistry<>( - Registry.LEVEL_STEM_REGISTRY, - Lifecycle.experimental(), - null - ); - writableRegistry.register( - dimensionKey, - levelStem, - Lifecycle.stable() - ); - for (Map.Entry, LevelStem> entry : inputDimensions.entrySet()) { - ResourceKey resourceKey = entry.getKey(); - if (resourceKey == dimensionKey) continue; - writableRegistry.register( - resourceKey, - entry.getValue(), - inputDimensions.lifecycle(entry.getValue()) - ); - } - return writableRegistry; - } - - - public static void migrateGeneratorSettings() { - final CompoundTag settingsNbt = WorldGenUtil.getPresetsNbt(); - - if (settingsNbt.size() == 0) { - CompoundTag oldGen = WorldGenUtil.getGeneratorNbt(); - if (oldGen != null) { - if (oldGen.contains("type")) { - BCLib.LOGGER.info("Found World with beta generator Settings."); - if ("bclib:bcl_world_preset_settings".equals(oldGen.getString("type"))) { - int netherVersion = 18; - int endVersion = 18; - if (oldGen.contains("minecraft:the_nether")) - netherVersion = oldGen.getInt("minecraft:the_nether"); - if (oldGen.contains("minecraft:the_end")) - endVersion = oldGen.getInt("minecraft:the_end"); - - if (netherVersion == 18) netherVersion = 0; - else if (netherVersion == 17) netherVersion = 1; - else netherVersion = 2; - - if (endVersion == 18) endVersion = 0; - else if (endVersion == 17) endVersion = 1; - else endVersion = 2; - - var presets = List.of( - TogetherWorldPreset.getDimensionsMap(PresetsRegistry.BCL_WORLD), - TogetherWorldPreset.getDimensionsMap(PresetsRegistry.BCL_WORLD_17), - TogetherWorldPreset.getDimensionsMap(WorldPresets.NORMAL) - ); - Map, ChunkGenerator> dimensions = new HashMap<>(); - dimensions.put(LevelStem.OVERWORLD, presets.get(0).get(LevelStem.OVERWORLD)); - dimensions.put(LevelStem.NETHER, presets.get(netherVersion).get(LevelStem.NETHER)); - dimensions.put(LevelStem.END, presets.get(endVersion).get(LevelStem.END)); - - TogetherWorldPreset.writeWorldPresetSettingsDirect(dimensions); - } - return; - } - } - - BCLib.LOGGER.info("Found World without generator Settings. Setting up data..."); - ResourceKey biomeSourceVersion = PresetsRegistry.BCL_WORLD; - - final CompoundTag bclRoot = WorldConfig.getRootTag(BCLib.MOD_ID); - - String bclVersion = "0.0.0"; - if (bclRoot.contains(TAG_VERSION)) { - bclVersion = bclRoot.getString(TAG_VERSION); - } - boolean isPre18 = !ModUtil.isLargerOrEqualVersion(bclVersion, "1.0.0"); - - if (isPre18) { - BCLib.LOGGER.info("World was create pre 1.18!"); - biomeSourceVersion = PresetsRegistry.BCL_WORLD_17; - } - - if (WorldConfig.hasMod("betternether")) { - BCLib.LOGGER.info("Found Data from BetterNether, using for migration."); - final CompoundTag bnRoot = WorldConfig.getRootTag("betternether"); - biomeSourceVersion = "1.17".equals(bnRoot.getString(TAG_BN_GEN_VERSION)) - ? PresetsRegistry.BCL_WORLD_17 - : PresetsRegistry.BCL_WORLD; - } - - Registry dimensions = TogetherWorldPreset.getDimensions(biomeSourceVersion); - if (dimensions != null) { - BCLib.LOGGER.info("Set world to BiomeSource Version " + biomeSourceVersion); - TogetherWorldPreset.writeWorldPresetSettings(dimensions); - } else { - BCLib.LOGGER.error("Failed to set world to BiomeSource Version " + biomeSourceVersion); - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiome.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiome.java deleted file mode 100644 index f7de7825..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiome.java +++ /dev/null @@ -1,491 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - -import org.betterx.bclib.util.WeightedList; - -import com.mojang.datafixers.Products; -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Registry; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.Climate; -import net.minecraft.world.level.levelgen.WorldgenRandom; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.Nullable; - - -/** - * Stores additional Data for a {@link Biome}. Instances of {@link BCLBiome} are linked to - * Biomes using a {@link ResourceKey}. The data is registerd and Stored in - * {@link BCLBiomeRegistry#BCL_BIOMES_REGISTRY} registries, allowing them to be overriden by Datapacks. - *

- * As such, if you extend BCLBiome with custom types, especially if those new type have a custom state, - * you need to provide a Codec for your class using - * {@link BCLBiomeRegistry#registerBiomeCodec(ResourceLocation, KeyDispatchDataCodec)}. - *

- * You may use {@link BCLBiome#codecWithSettings(RecordCodecBuilder.Instance)} to create a Codec that includes - * all default settings for {@link BCLBiome} as well as additional Data for your specific subclass. - */ -public class BCLBiome extends BCLBiomeSettings implements BiomeData { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> codecWithSettings(instance).apply( - instance, - BCLBiome::new - )); - public static final KeyDispatchDataCodec KEY_CODEC = KeyDispatchDataCodec.of(CODEC); - - public KeyDispatchDataCodec codec() { - return KEY_CODEC; - } - - private static class CodecAttributes { - public RecordCodecBuilder t0 = Codec.FLOAT.fieldOf("terrainHeight") - .orElse(0.1f) - .forGetter((T o1) -> o1.terrainHeight); - - public RecordCodecBuilder t1 = Codec.FLOAT.fieldOf("fogDensity") - .orElse(1.0f) - .forGetter((T o1) -> o1.fogDensity); - public RecordCodecBuilder t2 = Codec.FLOAT.fieldOf("genChance") - .orElse(1.0f) - .forGetter((T o1) -> o1.genChance); - public RecordCodecBuilder t3 = Codec.INT.fieldOf("edgeSize") - .orElse(0) - .forGetter((T o1) -> o1.edgeSize); - public RecordCodecBuilder t4 = Codec.BOOL.fieldOf("vertical") - .orElse(false) - .forGetter((T o1) -> o1.vertical); - public RecordCodecBuilder> t5 = - ResourceLocation.CODEC - .optionalFieldOf("edge") - .orElse(Optional.empty()) - .forGetter((T o1) -> o1.edge == null - ? Optional.empty() - : Optional.of(o1.edge.biomeID)); - public RecordCodecBuilder t6 = - ResourceLocation.CODEC.fieldOf("biome") - .forGetter((T o) -> ((BCLBiome) o).biomeID); - public RecordCodecBuilder>> t7 = - Climate.ParameterPoint.CODEC.listOf() - .optionalFieldOf("parameter_points") - .orElse(Optional.of(List.of())) - .forGetter((T o) -> - o.parameterPoints == null || o.parameterPoints.isEmpty() - ? Optional.empty() - : Optional.of(o.parameterPoints)); - - public RecordCodecBuilder> t8 = - ResourceLocation.CODEC.optionalFieldOf("parent") - .orElse(Optional.empty()) - .forGetter( - (T o1) -> - ((BCLBiome) o1).biomeParent == null - ? Optional.empty() - : Optional.of( - ((BCLBiome) o1).biomeParent.biomeID)); - public RecordCodecBuilder>> t9 = - WeightedList.listCodec( - ResourceLocation.CODEC, - "biomes", - "biome" - ) - .optionalFieldOf("sub_biomes") - .forGetter( - (T o) -> { - if (o.subbiomes == null - || o.subbiomes.isEmpty() - || (o.subbiomes.size() == 1 && o.subbiomes.contains( - o))) { - return Optional.empty(); - } - return Optional.of( - o.subbiomes.map( - b -> b.biomeID)); - }); - public RecordCodecBuilder> t10 = - Codec.STRING.optionalFieldOf("intended_for") - .orElse(Optional.of(BiomeAPI.BiomeType.NONE.getName())) - .forGetter((T o) -> - ((BCLBiome) o).intendedType == null - ? Optional.empty() - : Optional.of(((BCLBiome) o).intendedType.getName())); - } - - public static Products.P12, Float, Float, Float, Integer, Boolean, Optional, ResourceLocation, Optional>, Optional, Optional>, Optional, P12> codecWithSettings( - RecordCodecBuilder.Instance instance, - final RecordCodecBuilder p12 - ) { - CodecAttributes a = new CodecAttributes<>(); - return instance.group(a.t0, a.t1, a.t2, a.t3, a.t4, a.t5, a.t6, a.t7, a.t8, a.t9, a.t10, p12); - } - - public static Products.P13, Float, Float, Float, Integer, Boolean, Optional, ResourceLocation, Optional>, Optional, Optional>, Optional, P12, P13> codecWithSettings( - RecordCodecBuilder.Instance instance, - final RecordCodecBuilder p12, - final RecordCodecBuilder p13 - ) { - CodecAttributes a = new CodecAttributes<>(); - return instance.group(a.t0, a.t1, a.t2, a.t3, a.t4, a.t5, a.t6, a.t7, a.t8, a.t9, a.t10, p12, p13); - } - - public static Products.P15, Float, Float, Float, Integer, Boolean, Optional, ResourceLocation, Optional>, Optional, Optional>, Optional, P12, P13, P14, P15> codecWithSettings( - RecordCodecBuilder.Instance instance, - final RecordCodecBuilder p12, - final RecordCodecBuilder p13, - final RecordCodecBuilder p14, - final RecordCodecBuilder p15 - ) { - CodecAttributes a = new CodecAttributes<>(); - return instance.group(a.t0, a.t1, a.t2, a.t3, a.t4, a.t5, a.t6, a.t7, a.t8, a.t9, a.t10, p12, p13, p14, p15); - } - - public static Products.P14, Float, Float, Float, Integer, Boolean, Optional, ResourceLocation, Optional>, Optional, Optional>, Optional, P12, P13, P14> codecWithSettings( - RecordCodecBuilder.Instance instance, - final RecordCodecBuilder p12, - final RecordCodecBuilder p13, - final RecordCodecBuilder p14 - ) { - CodecAttributes a = new CodecAttributes<>(); - return instance.group(a.t0, a.t1, a.t2, a.t3, a.t4, a.t5, a.t6, a.t7, a.t8, a.t9, a.t10, p12, p13, p14); - } - - public static Products.P11, Float, Float, Float, Integer, Boolean, Optional, ResourceLocation, Optional>, Optional, Optional>, Optional> codecWithSettings( - RecordCodecBuilder.Instance instance - ) { - CodecAttributes a = new CodecAttributes<>(); - return instance.group(a.t0, a.t1, a.t2, a.t3, a.t4, a.t5, a.t6, a.t7, a.t8, a.t9, a.t10); - } - - protected final WeightedList subbiomes = new WeightedList<>(); - private final Map customData = Maps.newHashMap(); - private final ResourceLocation biomeID; - private final ResourceKey biomeKey; - final Biome biomeToRegister; - - protected final List parameterPoints = Lists.newArrayList(); - - private BCLBiome biomeParent; - - private BiomeAPI.BiomeType intendedType = BiomeAPI.BiomeType.NONE; - - protected BCLBiome( - float terrainHeight, - float fogDensity, - float genChance, - int edgeSize, - boolean vertical, - Optional edge, - ResourceLocation biomeID, - Optional> parameterPoints, - Optional biomeParent, - Optional> subbiomes, - Optional intendedType - ) { - super(terrainHeight, fogDensity, genChance, edgeSize, vertical, edge.map(BiomeAPI::getBiome).orElse(null)); - biomeToRegister = null; - this.biomeID = biomeID; - this.biomeKey = ResourceKey.create(Registry.BIOME_REGISTRY, biomeID); - if (subbiomes.isEmpty() || subbiomes.get().size() == 0) { - this.subbiomes.add(this, 1); - } else { - this.subbiomes.addAll(subbiomes.get().map(BiomeAPI::getBiome)); - } - this.biomeParent = biomeParent.map(BiomeAPI::getBiome).orElse(null); - if (parameterPoints.isPresent()) this.parameterPoints.addAll(parameterPoints.get()); - this.setIntendedType(intendedType.map(t -> BiomeAPI.BiomeType.create(t)).orElse(BiomeAPI.BiomeType.NONE)); - - - } - - /** - * Create wrapper for existing biome using its {@link ResourceLocation} identifier. - * - * @param biomeKey {@link ResourceKey} for the {@link Biome}. - */ - protected BCLBiome(ResourceKey biomeKey) { - this(biomeKey.location()); - } - - /** - * Create wrapper for existing biome using its {@link ResourceLocation} identifier. - * - * @param biomeID {@link ResourceLocation} biome ID. - */ - protected BCLBiome(ResourceLocation biomeID) { - this(ResourceKey.create(Registry.BIOME_REGISTRY, biomeID), null); - } - - - /** - * Create wrapper for existing biome using biome instance from {@link BuiltinRegistries}. - * - * @param biomeToRegister {@link Biome} to wrap. - * @param settings The Settings for this Biome or {@code null} if you want to apply default settings - */ - @ApiStatus.Internal - BCLBiome(Biome biomeToRegister, VanillaBiomeSettings settings) { - this(BiomeAPI.getBiomeID(biomeToRegister), biomeToRegister, settings); - } - - - /** - * Create wrapper for existing biome using biome instance from {@link BuiltinRegistries}. - * - * @param biomeToRegister {@link Biome} to wrap. - * @param biomeID Teh ResoureLocation for this Biome - */ - @ApiStatus.Internal - public BCLBiome(ResourceLocation biomeID, Biome biomeToRegister, BiomeAPI.BiomeType type) { - this(biomeID, biomeToRegister, (BCLBiomeSettings) null); - setIntendedType(type); - } - - /** - * Create a new Biome - * - * @param biomeID {@link ResourceLocation} biome ID. - * @param biomeToRegister {@link Biome} to wrap. - * @param defaults The Settings for this Biome or null if you want to apply the defaults - */ - protected BCLBiome(ResourceLocation biomeID, Biome biomeToRegister, BCLBiomeSettings defaults) { - this(ResourceKey.create(Registry.BIOME_REGISTRY, biomeID), biomeToRegister, defaults); - } - - /** - * Create a new Biome - * - * @param biomeKey {@link ResourceKey} of the wrapped Biome - * @param defaults The Settings for this Biome or null if you want to apply the defaults - */ - protected BCLBiome(ResourceKey biomeKey, BCLBiomeSettings defaults) { - this(biomeKey, null, defaults); - } - - /** - * Create a new Biome - * - * @param biomeKey {@link ResourceKey} of the wrapped Biome - * @param biomeToRegister The biome you want to use when this instance gets registered through the {@link BiomeAPI} - * @param defaults The Settings for this Biome or null if you want to apply the defaults - */ - protected BCLBiome(ResourceKey biomeKey, Biome biomeToRegister, BCLBiomeSettings defaults) { - this.biomeToRegister = biomeToRegister; - this.subbiomes.add(this, 1.0F); - this.biomeID = biomeKey.location(); - this.biomeKey = biomeKey; - - if (defaults != null) { - defaults.applyWithDefaults(this); - } - } - - /** - * Changes the intended Type for this Biome - * - * @param type the new type - * @return the same instance - */ - protected BCLBiome setIntendedType(BiomeAPI.BiomeType type) { - return _setIntendedType(type); - } - - BCLBiome _setIntendedType(BiomeAPI.BiomeType type) { - this.intendedType = type; - return this; - } - - public BiomeAPI.BiomeType getIntendedType() { - return this.intendedType; - } - - /** - * Get current biome edge. - * - * @return {@link BCLBiome} edge. - */ - @Nullable - public BCLBiome getEdge() { - return edge; - } - - /** - * Set biome edge for this biome instance. - * - * @param edge {@link BCLBiome} as the edge biome. - * @return same {@link BCLBiome}. - */ - BCLBiome setEdge(BCLBiome edge) { - this.edge = edge; - edge.biomeParent = this; - return this; - } - - /** - * Set biome edge for this biome instance. If there is already an edge, the - * biome is added as subBiome to the current edge-biome - * - * @param edge The new edge - * @return same {@link BCLBiome}. - */ - public BCLBiome addEdge(BCLBiome edge) { - if (this.edge != null) { - this.edge.addSubBiome(edge); - } else { - this.setEdge(edge); - } - return this; - } - - /** - * Adds sub-biome into this biome instance. Biome chance will be interpreted as a sub-biome generation chance. - * Biome itself has chance 1.0 compared to all its sub-biomes. - * - * @param biome {@link Random} to be added. - * @return same {@link BCLBiome}. - */ - public BCLBiome addSubBiome(BCLBiome biome) { - biome.biomeParent = this; - subbiomes.add(biome, biome.getGenChance()); - return this; - } - - /** - * Checks if specified biome is a sub-biome of this one. - * - * @param biome {@link Random}. - * @return true if this instance contains specified biome as a sub-biome. - */ - public boolean containsSubBiome(BCLBiome biome) { - return subbiomes.contains(biome); - } - - /** - * Getter for a random sub-biome from all existing sub-biomes. Will return biome itself if there are no sub-biomes. - * - * @param random {@link Random}. - * @return {@link BCLBiome}. - */ - public BCLBiome getSubBiome(WorldgenRandom random) { - return subbiomes.get(random); - } - - public void forEachSubBiome(BiConsumer consumer) { - for (int i = 0; i < subbiomes.size(); i++) - consumer.accept(subbiomes.get(i), subbiomes.getWeight(i)); - } - - /** - * Getter for parent {@link BCLBiome} or null if there are no parent biome. - * - * @return {@link BCLBiome} or null. - */ - @Nullable - public BCLBiome getParentBiome() { - return this.biomeParent; - } - - /** - * Compares biome instances (directly) and their parents. Used in custom world generator. - * - * @param biome {@link BCLBiome} - * @return true if biome or its parent is same. - */ - public boolean isSame(BCLBiome biome) { - return biome == this || (biome.biomeParent != null && biome.biomeParent == this); - } - - /** - * Getter for biome identifier. - * - * @return {@link ResourceLocation} - */ - public ResourceLocation getID() { - return biomeID; - } - - /** - * Getter for biomeKey - * - * @return {@link ResourceKey}. - */ - public ResourceKey getBiomeKey() { - return biomeKey; - } - - public ResourceKey getBCLBiomeKey() { - return ResourceKey.create(BCLBiomeRegistry.BCL_BIOMES_REGISTRY, biomeID); - } - - /** - * For internal use from BiomeAPI only - */ - void afterRegistration() { - - } - - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - BCLBiome biome = (BCLBiome) obj; - return biome != null && biomeID.equals(biome.biomeID); - } - - @Override - public int hashCode() { - return biomeID.hashCode(); - } - - @Override - public String toString() { - return biomeID.toString(); - } - - - /** - * Adds structures to this biome. For internal use only. - * Used inside {@link BCLBiomeBuilder}. - */ - void addClimateParameters(List params) { - this.parameterPoints.addAll(params); - } - - public void forEachClimateParameter(Consumer consumer) { - this.parameterPoints.forEach(consumer); - } - - /** - * Returns the group used in the config Files for this biome - *

- * Example: {@code Configs.BIOMES_CONFIG.getFloat(configGroup(), "generation_chance", 1.0);} - * - * @return The group name - */ - public String configGroup() { - return biomeID.getNamespace() + "." + biomeID.getPath(); - } - - private final boolean didLoadConfig = false; - - public boolean isEdgeBiome() { - if (getParentBiome() == null) return false; - return getParentBiome().edge == this; - } - - boolean allowFabricRegistration() { - return !isEdgeBiome(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeBuilder.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeBuilder.java deleted file mode 100644 index 885599b7..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeBuilder.java +++ /dev/null @@ -1,898 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - -import org.betterx.bclib.api.v2.levelgen.structures.BCLStructure; -import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleBuilder; -import org.betterx.bclib.api.v3.levelgen.features.BCLFeature; -import org.betterx.bclib.entity.BCLEntityWrapper; -import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor; -import org.betterx.bclib.util.CollectionsUtil; -import org.betterx.bclib.util.Pair; -import org.betterx.bclib.util.TriFunction; -import org.betterx.ui.ColorUtil; -import org.betterx.worlds.together.surfaceRules.SurfaceRuleRegistry; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.core.Holder; -import net.minecraft.core.HolderSet; -import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.data.worldgen.BiomeDefaultFeatures; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.sounds.Music; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.tags.TagKey; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.level.biome.*; -import net.minecraft.world.level.biome.Biome.BiomeBuilder; -import net.minecraft.world.level.biome.Biome.Precipitation; -import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.GenerationStep.Decoration; -import net.minecraft.world.level.levelgen.Noises; -import net.minecraft.world.level.levelgen.SurfaceRules; -import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -import net.fabricmc.fabric.api.biome.v1.BiomeModifications; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Consumer; - -public class BCLBiomeBuilder { - @FunctionalInterface - public interface BiomeSupplier extends TriFunction { - } - - - private static final BCLBiomeBuilder INSTANCE = new BCLBiomeBuilder(); - private static final SurfaceRules.ConditionSource SURFACE_NOISE = SurfaceRules.noiseCondition( - Noises.SOUL_SAND_LAYER, - -0.012 - ); - - private final List>>> carvers = new ArrayList<>( - 1); - private BiomeGenerationSettings.Builder generationSettings; - private BiomeSpecialEffects.Builder effectsBuilder; - private MobSpawnSettings.Builder spawnSettings; - private SurfaceRules.RuleSource surfaceRule; - private Precipitation precipitation; - private ResourceLocation biomeID; - - private final Set> tags = Sets.newHashSet(); - - private final List parameters = Lists.newArrayList(); - - private float temperature; - private float fogDensity; - private float genChance; - private float downfall; - private float height; - private int edgeSize; - private BCLBiome edge; - private boolean vertical; - - private BiomeAPI.BiomeType biomeType; - - - /** - * Starts new biome building process. - * - * @param biomeID {@link ResourceLocation} biome identifier. - * @return prepared {@link BCLBiomeBuilder} instance. - */ - public static BCLBiomeBuilder start(ResourceLocation biomeID) { - INSTANCE.biomeID = biomeID; - INSTANCE.precipitation = Precipitation.NONE; - INSTANCE.generationSettings = null; - INSTANCE.effectsBuilder = null; - INSTANCE.spawnSettings = null; - INSTANCE.temperature = 1.0F; - INSTANCE.fogDensity = 1.0F; - INSTANCE.edgeSize = 0; - INSTANCE.downfall = 1.0F; - INSTANCE.genChance = 1.0F; - INSTANCE.height = 0.1F; - INSTANCE.vertical = false; - INSTANCE.edge = null; - INSTANCE.carvers.clear(); - INSTANCE.parameters.clear(); - INSTANCE.tags.clear(); - INSTANCE.biomeType = null; - return INSTANCE; - } - - public BCLBiomeBuilder addNetherClimateParamater(float temperature, float humidity) { - parameters.add(Climate.parameters(temperature, humidity, 0, 0, 0, 0, 0)); - return this; - } - - /** - * Set the type for this Biome. If the type was set, the Biome can be registered. - * - * @param type selected Type - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder type(BiomeAPI.BiomeType type) { - this.biomeType = type; - return this; - } - - /** - * Set biome {@link Precipitation}. Affect biome visual effects (rain, snow, none). - * - * @param precipitation {@link Precipitation} - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder precipitation(Precipitation precipitation) { - this.precipitation = precipitation; - return this; - } - - /** - * Set biome temperature, affect plant color, biome generation and ice formation. - * - * @param temperature biome temperature. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder temperature(float temperature) { - this.temperature = temperature; - return this; - } - - /** - * Set biome wetness (same as downfall). Affect plant color and biome generation. - * - * @param wetness biome wetness (downfall). - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder wetness(float wetness) { - this.downfall = wetness; - return this; - } - - /** - * Adds mob spawning to biome. - * - * @param entityType {@link EntityType} mob type. - * @param weight spawn weight. - * @param minGroupCount minimum mobs in group. - * @param maxGroupCount maximum mobs in group. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder spawn( - EntityType entityType, - int weight, - int minGroupCount, - int maxGroupCount - ) { - getSpawns().addSpawn( - entityType.getCategory(), - new SpawnerData(entityType, weight, minGroupCount, maxGroupCount) - ); - return this; - } - - /** - * Adds mob spawning to biome. - * - * @param wrapper {@link BCLEntityWrapper} mob type. - * @param weight spawn weight. - * @param minGroupCount minimum mobs in group. - * @param maxGroupCount maximum mobs in group. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder spawn( - BCLEntityWrapper wrapper, - int weight, - int minGroupCount, - int maxGroupCount - ) { - if (wrapper.canSpawn()) { - return spawn(wrapper.type(), weight, minGroupCount, maxGroupCount); - } - - return this; - } - - /** - * Adds ambient particles to thr biome. - * - * @param particle {@link ParticleOptions} particles (or {@link net.minecraft.core.particles.ParticleType}). - * @param probability particle spawn probability, should have low value (example: 0.01F). - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder particles(ParticleOptions particle, float probability) { - getEffects().ambientParticle(new AmbientParticleSettings(particle, probability)); - return this; - } - - /** - * Sets sky color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder skyColor(int color) { - getEffects().skyColor(color); - return this; - } - - /** - * Sets sky color for the biome. Color represented as red, green and blue channel values. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder skyColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return skyColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets fog color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder fogColor(int color) { - getEffects().fogColor(color); - return this; - } - - /** - * Sets fog color for the biome. Color represented as red, green and blue channel values. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder fogColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return fogColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets fog density for the biome. - * - * @param density fog density as a float, default value is 1.0F. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder fogDensity(float density) { - this.fogDensity = density; - return this; - } - - /** - * Sets generation chance for this biome. - * - * @param genChance - * @return same {@link BCLBiomeBuilder}. - */ - public BCLBiomeBuilder genChance(float genChance) { - this.genChance = genChance; - return this; - } - - /** - * Sets edge size for this biome. - * - * @param edgeSize size of the Edge (in Blocks) - * @return same {@link BCLBiomeBuilder}. - */ - public BCLBiomeBuilder edgeSize(int edgeSize) { - this.edgeSize = edgeSize; - return this; - } - - /** - * Sets edge-Biome for this biome. - * - * @param edge The Edge Biome - * @return same {@link BCLBiomeBuilder}. - */ - public BCLBiomeBuilder edge(BCLBiome edge) { - this.edge = edge; - return this; - } - - - /** - * Sets edge-Biome for this biome. - * - * @param edge The Edge Biome - * @param edgeSize size of the Edge (in Blocks) - * @return same {@link BCLBiomeBuilder}. - */ - public BCLBiomeBuilder edge(BCLBiome edge, int edgeSize) { - this.edge(edge); - this.edgeSize(edgeSize); - return this; - } - - /** - * Sets water color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder waterColor(int color) { - getEffects().waterColor(color); - return this; - } - - /** - * Sets water color for the biome. Color represented as red, green and blue channel values. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder waterColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return waterColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets underwater fog color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder waterFogColor(int color) { - getEffects().waterFogColor(color); - return this; - } - - /** - * Sets underwater fog color for the biome. Color represented as red, green and blue channel values. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder waterFogColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return waterFogColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets water and underwater fig color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder waterAndFogColor(int color) { - return waterColor(color).waterFogColor(color); - } - - /** - * Sets water and underwater fig color for the biome. Color is in ARGB int format. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder waterAndFogColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return waterAndFogColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets grass color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder grassColor(int color) { - getEffects().grassColorOverride(color); - return this; - } - - /** - * Sets grass color for the biome. Color represented as red, green and blue channel values. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder grassColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return grassColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets leaves and plants color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder foliageColor(int color) { - getEffects().foliageColorOverride(color); - return this; - } - - /** - * Sets leaves and plants color for the biome. Color represented as red, green and blue channel values. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder foliageColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return foliageColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets grass, leaves and all plants color for the biome. Color is in ARGB int format. - * - * @param color ARGB color as integer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder plantsColor(int color) { - return grassColor(color).foliageColor(color); - } - - /** - * Sets grass, leaves and all plants color for the biome. Color represented as red, green and blue channel values. - * - * @param red red color component [0-255] - * @param green green color component [0-255] - * @param blue blue color component [0-255] - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder plantsColor(int red, int green, int blue) { - red = Mth.clamp(red, 0, 255); - green = Mth.clamp(green, 0, 255); - blue = Mth.clamp(blue, 0, 255); - return plantsColor(ColorUtil.color(red, green, blue)); - } - - /** - * Sets biome music, used for biomes in the Nether and End. - * - * @param music {@link Music} to use. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder music(Music music) { - getEffects().backgroundMusic(music); - return this; - } - - /** - * Sets biome music, used for biomes in the Nether and End. - * - * @param music {@link SoundEvent} to use. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder music(SoundEvent music) { - return music(new Music(music, 600, 2400, true)); - } - - /** - * Sets biome ambient loop sound. Can be used for biome environment. - * - * @param loopSound {@link SoundEvent} to use as a loop. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder loop(SoundEvent loopSound) { - getEffects().ambientLoopSound(loopSound); - return this; - } - - /** - * Sets biome mood sound. Can be used for biome environment. - * - * @param mood {@link SoundEvent} to use as a mood. - * @param tickDelay delay between sound events in ticks. - * @param blockSearchExtent block search radius (for area available for sound). - * @param soundPositionOffset offset in sound. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder mood(SoundEvent mood, int tickDelay, int blockSearchExtent, float soundPositionOffset) { - getEffects().ambientMoodSound(new AmbientMoodSettings(mood, tickDelay, blockSearchExtent, soundPositionOffset)); - return this; - } - - /** - * Sets biome mood sound. Can be used for biome environment. - * - * @param mood {@link SoundEvent} to use as a mood. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder mood(SoundEvent mood) { - return mood(mood, 6000, 8, 2.0F); - } - - /** - * Sets biome additionsl ambient sounds. - * - * @param additions {@link SoundEvent} to use. - * @param intensity sound intensity. Default is 0.0111F. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder additions(SoundEvent additions, float intensity) { - getEffects().ambientAdditionsSound(new AmbientAdditionsSettings(additions, intensity)); - return this; - } - - /** - * Sets biome additionsl ambient sounds. - * - * @param additions {@link SoundEvent} to use. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder additions(SoundEvent additions) { - return additions(additions, 0.0111F); - } - - /** - * Adds new feature to the biome. - * - * @param decoration {@link Decoration} feature step. - * @param feature {@link PlacedFeature}. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder feature(Decoration decoration, Holder feature) { - getGeneration().addFeature(decoration, feature); - return this; - } - - /** - * Adds vanilla Mushrooms. - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder defaultMushrooms() { - return feature(BiomeDefaultFeatures::addDefaultMushrooms); - } - - /** - * Adds vanilla Nether Ores. - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder netherDefaultOres() { - return feature(BiomeDefaultFeatures::addNetherDefaultOres); - } - - /** - * Will add features into biome, used for vanilla feature adding functions. - * - * @param featureAdd {@link Consumer} with {@link BiomeGenerationSettings.Builder}. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder feature(Consumer featureAdd) { - featureAdd.accept(getGeneration()); - return this; - } - - - /** - * Adds new feature to the biome. - * - * @param feature {@link BCLFeature}. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder feature(BCLFeature feature) { - return feature(feature.decoration, feature.placedFeature); - } - - /** - * Adds new structure feature into the biome. - * - * @param structureTag {@link TagKey} to add. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder structure(TagKey structureTag) { - tags.add(structureTag); - return this; - } - - /** - * Adds new structure feature into thr biome. Will add building biome into the structure list. - * - * @param structure {@link BCLStructure} to add. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder structure(BCLStructure structure) { - structure.addInternalBiome(biomeID); - return structure(structure.biomeTag); - } - - /** - * Adds new world carver into the biome. - * - * @param carver {@link ConfiguredWorldCarver} to add. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder carver(GenerationStep.Carving step, Holder> carver) { - final ResourceLocation immutableID = biomeID; - var oKey = carver.unwrapKey(); - if (oKey.isPresent()) { - BiomeModifications.addCarver( - ctx -> ctx.getBiomeKey().location().equals(immutableID), - step, - (ResourceKey>) oKey.get() - ); - } - //carvers.add(new Pair<>(step, carver)); - return this; - } - - /** - * Adds new world surface rule for the given block - * - * @param surfaceBlock {@link Block} to use. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder surface(Block surfaceBlock) { - return surface(surfaceBlock.defaultBlockState()); - } - - /** - * Adds new world surface rule for the given block - * - * @param surfaceBlock {@link BlockState} to use. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder surface(BlockState surfaceBlock) { - return surface(SurfaceRuleBuilder.start().surface(surfaceBlock).build()); - } - - /** - * Adds blocks to the biome surface and below it (with specified depth). - * - * @param surfaceBlock {@link Block} that will cover biome. - * @param subterrainBlock {@link Block} below it with specified depth. - * @param depth thickness of bottom block layer. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder surface(Block surfaceBlock, Block subterrainBlock, int depth) { - return surface(SurfaceRuleBuilder - .start() - .surface(surfaceBlock.defaultBlockState()) - .subsurface(subterrainBlock.defaultBlockState(), depth) - .build()); - } - - /** - * Adds surface rule to this biome. - * - * @param newSurfaceRule {link SurfaceRules.RuleSource} surface rule. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder surface(SurfaceRules.RuleSource newSurfaceRule) { - this.surfaceRule = newSurfaceRule; - return this; - } - - /** - * Changes the type for the Biome. The intended Type defines in which Dimension a - * Biome is allowed to spawn. Currently each Biome can only spawn in one dimension - * - * @param type The intended type - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder intendedType(BiomeAPI.BiomeType type) { - this.biomeType = type; - return this; - } - - - /** - * Changes the intended type for the Biome to an EndLand Biome - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder endLandBiome() { - return intendedType(BiomeAPI.BiomeType.BCL_END_LAND); - } - - /** - * Changes the intended type for the Biome to an EndVoid (aka small islands) Biome - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder endVoidBiome() { - return intendedType(BiomeAPI.BiomeType.BCL_END_VOID); - } - - /** - * Changes the intended type for the Biome to an Endbarrens Biome - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder endBarrensBiome() { - return intendedType(BiomeAPI.BiomeType.BCL_END_BARRENS); - } - - /** - * Changes the intended type for the Biome to an End Center Island Biome - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder endCenterBiome() { - return intendedType(BiomeAPI.BiomeType.BCL_END_CENTER); - } - - /** - * Changes the intended type for the Biome to a Nether Biome - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder netherBiome() { - return intendedType(BiomeAPI.BiomeType.BCL_NETHER); - } - - public BCLBiomeBuilder tag(TagKey... tag) { - for (TagKey t : tag) { - tags.add(t); - } - return this; - } - - /** - * Set terrain height for the biome. Can be used in custom generators, doesn't change vanilla biome distribution or generation. - * - * @param height a relative float terrain height value. - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder terrainHeight(float height) { - this.height = height; - return this; - } - - - /** - * Make this a vertical Biome - * - * @return same {@link BCLBiomeBuilder} instance. - */ - public BCLBiomeBuilder vertical() { - this.vertical = vertical; - return this; - } - - - private static BiomeGenerationSettings fixGenerationSettings(BiomeGenerationSettings settings) { - //Fabric Biome Modification API can not handle an empty carver map, thus we will create one with - //an empty HolderSet for every possible step: - //https://github.com/FabricMC/fabric/issues/2079 - //TODO: Remove, once fabric gets fixed - if (settings instanceof BiomeGenerationSettingsAccessor acc) { - Map>> carvers = CollectionsUtil.getMutable(acc.bclib_getCarvers()); - for (GenerationStep.Carving step : GenerationStep.Carving.values()) { - carvers.computeIfAbsent(step, __ -> HolderSet.direct(Lists.newArrayList())); - } - acc.bclib_setCarvers(carvers); - } - return settings; - } - - - /** - * Get or create {@link BiomeSpecialEffects.Builder} for biome visual effects. - * For internal usage only. - * For internal usage only. - * - * @return new or same {@link BiomeSpecialEffects.Builder} instance. - */ - private BiomeSpecialEffects.Builder getEffects() { - if (effectsBuilder == null) { - effectsBuilder = new BiomeSpecialEffects.Builder(); - } - return effectsBuilder; - } - - /** - * Get or create {@link MobSpawnSettings.Builder} for biome mob spawning. - * For internal usage only. - * - * @return new or same {@link MobSpawnSettings.Builder} instance. - */ - private MobSpawnSettings.Builder getSpawns() { - if (spawnSettings == null) { - spawnSettings = new MobSpawnSettings.Builder(); - } - return spawnSettings; - } - - /** - * Get or create {@link BiomeGenerationSettings.Builder} for biome features and generation. - * For internal usage only. - * - * @return new or same {@link BiomeGenerationSettings.Builder} instance. - */ - private BiomeGenerationSettings.Builder getGeneration() { - if (generationSettings == null) { - generationSettings = new BiomeGenerationSettings.Builder(); - } - return generationSettings; - } - - /** - * Finalize biome creation. - * - * @return created {@link BCLBiome} instance. - */ - public BCLBiome build() { - return build((BiomeSupplier) BCLBiome::new); - } - - - /** - * Finalize biome creation. - * - * @param biomeConstructor {@link BiomeSupplier} biome constructor. - * @return created {@link BCLBiome} instance. - */ - public T build(BiomeSupplier biomeConstructor) { - BiomeBuilder builder = new BiomeBuilder() - .precipitation(precipitation) - .temperature(temperature) - .downfall(downfall); - - builder.mobSpawnSettings(getSpawns().build()); - builder.specialEffects(getEffects().build()); - - builder.generationSettings(fixGenerationSettings(getGeneration().build())); - - BCLBiomeSettings settings = BCLBiomeSettings.createBCL() - .setTerrainHeight(height) - .setFogDensity(fogDensity) - .setGenChance(genChance) - .setEdgeSize(edgeSize) - .setEdge(edge) - .setVertical(vertical) - .build(); - - final Biome biome = builder.build(); - final T res = biomeConstructor.apply(biomeID, biome, settings); - tags.forEach(tagKey -> TagManager.BIOMES.add(tagKey, res.getBiomeKey())); - - //res.addBiomeTags(tags); - //res.setSurface(surfaceRule); - SurfaceRuleRegistry.registerRule(biomeID, surfaceRule, biomeID); - res.addClimateParameters(parameters); - if (biomeType != null) - res._setIntendedType(biomeType); - - - //carvers.forEach(cfg -> BiomeAPI.addBiomeCarver(biome, cfg.second, cfg.first)); - return res; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeRegistry.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeRegistry.java deleted file mode 100644 index ae926be0..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeRegistry.java +++ /dev/null @@ -1,167 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - -import org.betterx.bclib.BCLib; -import org.betterx.worlds.together.WorldsTogether; -import org.betterx.worlds.together.world.event.WorldBootstrap; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.Lifecycle; -import net.minecraft.core.Holder; -import net.minecraft.core.MappedRegistry; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.world.level.biome.Biomes; - -import java.util.Optional; -import java.util.stream.Stream; -import org.jetbrains.annotations.ApiStatus; - -public class BCLBiomeRegistry { - public static final ResourceKey> BCL_BIOMES_REGISTRY = - createRegistryKey(WorldsTogether.makeID("worldgen/betterx/biome")); - - public static final ResourceKey>> BCL_BIOME_CODEC_REGISTRY = - createRegistryKey(WorldsTogether.makeID("worldgen/betterx/biome_codec")); - - public static Registry> BIOME_CODECS = Registry.registerSimple( - BCL_BIOME_CODEC_REGISTRY, - BCLBiomeRegistry::bootstrapCodecs - ); - public static Registry BUILTIN_BCL_BIOMES = new MappedRegistry<>( - BCL_BIOMES_REGISTRY, - Lifecycle.stable(), null - ); - - /** - * Empty biome used as default value if requested biome doesn't exist or linked. Shouldn't be registered anywhere to prevent bugs. - * Have {@code Biomes.THE_VOID} as the reference biome. - **/ - public static final BCLBiome EMPTY_BIOME = new BCLBiome(Biomes.THE_VOID.location()); - - /** - * Register a codec for a custom subclass of {@link BCLBiome}. Each subclass needs to provide - * a codec, otherwise the instance will get rebuild as a regular BCLib biome loosing the Type - * of the class as well as all member values - * - * @param location A {@link ResourceLocation} identifying this class - * @param codec The matching Codec - * @return The codec that will get used - */ - public static Codec registerBiomeCodec( - ResourceLocation location, - KeyDispatchDataCodec codec - ) { - Registry.register(BIOME_CODECS, location, codec.codec()); - return codec.codec(); - } - - /** - * Register new Biome Data - * - * @param access The {@link RegistryAccess} to use. If null, we will use the - * built inregistry ({@link BCLBiomeRegistry#BUILTIN_BCL_BIOMES}) - * @param biome The Biome Data to register - * @return The resource-key for the registry - */ - @ApiStatus.Internal - public static ResourceKey register(RegistryAccess access, BCLBiome biome) { - Registry.register( - access == null ? BUILTIN_BCL_BIOMES : access.registryOrThrow(BCL_BIOMES_REGISTRY), - biome.getBCLBiomeKey(), - biome - ); - return biome.getBCLBiomeKey(); - } - - private static ResourceKey> createRegistryKey(ResourceLocation location) { - return ResourceKey.createRegistryKey(location); - } - - private static Codec bootstrapCodecs(Registry> registry) { - return Registry.register(registry, BCLib.makeID("biome"), BCLBiome.KEY_CODEC.codec()); - } - - - @ApiStatus.Internal - public static Holder bootstrap(Registry registry) { - BuiltinRegistries.register(registry, BiomeAPI.SMALL_END_ISLANDS.getBCLBiomeKey(), BiomeAPI.SMALL_END_ISLANDS); - BuiltinRegistries.register(registry, BiomeAPI.END_BARRENS.getBCLBiomeKey(), BiomeAPI.END_BARRENS); - BuiltinRegistries.register(registry, BiomeAPI.END_HIGHLANDS.getBCLBiomeKey(), BiomeAPI.END_HIGHLANDS); - BuiltinRegistries.register(registry, BiomeAPI.END_MIDLANDS.getBCLBiomeKey(), BiomeAPI.END_MIDLANDS); - BuiltinRegistries.register(registry, BiomeAPI.THE_END.getBCLBiomeKey(), BiomeAPI.THE_END); - BuiltinRegistries.register( - registry, - BiomeAPI.BASALT_DELTAS_BIOME.getBCLBiomeKey(), - BiomeAPI.BASALT_DELTAS_BIOME - ); - BuiltinRegistries.register( - registry, - BiomeAPI.SOUL_SAND_VALLEY_BIOME.getBCLBiomeKey(), - BiomeAPI.SOUL_SAND_VALLEY_BIOME - ); - BuiltinRegistries.register( - registry, - BiomeAPI.WARPED_FOREST_BIOME.getBCLBiomeKey(), - BiomeAPI.WARPED_FOREST_BIOME - ); - BuiltinRegistries.register( - registry, - BiomeAPI.CRIMSON_FOREST_BIOME.getBCLBiomeKey(), - BiomeAPI.CRIMSON_FOREST_BIOME - ); - BuiltinRegistries.register( - registry, - BiomeAPI.NETHER_WASTES_BIOME.getBCLBiomeKey(), - BiomeAPI.NETHER_WASTES_BIOME - ); - return BuiltinRegistries.register(registry, EMPTY_BIOME.getBCLBiomeKey(), EMPTY_BIOME); - } - - public static BCLBiome get(ResourceLocation loc) { - return get(WorldBootstrap.getLastRegistryAccessOrElseBuiltin(), loc); - } - - public static BCLBiome get(RegistryAccess access, ResourceLocation loc) { - return getBclBiomesRegistry(access).get(loc); - } - - public static BCLBiome getOrElseEmpty(ResourceLocation loc) { - return getOrElseEmpty(WorldBootstrap.getLastRegistryAccessOrElseBuiltin(), loc); - } - - public static BCLBiome getOrElseEmpty(RegistryAccess access, ResourceLocation loc) { - BCLBiome res = get(access, loc); - if (res == null) return EMPTY_BIOME; - return res; - } - - public static Stream> getAll(BiomeAPI.BiomeType dim) { - return getAll(WorldBootstrap.getLastRegistryAccessOrElseBuiltin(), dim); - } - - public static Stream> getAll(RegistryAccess access, BiomeAPI.BiomeType dim) { - return getBclBiomesRegistry(access) - .entrySet() - .stream() - .filter(e -> e.getValue().getIntendedType().is(dim)) - .map(e -> e.getKey()); - } - - private static Registry getBclBiomesRegistry(RegistryAccess access) { - if (access != null) { - return ((Optional>) access - .registry(BCLBiomeRegistry.BCL_BIOMES_REGISTRY)) - .orElse(BUILTIN_BCL_BIOMES); - } else { - return BUILTIN_BCL_BIOMES; - } - } - - public static void ensureStaticallyLoaded() { - - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeSettings.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeSettings.java deleted file mode 100644 index 948702c6..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BCLBiomeSettings.java +++ /dev/null @@ -1,218 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - -import org.betterx.bclib.api.v2.generator.BiomePicker; -import org.betterx.bclib.config.Configs; - -import net.minecraft.world.level.biome.Biome; - -public class BCLBiomeSettings { - public static Builder createBCL() { - return new Builder(); - } - - public static class Builder extends CommonBuilder { - public Builder() { - super(new BCLBiomeSettings()); - } - } - - public static class CommonBuilder { - private final T storage; - - CommonBuilder(T storage) { - this.storage = storage; - } - - public T build() { - return storage; - } - - /** - * Set gen chance for this biome, default value is 1.0. - * - * @param genChance chance of this biome to be generated. - * @return same {@link BCLBiomeSettings}. - */ - public R setGenChance(float genChance) { - storage.genChance = genChance; - return (R) this; - } - - /** - * Setter for terrain height, can be used in custom terrain generator. - * - * @param terrainHeight a relative float terrain height value. - * @return same {@link Builder}. - */ - public R setTerrainHeight(float terrainHeight) { - storage.terrainHeight = terrainHeight; - return (R) this; - } - - /** - * Set biome vertical distribution (for tall Nether only). - * - * @return same {@link Builder}. - */ - public R setVertical() { - return setVertical(true); - } - - /** - * Set biome vertical distribution (for tall Nether only). - * - * @param vertical {@code boolean} value. - * @return same {@link Builder}. - */ - public R setVertical(boolean vertical) { - storage.vertical = vertical; - return (R) this; - } - - /** - * Set edges size for this biome. Size is in blocks. - * - * @param size as a float value. - * @return same {@link Builder}. - */ - public R setEdgeSize(int size) { - storage.edgeSize = size; - return (R) this; - } - - /** - * Set edges:biome for this biome. - * - * @param edge The {@link Biome}. - * @return same {@link Builder}. - */ - public R setEdge(BCLBiome edge) { - storage.edge = edge; - return (R) this; - } - - /** - * Sets fog density for this biome. - * - * @param fogDensity - * @return same {@link Builder}. - */ - public R setFogDensity(float fogDensity) { - storage.fogDensity = fogDensity; - return (R) this; - } - } - - BCLBiomeSettings( - float terrainHeight, - float fogDensity, - float genChance, - int edgeSize, - boolean vertical, - BCLBiome edge - ) { - this.terrainHeight = terrainHeight; - this.fogDensity = fogDensity; - this.genChance = genChance; - this.edgeSize = edgeSize; - this.vertical = vertical; - this.edge = edge; - } - - protected BCLBiomeSettings() { - this.terrainHeight = 0.1F; - this.fogDensity = 1.0F; - this.genChance = 1.0F; - this.edgeSize = 0; - this.vertical = false; - this.edge = null; - } - - float terrainHeight; - float fogDensity; - float genChance; - int edgeSize; - boolean vertical; - BCLBiome edge; - - - /** - * Getter for biome generation chance, used in {@link BiomePicker} and in custom generators. - * - * @return biome generation chance as float. - */ - public float getGenChance() { - return this.genChance; - } - - /** - * Checks if biome is vertical, for tall Nether only (or for custom generators). - * - * @return is biome vertical or not. - */ - public boolean isVertical() { - return vertical; - } - - /** - * Getter for terrain height, can be used in custom terrain generator. - * - * @return terrain height. - */ - public float getTerrainHeight() { - return terrainHeight; - } - - /** - * Getter for fog density, used in custom for renderer. - * - * @return fog density as a float. - */ - public float getFogDensity() { - return fogDensity; - } - - /** - * Getter for biome edge size. - * - * @return edge size in blocks. - */ - public int getEdgeSize() { - return edgeSize; - } - - /** - * Getter for edge-biome. - * - * @return The assigned edge biome. - */ - public BCLBiome getEdge() { - return edge; - } - - /** - * Load values from Config and apply to the passed Biome. The Default values for the loaded settings - * are derifed from the values store in this object - * - * @param biome {@link BCLBiome} to assign values to - */ - public void applyWithDefaults(BCLBiome biome) { - final String group = biome.configGroup(); - biome.genChance = Configs.BIOMES_CONFIG.getFloat(group, "generation_chance", this.genChance); - - if (edge != null) { - biome.edgeSize = Configs.BIOMES_CONFIG.getInt(group, "edge_size", this.edgeSize); - if (edgeSize > 0) { - biome.setEdge(edge); - } - } - - if (!(this instanceof VanillaBiomeSettings)) { - biome.fogDensity = Configs.BIOMES_CONFIG.getFloat(group, "fog_density", this.fogDensity); - biome.vertical = Configs.BIOMES_CONFIG.getBoolean(group, "vertical", this.vertical); - biome.terrainHeight = Configs.BIOMES_CONFIG.getFloat(group, "terrain_height", this.terrainHeight); - } - - Configs.BIOMES_CONFIG.saveChanges(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BiomeAPI.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BiomeAPI.java deleted file mode 100644 index cf3b7e53..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BiomeAPI.java +++ /dev/null @@ -1,930 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v3.levelgen.features.BCLFeature; -import org.betterx.bclib.interfaces.SurfaceMaterialProvider; -import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor; -import org.betterx.bclib.mixin.common.MobSpawnSettingsAccessor; -import org.betterx.bclib.util.CollectionsUtil; -import org.betterx.worlds.together.tag.v3.CommonBiomeTags; -import org.betterx.worlds.together.tag.v3.TagManager; -import org.betterx.worlds.together.world.event.WorldBootstrap; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.core.HolderSet; -import net.minecraft.core.Registry; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BiomeTags; -import net.minecraft.util.random.WeightedRandomList; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.Biomes; -import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.PalettedContainer; -import net.minecraft.world.level.chunk.PalettedContainerRO; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.GenerationStep.Decoration; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -import net.fabricmc.fabric.api.biome.v1.NetherBiomes; -import net.fabricmc.fabric.api.biome.v1.TheEndBiomes; - -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; - -import java.util.*; -import java.util.function.BiConsumer; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class BiomeAPI { - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * - * @param bclbiome {@link BCLBiome} - * @param dim The Dimension fo rthis Biome - * @return {@link BCLBiome} - */ - public static BCLBiome registerBuiltinBiomeAndOverrideIntendedDimension(BCLBiome bclbiome, BiomeType dim) { - return registerBiomeAndOverrideIntendedDimension(bclbiome, dim, BuiltinRegistries.BIOME); - } - - static BCLBiome registerBiomeAndOverrideIntendedDimension( - BCLBiome bclbiome, - BiomeType dim, - Registry registryOrNull - ) { - bclbiome._setIntendedType(dim); - return registerBiome(bclbiome, registryOrNull); - } - - public static class BiomeType { - public static final Codec DIRECT_CODEC = RecordCodecBuilder.create(instance -> instance - .group( - Codec.STRING.fieldOf("name") - .orElse("undefined") - .forGetter(o -> o.name) - - ).apply(instance, BiomeType::create)); - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - Codec.STRING.fieldOf("name") - .orElse("undefined") - .forGetter(o -> o.name), - Codec.STRING.fieldOf("parent") - .orElse("none") - .forGetter(o -> o.parentOrNull == null ? "none" : o.parentOrNull.name) - - ).apply(instance, BiomeType::create)); - - private static final Map KNOWN_TYPES = new HashMap<>(); - - public static final BiomeType NONE = new BiomeType("NONE"); - public static final BiomeType OVERWORLD = new BiomeType("OVERWORLD"); - public static final BiomeType NETHER = new BiomeType("NETHER"); - public static final BiomeType BCL_NETHER = new BiomeType("BCL_NETHER", NETHER, (biome, ignored) -> { - ResourceKey key = biome.getBiomeKey(); - if (!biome.isEdgeBiome()) { - biome.forEachClimateParameter(p -> NetherBiomes.addNetherBiome(key, p)); - } - }); - public static final BiomeType END = new BiomeType("END"); - public static final BiomeType END_IGNORE = new BiomeType("END_IGNORE", END); - public static final BiomeType END_LAND = new BiomeType("END_LAND", END); - public static final BiomeType END_VOID = new BiomeType("END_VOID", END); - public static final BiomeType END_CENTER = new BiomeType("END_CENTER", END); - public static final BiomeType END_BARRENS = new BiomeType("END_BARRENS", END); - public static final BiomeType BCL_END_LAND = new BiomeType("BCL_END_LAND", END_LAND, (biome, ignored) -> { - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - - if (biome.isEdgeBiome()) { - ResourceKey parentKey = biome.getParentBiome().getBiomeKey(); - TheEndBiomes.addMidlandsBiome(parentKey, key, weight); - } else { - TheEndBiomes.addHighlandsBiome(key, weight); - } - }); - public static final BiomeType BCL_END_VOID = new BiomeType("BCL_END_VOID", END_VOID, (biome, ignored) -> { - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - if (!biome.isEdgeBiome()) { - TheEndBiomes.addSmallIslandsBiome(key, weight); - } - }); - public static final BiomeType BCL_END_CENTER = new BiomeType("BCL_END_CENTER", END_CENTER, (biome, ignored) -> { - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - if (!biome.isEdgeBiome()) { - TheEndBiomes.addMainIslandBiome(key, weight); - } - }); - - public static final BiomeType BCL_END_BARRENS = new BiomeType( - "BCL_END_BARRENS", - END_BARRENS, - (biome, highlandBiome) -> { - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - if (!biome.isEdgeBiome()) { - ResourceKey parentKey = highlandBiome.getBiomeKey(); - TheEndBiomes.addBarrensBiome(parentKey, key, weight); - } - } - ); - - public final BiomeType parentOrNull; - private final String name; - - @FunctionalInterface - interface ExtraRegisterTaks { - void register(@NotNull BCLBiome biome, @Nullable BCLBiome parent); - } - - final ExtraRegisterTaks extraRegisterTask; - - private static BiomeType create(String name, String parentOrNull) { - BiomeType known = KNOWN_TYPES.get(name); - BiomeType parent = parentOrNull == null || "none".equals(parentOrNull) - ? null - : KNOWN_TYPES.get(parentOrNull); - if (known != null) { - if (known.parentOrNull != parent) { - BCLib.LOGGER.warning("BiomeType " + name + " was deserialized with parent " + parent + " but already has " + known.parentOrNull); - } - return known; - } - return new BiomeType(name, parent); - } - - static BiomeType create(String name) { - BiomeType known = KNOWN_TYPES.get(name); - if (known != null) { - return known; - } - return NONE; - } - - public BiomeType(String name) { - this(name, null); - } - - public BiomeType(String name, BiomeType parentOrNull) { - this(name, parentOrNull, (b, a) -> { - }); - } - - public BiomeType(String name, BiomeType parentOrNull, ExtraRegisterTaks extraRegisterTask) { - this.parentOrNull = parentOrNull; - this.name = name; - this.extraRegisterTask = extraRegisterTask; - KNOWN_TYPES.put(name, this); - } - - public boolean is(BiomeType d) { - if (d == this) return true; - if (parentOrNull != null) return parentOrNull.is(d); - return false; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - String str = name; - if (parentOrNull != null) str += " -> " + parentOrNull; - return str; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - BiomeType biomeType = (BiomeType) o; - return name.equals(biomeType.name); - } - - @Override - public int hashCode() { - return Objects.hash(name); - } - } - - public static final BCLBiome NETHER_WASTES_BIOME = InternalBiomeAPI.wrapNativeBiome( - Biomes.NETHER_WASTES, - InternalBiomeAPI.OTHER_NETHER - ); - public static final BCLBiome CRIMSON_FOREST_BIOME = InternalBiomeAPI.wrapNativeBiome( - Biomes.CRIMSON_FOREST, - InternalBiomeAPI.OTHER_NETHER - ); - public static final BCLBiome WARPED_FOREST_BIOME = InternalBiomeAPI.wrapNativeBiome( - Biomes.WARPED_FOREST, - InternalBiomeAPI.OTHER_NETHER - ); - public static final BCLBiome SOUL_SAND_VALLEY_BIOME = InternalBiomeAPI.wrapNativeBiome( - Biomes.SOUL_SAND_VALLEY, - InternalBiomeAPI.OTHER_NETHER - ); - public static final BCLBiome BASALT_DELTAS_BIOME = InternalBiomeAPI.wrapNativeBiome( - Biomes.BASALT_DELTAS, - InternalBiomeAPI.OTHER_NETHER - ); - - - public static final BCLBiome THE_END = InternalBiomeAPI.wrapNativeBiome( - Biomes.THE_END, - 0.5F, - InternalBiomeAPI.OTHER_END_CENTER - ); - - public static final BCLBiome END_MIDLANDS = InternalBiomeAPI.wrapNativeBiome( - Biomes.END_MIDLANDS, - 0.5F, - InternalBiomeAPI.OTHER_END_LAND - ); - - public static final BCLBiome END_HIGHLANDS = InternalBiomeAPI.wrapNativeBiome( - Biomes.END_HIGHLANDS, - END_MIDLANDS, - 8, - 0.5F, - InternalBiomeAPI.OTHER_END_LAND - ); - - - public static final BCLBiome END_BARRENS = InternalBiomeAPI.wrapNativeBiome( - Biomes.END_BARRENS, - InternalBiomeAPI.OTHER_END_BARRENS - ); - - public static final BCLBiome SMALL_END_ISLANDS = InternalBiomeAPI.wrapNativeBiome( - Biomes.SMALL_END_ISLANDS, - InternalBiomeAPI.OTHER_END_VOID - ); - - - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * - * @param bclbiome {@link BCLBiome} - * @return {@link BCLBiome} - */ - static BCLBiome registerBiome(BCLBiome bclbiome, Registry registryOrNull) { - BiomeType dim = bclbiome.getIntendedType(); - if (registryOrNull != null - && bclbiome.biomeToRegister != null - && registryOrNull.get(bclbiome.getID()) == null) { - Registry.register(registryOrNull, bclbiome.getBiomeKey(), bclbiome.biomeToRegister); - - BCLBiomeRegistry.register(null, bclbiome); - } - - if (dim != null && dim.is(BiomeType.NETHER)) { - TagManager.BIOMES.add(BiomeTags.IS_NETHER, bclbiome.getBiomeKey()); - TagManager.BIOMES.add(CommonBiomeTags.IN_NETHER, bclbiome.getBiomeKey()); - } else if (dim != null && dim.is(BiomeType.END)) { - TagManager.BIOMES.add(BiomeTags.IS_END, bclbiome.getBiomeKey()); - TagManager.BIOMES.add(CommonBiomeTags.IN_END, bclbiome.getBiomeKey()); - } - - bclbiome.afterRegistration(); - - return bclbiome; - } - - public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome) { - return registerSubBiome( - parent, - subBiome, - parent.getIntendedType() - ); - } - - public static BCLBiome registerSubBiome(BCLBiome parent, Biome subBiome, float genChance) { - return registerSubBiome( - parent, - subBiome, - genChance, - parent.getIntendedType() - ); - } - - public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome, BiomeType dim) { - registerBuiltinBiomeAndOverrideIntendedDimension(subBiome, dim); - parent.addSubBiome(subBiome); - - return subBiome; - } - - public static BCLBiome registerSubBiome(BCLBiome parent, Biome biome, float genChance, BiomeType dim) { - BCLBiome subBiome = new BCLBiome(biome, VanillaBiomeSettings.createVanilla().setGenChance(genChance).build()); - return registerSubBiome(parent, subBiome, dim); - } - - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * After that biome will be added to BCLib End Biome Generator and into Fabric Biome API as a land biome (will generate only on islands). - * - * @param biome {@link BCLBiome} - * @return {@link BCLBiome} - */ - public static BCLBiome registerEndLandBiome(BCLBiome biome) { - registerBuiltinBiomeAndOverrideIntendedDimension(biome, BiomeType.BCL_END_LAND); - - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - - if (biome.isEdgeBiome()) { - ResourceKey parentKey = biome.getParentBiome().getBiomeKey(); - TheEndBiomes.addMidlandsBiome(parentKey, key, weight); - } else { - TheEndBiomes.addHighlandsBiome(key, weight); - } - - return biome; - } - - - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * After that biome will be added to BCLib End Biome Generator and into Fabric Biome API as a void biome (will generate only in the End void - between islands). - * - * @param biome {@link BCLBiome} - * @return {@link BCLBiome} - */ - public static BCLBiome registerEndVoidBiome(BCLBiome biome) { - registerBuiltinBiomeAndOverrideIntendedDimension(biome, BiomeType.BCL_END_VOID); - - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - if (!biome.isEdgeBiome()) { - TheEndBiomes.addSmallIslandsBiome(key, weight); - } - return biome; - } - - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * After that biome will be added to BCLib End Biome Generator and into Fabric Biome API as a center island - * biome (will generate only on the center island). - * - * @param biome {@link BCLBiome} - * @return {@link BCLBiome} - */ - public static BCLBiome registerEndCenterBiome(BCLBiome biome) { - registerBuiltinBiomeAndOverrideIntendedDimension(biome, BiomeType.BCL_END_CENTER); - - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - if (!biome.isEdgeBiome()) { - TheEndBiomes.addMainIslandBiome(key, weight); - } - return biome; - } - - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * After that biome will be added to BCLib End Biome Generator and into Fabric Biome API as a barrens island - * biome (will generate on the edge of midland biomes on the larger islands). - * - * @param biome {@link BCLBiome} - * @return {@link BCLBiome} - */ - public static BCLBiome registerEndBarrensBiome(BCLBiome highlandBiome, BCLBiome biome) { - registerBuiltinBiomeAndOverrideIntendedDimension(biome, BiomeType.BCL_END_BARRENS); - - float weight = biome.getGenChance(); - ResourceKey key = biome.getBiomeKey(); - if (!biome.isEdgeBiome()) { - ResourceKey parentKey = highlandBiome.getBiomeKey(); - TheEndBiomes.addBarrensBiome(parentKey, key, weight); - } - return biome; - } - - - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * After that biome will be added to BCLib Nether Biome Generator and into Fabric Biome API. - * - * @param bclBiome {@link BCLBiome} - * @return {@link BCLBiome} - */ - public static BCLBiome registerNetherBiome(BCLBiome bclBiome) { - registerBuiltinBiomeAndOverrideIntendedDimension(bclBiome, BiomeType.BCL_NETHER); - - ResourceKey key = bclBiome.getBiomeKey(); - if (!bclBiome.isEdgeBiome()) { - bclBiome.forEachClimateParameter(p -> NetherBiomes.addNetherBiome(key, p)); - } - return bclBiome; - } - - /** - * Get {@link BCLBiome} from biome on client. Used in fog rendering. - * - * @param biome - {@link Biome} from client world. - * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. - */ - public static BCLBiome getRenderBiome(Biome biome) { - BCLBiome endBiome = InternalBiomeAPI.CLIENT.get(biome); - if (endBiome == null) { - ResourceLocation id = WorldBootstrap.getLastRegistryAccessOrElseBuiltin() - .registryOrThrow(Registry.BIOME_REGISTRY) - .getKey(biome); - endBiome = id == null - ? BCLBiomeRegistry.EMPTY_BIOME - : BCLBiomeRegistry.getOrElseEmpty(id); - InternalBiomeAPI.CLIENT.put(biome, endBiome); - } - return endBiome; - } - - /** - * Get biome {@link ResourceKey} from given {@link Biome}. - * - * @param biome - {@link Biome} from server world. - * @return biome {@link ResourceKey} or {@code null}. - */ - @Nullable - public static ResourceKey getBiomeKey(Biome biome) { - if (InternalBiomeAPI.biomeRegistry != null) { - Optional> key = InternalBiomeAPI.biomeRegistry.getResourceKey(biome); - if (key.isPresent()) return key.get(); - } - return BuiltinRegistries.BIOME - .getResourceKey(biome) - .orElseGet(null); - } - - /** - * Get biome {@link ResourceLocation} from given {@link Biome}. - * - * @param biome - {@link Biome} from server world. - * @return biome {@link ResourceLocation}. - */ - public static ResourceLocation getBiomeID(Biome biome) { - ResourceLocation id = null; - if (InternalBiomeAPI.biomeRegistry != null) { - id = InternalBiomeAPI.biomeRegistry.getKey(biome); - } - if (id == null) { - id = BuiltinRegistries.BIOME.getKey(biome); - } - - if (id == null) { - BCLib.LOGGER.error("Unable to get ID for " + biome + ". Falling back to empty Biome..."); - id = BCLBiomeRegistry.EMPTY_BIOME.getID(); - } - - return id; - } - - /** - * Get biome {@link ResourceLocation} from given {@link Biome}. - * - * @param biome - {@link Holder} from server world. - * @return biome {@link ResourceLocation}. - */ - public static ResourceLocation getBiomeID(Holder biome) { - return biome - .unwrapKey() - .map(h -> h.location()) - .orElse(null); - } - - public static ResourceKey getBiomeKey(Holder biome) { - return biome.unwrapKey().orElse(null); - } - - public static ResourceKey getBiomeKeyOrThrow(Holder biome) { - return biome.unwrapKey().orElseThrow(); - } - - public static Holder getBiomeHolder(BCLBiome biome) { - return getBiomeHolder(biome.getBiomeKey()); - } - - public static Holder getBiomeHolder(Biome biome) { - Optional> key = Optional.empty(); - if (InternalBiomeAPI.biomeRegistry != null) { - key = InternalBiomeAPI.biomeRegistry.getResourceKey(biome); - } else { - key = BuiltinRegistries.BIOME.getResourceKey(biome); - } - - return getBiomeHolder(key.orElseThrow()); - } - - public static Holder getBiomeHolder(ResourceKey biomeKey) { - if (InternalBiomeAPI.biomeRegistry != null) { - return InternalBiomeAPI.biomeRegistry.getOrCreateHolderOrThrow(biomeKey); - } - return BuiltinRegistries.BIOME.getOrCreateHolderOrThrow(biomeKey); - } - - public static Holder getBiomeHolder(ResourceLocation biome) { - return getBiomeHolder(ResourceKey.create(Registry.BIOME_REGISTRY, biome)); - } - - /** - * Get {@link BCLBiome} from given {@link ResourceLocation}. - * - * @param biomeID - biome {@link ResourceLocation}. - * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. - */ - public static BCLBiome getBiome(ResourceLocation biomeID) { - if (biomeID == null) return BCLBiomeRegistry.EMPTY_BIOME; - return BCLBiomeRegistry.getOrElseEmpty(biomeID); - } - - /** - * Get {@link BCLBiome} from given {@link Biome}. - * - * @param biome - biome {@link Biome}. - * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. - */ - public static BCLBiome getBiome(Biome biome) { - return getBiome(BiomeAPI.getBiomeID(biome)); - } - - /** - * Get {@link BCLBiome} from given {@link Biome}. - * - * @param biome - biome {@link Biome}. - * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. - */ - public static BCLBiome getBiome(Holder biome) { - return getBiome(BiomeAPI.getBiomeID(biome)); - } - - /** - * Check if biome with {@link ResourceLocation} exists in API registry. - * - * @param biomeID - biome {@link ResourceLocation}. - * @return {@code true} if biome exists in API registry and {@code false} if not. - */ - public static boolean hasBiome(ResourceLocation biomeID) { - return BCLBiomeRegistry.get(biomeID) != null; - } - - public static Holder getFromRegistry(ResourceLocation biomeID) { - if (InternalBiomeAPI.biomeRegistry != null) - return InternalBiomeAPI.biomeRegistry.getHolder(ResourceKey.create(Registry.BIOME_REGISTRY, biomeID)) - .orElseThrow(); - return getFromBuiltinRegistry(biomeID); - } - - @Nullable - public static Holder getFromRegistry(ResourceKey key) { - if (InternalBiomeAPI.biomeRegistry != null) - return InternalBiomeAPI.biomeRegistry.getHolder(key).orElseThrow(); - return getFromBuiltinRegistry(key); - } - - @Nullable - public static Holder getFromBuiltinRegistry(ResourceLocation biomeID) { - return BuiltinRegistries.BIOME.getHolder(ResourceKey.create(Registry.BIOME_REGISTRY, biomeID)).orElse(null); - } - - @Nullable - public static Holder getFromBuiltinRegistry(ResourceKey key) { - return BuiltinRegistries.BIOME.getHolder(key).orElse(null); - } - - - public static boolean isDatapackBiome(ResourceLocation biomeID) { - return getFromBuiltinRegistry(biomeID) == null; - } - - public static boolean wasRegisteredAs(ResourceLocation biomeID, BiomeType dim) { - if (BCLBiomeRegistry.EMPTY_BIOME.getID().equals(biomeID)) - return false; - return BCLBiomeRegistry.getOrElseEmpty(biomeID).getIntendedType().is(dim); - } - - public static boolean wasRegisteredAsNetherBiome(ResourceLocation biomeID) { - return wasRegisteredAs(biomeID, BiomeType.NETHER); - } - - public static boolean wasRegisteredAsEndBiome(ResourceLocation biomeID) { - return wasRegisteredAs(biomeID, BiomeType.END); - } - - public static boolean wasRegisteredAsEndLandBiome(ResourceLocation biomeID) { - return wasRegisteredAs(biomeID, BiomeType.END_LAND); - } - - public static boolean wasRegisteredAsEndVoidBiome(ResourceLocation biomeID) { - return wasRegisteredAs(biomeID, BiomeType.END_VOID); - } - - public static boolean wasRegisteredAsEndCenterBiome(ResourceLocation biomeID) { - return wasRegisteredAs(biomeID, BiomeType.END_CENTER); - } - - public static boolean wasRegisteredAsEndBarrensBiome(ResourceLocation biomeID) { - return wasRegisteredAs(biomeID, BiomeType.END_BARRENS); - } - - /** - * Registers new biome modification for specified dimension. Will work both for mod and datapack biomes. - * - * @param dimensionID {@link ResourceLocation} dimension ID, example: Level.OVERWORLD or "minecraft:overworld". - * @param modification {@link BiConsumer} with {@link ResourceKey} biome ID and {@link Biome} parameters. - */ - public static void registerBiomeModification( - ResourceKey dimensionID, - BiConsumer> modification - ) { - List>> modifications = InternalBiomeAPI.MODIFICATIONS.computeIfAbsent( - dimensionID, - k -> Lists.newArrayList() - ); - modifications.add(modification); - } - - /** - * Registers new biome modification for the Overworld. Will work both for mod and datapack biomes. - * - * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. - */ - public static void registerOverworldBiomeModification(BiConsumer> modification) { - registerBiomeModification(LevelStem.OVERWORLD, modification); - } - - /** - * Registers new biome modification for the Nether. Will work both for mod and datapack biomes. - * - * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. - */ - public static void registerNetherBiomeModification(BiConsumer> modification) { - registerBiomeModification(LevelStem.NETHER, modification); - } - - /** - * Registers new biome modification for the End. Will work both for mod and datapack biomes. - * - * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. - */ - public static void registerEndBiomeModification(BiConsumer> modification) { - registerBiomeModification(LevelStem.END, modification); - } - - /** - * Registers new biome modification for specified dimension that is executed when all - * BiomeTags are finalized by the game during level load. Will work both for mod and - * datapack biomes. - * - * @param dimensionID {@link ResourceLocation} dimension ID, example: Level.OVERWORLD or "minecraft:overworld". - * @param modification {@link BiConsumer} with {@link ResourceKey} biome ID and {@link Biome} parameters. - */ - public static void onFinishingBiomeTags( - ResourceKey dimensionID, - BiConsumer> modification - ) { - List>> modifications = InternalBiomeAPI.TAG_ADDERS.computeIfAbsent( - dimensionID, - k -> Lists.newArrayList() - ); - modifications.add(modification); - } - - /** - * Registers new biome modification for the Nether dimension that is executed when all - * BiomeTags are finalized by the game during level load. Will work both for mod and - * datapack biomes. - * - * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. - */ - public static void onFinishingNetherBiomeTags(BiConsumer> modification) { - onFinishingBiomeTags(Level.NETHER, modification); - } - - /** - * Registers new biome modification for the End that is executed when all - * BiomeTags are finalized by the game during level load. Will work both for mod and - * datapack biomes. - * - * @param modification {@link BiConsumer} with {@link ResourceLocation} biome ID and {@link Biome} parameters. - */ - public static void onFinishingEndBiomeTags(BiConsumer> modification) { - onFinishingBiomeTags(Level.END, modification); - } - - - /** - * Adds new features to existing biome. - * - * @param biome {@link Biome} to add features in. - * @param feature {@link ConfiguredFeature} to add. - */ - public static void addBiomeFeature( - Holder biome, - BCLFeature feature - ) { - addBiomeFeature(biome, feature.getDecoration(), feature.getPlacedFeature()); - } - - /** - * Adds new features to existing biome. - * - * @param biome {@link Biome} to add features in. - * @param step a {@link Decoration} step for the feature. - * @param featureList {@link ConfiguredFeature} to add. - */ - public static void addBiomeFeature(Holder biome, Decoration step, Holder... featureList) { - addBiomeFeature(biome, step, List.of(featureList)); - } - - /** - * Adds new features to existing biome. - * - * @param biome {@link Biome} to add features in. - * @param step a {@link Decoration} step for the feature. - * @param additionalFeatures List of {@link ConfiguredFeature} to add. - */ - private static void addBiomeFeature( - Holder biome, - Decoration step, - List> additionalFeatures - ) { - BiomeGenerationSettingsAccessor accessor = (BiomeGenerationSettingsAccessor) biome.value() - .getGenerationSettings(); - List> allFeatures = CollectionsUtil.getMutable(accessor.bclib_getFeatures()); - List> features = getFeaturesListCopy(allFeatures, step); - - for (var feature : additionalFeatures) { - if (!features.contains(feature)) - features.add(feature); - } - - allFeatures.set(step.ordinal(), HolderSet.direct(features)); - final Supplier>> flowerFeatures = Suppliers.memoize(() -> allFeatures.stream() - .flatMap( - HolderSet::stream) - .map(Holder::value) - .flatMap( - PlacedFeature::getFeatures) - .filter(configuredFeature -> configuredFeature.feature() == Feature.FLOWER) - .collect( - ImmutableList.toImmutableList())); - final Supplier> featureSet = Suppliers.memoize(() -> allFeatures.stream() - .flatMap(HolderSet::stream) - .map(Holder::value) - .collect(Collectors.toSet())); - accessor.bclib_setFeatures(allFeatures); - accessor.bclib_setFeatureSet(featureSet); - accessor.bclib_setFlowerFeatures(flowerFeatures); - } - - - /** - * Adds mob spawning to specified biome. - * - * @param biome {@link Biome} to add mob spawning. - * @param entityType {@link EntityType} mob type. - * @param weight spawn weight. - * @param minGroupCount minimum mobs in group. - * @param maxGroupCount maximum mobs in group. - */ - public static void addBiomeMobSpawn( - Holder biome, - EntityType entityType, - int weight, - int minGroupCount, - int maxGroupCount - ) { - final MobCategory category = entityType.getCategory(); - MobSpawnSettingsAccessor accessor = (MobSpawnSettingsAccessor) biome.value().getMobSettings(); - Map> spawners = CollectionsUtil.getMutable(accessor.bcl_getSpawners()); - List mobs = spawners.containsKey(category) - ? CollectionsUtil.getMutable(spawners.get(category) - .unwrap()) - : Lists.newArrayList(); - mobs.add(new SpawnerData(entityType, weight, minGroupCount, maxGroupCount)); - spawners.put(category, WeightedRandomList.create(mobs)); - accessor.bcl_setSpawners(spawners); - } - - - public static Optional findTopMaterial(WorldGenLevel world, BlockPos pos) { - return findTopMaterial(getBiome(world.getBiome(pos))); - } - - public static Optional findTopMaterial(Holder biome) { - return findTopMaterial(getBiome(biome.value())); - } - - public static Optional findTopMaterial(Biome biome) { - return findTopMaterial(getBiome(biome)); - } - - public static Optional findTopMaterial(BCLBiome biome) { - if (biome instanceof SurfaceMaterialProvider smp) { - return Optional.of(smp.getTopMaterial()); - } - return Optional.empty(); - } - - public static Optional findUnderMaterial(Holder biome) { - return findUnderMaterial(getBiome(biome.value())); - } - - public static Optional findUnderMaterial(BCLBiome biome) { - if (biome instanceof SurfaceMaterialProvider smp) { - return Optional.of(smp.getUnderMaterial()); - } - return Optional.empty(); - } - - /** - * Set biome in chunk at specified position. - * - * @param chunk {@link ChunkAccess} chunk to set biome in. - * @param pos {@link BlockPos} biome position. - * @param biome {@link Holder} instance. Should be biome from world. - */ - public static void setBiome(ChunkAccess chunk, BlockPos pos, Holder biome) { - int sectionY = (pos.getY() - chunk.getMinBuildHeight()) >> 4; - PalettedContainerRO> biomes = chunk.getSection(sectionY).getBiomes(); - if (biomes instanceof PalettedContainer> palette) { - palette.set((pos.getX() & 15) >> 2, (pos.getY() & 15) >> 2, (pos.getZ() & 15) >> 2, biome); - } else { - BCLib.LOGGER.warning("Unable to change Biome at " + pos); - } - } - - /** - * Set biome in world at specified position. - * - * @param level {@link LevelAccessor} world to set biome in. - * @param pos {@link BlockPos} biome position. - * @param biome {@link Holder} instance. Should be biome from world. - */ - public static void setBiome(LevelAccessor level, BlockPos pos, Holder biome) { - ChunkAccess chunk = level.getChunk(pos); - setBiome(chunk, pos, biome); - } - - private static void sortFeatures(List> features) { -// InternalBiomeAPI.initFeatureOrder(); -// -// Set> featuresWithoutDuplicates = Sets.newHashSet(); -// features.forEach(holder -> featuresWithoutDuplicates.add(holder)); -// -// if (featuresWithoutDuplicates.size() != features.size()) { -// features.clear(); -// featuresWithoutDuplicates.forEach(feature -> features.add(feature)); -// } -// -// features.forEach(feature -> { -// InternalBiomeAPI.FEATURE_ORDER.computeIfAbsent( -// feature, -// f -> InternalBiomeAPI.FEATURE_ORDER_ID.getAndIncrement() -// ); -// }); -// -// features.sort((f1, f2) -> { -// int v1 = InternalBiomeAPI.FEATURE_ORDER.getOrDefault(f1, 70000); -// int v2 = InternalBiomeAPI.FEATURE_ORDER.getOrDefault(f2, 70000); -// return Integer.compare(v1, v2); -// }); - } - - - private static List> getFeaturesListCopy( - List> features, - Decoration step - ) { - return getFeaturesListCopy(features, step.ordinal()); - } - - private static List> getFeaturesListCopy(List> features, int index) { - while (features.size() <= index) { - features.add(HolderSet.direct(Lists.newArrayList())); - } - return features.get(index).stream().collect(Collectors.toList()); - } - -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BiomeData.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BiomeData.java deleted file mode 100644 index 2997ef38..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/BiomeData.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - -import com.mojang.serialization.Codec; -import net.minecraft.util.KeyDispatchDataCodec; - -import java.util.function.Function; - -public interface BiomeData { - Codec CODEC = BCLBiomeRegistry - .BIOME_CODECS - .byNameCodec() - .dispatch(b -> b.codec().codec(), Function.identity()); - - KeyDispatchDataCodec codec(); -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/InternalBiomeAPI.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/InternalBiomeAPI.java deleted file mode 100644 index 53e782a2..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/InternalBiomeAPI.java +++ /dev/null @@ -1,335 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.mixin.common.BiomeGenerationSettingsAccessor; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -import net.fabricmc.fabric.api.event.registry.DynamicRegistrySetupCallback; -import net.fabricmc.fabric.api.event.registry.RegistryEntryAddedCallback; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import org.apache.commons.lang3.mutable.MutableInt; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.BiConsumer; -import java.util.stream.Stream; -import org.jetbrains.annotations.ApiStatus; - -@ApiStatus.Internal -public class InternalBiomeAPI { - public static final BiomeAPI.BiomeType OTHER_NETHER = new BiomeAPI.BiomeType( - "OTHER_NETHER", - BiomeAPI.BiomeType.NETHER - ); - public static final BiomeAPI.BiomeType OTHER_END_LAND = new BiomeAPI.BiomeType( - "OTHER_END_LAND", - BiomeAPI.BiomeType.END_LAND - ); - public static final BiomeAPI.BiomeType OTHER_END_VOID = new BiomeAPI.BiomeType( - "OTHER_END_VOID", - BiomeAPI.BiomeType.END_VOID - ); - public static final BiomeAPI.BiomeType OTHER_END_CENTER = new BiomeAPI.BiomeType( - "OTHER_END_CENTER", - BiomeAPI.BiomeType.END_CENTER - ); - public static final BiomeAPI.BiomeType OTHER_END_BARRENS = new BiomeAPI.BiomeType( - "OTHER_END_BARRENS", - BiomeAPI.BiomeType.END_BARRENS - ); - static final Map CLIENT = Maps.newHashMap(); - static final Map, Integer> FEATURE_ORDER = Maps.newHashMap(); - - static final Map, AtomicInteger> BIOME_ADDITIONS = Maps.newHashMap(); - static final MutableInt FEATURE_ORDER_ID = new MutableInt(0); - static final Map, List>>> MODIFICATIONS = Maps.newHashMap(); - static final Map>>> TAG_ADDERS = Maps.newHashMap(); - static Registry biomeRegistry; - static RegistryAccess registryAccess; - - static void initFeatureOrder() { - if (!FEATURE_ORDER.isEmpty()) { - return; - } - - BuiltinRegistries.BIOME - .entrySet() - .stream() - .filter(entry -> entry - .getKey() - .location() - .getNamespace() - .equals("minecraft")) - .map(Map.Entry::getValue) - .map(biome -> (BiomeGenerationSettingsAccessor) biome.getGenerationSettings()) - .map(BiomeGenerationSettingsAccessor::bclib_getFeatures) - .forEach(stepFeatureSuppliers -> stepFeatureSuppliers.forEach(step -> step.forEach(feature -> { - FEATURE_ORDER.computeIfAbsent(feature, f -> FEATURE_ORDER_ID.getAndIncrement()); - }))); - } - - public static RegistryAccess worldRegistryAccess() { - return registryAccess; - } - - /** - * Initialize registry for current server. - * - * @param access - The new, active {@link RegistryAccess} for the current session. - */ - public static void initRegistry(RegistryAccess access) { - if (access != registryAccess) { - registryAccess = access; - Registry biomeRegistry = access.registry(Registry.BIOME_REGISTRY).orElse(null); - - if (biomeRegistry != InternalBiomeAPI.biomeRegistry) { - InternalBiomeAPI.biomeRegistry = biomeRegistry; - CLIENT.clear(); - - BIOMES_TO_SORT.forEach(id -> { - Biome b = biomeRegistry.get(id); - if (b != null) { -// BCLib.LOGGER.info("Found non fabric/bclib Biome: " + id + "(" + b + ")"); -// BiomeAPI.sortBiomeFeatures(b); - } else { - BCLib.LOGGER.info("Unknown Biome: " + id); - } - }); - } - } - } - - /** - * For internal use only. - *

- * This method gets called before a world is loaded/created to flush cashes we build. - */ - public static void prepareNewLevel() { - BIOMES_TO_SORT.clear(); - } - - /** - * Load biomes from Fabric API. For internal usage only. - */ - public static void loadFabricAPIBiomes() { -// FabricBiomesData.NETHER_BIOMES.forEach((key) -> { -// if (!BiomeAPI.hasBiome(key.location())) { -// Optional> optional = BuiltinRegistries.BIOME.getHolder(key); -// if (optional.isPresent()) { -// BiomeAPI.registerNetherBiome(optional.get().value()); -// } -// } -// }); -// -// FabricBiomesData.END_LAND_BIOMES.forEach((key, weight) -> { -// if (!BiomeAPI.hasBiome(key.location())) { -// Optional> optional = BuiltinRegistries.BIOME.getHolder(key); -// if (optional.isPresent()) { -// BiomeAPI.registerEndLandBiome(optional.get(), weight); -// } -// } -// }); -// -// FabricBiomesData.END_VOID_BIOMES.forEach((key, weight) -> { -// if (!BiomeAPI.hasBiome(key.location())) { -// Optional> optional = BuiltinRegistries.BIOME.getHolder(key); -// if (optional.isPresent()) { -// BiomeAPI.registerEndVoidBiome(optional.get(), weight); -// } -// } -// }); - } - - /** - * For internal use only - */ - public static void _runBiomeTagAdders() { - for (var mod : TAG_ADDERS.entrySet()) { - Stream s = null; - if (mod.getKey() == Level.NETHER) - s = BCLBiomeRegistry.getAll(BiomeAPI.BiomeType.NETHER).map(k -> k.location()); - else if (mod.getKey() == Level.END) - s = BCLBiomeRegistry.getAll(BiomeAPI.BiomeType.END).map(k -> k.location()); - if (s != null) { - s.forEach(id -> { - Holder biomeHolder = BiomeAPI.getFromRegistry(id); - if (biomeHolder != null && biomeHolder.isBound()) { - mod.getValue().forEach(c -> c.accept(id, biomeHolder)); - } else { - BCLib.LOGGER.info("No Holder for " + id); - } - }); - } - } - } - - public static void applyModifications(BiomeSource source, ResourceKey dimension) { - BCLib.LOGGER.info("\nApply Modifications for " + dimension.location() + source.toString() - .replace("\n", "\n ")); - - final Set> biomes = source.possibleBiomes(); - List>> modifications = MODIFICATIONS.get(dimension); - for (Holder biomeHolder : biomes) { - if (biomeHolder.isBound()) { - applyModificationsAndUpdateFeatures(modifications, biomeHolder); - } - } - } - - private static void applyModificationsAndUpdateFeatures( - List>> modifications, - Holder biome - ) { - ResourceLocation biomeID = BiomeAPI.getBiomeID(biome); - if (modifications != null) { - modifications.forEach(consumer -> { - consumer.accept(biomeID, biome); - }); - } - } - - private static final Set BIOMES_TO_SORT = Sets.newHashSet(); - - - /** - * Register {@link BCLBiome} wrapper for {@link Biome}. - * After that biome will be added to BCLib End Biome Generator and into Fabric Biome API as a land biome (will generate only on islands). - * - * @param biomeKey The source biome to wrap - * @return {@link BCLBiome} - */ - public static BCLBiome wrapNativeBiome(ResourceKey biomeKey, BiomeAPI.BiomeType type) { - return wrapNativeBiome(biomeKey, -1, type); - } - - /** - * Register {@link BCLBiome} wrapper for {@link Biome}. - * After that biome will be added to BCLib End Biome Generator and into Fabric Biome API as a land biome (will generate only on islands). - * - * @param biomeKey The source biome to wrap - * @param genChance generation chance. If <0 the default genChance is used - * @return {@link BCLBiome} - */ - public static BCLBiome wrapNativeBiome(ResourceKey biomeKey, float genChance, BiomeAPI.BiomeType type) { - return wrapNativeBiome( - biomeKey, - genChance < 0 ? null : VanillaBiomeSettings.createVanilla().setGenChance(genChance).build(), - type - ); - } - - public static BCLBiome wrapNativeBiome( - ResourceKey biomeKey, - BCLBiome edgeBiome, - int edgeBiomeSize, - float genChance, - BiomeAPI.BiomeType type - ) { - VanillaBiomeSettings.Builder settings = VanillaBiomeSettings.createVanilla(); - if (genChance >= 0) settings.setGenChance(genChance); - settings.setEdge(edgeBiome); - settings.setEdgeSize(edgeBiomeSize); - return wrapNativeBiome(biomeKey, settings.build(), type); - } - - /** - * Register {@link BCLBiome} wrapper for {@link Biome}. - * After that biome will be added to BCLib End Biome Generator and into Fabric Biome API as a land biome (will generate only on islands). - * - * @param biomeKey The source biome to wrap - * @param setings the {@link VanillaBiomeSettings} to use - * @return {@link BCLBiome} - */ - private static BCLBiome wrapNativeBiome( - ResourceKey biomeKey, - VanillaBiomeSettings setings, - BiomeAPI.BiomeType type - ) { - BCLBiome bclBiome = BiomeAPI.getBiome(biomeKey.location()); - if (bclBiome == BCLBiomeRegistry.EMPTY_BIOME) { - bclBiome = new BCLBiome(biomeKey, setings); - bclBiome._setIntendedType(type); - } - - registerBuiltinBiome(bclBiome); - return bclBiome; - } - - static { - DynamicRegistrySetupCallback.EVENT.register(registryManager -> { - Optional> oBiomeRegistry = registryManager.registry(Registry.BIOME_REGISTRY); - RegistryEntryAddedCallback - .event(oBiomeRegistry.get()) - .register((rawId, id, biome) -> { - BCLBiome b = BiomeAPI.getBiome(id); - if (!"minecraft".equals(id.getNamespace()) && (b == null || b == BCLBiomeRegistry.EMPTY_BIOME)) { - //BCLib.LOGGER.info(" #### " + rawId + ", " + biome + ", " + id); - //BIOMES_TO_SORT.add(id); -// BIOME_ADDITIONS.computeIfAbsent(oBiomeRegistry.get(), reg -> new AtomicInteger(0)) -// .incrementAndGet(); - } - }); - }); - } - - /** - * The BCLBiomeSource keeps track of Modifications that happen after the BiomeSource was initialized. - * This appears to happen especially for new Worlds where the Biome Source is deserialized - * when the WolrdPreset registry is built for the CreateScreen. However Farbic Biomes are not yet - * added to the biomeRegistry at this stage. - * The counter is incremented in the DynamicRegistrySetupCallback.EVENT for the Biome Registry - * - * @param registry The registry you want to check - * @return The current number of additions since the world creation was started - */ - public static int getBiomeRegistryModificationCount(Registry registry) { - if (registry == null) return 0; - return BIOME_ADDITIONS.computeIfAbsent(registry, reg -> new AtomicInteger(0)).get(); - } - - public static boolean registryContainsBound(ResourceKey key) { - Registry reg = biomeRegistry; - if (reg == null) reg = BuiltinRegistries.BIOME; - - if (reg.containsKey(key)) { - return reg.getOrCreateHolderOrThrow(key).isBound(); - } - return false; - } - - public static void registerBCLBiomeData(BCLBiome biome) { - try { - BCLBiomeRegistry.register(registryAccess, biome); - } catch (IllegalStateException e) { - BCLib.LOGGER.warning("Unable to register Dummy Biome Entry for " + biome.getID()); - } - } - - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * - * @param bclbiome {@link BCLBiome} - * @return {@link BCLBiome} - */ - - public static BCLBiome registerBuiltinBiome(BCLBiome bclbiome) { - return BiomeAPI.registerBiome(bclbiome, BuiltinRegistries.BIOME); - } - -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/VanillaBiomeSettings.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/VanillaBiomeSettings.java deleted file mode 100644 index 33db568e..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/biomes/VanillaBiomeSettings.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.biomes; - - -public class VanillaBiomeSettings extends BCLBiomeSettings { - public static class Builder extends BCLBiomeSettings.CommonBuilder { - public Builder() { - super(new VanillaBiomeSettings()); - } - } - - public static Builder createVanilla() { - return new Builder(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/features/config/ScatterFeatureConfig.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/features/config/ScatterFeatureConfig.java deleted file mode 100644 index ef88a4ec..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/features/config/ScatterFeatureConfig.java +++ /dev/null @@ -1,548 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.features.config; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.blocks.BlockProperties; -import org.betterx.bclib.util.BlocksHelper; - -import com.mojang.datafixers.util.Function15; -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.util.valueproviders.ConstantInt; -import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; - -import java.util.Optional; - -public abstract class ScatterFeatureConfig implements FeatureConfiguration { - public interface Instancer extends Function15, Optional, Optional, Float, Float, Float, Float, Integer, Integer, Float, Float, Float, Boolean, IntProvider, T> { - } - - public final BlockStateProvider clusterBlock; - public final BlockStateProvider tipBlock; - public final BlockStateProvider bottomBlock; - public final Optional baseState; - public final float baseReplaceChance; - public final float chanceOfDirectionalSpread; - public final float chanceOfSpreadRadius2; - public final float chanceOfSpreadRadius3; - public final int minHeight; - public final int maxHeight; - public final float maxSpread; - public final float sizeVariation; - public final float floorChance; - - public final IntProvider spreadCount; - - public final boolean growWhileFree; - - public ScatterFeatureConfig( - BlockStateProvider clusterBlock, - Optional tipBlock, - Optional bottomBlock, - Optional baseState, - float baseReplaceChance, - float chanceOfDirectionalSpread, - float chanceOfSpreadRadius2, - float chanceOfSpreadRadius3, - int minHeight, - int maxHeight, - float maxSpread, - float sizeVariation, - float floorChance, - boolean growWhileFree, - IntProvider spreadCount - ) { - this.clusterBlock = clusterBlock; - this.tipBlock = tipBlock.orElse(clusterBlock); - this.bottomBlock = bottomBlock.orElse(clusterBlock); - this.baseState = baseState; - this.baseReplaceChance = baseReplaceChance; - this.chanceOfDirectionalSpread = chanceOfDirectionalSpread; - this.chanceOfSpreadRadius2 = chanceOfSpreadRadius2; - this.chanceOfSpreadRadius3 = chanceOfSpreadRadius3; - this.minHeight = minHeight; - this.maxHeight = maxHeight; - this.maxSpread = maxSpread; - this.sizeVariation = sizeVariation; - this.floorChance = floorChance; - this.growWhileFree = growWhileFree; - this.spreadCount = spreadCount; - } - - - public boolean isFloor(RandomSource random) { - return random.nextFloat() < floorChance; - } - - public abstract boolean isValidBase(BlockState state); - - public abstract BlockState createBlock(int height, int maxHeight, RandomSource random, BlockPos pos); - - public static Codec buildCodec(Instancer instancer) { - return RecordCodecBuilder.create((instance) -> instance - .group( - BlockStateProvider.CODEC - .fieldOf("cluster_block") - .forGetter((T cfg) -> cfg.clusterBlock), - BlockStateProvider.CODEC - .optionalFieldOf("tip_block") - .orElse(Optional.empty()) - .forGetter((T cfg) -> cfg.tipBlock == cfg.clusterBlock - ? Optional.empty() - : Optional.of(cfg.tipBlock)), - BlockStateProvider.CODEC - .optionalFieldOf("bottom_block") - .orElse(Optional.empty()) - .forGetter((T cfg) -> cfg.bottomBlock == cfg.clusterBlock - ? Optional.empty() - : Optional.of(cfg.bottomBlock)), - BlockState.CODEC - .optionalFieldOf("base_state") - .forGetter((T cfg) -> cfg.baseState), - Codec - .floatRange(0.0F, 1.0F) - .fieldOf("baseReplaceChance") - .orElse(1.0F) - .forGetter((T cfg) -> cfg.baseReplaceChance), - Codec - .floatRange(0.0F, 1.0F) - .fieldOf("chance_of_directional_spread") - .orElse(0.7F) - .forGetter((T cfg) -> cfg.chanceOfDirectionalSpread), - Codec - .floatRange(0.0F, 1.0F) - .fieldOf("chance_of_spread_radius2") - .orElse(0.5F) - .forGetter((T cfg) -> cfg.chanceOfSpreadRadius2), - Codec - .floatRange(0.0F, 1.0F) - .fieldOf("chance_of_spread_radius3") - .orElse(0.5F) - .forGetter((T cfg) -> cfg.chanceOfSpreadRadius3), - Codec - .intRange(1, 64) - .fieldOf("min_height") - .orElse(2) - .forGetter((T cfg) -> cfg.minHeight), - Codec - .intRange(1, 64) - .fieldOf("max_height") - .orElse(7) - .forGetter((T cfg) -> cfg.maxHeight), - Codec - .floatRange(0, 16) - .fieldOf("max_spread") - .orElse(2f) - .forGetter((T cfg) -> cfg.maxSpread), - Codec - .floatRange(0, 1) - .fieldOf("size_variation") - .orElse(0.7f) - .forGetter((T cfg) -> cfg.sizeVariation), - Codec - .floatRange(0, 1) - .fieldOf("floor_chance") - .orElse(0.5f) - .forGetter((T cfg) -> cfg.floorChance), - Codec - .BOOL - .fieldOf("grow_while_empty") - .orElse(false) - .forGetter((T cfg) -> cfg.growWhileFree), - IntProvider.codec(0, 64) - .fieldOf("length") - .orElse(UniformInt.of(0, 3)) - .forGetter(cfg -> cfg.spreadCount) - ) - .apply(instance, instancer) - ); - } - - public static class Builder { - private BlockStateProvider clusterBlock; - private BlockStateProvider tipBlock; - private BlockStateProvider bottomBlock; - private Optional baseState = Optional.empty(); - private float baseReplaceChance = 0; - private float chanceOfDirectionalSpread = 0; - private float chanceOfSpreadRadius2 = 0; - private float chanceOfSpreadRadius3 = 0; - private int minHeight = 2; - private int maxHeight = 12; - private float maxSpread = 0; - private float sizeVariation = 0; - private float floorChance = 0.5f; - private boolean growWhileFree = false; - public IntProvider spreadCount = ConstantInt.of(0); - private final Instancer instancer; - - public Builder(Instancer instancer) { - this.instancer = instancer; - } - - public static Builder start(Instancer instancer) { - return new Builder<>(instancer); - } - - public Builder block(Block b) { - return block(b.defaultBlockState()); - } - - public Builder singleBlock(Block b) { - return block(b.defaultBlockState()).heightRange(1, 1).spread(0, 0, ConstantInt.of(0)); - } - - public Builder block(BlockState s) { - this.clusterBlock = BlockStateProvider.simple(s); - if (tipBlock == null) tipBlock = BlockStateProvider.simple(s); - if (bottomBlock == null) bottomBlock = BlockStateProvider.simple(s); - return this; - } - - public Builder tipBlock(BlockState s) { - tipBlock = BlockStateProvider.simple(s); - return this; - } - - public Builder bottomBlock(BlockState s) { - bottomBlock = BlockStateProvider.simple(s); - return this; - } - - public Builder tripleShape(Block s) { - return tripleShape(s.defaultBlockState()); - } - - public Builder tripleShape(BlockState s) { - block(s.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.MIDDLE)); - tipBlock(s.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.TOP)); - bottomBlock(s.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.BOTTOM)); - return this; - } - - public Builder tripleShapeCeil(Block s) { - return tripleShapeCeil(s.defaultBlockState()); - } - - public Builder tripleShapeCeil(BlockState s) { - block(s.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.MIDDLE)); - tipBlock(s.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.BOTTOM)); - bottomBlock(s.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.TOP)); - return this; - } - - public Builder block(BlockStateProvider s) { - this.clusterBlock = s; - if (tipBlock == null) tipBlock = s; - if (bottomBlock == null) bottomBlock = s; - return this; - } - - public Builder tipBlock(BlockStateProvider s) { - tipBlock = s; - return this; - } - - public Builder bottomBlock(BlockStateProvider s) { - bottomBlock = s; - return this; - } - - public Builder heightRange(int min, int max) { - minHeight = min; - maxHeight = max; - return this; - } - - public Builder growWhileFree() { - growWhileFree = true; - return this; - } - - public Builder minHeight(int h) { - minHeight = h; - return this; - } - - public Builder maxHeight(int h) { - maxHeight = h; - return this; - } - - public Builder generateBaseBlock(BlockState baseState) { - return generateBaseBlock(baseState, 1, 0, 0, 0); - } - - public Builder generateBaseBlock(BlockState baseState, float baseReplaceChance) { - return generateBaseBlock(baseState, baseReplaceChance, 0, 0, 0); - } - - - public Builder generateBaseBlock( - BlockState baseState, - float chanceOfDirectionalSpread, - float chanceOfSpreadRadius2, - float chanceOfSpreadRadius3 - ) { - return generateBaseBlock( - baseState, - 1, - chanceOfDirectionalSpread, - chanceOfSpreadRadius2, - chanceOfSpreadRadius3 - ); - } - - public Builder generateBaseBlock( - BlockState baseState, - float baseReplaceChance, - float chanceOfDirectionalSpread, - float chanceOfSpreadRadius2, - float chanceOfSpreadRadius3 - ) { - if (this.baseState.isPresent() && this.baseReplaceChance == 0) { - BCLib.LOGGER.error("Base generation was already selected."); - } - this.baseState = Optional.of(baseState); - this.baseReplaceChance = baseReplaceChance; - this.chanceOfDirectionalSpread = chanceOfDirectionalSpread; - this.chanceOfSpreadRadius2 = chanceOfSpreadRadius2; - this.chanceOfSpreadRadius3 = chanceOfSpreadRadius3; - return this; - } - - public Builder noSpread() { - return spread(0, 0, ConstantInt.of(0)); - } - - - public Builder spread(float maxSpread, float sizeVariation) { - return spread(maxSpread, sizeVariation, ConstantInt.of((int) Math.min(16, 4 * maxSpread * maxSpread))); - } - - public Builder spread(float maxSpread, float sizeVariation, IntProvider spreadCount) { - this.spreadCount = spreadCount; // - this.maxSpread = maxSpread; - this.sizeVariation = sizeVariation; - return this; - } - - public Builder floorChance(float chance) { - this.floorChance = chance; - return this; - } - - public Builder onFloor() { - this.floorChance = 1; - return this; - } - - public Builder onCeil() { - this.floorChance = 0; - return this; - } - - public T build() { - return instancer.apply( - this.clusterBlock, - Optional.of(this.tipBlock), - Optional.of(this.bottomBlock), - this.baseState, - this.baseReplaceChance, - this.chanceOfDirectionalSpread, - this.chanceOfSpreadRadius2, - this.chanceOfSpreadRadius3, - this.minHeight, - this.maxHeight, - this.maxSpread, - this.sizeVariation, - this.floorChance, - this.growWhileFree, - this.spreadCount - ); - } - } - - public static Builder startOnSolid() { - return Builder.start(OnSolid::new); - } - - public static class OnSolid extends ScatterFeatureConfig { - public static final Codec CODEC = buildCodec(OnSolid::new); - - protected OnSolid( - BlockStateProvider clusterBlock, - Optional tipBlock, - Optional bottomBlock, - Optional baseState, - float baseReplaceChance, - float chanceOfDirectionalSpread, - float chanceOfSpreadRadius2, - float chanceOfSpreadRadius3, - int minHeight, - int maxHeight, - float maxSpread, - float sizeVariation, - float floorChance, - boolean growWhileFree, - IntProvider spreadCount - ) { - super( - clusterBlock, - tipBlock, - bottomBlock, - baseState, - baseReplaceChance, - chanceOfDirectionalSpread, - chanceOfSpreadRadius2, - chanceOfSpreadRadius3, - minHeight, - maxHeight, - maxSpread, - sizeVariation, - floorChance, - growWhileFree, - spreadCount - ); - } - - - @Override - public boolean isValidBase(BlockState state) { - return BlocksHelper.isTerrain(state) - || baseState.map(s -> state.is(s.getBlock())).orElse(false); - } - - @Override - public BlockState createBlock(int height, int maxHeight, RandomSource random, BlockPos pos) { - if (height == 0) return this.bottomBlock.getState(random, pos); - return height == maxHeight - ? this.tipBlock.getState(random, pos) - : this.clusterBlock.getState(random, pos); - } - } - - - public static Builder startExtendTop() { - return Builder.start(ExtendTop::new); - } - - public static class ExtendTop extends ScatterFeatureConfig { - public static final Codec CODEC = buildCodec(ExtendTop::new); - - protected ExtendTop( - BlockStateProvider clusterBlock, - Optional tipBlock, - Optional bottomBlock, - Optional baseState, - float baseReplaceChance, - float chanceOfDirectionalSpread, - float chanceOfSpreadRadius2, - float chanceOfSpreadRadius3, - int minHeight, - int maxHeight, - float maxSpread, - float sizeVariation, - float floorChance, - boolean growWhileFree, - IntProvider spreadCount - ) { - super( - clusterBlock, - tipBlock, - bottomBlock, - baseState, - baseReplaceChance, - chanceOfDirectionalSpread, - chanceOfSpreadRadius2, - chanceOfSpreadRadius3, - minHeight, - maxHeight, - maxSpread, - sizeVariation, - floorChance, - growWhileFree, - spreadCount - ); - } - - - @Override - public boolean isValidBase(BlockState state) { - return BlocksHelper.isTerrain(state) - || baseState.map(s -> state.is(s.getBlock())).orElse(false); - } - - @Override - public BlockState createBlock(int height, int maxHeight, RandomSource random, BlockPos pos) { - if (height == 0) return this.bottomBlock.getState(random, pos); - if (height == 1) return this.clusterBlock.getState(random, pos); - return this.tipBlock.getState(random, pos); - } - } - - public static Builder startExtendBottom() { - return Builder.start(ExtendBottom::new); - } - - public static class ExtendBottom extends ScatterFeatureConfig { - public static final Codec CODEC = buildCodec(ExtendBottom::new); - - protected ExtendBottom( - BlockStateProvider clusterBlock, - Optional tipBlock, - Optional bottomBlock, - Optional baseState, - float baseReplaceChance, - float chanceOfDirectionalSpread, - float chanceOfSpreadRadius2, - float chanceOfSpreadRadius3, - int minHeight, - int maxHeight, - float maxSpread, - float sizeVariation, - float floorChance, - boolean growWhileFree, - IntProvider spreadCount - ) { - super( - clusterBlock, - tipBlock, - bottomBlock, - baseState, - baseReplaceChance, - chanceOfDirectionalSpread, - chanceOfSpreadRadius2, - chanceOfSpreadRadius3, - minHeight, - maxHeight, - maxSpread, - sizeVariation, - floorChance, - growWhileFree, - spreadCount - ); - } - - - @Override - public boolean isValidBase(BlockState state) { - return BlocksHelper.isTerrain(state) - || baseState.map(s -> state.is(s.getBlock())).orElse(false); - } - - @Override - public BlockState createBlock(int height, int maxHeight, RandomSource random, BlockPos pos) { - if (height == maxHeight) return this.tipBlock.getState(random, pos); - if (height == maxHeight - 1) return this.clusterBlock.getState(random, pos); - return this.bottomBlock.getState(random, pos); - } - } - -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/features/features/DefaultFeature.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/features/features/DefaultFeature.java deleted file mode 100644 index 89cec529..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/features/features/DefaultFeature.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.features.features; - -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.Heightmap.Types; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; - -public abstract class DefaultFeature extends Feature { - public static final BlockState AIR = Blocks.AIR.defaultBlockState(); - public static final BlockState WATER = Blocks.WATER.defaultBlockState(); - - public DefaultFeature() { - super(NoneFeatureConfiguration.CODEC); - } - - public static int getYOnSurface(WorldGenLevel world, int x, int z) { - return world.getHeight(Types.WORLD_SURFACE, x, z); - } - - public static int getYOnSurfaceWG(WorldGenLevel world, int x, int z) { - return world.getHeight(Types.WORLD_SURFACE_WG, x, z); - } - - public static BlockPos getPosOnSurface(WorldGenLevel world, BlockPos pos) { - return world.getHeightmapPos(Types.WORLD_SURFACE, pos); - } - - public static BlockPos getPosOnSurfaceWG(WorldGenLevel world, BlockPos pos) { - return world.getHeightmapPos(Types.WORLD_SURFACE_WG, pos); - } - - public static BlockPos getPosOnSurfaceRaycast(WorldGenLevel world, BlockPos pos) { - return getPosOnSurfaceRaycast(world, pos, 256); - } - - public static BlockPos getPosOnSurfaceRaycast(WorldGenLevel world, BlockPos pos, int dist) { - int h = BlocksHelper.downRay(world, pos, dist); - return pos.below(h); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/BCLStructure.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/BCLStructure.java deleted file mode 100644 index 915c067e..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/BCLStructure.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeBuilder; -import org.betterx.bclib.mixin.common.StructuresAccessor; - -import com.mojang.serialization.Codec; -import net.minecraft.core.*; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.data.worldgen.StructureSets; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.structure.*; -import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; - -import com.google.common.collect.Lists; - -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import org.jetbrains.annotations.NotNull; - -public class BCLStructure { - private final Holder structure; - private final GenerationStep.Decoration featureStep; - private final List biomes = Lists.newArrayList(); - private final ResourceLocation id; - public final TagKey biomeTag; - public final ResourceKey structureKey; - public final S baseStructure; - public final ResourceKey structureSetKey; - public final StructurePlacement spreadConfig; - - public final StructureType structureType; - - public final Codec STRUCTURE_CODEC; - - - private static HolderSet biomes(TagKey tagKey) { - return BuiltinRegistries.BIOME.getOrCreateTag(tagKey); - } - - private static Structure.StructureSettings structure( - TagKey tagKey, - Map map, - GenerationStep.Decoration decoration, - TerrainAdjustment terrainAdjustment - ) { - return new Structure.StructureSettings(biomes(tagKey), map, decoration, terrainAdjustment); - } - - private static Structure.StructureSettings structure( - TagKey tagKey, - GenerationStep.Decoration decoration, - TerrainAdjustment terrainAdjustment - ) { - return structure(tagKey, Map.of(), decoration, terrainAdjustment); - } - - private static StructureType registerStructureType( - ResourceLocation id, - Codec codec - ) { - return Registry.register(Registry.STRUCTURE_TYPES, id, () -> codec); - } - - protected BCLStructure( - @NotNull ResourceLocation id, - @NotNull Function structureBuilder, - GenerationStep.Decoration step, - @NotNull StructurePlacement placement, - @NotNull Codec codec, - @NotNull TagKey biomeTag, - @NotNull TerrainAdjustment terrainAdjustment - ) { - this.id = id; - this.featureStep = step; - this.STRUCTURE_CODEC = codec; - this.spreadConfig = placement; - this.structureKey = ResourceKey.create(Registry.STRUCTURE_REGISTRY, id); - this.structureSetKey = ResourceKey.create(Registry.STRUCTURE_SET_REGISTRY, id); - - this.structureType = registerStructureType(id, STRUCTURE_CODEC); - - this.biomeTag = biomeTag; - this.baseStructure = structureBuilder.apply(structure(this.biomeTag, featureStep, terrainAdjustment)); - this.structure = StructuresAccessor.callRegister(structureKey, this.baseStructure); - StructureSets.register(structureSetKey, this.structure, spreadConfig); - } - - /** - * runs the {@code PieceGeneratorSupplier.Context::validBiome} from the given context at - * height=5 in the middle of the chunk. - * - * @param context The context to test with. - * @return true, if this feature can spawn in the current biome - */ - public static boolean isValidBiome(Structure.GenerationContext context) { - return isValidBiome(context, 5); - } - - /** - * runs the {@code PieceGeneratorSupplier.Context::validBiome} from the given context at the - * given height in the middle of the chunk. - * - * @param context The context to test with. - * @param yPos The Height to test for - * @return true, if this feature can spawn in the current biome - */ - public static boolean isValidBiome(Structure.GenerationContext context, int yPos) { - BlockPos blockPos = context.chunkPos().getMiddleBlockPosition(yPos); - return context.validBiome().test( - context - .chunkGenerator() - .getBiomeSource() - .getNoiseBiome( - QuartPos.fromBlock(blockPos.getX()), - QuartPos.fromBlock(blockPos.getY()), - QuartPos.fromBlock(blockPos.getZ()), - context.randomState().sampler() - ) - ); - } - - public Holder getStructure() { - return structure; - } - - public GenerationStep.Decoration getFeatureStep() { - return featureStep; - } - - /** - * Get the structure ID; - * - * @return {@link ResourceLocation} id. - */ - public ResourceLocation getID() { - return id; - } - - /** - * Adds biome into internal biome list, used in {@link BCLBiomeBuilder}. - * - * @param biome {@link ResourceLocation} biome ID. - */ - public void addInternalBiome(ResourceLocation biome) { - biomes.add(biome); - } - - /** - * Get biome list where this structure feature can generate. Only represents biomes made with {@link BCLBiomeBuilder} and only - * if structure was added during building process. Modification of this list will not affect structure generation. - * - * @return {@link List} of biome {@link ResourceLocation}. - */ - public List getBiomes() { - return biomes; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/BCLStructureBuilder.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/BCLStructureBuilder.java deleted file mode 100644 index 6c126124..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/BCLStructureBuilder.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import org.betterx.worlds.together.tag.v3.TagManager; - -import com.mojang.serialization.Codec; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.TerrainAdjustment; -import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement; -import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadType; -import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement; - -import java.util.function.Function; - -public class BCLStructureBuilder { - private static final BCLStructureBuilder INSTANCE = new BCLStructureBuilder(); - - private ResourceLocation structureID; - private Function structureBuilder; - - private GenerationStep.Decoration step; - - private Codec codec; - - private StructurePlacement placement; - - private TagKey biomeTag; - - private TerrainAdjustment terrainAdjustment; - - private BCLStructureBuilder() { - } - - public static BCLStructureBuilder start( - ResourceLocation structureID, - Function structureBuilder - ) { - INSTANCE.structureID = structureID; - INSTANCE.structureBuilder = structureBuilder; - - INSTANCE.step = GenerationStep.Decoration.SURFACE_STRUCTURES; - INSTANCE.terrainAdjustment = TerrainAdjustment.NONE; - INSTANCE.codec = null; - INSTANCE.placement = null; - INSTANCE.biomeTag = null; - - return INSTANCE; - } - - public BCLStructureBuilder adjustment(TerrainAdjustment value) { - this.terrainAdjustment = value; - return this; - } - - public BCLStructureBuilder step(GenerationStep.Decoration value) { - this.step = value; - return this; - } - - public BCLStructureBuilder codec(Codec value) { - this.codec = value; - return this; - } - - public BCLStructureBuilder placement(StructurePlacement value) { - this.placement = value; - return this; - } - - public BCLStructureBuilder randomPlacement(int spacing, int separation) { - this.placement = new RandomSpreadStructurePlacement( - spacing, - separation, - RandomSpreadType.LINEAR, - 13323129 + spacing + separation + structureID.toString().hashCode() % 10000 - ); - return this; - } - - public BCLStructureBuilder biomeTag(String modID, String path) { - this.biomeTag = TagManager.BIOMES.makeStructureTag(modID, path); - return this; - } - - public BCLStructureBuilder biomeTag(TagKey tag) { - this.biomeTag = tag; - return this; - } - - public BCLStructure build() { - if (placement == null) { - throw new IllegalStateException("Placement needs to be defined for " + this.structureID); - } - if (codec == null) codec(Structure.simpleCodec(structureBuilder)); - if (biomeTag == null) biomeTag(structureID.getNamespace(), structureID.getPath()); - - return new BCLStructure<>( - structureID, - structureBuilder, - step, - placement, - codec, - biomeTag, - terrainAdjustment - ); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureNBT.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureNBT.java deleted file mode 100644 index 92837a7c..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureNBT.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import org.betterx.bclib.BCLib; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.core.Vec3i; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; - -import com.google.common.collect.Maps; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Map; - -public class StructureNBT { - public final ResourceLocation location; - protected StructureTemplate structure; - - - protected StructureNBT(ResourceLocation location) { - this.location = location; - this.structure = readStructureFromJar(location); - } - - protected StructureNBT(ResourceLocation location, StructureTemplate structure) { - this.location = location; - this.structure = structure; - } - - public static Rotation getRandomRotation(RandomSource random) { - return Rotation.getRandom(random); - } - - public static Mirror getRandomMirror(RandomSource random) { - return Mirror.values()[random.nextInt(3)]; - } - - private static final Map STRUCTURE_CACHE = Maps.newHashMap(); - - public static StructureNBT create(ResourceLocation location) { - return STRUCTURE_CACHE.computeIfAbsent(location, r -> new StructureNBT(r)); - } - - public boolean generateCentered(ServerLevelAccessor world, BlockPos pos, Rotation rotation, Mirror mirror) { - if (structure == null) { - BCLib.LOGGER.error("No structure: " + location.toString()); - return false; - } - - MutableBlockPos blockpos2 = new MutableBlockPos().set(structure.getSize()); - if (mirror == Mirror.FRONT_BACK) - blockpos2.setX(-blockpos2.getX()); - if (mirror == Mirror.LEFT_RIGHT) - blockpos2.setZ(-blockpos2.getZ()); - blockpos2.set(blockpos2.rotate(rotation)); - StructurePlaceSettings data = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror); - BlockPos newPos = pos.offset(-blockpos2.getX() >> 1, 0, -blockpos2.getZ() >> 1); - structure.placeInWorld( - world, - newPos, - newPos, - data, - world.getRandom(), - Block.UPDATE_CLIENTS - ); - return true; - } - - private static final Map READER_CACHE = Maps.newHashMap(); - - private static StructureTemplate readStructureFromJar(ResourceLocation resource) { - return READER_CACHE.computeIfAbsent(resource, r -> _readStructureFromJar(r)); - } - - private static StructureTemplate _readStructureFromJar(ResourceLocation resource) { - String ns = resource.getNamespace(); - String nm = resource.getPath(); - - try { - InputStream inputstream = MinecraftServer.class.getResourceAsStream("/data/" + ns + "/structures/" + nm + ".nbt"); - return readStructureFromStream(inputstream); - } catch (IOException e) { - e.printStackTrace(); - } - - return null; - } - - private static StructureTemplate readStructureFromStream(InputStream stream) throws IOException { - CompoundTag nbttagcompound = NbtIo.readCompressed(stream); - - StructureTemplate template = new StructureTemplate(); - template.load(nbttagcompound); - - return template; - } - - public BlockPos getSize(Rotation rotation) { - if (rotation == Rotation.NONE || rotation == Rotation.CLOCKWISE_180) - return new BlockPos(structure.getSize()); - else { - Vec3i size = structure.getSize(); - int x = size.getX(); - int z = size.getZ(); - return new BlockPos(z, size.getY(), x); - } - } - - public String getName() { - return location.getPath(); - } - - public BoundingBox getBoundingBox(BlockPos pos, Rotation rotation, Mirror mirror) { - return structure.getBoundingBox(new StructurePlaceSettings().setRotation(rotation).setMirror(mirror), pos); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructurePlacementType.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructurePlacementType.java deleted file mode 100644 index bcace34e..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructurePlacementType.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import com.mojang.serialization.Codec; -import net.minecraft.util.StringRepresentable; - -public enum StructurePlacementType implements StringRepresentable { - FLOOR, WALL, CEIL, LAVA, UNDER; - - public static final Codec CODEC = StringRepresentable.fromEnum(StructurePlacementType::values); - - public String getName() { - return this.getSerializedName(); - } - - @Override - public String getSerializedName() { - return this.name().toLowerCase(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureWorld.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureWorld.java deleted file mode 100644 index 002b37d8..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureWorld.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtUtils; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.levelgen.structure.BoundingBox; - -import com.google.common.collect.Maps; - -import java.util.Map; - -public class StructureWorld { - private final Map parts = Maps.newHashMap(); - private ChunkPos lastPos; - private Part lastPart; - private int minX = Integer.MAX_VALUE; - private int minY = Integer.MAX_VALUE; - private int minZ = Integer.MAX_VALUE; - private int maxX = Integer.MIN_VALUE; - private int maxY = Integer.MIN_VALUE; - private int maxZ = Integer.MIN_VALUE; - - public StructureWorld() { - } - - public StructureWorld(CompoundTag tag) { - minX = tag.getInt("minX"); - maxX = tag.getInt("maxX"); - minY = tag.getInt("minY"); - maxY = tag.getInt("maxY"); - minZ = tag.getInt("minZ"); - maxZ = tag.getInt("maxZ"); - - ListTag map = tag.getList("parts", 10); - map.forEach((element) -> { - CompoundTag compound = (CompoundTag) element; - Part part = new Part(compound); - int x = compound.getInt("x"); - int z = compound.getInt("z"); - parts.put(new ChunkPos(x, z), part); - }); - } - - public void setBlock(BlockPos pos, BlockState state) { - ChunkPos cPos = new ChunkPos(pos); - - if (cPos.equals(lastPos)) { - lastPart.addBlock(pos, state); - return; - } - - Part part = parts.get(cPos); - if (part == null) { - part = new Part(); - parts.put(cPos, part); - - if (cPos.x < minX) minX = cPos.x; - if (cPos.x > maxX) maxX = cPos.x; - if (cPos.z < minZ) minZ = cPos.z; - if (cPos.z > maxZ) maxZ = cPos.z; - } - if (pos.getY() < minY) minY = pos.getY(); - if (pos.getY() > maxY) maxY = pos.getY(); - part.addBlock(pos, state); - - lastPos = cPos; - lastPart = part; - } - - public boolean placeChunk(WorldGenLevel world, ChunkPos chunkPos) { - Part part = parts.get(chunkPos); - if (part != null) { - ChunkAccess chunk = world.getChunk(chunkPos.x, chunkPos.z); - part.placeChunk(chunk); - return true; - } - return false; - } - - public CompoundTag toBNT() { - CompoundTag tag = new CompoundTag(); - tag.putInt("minX", minX); - tag.putInt("maxX", maxX); - tag.putInt("minY", minY); - tag.putInt("maxY", maxY); - tag.putInt("minZ", minZ); - tag.putInt("maxZ", maxZ); - ListTag map = new ListTag(); - tag.put("parts", map); - parts.forEach((pos, part) -> { - map.add(part.toNBT(pos.x, pos.z)); - }); - return tag; - } - - public BoundingBox getBounds() { - if (minX == Integer.MAX_VALUE || maxX == Integer.MIN_VALUE || minZ == Integer.MAX_VALUE || maxZ == Integer.MIN_VALUE) { - return BoundingBox.infinite(); - } - return new BoundingBox(minX << 4, minY, minZ << 4, (maxX << 4) | 15, maxY, (maxZ << 4) | 15); - } - - private static final class Part { - Map blocks = Maps.newHashMap(); - - public Part() { - } - - public Part(CompoundTag tag) { - ListTag map = tag.getList("blocks", 10); - ListTag map2 = tag.getList("states", 10); - BlockState[] states = new BlockState[map2.size()]; - for (int i = 0; i < states.length; i++) { - states[i] = NbtUtils.readBlockState((CompoundTag) map2.get(i)); - } - - map.forEach((element) -> { - CompoundTag block = (CompoundTag) element; - BlockPos pos = NbtUtils.readBlockPos(block.getCompound("pos")); - int stateID = block.getInt("state"); - BlockState state = stateID < states.length ? states[stateID] : Block.stateById(stateID); - blocks.put(pos, state); - }); - } - - void addBlock(BlockPos pos, BlockState state) { - BlockPos inner = new BlockPos(pos.getX() & 15, pos.getY(), pos.getZ() & 15); - blocks.put(inner, state); - } - - void placeChunk(ChunkAccess chunk) { - blocks.forEach((pos, state) -> { - chunk.setBlockState(pos, state, false); - }); - } - - CompoundTag toNBT(int x, int z) { - CompoundTag tag = new CompoundTag(); - tag.putInt("x", x); - tag.putInt("z", z); - ListTag map = new ListTag(); - tag.put("blocks", map); - ListTag stateMap = new ListTag(); - tag.put("states", stateMap); - - int[] id = new int[1]; - Map states = Maps.newHashMap(); - - blocks.forEach((pos, state) -> { - int stateID = states.getOrDefault(states, -1); - if (stateID < 0) { - stateID = id[0]++; - states.put(state, stateID); - stateMap.add(NbtUtils.writeBlockState(state)); - } - - CompoundTag block = new CompoundTag(); - block.put("pos", NbtUtils.writeBlockPos(pos)); - block.putInt("state", stateID); - map.add(block); - }); - - return tag; - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureWorldNBT.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureWorldNBT.java deleted file mode 100644 index 58d7c187..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/StructureWorldNBT.java +++ /dev/null @@ -1,279 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import org.betterx.bclib.util.BlocksHelper; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.levelgen.structure.BoundingBox; - -import com.google.common.collect.Maps; - -import java.util.Map; - -public class StructureWorldNBT extends StructureNBT { - public static final Codec CODEC = - RecordCodecBuilder.create((instance) -> - instance.group( - ResourceLocation.CODEC - .fieldOf("location") - .forGetter((cfg) -> cfg.location), - - Codec - .INT - .fieldOf("offset_y") - .orElse(0) - .forGetter((cfg) -> cfg.offsetY), - - StructurePlacementType.CODEC - .fieldOf("placement") - .orElse(StructurePlacementType.FLOOR) - .forGetter((cfg) -> cfg.type), - Codec - .FLOAT - .fieldOf("chance") - .orElse(1.0f) - .forGetter((cfg) -> cfg.chance) - ) - .apply(instance, StructureWorldNBT::new) - ); - - public final StructurePlacementType type; - public final int offsetY; - public final float chance; - - protected StructureWorldNBT(ResourceLocation location, int offsetY, StructurePlacementType type, float chance) { - super(location); - this.offsetY = offsetY; - this.type = type; - this.chance = chance; - } - - private static final Map READER_CACHE = Maps.newHashMap(); - - public static StructureWorldNBT create(ResourceLocation location, int offsetY, StructurePlacementType type) { - return create(location, offsetY, type, 1.0f); - } - - public static StructureWorldNBT create( - ResourceLocation location, - int offsetY, - StructurePlacementType type, - float chance - ) { - String key = location.toString() + "::" + offsetY + "::" + type.getSerializedName(); - return READER_CACHE.computeIfAbsent(key, r -> new StructureWorldNBT(location, offsetY, type, chance)); - } - - public boolean generateIfPlaceable( - ServerLevelAccessor level, - BlockPos pos, - RandomSource random - ) { - return generateIfPlaceable( - level, - pos, - getRandomRotation(random), - getRandomMirror(random) - ); - } - - public boolean generateIfPlaceable( - ServerLevelAccessor level, - BlockPos pos, - Rotation r, - Mirror m - ) { - if (canGenerate(level, pos, r)) { - return generate(level, pos, r, m); - } - return false; - } - - public boolean generate(ServerLevelAccessor level, BlockPos pos, Rotation r, Mirror m) { - return generateCentered(level, pos.above(offsetY), r, m); - } - - protected boolean canGenerate(LevelAccessor level, BlockPos pos, Rotation rotation) { - if (type == StructurePlacementType.FLOOR) - return canGenerateFloor(level, pos, rotation); - else if (type == StructurePlacementType.LAVA) - return canGenerateLava(level, pos, rotation); - else if (type == StructurePlacementType.UNDER) - return canGenerateUnder(level, pos, rotation); - else if (type == StructurePlacementType.CEIL) - return canGenerateCeil(level, pos, rotation); - else - return false; - } - - private boolean containsBedrock(LevelAccessor level, BlockPos startPos) { - for (int i = 0; i < this.structure.getSize().getY(); i += 2) { - if (level.getBlockState(startPos.above(i)).is(Blocks.BEDROCK)) { - return true; - } - } - return false; - } - - protected boolean canGenerateFloorFreeAbove(LevelAccessor world, BlockPos pos, Rotation rotation) { - if (containsBedrock(world, pos)) return false; - - return getAirFractionFoundation(world, pos, rotation) < 0.5 - && world.getBlockState(pos.above(2)).is(Blocks.AIR) - && world.getBlockState(pos.above(4)).is(Blocks.AIR); - } - - protected boolean canGenerateFloor(LevelAccessor world, BlockPos pos, Rotation rotation) { - if (containsBedrock(world, pos)) return false; - - return getAirFraction(world, pos, rotation) > 0.6 && getAirFractionFoundation(world, pos, rotation) < 0.5; - } - - protected boolean canGenerateLava(LevelAccessor world, BlockPos pos, Rotation rotation) { - if (containsBedrock(world, pos)) return false; - - return getLavaFractionFoundation(world, pos, rotation) > 0.9 && getAirFraction(world, pos, rotation) > 0.9; - } - - protected boolean canGenerateUnder(LevelAccessor world, BlockPos pos, Rotation rotation) { - if (containsBedrock(world, pos)) return false; - - return getAirFraction(world, pos, rotation) < 0.2; - } - - protected boolean canGenerateCeil(LevelAccessor world, BlockPos pos, Rotation rotation) { - if (containsBedrock(world, pos)) return false; - - return getAirFractionBottom(world, pos, rotation) > 0.8 && getAirFraction(world, pos, rotation) < 0.6; - } - - public BoundingBox boundingBox(Rotation r, BlockPos p) { - return getBoundingBox(p, r, Mirror.NONE); - } - - protected float getAirFraction(LevelAccessor world, BlockPos pos, Rotation rotation) { - final MutableBlockPos POS = new MutableBlockPos(); - int airCount = 0; - - MutableBlockPos size = new MutableBlockPos().set(new BlockPos(structure.getSize()).rotate(rotation)); - size.setX(Math.abs(size.getX()) >> 1); - size.setZ(Math.abs(size.getZ()) >> 1); - - BlockPos start = pos.offset(-size.getX(), 0, -size.getZ()); - BlockPos end = pos.offset(size.getX(), size.getY() + offsetY, size.getZ()); - int count = 0; - - for (int x = start.getX(); x <= end.getX(); x++) { - POS.setX(x); - for (int y = start.getY(); y <= end.getY(); y++) { - POS.setY(y); - for (int z = start.getZ(); z <= end.getZ(); z++) { - POS.setZ(z); - if (world.isEmptyBlock(POS)) - airCount++; - count++; - } - } - } - - return (float) airCount / count; - } - - private float getLavaFractionFoundation(LevelAccessor world, BlockPos pos, Rotation rotation) { - final MutableBlockPos POS = new MutableBlockPos(); - int lavaCount = 0; - - MutableBlockPos size = new MutableBlockPos().set(new BlockPos(structure.getSize()).rotate(rotation)); - size.setX(Math.abs(size.getX()) >> 1); - size.setZ(Math.abs(size.getZ()) >> 1); - - BlockPos start = pos.offset(-(size.getX()), 0, -(size.getZ())); - BlockPos end = pos.offset(size.getX(), 0, size.getZ()); - int count = 0; - - POS.setY(pos.getY() - 1); - for (int x = start.getX(); x <= end.getX(); x++) { - POS.setX(x); - for (int z = start.getZ(); z <= end.getZ(); z++) { - POS.setZ(z); - - if (BlocksHelper.isLava(world.getBlockState(POS))) - lavaCount++; - count++; - } - } - - return (float) lavaCount / count; - } - - private float getAirFractionFoundation(LevelAccessor world, BlockPos pos, Rotation rotation) { - final MutableBlockPos POS = new MutableBlockPos(); - int airCount = 0; - - MutableBlockPos size = new MutableBlockPos().set(new BlockPos(structure.getSize()).rotate(rotation)); - size.setX(Math.abs(size.getX()) >> 1); - size.setZ(Math.abs(size.getZ()) >> 1); - - BlockPos start = pos.offset(-(size.getX()), -1, -(size.getZ())); - BlockPos end = pos.offset(size.getX(), 0, size.getZ()); - int count = 0; - - for (int x = start.getX(); x <= end.getX(); x++) { - POS.setX(x); - for (int y = start.getY(); y <= end.getY(); y++) { - POS.setY(y); - for (int z = start.getZ(); z <= end.getZ(); z++) { - POS.setZ(z); - if (world.getBlockState(POS).getMaterial().isReplaceable()) - airCount++; - count++; - } - } - } - - return (float) airCount / count; - } - - private float getAirFractionBottom(LevelAccessor world, BlockPos pos, Rotation rotation) { - final MutableBlockPos POS = new MutableBlockPos(); - int airCount = 0; - - MutableBlockPos size = new MutableBlockPos().set(new BlockPos(structure.getSize()).rotate(rotation)); - size.setX(Math.abs(size.getX())); - size.setZ(Math.abs(size.getZ())); - - float y1 = Math.min(offsetY, 0); - float y2 = Math.max(offsetY, 0); - BlockPos start = pos.offset(-(size.getX() >> 1), y1, -(size.getZ() >> 1)); - BlockPos end = pos.offset(size.getX() >> 1, y2, size.getZ() >> 1); - int count = 0; - - for (int x = start.getX(); x <= end.getX(); x++) { - POS.setX(x); - for (int y = start.getY(); y <= end.getY(); y++) { - POS.setY(y); - for (int z = start.getZ(); z <= end.getZ(); z++) { - POS.setZ(z); - if (world.getBlockState(POS).getMaterial().isReplaceable()) - airCount++; - count++; - } - } - } - - return (float) airCount / count; - } - - public boolean loaded() { - return structure != null; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/TemplatePiece.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/TemplatePiece.java deleted file mode 100644 index 4b2ca88b..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/TemplatePiece.java +++ /dev/null @@ -1,210 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.util.BlocksHelper; -import org.betterx.bclib.util.MHelper; -import org.betterx.bclib.util.StructureErode; -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.core.Vec3i; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.StructureManager; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.TemplateStructurePiece; -import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceSerializationContext; -import net.minecraft.world.level.levelgen.structure.pieces.StructurePieceType; -import net.minecraft.world.level.levelgen.structure.templatesystem.BlockIgnoreProcessor; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager; - -public class TemplatePiece extends TemplateStructurePiece { - private final int erosion; - private final boolean cover; - public static final StructurePieceType INSTANCE = setTemplatePieceId( - TemplatePiece::new, - "template_piece" - ); - - - private static StructurePieceType setFullContextPieceId(StructurePieceType structurePieceType, String id) { - return Registry.register(Registry.STRUCTURE_PIECE, BCLib.makeID(id), structurePieceType); - } - - private static StructurePieceType setTemplatePieceId( - StructurePieceType.StructureTemplateType structureTemplateType, - String string - ) { - return setFullContextPieceId(structureTemplateType, string); - } - - - public static void ensureStaticInitialization() { - } - - public TemplatePiece( - StructureTemplateManager structureTemplateManager, - ResourceLocation resourceLocation, - BlockPos centerPos, - Rotation rotation, - Mirror mirror, - BlockPos halfSize - ) { - this(structureTemplateManager, resourceLocation, centerPos, rotation, mirror, halfSize, 0, false); - } - - public TemplatePiece( - StructureTemplateManager structureTemplateManager, - ResourceLocation resourceLocation, - BlockPos centerPos, - Rotation rotation, - Mirror mirror, - BlockPos halfSize, - int erosion, - boolean cover - ) { - super( - INSTANCE, - 0, - structureTemplateManager, - resourceLocation, - resourceLocation.toString(), - makeSettings(rotation, mirror, halfSize), - shiftPos(rotation, mirror, halfSize, centerPos) - ); - this.erosion = erosion; - this.cover = cover; - } - - public TemplatePiece(StructureTemplateManager structureTemplateManager, CompoundTag compoundTag) { - super( - INSTANCE, - compoundTag, - structureTemplateManager, - (ResourceLocation resourceLocation) -> makeSettings(compoundTag) - ); - if (compoundTag.contains("E")) - this.erosion = compoundTag.getInt("E"); - else - this.erosion = 0; - - if (compoundTag.contains("C")) - this.cover = compoundTag.getBoolean("C"); - else - this.cover = true; - } - - private static BlockPos shiftPos( - Rotation rotation, - Mirror mirror, - BlockPos halfSize, - BlockPos pos - ) { - halfSize = StructureTemplate.transform(halfSize, mirror, rotation, halfSize); - return pos.offset(-halfSize.getX(), 0, -halfSize.getZ()); - } - - private static StructurePlaceSettings makeSettings(CompoundTag compoundTag) { - return makeSettings( - Rotation.valueOf(compoundTag.getString("R")), - Mirror.valueOf(compoundTag.getString("M")), - new BlockPos(compoundTag.getInt("RX"), compoundTag.getInt("RY"), compoundTag.getInt("RZ")) - ); - - } - - private static StructurePlaceSettings makeSettings(Rotation rotation, Mirror mirror, BlockPos halfSize) { - return new StructurePlaceSettings().setRotation(rotation) - .setMirror(mirror) - .setRotationPivot(halfSize) - .addProcessor(BlockIgnoreProcessor.STRUCTURE_BLOCK); - } - - @Override - protected void addAdditionalSaveData( - StructurePieceSerializationContext structurePieceSerializationContext, - CompoundTag tag - ) { - super.addAdditionalSaveData(structurePieceSerializationContext, tag); - tag.putString("R", this.placeSettings.getRotation().name()); - tag.putString("M", this.placeSettings.getMirror().name()); - tag.putInt("RX", this.placeSettings.getRotationPivot().getX()); - tag.putInt("RY", this.placeSettings.getRotationPivot().getY()); - tag.putInt("RZ", this.placeSettings.getRotationPivot().getZ()); - tag.putInt("E", this.erosion); - tag.putBoolean("C", this.cover); - } - - @Override - protected void handleDataMarker( - String string, - BlockPos blockPos, - ServerLevelAccessor serverLevelAccessor, - RandomSource randomSource, - BoundingBox boundingBox - ) { - - } - - @Override - public void postProcess( - WorldGenLevel world, - StructureManager structureManager, - ChunkGenerator chunkGenerator, - RandomSource random, - BoundingBox boundingBox, - ChunkPos chunkPos, - BlockPos blockPos - ) { - BlockState coverState = null; - if (cover) { - BlockPos.MutableBlockPos mPos = new BlockPos( - this.boundingBox.minX() - 1, - blockPos.getY(), - this.boundingBox.minZ() - 1 - ).mutable(); - if (BlocksHelper.findOnSurroundingSurface( - world, - mPos, - Direction.DOWN, - 8, - s -> s.is(CommonBlockTags.TERRAIN) - )) { - mPos.move(Direction.DOWN); - coverState = world.getBlockState(mPos); - } - } - super.postProcess(world, structureManager, chunkGenerator, random, boundingBox, chunkPos, blockPos); - BoundingBox bounds = BoundingBox.fromCorners(new Vec3i( - boundingBox.minX(), - this.boundingBox.minY(), - boundingBox.minZ() - ), new Vec3i(boundingBox.maxX(), this.boundingBox.maxY(), boundingBox.maxZ())); - - if (erosion > 0) { - int x1 = MHelper.min(bounds.maxX(), this.boundingBox.maxX()); - int x0 = MHelper.max(bounds.minX(), this.boundingBox.minX()); - int z1 = MHelper.min(bounds.maxZ(), this.boundingBox.maxZ()); - int z0 = MHelper.max(bounds.minZ(), this.boundingBox.minZ()); - bounds = BoundingBox.fromCorners(new Vec3i(x0, bounds.minY(), z0), new Vec3i(x1, bounds.maxY(), z1)); - StructureErode.erode(world, bounds, erosion, random); - } - - if (cover) { - //System.out.println("CoverState:" + coverState + ", " + blockPos + " " + boundingBox.getCenter()); - StructureErode.cover(world, bounds, random, coverState); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/TemplateStructure.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/TemplateStructure.java deleted file mode 100644 index bf8ab098..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/TemplateStructure.java +++ /dev/null @@ -1,276 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ChunkPos; -import net.minecraft.world.level.NoiseColumn; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.WorldGenerationContext; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; - -import com.google.common.collect.ImmutableList; - -import java.util.List; -import java.util.Optional; -import java.util.function.BiFunction; -import java.util.function.BiPredicate; - -public abstract class TemplateStructure extends Structure { - protected final List configs; - - public static Codec simpleTemplateCodec(BiFunction, T> instancer) { - return RecordCodecBuilder.create((instance) -> instance - .group( - Structure.settingsCodec(instance), - ExtraCodecs.nonEmptyList(Config.CODEC.listOf()) - .fieldOf("configs") - .forGetter((T ruinedPortalStructure) -> ruinedPortalStructure.configs) - ) - .apply(instance, instancer) - ); - } - - - protected TemplateStructure( - StructureSettings structureSettings, - ResourceLocation location, - int offsetY, - StructurePlacementType type, - float chance - ) { - this(structureSettings, List.of(new Config(location, offsetY, type, chance))); - } - - protected TemplateStructure( - StructureSettings structureSettings, - List configs - ) { - super(structureSettings); - this.configs = configs; - } - - protected Config randomConfig(RandomSource random) { - if (this.configs.size() > 1) { - final float chanceSum = configs.parallelStream().map(c -> c.chance()).reduce(0.0f, (p, c) -> p + c); - float rnd = random.nextFloat() * chanceSum; - - for (Config c : configs) { - rnd -= c.chance(); - if (rnd <= 0) return c; - } - } else { - return this.configs.get(0); - } - - return null; - } - - protected boolean isLavaPlaceable(BlockState state, BlockState before) { - return (state == null || state.is(Blocks.AIR)) && before.is(Blocks.LAVA); - } - - protected boolean isFloorPlaceable(BlockState state, BlockState before) { - return (state == null || state.is(Blocks.AIR)) && before.getMaterial().isSolid(); - } - - protected int erosion(RandomSource rnd) { - return 0; - } - - protected boolean cover(RandomSource rnd) { - return false; - } - - @Override - public Optional findGenerationPoint(GenerationContext ctx) { - WorldGenerationContext worldGenerationContext = new WorldGenerationContext( - ctx.chunkGenerator(), - ctx.heightAccessor() - ); - final Config config = randomConfig(ctx.random()); - if (config == null) return Optional.empty(); - ChunkPos chunkPos = ctx.chunkPos(); - final int x = chunkPos.getMinBlockX(); - final int z = chunkPos.getMinBlockZ(); - StructureTemplate structureTemplate = ctx.structureTemplateManager().getOrCreate(config.location); - - - final BiPredicate isCorrectBase; - final int searchStep; - final int minBaseCount; - final float minAirRatio = 0.6f; - if (config.type == StructurePlacementType.LAVA) { - isCorrectBase = this::isLavaPlaceable; - minBaseCount = 5; - searchStep = 1; - } else if (config.type == StructurePlacementType.CEIL) { - isCorrectBase = this::isFloorPlaceable; - minBaseCount = 3; - searchStep = -1; - } else { - isCorrectBase = this::isFloorPlaceable; - minBaseCount = 3; - searchStep = 1; - } - - - final int seaLevel = - ctx.chunkGenerator().getSeaLevel() - + (searchStep > 0 ? 0 : (structureTemplate.getSize(Rotation.NONE).getY() + config.offsetY)); - final int maxHeight = - worldGenerationContext.getGenDepth() - - 4 - - (searchStep > 0 ? (structureTemplate.getSize(Rotation.NONE).getY() + config.offsetY) : 0); - - BlockPos halfSize = new BlockPos( - structureTemplate.getSize().getX() / 2, - 0, - structureTemplate.getSize().getZ() / 2 - ); - Rotation rotation = StructureNBT.getRandomRotation(ctx.random()); - Mirror mirror = StructureNBT.getRandomMirror(ctx.random()); - BlockPos.MutableBlockPos centerPos = new BlockPos.MutableBlockPos( - x, - 0, - z - ); - BoundingBox boundingBox = structureTemplate.getBoundingBox(centerPos, rotation, halfSize, mirror); - - var noiseColumns = ImmutableList - .of( - new BlockPos(boundingBox.getCenter().getX(), 0, boundingBox.getCenter().getZ()), - new BlockPos(boundingBox.minX(), 0, boundingBox.minZ()), - new BlockPos(boundingBox.maxX(), 0, boundingBox.minZ()), - new BlockPos(boundingBox.minX(), 0, boundingBox.maxZ()), - new BlockPos(boundingBox.maxX(), 0, boundingBox.maxZ()) - ) - .stream() - .map(blockPos -> ctx.chunkGenerator().getBaseColumn( - blockPos.getX(), - blockPos.getZ(), - ctx.heightAccessor(), - ctx.randomState() - )).toList(); - - int y = noiseColumns - .stream() - .map(column -> findY(column, isCorrectBase, searchStep, seaLevel, maxHeight)) - .reduce( - searchStep > 0 ? Integer.MAX_VALUE : Integer.MIN_VALUE, - (p, c) -> searchStep > 0 ? Math.min(p, c) : Math.max(p, c) - ); - - if (y >= maxHeight || y < seaLevel) return Optional.empty(); - if (!BCLStructure.isValidBiome(ctx, y)) return Optional.empty(); - - int baseCount = noiseColumns - .stream() - .map(column -> isCorrectBase.test(null, column.getBlock(y - searchStep))) - .filter(b -> b) - .map(b -> 1) - .reduce(0, (p, c) -> p + c); - - if (baseCount < minBaseCount) return Optional.empty(); - - float airRatio = noiseColumns - .stream() - .map(column -> airRatio(column, y, boundingBox.getYSpan(), searchStep)) - .reduce(0.0f, (p, c) -> p + c) / noiseColumns.size(); - - if (airRatio < minAirRatio) return Optional.empty(); - - centerPos.setY(y - (searchStep == 1 ? 0 : (structureTemplate.getSize(Rotation.NONE).getY()))); - - int erosion = erosion(ctx.random()); - boolean cover = cover(ctx.random()); - // if (!structure.canGenerate(ctx.chunkGenerator()., centerPos)) - return Optional.of(new GenerationStub( - centerPos, - structurePiecesBuilder -> - structurePiecesBuilder.addPiece( - new TemplatePiece( - ctx.structureTemplateManager(), - config.location, - centerPos.offset( - 0, - config.offsetY, - 0 - ), - rotation, - mirror, - halfSize, - erosion, - cover - )) - )); - - } - - private float airRatio(NoiseColumn column, int y, int height, int searchStep) { - int airCount = 0; - for (int i = y; i < y + height && i > y - height; i += searchStep) { - BlockState state = column.getBlock(i); - if (state.isAir() || state.getMaterial().isReplaceable()) { - airCount++; - } - } - return airCount / (float) height; - } - - - private int findY( - NoiseColumn column, - BiPredicate isCorrectBase, - int searchStep, - int seaLevel, - int maxHeight - ) { - int y = searchStep > 0 ? seaLevel : maxHeight - 1; - BlockState state = column.getBlock(y - searchStep); - - for (; y < maxHeight && y >= seaLevel; y += searchStep) { - BlockState before = state; - state = column.getBlock(y); - if (isCorrectBase.test(state, before)) break; - } - return y; - } - - - public record Config(ResourceLocation location, int offsetY, StructurePlacementType type, float chance) { - public static final Codec CODEC = - RecordCodecBuilder.create((instance) -> - instance.group( - ResourceLocation.CODEC - .fieldOf("location") - .forGetter((cfg) -> cfg.location), - - Codec - .INT - .fieldOf("offset_y") - .orElse(0) - .forGetter((cfg) -> cfg.offsetY), - - StructurePlacementType.CODEC - .fieldOf("placement") - .orElse(StructurePlacementType.FLOOR) - .forGetter((cfg) -> cfg.type), - Codec - .FLOAT - .fieldOf("chance") - .orElse(1.0f) - .forGetter((cfg) -> cfg.chance) - ) - .apply(instance, Config::new) - ); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/templatesystem/DestructionStructureProcessor.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/templatesystem/DestructionStructureProcessor.java deleted file mode 100644 index 46f3b172..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/templatesystem/DestructionStructureProcessor.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures.templatesystem; - -import org.betterx.bclib.util.BlocksHelper; -import org.betterx.bclib.util.MHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; - -public class DestructionStructureProcessor extends StructureProcessor { - private int chance = 4; - - public void setChance(int chance) { - this.chance = chance; - } - - @Override - public StructureBlockInfo processBlock( - LevelReader worldView, - BlockPos pos, - BlockPos blockPos, - StructureBlockInfo structureBlockInfo, - StructureBlockInfo structureBlockInfo2, - StructurePlaceSettings structurePlacementData - ) { - if (!BlocksHelper.isInvulnerable( - structureBlockInfo2.state, - worldView, - structureBlockInfo2.pos - ) && MHelper.RANDOM.nextInt(chance) == 0) { - return null; - } - return structureBlockInfo2; - } - - @Override - protected StructureProcessorType getType() { - return StructureProcessorType.RULE; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/templatesystem/TerrainStructureProcessor.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/templatesystem/TerrainStructureProcessor.java deleted file mode 100644 index e849af3a..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/structures/templatesystem/TerrainStructureProcessor.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.structures.templatesystem; - -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessor; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate.StructureBlockInfo; - -public class TerrainStructureProcessor extends StructureProcessor { - private final Block defaultBlock; - - public TerrainStructureProcessor(Block defaultBlock) { - this.defaultBlock = defaultBlock; - } - - @Override - public StructureBlockInfo processBlock( - LevelReader worldView, - BlockPos pos, - BlockPos blockPos, - StructureBlockInfo structureBlockInfo, - StructureBlockInfo structureBlockInfo2, - StructurePlaceSettings structurePlacementData - ) { - BlockPos bpos = structureBlockInfo2.pos; - if (structureBlockInfo2.state.is(defaultBlock) && worldView.isEmptyBlock(bpos.above())) { - final BlockState top = BiomeAPI.findTopMaterial(worldView.getBiome(pos)) - .orElse(defaultBlock.defaultBlockState()); - return new StructureBlockInfo(bpos, top, structureBlockInfo2.nbt); - } - return structureBlockInfo2; - } - - @Override - protected StructureProcessorType getType() { - return StructureProcessorType.RULE; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/SurfaceRuleBuilder.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/SurfaceRuleBuilder.java deleted file mode 100644 index 92c04e97..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/SurfaceRuleBuilder.java +++ /dev/null @@ -1,340 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface; - -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.bclib.api.v2.levelgen.surface.rules.Conditions; -import org.betterx.bclib.api.v2.levelgen.surface.rules.DoubleBlockSurfaceNoiseCondition; -import org.betterx.bclib.api.v2.levelgen.surface.rules.NoiseCondition; - -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.SurfaceRules; -import net.minecraft.world.level.levelgen.SurfaceRules.RuleSource; -import net.minecraft.world.level.levelgen.placement.CaveSurface; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -public class SurfaceRuleBuilder { - private static final Map RULES_CACHE = Maps.newHashMap(); - private static final SurfaceRuleBuilder INSTANCE = new SurfaceRuleBuilder(); - private final List rules = Lists.newArrayList(); - private SurfaceRuleEntry entryInstance; - private ResourceKey biomeKey; - - private SurfaceRuleBuilder() { - } - - public static SurfaceRuleBuilder start() { - INSTANCE.biomeKey = null; - INSTANCE.rules.clear(); - return INSTANCE; - } - - /** - * Restricts surface to only one biome. - * - * @param biomeKey {@link ResourceKey} for the {@link Biome}. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder biome(ResourceKey biomeKey) { - this.biomeKey = biomeKey; - return this; - } - - /** - * Restricts surface to only one biome. - * - * @param biome {@link Biome}. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder biome(Biome biome) { - return biome(BiomeAPI.getBiomeKey(biome)); - } - - /** - * Set biome surface with specified {@link BlockState}. Example - block of grass in the Overworld biomes - * - * @param state {@link BlockState} for the ground cover. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder surface(BlockState state) { - entryInstance = getFromCache("surface_" + state.toString(), () -> { - RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.ON_FLOOR, rule); - return new SurfaceRuleEntry(2, rule); - }); - rules.add(entryInstance); - return this; - } - - /** - * Set biome subsurface with specified {@link BlockState}. Example - dirt in the Overworld biomes. - * - * @param state {@link BlockState} for the subterrain layer. - * @param depth block layer depth. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder subsurface(BlockState state, int depth) { - entryInstance = getFromCache("subsurface_" + depth + "_" + state.toString(), () -> { - RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(depth, false, CaveSurface.FLOOR), rule); - return new SurfaceRuleEntry(3, rule); - }); - rules.add(entryInstance); - return this; - } - - /** - * Set biome filler with specified {@link BlockState}. Example - stone in the Overworld biomes. The rule is added with priority 10. - * - * @param state {@link BlockState} for filling. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder filler(BlockState state) { - entryInstance = getFromCache( - "fill_" + state.toString(), - () -> new SurfaceRuleEntry(10, SurfaceRules.state(state)) - ); - rules.add(entryInstance); - return this; - } - - /** - * Set biome floor with specified {@link BlockState}. Example - underside of a gravel floor. The rule is added with priority 3. - * - * @param state {@link BlockState} for the ground cover. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder floor(BlockState state) { - entryInstance = getFromCache("floor_" + state.toString(), () -> { - RuleSource rule = SurfaceRules.state(state); - return new SurfaceRuleEntry(3, SurfaceRules.ifTrue(SurfaceRules.ON_FLOOR, rule)); - }); - rules.add(entryInstance); - return this; - } - - /** - * Set biome floor material with specified {@link BlockState} and height. The rule is added with priority 3. - * - * @param state {@link BlockState} for the subterrain layer. - * @param height block layer height. - * @param noise The noise object that is applied - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder belowFloor(BlockState state, int height, NoiseCondition noise) { - entryInstance = getFromCache( - "below_floor_" + height + "_" + state.toString() + "_" + noise.getClass() - .getSimpleName(), - () -> { - RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue( - SurfaceRules.stoneDepthCheck( - height, - false, - CaveSurface.FLOOR - ), - SurfaceRules.ifTrue(noise, rule) - ); - return new SurfaceRuleEntry(3, rule); - } - ); - rules.add(entryInstance); - return this; - } - - /** - * Set biome floor material with specified {@link BlockState} and height. The rule is added with priority 3. - * - * @param state {@link BlockState} for the subterrain layer. - * @param height block layer height. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder belowFloor(BlockState state, int height) { - entryInstance = getFromCache("below_floor_" + height + "_" + state.toString(), () -> { - RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, CaveSurface.FLOOR), rule); - return new SurfaceRuleEntry(3, rule); - }); - rules.add(entryInstance); - return this; - } - - /** - * Set biome ceiling with specified {@link BlockState}. Example - block of sandstone in the Overworld desert in air pockets. The rule is added with priority 3. - * - * @param state {@link BlockState} for the ground cover. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder ceil(BlockState state) { - entryInstance = getFromCache("ceil_" + state.toString(), () -> { - RuleSource rule = SurfaceRules.state(state); - return new SurfaceRuleEntry(3, SurfaceRules.ifTrue(SurfaceRules.ON_CEILING, rule)); - }); - rules.add(entryInstance); - return this; - } - - /** - * Set biome ceiling material with specified {@link BlockState} and height. Example - sandstone in the Overworld deserts. The rule is added with priority 3. - * - * @param state {@link BlockState} for the subterrain layer. - * @param height block layer height. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder aboveCeil(BlockState state, int height) { - entryInstance = getFromCache("above_ceil_" + height + "_" + state.toString(), () -> { - RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(height, false, CaveSurface.CEILING), rule); - return new SurfaceRuleEntry(3, rule); - }); - rules.add(entryInstance); - return this; - } - - /** - * Will cover steep areas (with large terrain angle). Example - Overworld mountains. - * - * @param state {@link BlockState} for the steep layer. - * @param depth layer depth - * @return - */ - public SurfaceRuleBuilder steep(BlockState state, int depth) { - entryInstance = getFromCache("steep_" + depth + "_" + state.toString(), () -> { - RuleSource rule = SurfaceRules.state(state); - rule = SurfaceRules.ifTrue(SurfaceRules.stoneDepthCheck(depth, false, CaveSurface.FLOOR), rule); - rule = SurfaceRules.ifTrue(SurfaceRules.steep(), rule); - int priority = depth < 1 ? 0 : 1; - return new SurfaceRuleEntry(priority, rule); - }); - rules.add(entryInstance); - return this; - } - - /** - * Allows to add custom rule. - * - * @param priority rule priority, lower values = higher priority (rule will be applied before others). - * @param rule custom {@link SurfaceRules.RuleSource}. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder rule(int priority, SurfaceRules.RuleSource rule) { - rules.add(new SurfaceRuleEntry(priority, rule)); - return this; - } - - /** - * Allows to add custom rule. - * - * @param rule custom {@link SurfaceRules.RuleSource}. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder rule(SurfaceRules.RuleSource rule) { - return rule(7, rule); - } - - /** - * Set biome floor with specified {@link BlockState} and the {@link DoubleBlockSurfaceNoiseCondition}. The rule is added with priority 3. - * - * @param surfaceBlockA {@link BlockState} for the ground cover. - * @param surfaceBlockB {@link BlockState} for the alternative ground cover. - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder chancedFloor(BlockState surfaceBlockA, BlockState surfaceBlockB) { - return chancedFloor(surfaceBlockA, surfaceBlockB, Conditions.DOUBLE_BLOCK_SURFACE_NOISE); - } - - /** - * Set biome floor with specified {@link BlockState} and the given Noise Function. The rule is added with priority 3. - * - * @param surfaceBlockA {@link BlockState} for the ground cover. - * @param surfaceBlockB {@link BlockState} for the alternative ground cover. - * @param noise The {@link NoiseCondition} - * @return same {@link SurfaceRuleBuilder} instance. - */ - public SurfaceRuleBuilder chancedFloor(BlockState surfaceBlockA, BlockState surfaceBlockB, NoiseCondition noise) { - entryInstance = getFromCache( - "chancedFloor_" + surfaceBlockA + "_" + surfaceBlockB + "_" + noise.getClass() - .getSimpleName(), - () -> { - RuleSource rule = - SurfaceRules.ifTrue( - SurfaceRules.ON_FLOOR, - SurfaceRules.sequence( - SurfaceRules.ifTrue( - noise, - SurfaceRules.state( - surfaceBlockA) - ), - SurfaceRules.state(surfaceBlockB) - ) - ); - return new SurfaceRuleEntry(4, rule); - } - ); - rules.add(entryInstance); - return this; - } - - public SurfaceRuleBuilder chancedFloor(BlockState surfaceBlockA, RuleSource surfaceBlockB, NoiseCondition noise) { - entryInstance = getFromCache( - "chancedFloor_" + surfaceBlockA + "_" + surfaceBlockB + "_" + noise.getClass() - .getSimpleName(), - () -> { - RuleSource rule = - SurfaceRules.ifTrue( - SurfaceRules.ON_FLOOR, - SurfaceRules.sequence( - SurfaceRules.ifTrue( - noise, - SurfaceRules.state( - surfaceBlockA) - ), - surfaceBlockB - ) - ); - return new SurfaceRuleEntry(4, rule); - } - ); - rules.add(entryInstance); - return this; - } - - /** - * Finalise rule building process. - * - * @return {@link SurfaceRules.RuleSource}. - */ - public SurfaceRules.RuleSource build() { - Collections.sort(rules); - List ruleList = rules.stream().map(entry -> entry.getRule()).toList(); - SurfaceRules.RuleSource[] ruleArray = ruleList.toArray(new SurfaceRules.RuleSource[ruleList.size()]); - SurfaceRules.RuleSource rule = SurfaceRules.sequence(ruleArray); - if (biomeKey != null) { - rule = SurfaceRules.ifTrue(SurfaceRules.isBiome(biomeKey), rule); - } - return rule; - } - - /** - * Internal function, will take entry from cache or create it if necessary. - * - * @param name {@link String} entry internal name. - * @param supplier {@link Supplier} for {@link SurfaceRuleEntry}. - * @return new or existing {@link SurfaceRuleEntry}. - */ - private static SurfaceRuleEntry getFromCache(String name, Supplier supplier) { - SurfaceRuleEntry entry = RULES_CACHE.get(name); - if (entry == null) { - entry = supplier.get(); - RULES_CACHE.put(name, entry); - } - return entry; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/SurfaceRuleEntry.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/SurfaceRuleEntry.java deleted file mode 100644 index 323beb3f..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/SurfaceRuleEntry.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface; - -import net.minecraft.world.entity.Mob; -import net.minecraft.world.level.levelgen.SurfaceRules; - -import org.jetbrains.annotations.NotNull; - -public class SurfaceRuleEntry implements Comparable { - private final SurfaceRules.RuleSource rule; - private final byte priority; - - public SurfaceRuleEntry(int priority, SurfaceRules.RuleSource rule) { - this.priority = (byte) priority; - this.rule = rule; - } - - protected SurfaceRules.RuleSource getRule() { - return rule; - } - - @Override - public int compareTo(@NotNull SurfaceRuleEntry entry) { - return Integer.compare(priority, entry.priority); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/Conditions.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/Conditions.java deleted file mode 100644 index 63920e1a..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/Conditions.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.interfaces.NumericProvider; - -import com.mojang.serialization.Codec; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.valueproviders.UniformFloat; -import net.minecraft.world.level.levelgen.SurfaceRules; - -public class Conditions { - public static final ThresholdCondition DOUBLE_BLOCK_SURFACE_NOISE = new ThresholdCondition( - 4141, - 0, - UniformFloat.of(-0.4f, 0.4f), - 0.1, - 0.1 - ); - - public static final ThresholdCondition FORREST_FLOOR_SURFACE_NOISE_A = new ThresholdCondition( - 614, - 0, - UniformFloat.of(-0.2f, 0f), - 0.1, - 0.1 - ); - - public static final ThresholdCondition FORREST_FLOOR_SURFACE_NOISE_B = new ThresholdCondition( - 614, - 0, - UniformFloat.of(-0.7f, -0.5f), - 0.1, - 0.1 - ); - - public static final ThresholdCondition NETHER_SURFACE_NOISE = new ThresholdCondition( - 245, - 0, - UniformFloat.of(-0.7f, -0.5f), - 0.05, - 0.05 - ); - - public static final ThresholdCondition NETHER_SURFACE_NOISE_LARGE = new ThresholdCondition( - 523, - 0, - UniformFloat.of(-0.4f, -0.3f), - 0.5, - 0.5 - ); - - public static final VolumeThresholdCondition NETHER_VOLUME_NOISE = new VolumeThresholdCondition( - 245, - 0, - UniformFloat.of(-0.1f, 0.2f), - 0.1, - 0.2, - 0.1 - ); - - public static final VolumeThresholdCondition NETHER_VOLUME_NOISE_LARGE = new VolumeThresholdCondition( - 523, - 0, - UniformFloat.of(-0.1f, 0.4f), - 0.2, - 0.2, - 0.2 - ); - - public static final NumericProvider NETHER_NOISE = new NetherNoiseCondition(); - - public static void register(ResourceLocation location, Codec codec) { - Registry.register(Registry.CONDITION, location, codec); - } - - public static void registerNumeric(ResourceLocation location, Codec codec) { - Registry.register(NumericProvider.NUMERIC_PROVIDER, location, codec); - } - - public static void registerAll() { - registerNumeric(BCLib.makeID("rnd_int"), RandomIntProvider.CODEC); - registerNumeric(BCLib.makeID("nether_noise"), NetherNoiseCondition.CODEC); - register(BCLib.makeID("threshold_condition"), ThresholdCondition.CODEC); - register(BCLib.makeID("volume_threshold_condition"), VolumeThresholdCondition.CODEC); - register(BCLib.makeID("rough_noise_condition"), RoughNoiseCondition.CODEC); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/DoubleBlockSurfaceNoiseCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/DoubleBlockSurfaceNoiseCondition.java deleted file mode 100644 index 6aa0ec7c..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/DoubleBlockSurfaceNoiseCondition.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -public class DoubleBlockSurfaceNoiseCondition { - public static final ThresholdCondition CONDITION = Conditions.DOUBLE_BLOCK_SURFACE_NOISE; -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/NetherNoiseCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/NetherNoiseCondition.java deleted file mode 100644 index 6df8b05a..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/NetherNoiseCondition.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.interfaces.NumericProvider; -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; -import org.betterx.bclib.util.MHelper; - -import com.mojang.serialization.Codec; - -public class NetherNoiseCondition implements NumericProvider { - public static final Codec CODEC = Codec.BYTE.fieldOf("nether_noise") - .xmap( - (obj) -> (NetherNoiseCondition) Conditions.NETHER_NOISE, - obj -> (byte) 0 - ) - .codec(); - - - NetherNoiseCondition() { - } - - - @Override - public Codec pcodec() { - return CODEC; - } - - @Override - public int getNumber(SurfaceRulesContextAccessor context) { - final int x = context.getBlockX(); - final int y = context.getBlockY(); - final int z = context.getBlockZ(); - double value = Conditions.NETHER_VOLUME_NOISE.noiseContext.noise.eval( - x * Conditions.NETHER_VOLUME_NOISE.scaleX, - y * Conditions.NETHER_VOLUME_NOISE.scaleY, - z * Conditions.NETHER_VOLUME_NOISE.scaleZ - ); - - int offset = Conditions.NETHER_VOLUME_NOISE.noiseContext.random.nextInt(20) == 0 ? 3 : 0; - - float cmp = MHelper.randRange(0.4F, 0.5F, Conditions.NETHER_VOLUME_NOISE.noiseContext.random); - if (value > cmp || value < -cmp) return 2 + offset; - - if (value > Conditions.NETHER_VOLUME_NOISE.range.sample(Conditions.NETHER_VOLUME_NOISE.noiseContext.random)) - return 0 + offset; - - return 1 + offset; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/NoiseCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/NoiseCondition.java deleted file mode 100644 index 87405225..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/NoiseCondition.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; - -import net.minecraft.world.level.levelgen.SurfaceRules; - -public interface NoiseCondition extends SurfaceRules.ConditionSource { - boolean test(SurfaceRulesContextAccessor context); -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/RandomIntProvider.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/RandomIntProvider.java deleted file mode 100644 index c97f5fb6..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/RandomIntProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.interfaces.NumericProvider; -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; -import org.betterx.bclib.util.MHelper; - -import com.mojang.serialization.Codec; - -public record RandomIntProvider(int range) implements NumericProvider { - public static final Codec CODEC = Codec.INT.fieldOf("range") - .xmap(RandomIntProvider::new, obj -> obj.range) - .codec(); - - @Override - public int getNumber(SurfaceRulesContextAccessor context) { - return MHelper.RANDOM.nextInt(range); - } - - @Override - public Codec pcodec() { - return CODEC; - } - - static { - - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/RoughNoiseCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/RoughNoiseCondition.java deleted file mode 100644 index e578bcf4..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/RoughNoiseCondition.java +++ /dev/null @@ -1,116 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - - -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; -import org.betterx.bclib.noise.Noises; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.util.RandomSource; -import net.minecraft.util.valueproviders.FloatProvider; -import net.minecraft.util.valueproviders.UniformFloat; -import net.minecraft.world.level.levelgen.SurfaceRules; -import net.minecraft.world.level.levelgen.synth.NormalNoise; - -public class RoughNoiseCondition implements SurfaceRules.ConditionSource { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - ResourceKey.codec(Registry.NOISE_REGISTRY).fieldOf("noise").forGetter(o -> o.noise), - Codec.DOUBLE.fieldOf("min_threshold").forGetter(o -> o.minThreshold), - Codec.DOUBLE.fieldOf("max_threshold").forGetter(o -> o.maxThreshold), - FloatProvider.CODEC.fieldOf("roughness").forGetter(o -> o.roughness) - ) - .apply( - instance, - (noise1, minThreshold1, maxThreshold1, roughness1) -> new RoughNoiseCondition( - noise1, - roughness1, - minThreshold1, - maxThreshold1 - ) - )); - - public static final KeyDispatchDataCodec KEY_CODEC = KeyDispatchDataCodec.of(CODEC); - - private final ResourceKey noise; - private final double minThreshold; - private final double maxThreshold; - private final FloatProvider roughness; - - public RoughNoiseCondition( - ResourceKey noise, - FloatProvider roughness, - double minThreshold, - double maxThreshold - ) { - this.noise = noise; - this.minThreshold = minThreshold; - - this.maxThreshold = maxThreshold; - this.roughness = roughness; - } - - public RoughNoiseCondition( - ResourceKey noise, - FloatProvider roughness, - double minThreshold - ) { - this(noise, roughness, minThreshold, Double.MAX_VALUE); - } - - public RoughNoiseCondition( - ResourceKey noise, - double minThreshold - ) { - this(noise, UniformFloat.of(-0.2f, 0.4f), minThreshold, Double.MAX_VALUE); - } - - public RoughNoiseCondition( - ResourceKey noise, - double minThreshold, - double maxThreshold - ) { - this(noise, UniformFloat.of(-0.1f, 0.4f), minThreshold, maxThreshold); - } - - @Override - public KeyDispatchDataCodec codec() { - return KEY_CODEC; - } - - @Override - public SurfaceRules.Condition apply(final SurfaceRules.Context context2) { - final SurfaceRulesContextAccessor ctx = SurfaceRulesContextAccessor.class.cast(context2); - final NormalNoise normalNoise = ctx.getRandomState().getOrCreateNoise(this.noise); - final RandomSource roughnessSource = ctx.getRandomState() - .getOrCreateRandomFactory(Noises.ROUGHNESS_NOISE.location()) - .fromHashOf(Noises.ROUGHNESS_NOISE.location()); - - class NoiseThresholdCondition extends SurfaceRules.LazyCondition { - NoiseThresholdCondition() { - super(context2); - } - - @Override - protected long getContextLastUpdate() { - final SurfaceRulesContextAccessor ctx = SurfaceRulesContextAccessor.class.cast(this.context); - return ctx.getLastUpdateY() + ctx.getLastUpdateXZ(); - } - - protected boolean compute() { - double d = normalNoise - .getValue( - ctx.getBlockX(), - ctx.getBlockZ(), - ctx.getBlockZ() - ) + roughness.sample(roughnessSource); - return d >= minThreshold && d <= maxThreshold; - } - } - - return new NoiseThresholdCondition(); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/SurfaceNoiseCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/SurfaceNoiseCondition.java deleted file mode 100644 index 80d7d4a5..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/SurfaceNoiseCondition.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; - -import net.minecraft.world.level.levelgen.SurfaceRules.Condition; -import net.minecraft.world.level.levelgen.SurfaceRules.Context; -import net.minecraft.world.level.levelgen.SurfaceRules.LazyXZCondition; - -public abstract class SurfaceNoiseCondition implements NoiseCondition { - @Override - public final Condition apply(Context context2) { - final SurfaceNoiseCondition self = this; - - class Generator extends LazyXZCondition { - Generator() { - super(context2); - } - - @Override - protected boolean compute() { - final SurfaceRulesContextAccessor context = SurfaceRulesContextAccessor.class.cast(this.context); - if (context == null) return false; - return self.test(context); - } - } - - return new Generator(); - } - - public abstract boolean test(SurfaceRulesContextAccessor context); - - -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/SwitchRuleSource.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/SwitchRuleSource.java deleted file mode 100644 index c5ce2fe9..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/SwitchRuleSource.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.interfaces.NumericProvider; -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Registry; -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.SurfaceRules.Context; -import net.minecraft.world.level.levelgen.SurfaceRules.RuleSource; -import net.minecraft.world.level.levelgen.SurfaceRules.SurfaceRule; - -import java.util.List; -import org.jetbrains.annotations.Nullable; - -// -public record SwitchRuleSource(NumericProvider selector, List collection) implements RuleSource { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance.group( - NumericProvider.CODEC.fieldOf("selector").forGetter(SwitchRuleSource::selector), - RuleSource.CODEC.listOf().fieldOf("collection").forGetter(SwitchRuleSource::collection) - ) - .apply( - instance, - SwitchRuleSource::new - )); - - private static final KeyDispatchDataCodec KEY_CODEC = KeyDispatchDataCodec.of(SwitchRuleSource.CODEC); - - @Override - public KeyDispatchDataCodec codec() { - return KEY_CODEC; - } - - @Override - public SurfaceRule apply(Context context) { - - return new SurfaceRule() { - @Nullable - @Override - public BlockState tryApply(int x, int y, int z) { - final SurfaceRulesContextAccessor ctx = SurfaceRulesContextAccessor.class.cast(context); - int nr = Math.max(0, selector.getNumber(ctx)) % collection.size(); - - return collection.get(nr).apply(context).tryApply(x, y, z); - } - }; - } - - static { - Registry.register(Registry.RULE, "bclib_switch_rule", SwitchRuleSource.CODEC); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/ThresholdCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/ThresholdCondition.java deleted file mode 100644 index f6a40db7..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/ThresholdCondition.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; -import org.betterx.bclib.noise.OpenSimplexNoise; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.util.RandomSource; -import net.minecraft.util.valueproviders.ConstantFloat; -import net.minecraft.util.valueproviders.FloatProvider; -import net.minecraft.world.level.levelgen.SurfaceRules; -import net.minecraft.world.level.levelgen.ThreadSafeLegacyRandomSource; - -import com.google.common.collect.Maps; - -import java.util.Map; - -public class ThresholdCondition extends SurfaceNoiseCondition { - private static final Map NOISES = Maps.newHashMap(); - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - Codec.LONG.fieldOf("seed").forGetter(p -> p.noiseContext.seed), - Codec.DOUBLE.fieldOf("threshold").orElse(0.0).forGetter(p -> p.threshold), - FloatProvider.CODEC.fieldOf("threshold_offset").orElse(ConstantFloat.of(0)).forGetter(p -> p.range), - Codec.DOUBLE.fieldOf("scale_x").orElse(0.1).forGetter(p -> p.scaleX), - Codec.DOUBLE.fieldOf("scale_z").orElse(0.1).forGetter(p -> p.scaleZ) - ) - .apply(instance, ThresholdCondition::new)); - public static final KeyDispatchDataCodec KEY_CODEC = KeyDispatchDataCodec.of(CODEC); - private final Context noiseContext; - private final double threshold; - private final FloatProvider range; - private final double scaleX; - private final double scaleZ; - - public ThresholdCondition(long noiseSeed, double threshold, FloatProvider range, double scaleX, double scaleZ) { - this.threshold = threshold; - this.range = range; - this.scaleX = scaleX; - this.scaleZ = scaleZ; - - noiseContext = NOISES.computeIfAbsent(noiseSeed, seed -> new Context(seed)); - } - - @Override - public boolean test(SurfaceRulesContextAccessor context) { - final double x = context.getBlockX() * scaleX; - final double z = context.getBlockZ() * scaleZ; - if (noiseContext.lastX == x && noiseContext.lastZ == z) - return noiseContext.lastValue + range.sample(noiseContext.random) > threshold; - double value = noiseContext.noise.eval(x, z); - - noiseContext.lastX = x; - noiseContext.lastZ = z; - noiseContext.lastValue = value; - return value + range.sample(noiseContext.random) > threshold; - } - - @Override - public KeyDispatchDataCodec codec() { - return KEY_CODEC; - } - - static class Context { - public final OpenSimplexNoise noise; - public final RandomSource random; - public final long seed; - - public double lastX = Integer.MIN_VALUE; - public double lastZ = Integer.MIN_VALUE; - public double lastValue = 0; - - Context(long seed) { - this.seed = seed; - this.noise = new OpenSimplexNoise(seed); - this.random = new ThreadSafeLegacyRandomSource(seed * 2); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/VolumeNoiseCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/VolumeNoiseCondition.java deleted file mode 100644 index 54dae221..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/VolumeNoiseCondition.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; - -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.world.level.levelgen.SurfaceRules.Condition; -import net.minecraft.world.level.levelgen.SurfaceRules.ConditionSource; -import net.minecraft.world.level.levelgen.SurfaceRules.Context; -import net.minecraft.world.level.levelgen.SurfaceRules.LazyCondition; - -public abstract class VolumeNoiseCondition implements NoiseCondition { - public abstract KeyDispatchDataCodec codec(); - - @Override - public final Condition apply(Context context2) { - final VolumeNoiseCondition self = this; - - class Generator extends LazyCondition { - Generator() { - super(context2); - } - - @Override - protected long getContextLastUpdate() { - final SurfaceRulesContextAccessor ctx = SurfaceRulesContextAccessor.class.cast(this.context); - return ctx.getLastUpdateY() + ctx.getLastUpdateXZ(); - } - - @Override - protected boolean compute() { - final SurfaceRulesContextAccessor context = SurfaceRulesContextAccessor.class.cast(this.context); - if (context == null) return false; - return self.test(context); - } - } - - return new Generator(); - } - - public abstract boolean test(SurfaceRulesContextAccessor context); -} diff --git a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/VolumeThresholdCondition.java b/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/VolumeThresholdCondition.java deleted file mode 100644 index f26af967..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/levelgen/surface/rules/VolumeThresholdCondition.java +++ /dev/null @@ -1,106 +0,0 @@ -package org.betterx.bclib.api.v2.levelgen.surface.rules; - -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; -import org.betterx.bclib.noise.OpenSimplexNoise; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.util.RandomSource; -import net.minecraft.util.valueproviders.ConstantFloat; -import net.minecraft.util.valueproviders.FloatProvider; -import net.minecraft.world.level.levelgen.SurfaceRules; -import net.minecraft.world.level.levelgen.ThreadSafeLegacyRandomSource; - -import com.google.common.collect.Maps; - -import java.util.Map; - -public class VolumeThresholdCondition extends VolumeNoiseCondition { - private static final Map NOISES = Maps.newHashMap(); - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - Codec.LONG.fieldOf("seed").forGetter(p -> p.noiseContext.seed), - Codec.DOUBLE.fieldOf("threshold").orElse(0.0).forGetter(p -> p.threshold), - FloatProvider.CODEC.fieldOf("threshold_offset").orElse(ConstantFloat.of(0)).forGetter(p -> p.range), - Codec.DOUBLE.fieldOf("scale_x").orElse(0.1).forGetter(p -> p.scaleX), - Codec.DOUBLE.fieldOf("scale_y").orElse(0.1).forGetter(p -> p.scaleY), - Codec.DOUBLE.fieldOf("scale_z").orElse(0.1).forGetter(p -> p.scaleZ) - ) - .apply(instance, VolumeThresholdCondition::new)); - public static final KeyDispatchDataCodec KEY_CODEC = KeyDispatchDataCodec.of(CODEC); - public final VolumeThresholdCondition.Context noiseContext; - public final double threshold; - public final FloatProvider range; - public final double scaleX; - public final double scaleY; - public final double scaleZ; - - public VolumeThresholdCondition( - long noiseSeed, - double threshold, - FloatProvider range, - double scaleX, - double scaleY, - double scaleZ - ) { - this.threshold = threshold; - this.range = range; - this.scaleX = scaleX; - this.scaleY = scaleY; - this.scaleZ = scaleZ; - - noiseContext = NOISES.computeIfAbsent(noiseSeed, seed -> new Context(seed)); - } - - public double getValue(SurfaceRulesContextAccessor context) { - return getValue(context.getBlockX(), context.getBlockY(), context.getBlockZ()); - } - - public double getValue(int xx, int yy, int zz) { - final double x = xx * scaleX; - final double y = yy * scaleY; - final double z = zz * scaleZ; - - if (noiseContext.lastX == x - && noiseContext.lastY == y - && noiseContext.lastZ == z) - return noiseContext.lastValue + range.sample(noiseContext.random); - - double value = noiseContext.noise.eval(x, y, z); - - noiseContext.lastX = x; - noiseContext.lastZ = z; - noiseContext.lastY = y; - noiseContext.lastValue = value; - - return value + range.sample(noiseContext.random); - } - - @Override - public boolean test(SurfaceRulesContextAccessor context) { - return getValue(context) > threshold; - } - - @Override - public KeyDispatchDataCodec codec() { - return KEY_CODEC; - } - - public static class Context { - public final OpenSimplexNoise noise; - public final RandomSource random; - public final long seed; - - double lastX = Integer.MIN_VALUE; - double lastY = Integer.MIN_VALUE; - double lastZ = Integer.MIN_VALUE; - double lastValue = 0; - - Context(long seed) { - this.seed = seed; - this.noise = new OpenSimplexNoise(seed); - this.random = new ThreadSafeLegacyRandomSource(seed * 3 + 1); - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/poi/BCLPoiType.java b/src/main/java/org/betterx/bclib/api/v2/poi/BCLPoiType.java deleted file mode 100644 index 7c2a3204..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/poi/BCLPoiType.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.betterx.bclib.api.v2.poi; - -import net.minecraft.core.BlockPos; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.ai.village.poi.PoiManager; -import net.minecraft.world.entity.ai.village.poi.PoiRecord; -import net.minecraft.world.entity.ai.village.poi.PoiType; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.border.WorldBorder; - -import com.google.common.collect.ImmutableSet; - -import java.util.Comparator; -import java.util.Optional; -import java.util.Set; - -public class BCLPoiType { - public final ResourceKey key; - public final PoiType type; - public final Set matchingStates; - public final int maxTickets; - public final int validRange; - - public BCLPoiType( - ResourceKey key, - PoiType type, - Set matchingStates, - int maxTickets, - int validRange - ) { - this.key = key; - this.type = type; - this.matchingStates = matchingStates; - this.maxTickets = maxTickets; - this.validRange = validRange; - } - - public static Set getBlockStates(Block block) { - return ImmutableSet.copyOf(block.getStateDefinition().getPossibleStates()); - } - - public void setTag(TagKey tag) { - org.betterx.bclib.api.v2.poi.PoiManager.setTag(key, tag); - } - - public Optional findPoiAround( - ServerLevel level, - BlockPos center, - boolean wideSearch, - WorldBorder worldBorder - ) { - return findPoiAround(key, level, center, wideSearch, worldBorder); - } - - public Optional findPoiAround( - ServerLevel level, - BlockPos center, - int radius, - WorldBorder worldBorder - ) { - return findPoiAround(key, level, center, radius, worldBorder); - } - - public static Optional findPoiAround( - ResourceKey key, - ServerLevel level, - BlockPos center, - boolean wideSearch, - WorldBorder worldBorder - ) { - return findPoiAround(key, level, center, wideSearch ? 16 : 128, worldBorder); - } - - public static Optional findPoiAround( - ResourceKey key, - ServerLevel level, - BlockPos center, - int radius, - WorldBorder worldBorder - ) { - PoiManager poiManager = level.getPoiManager(); - - poiManager.ensureLoadedAndValid(level, center, radius); - Optional record = poiManager - .getInSquare(holder -> holder.is(key), center, radius, PoiManager.Occupancy.ANY) - .filter(poiRecord -> worldBorder.isWithinBounds(poiRecord.getPos())) - .sorted(Comparator.comparingDouble(poiRecord -> poiRecord.getPos().distSqr(center)) - .thenComparingInt(poiRecord -> poiRecord.getPos().getY())) - .filter(poiRecord -> level.getBlockState(poiRecord.getPos()) - .hasProperty(BlockStateProperties.HORIZONTAL_AXIS)) - .findFirst(); - - return record.map(poiRecord -> poiRecord.getPos()); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/poi/PoiManager.java b/src/main/java/org/betterx/bclib/api/v2/poi/PoiManager.java deleted file mode 100644 index 456146de..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/poi/PoiManager.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.betterx.bclib.api.v2.poi; - -import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; -import org.betterx.worlds.together.tag.v3.CommonPoiTags; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.ai.village.poi.PoiType; -import net.minecraft.world.entity.ai.village.poi.PoiTypes; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.*; -import org.jetbrains.annotations.ApiStatus; - -public class PoiManager { - public static BCLPoiType register( - ResourceLocation location, - Set matchingStates, - int maxTickets, - int validRanges - ) { - ResourceKey key = ResourceKey.create(Registry.POINT_OF_INTEREST_TYPE_REGISTRY, location); - PoiType type = PoiTypes.register(Registry.POINT_OF_INTEREST_TYPE, key, matchingStates, maxTickets, validRanges); - return new BCLPoiType(key, type, matchingStates, maxTickets, validRanges); - } - - public static void setTag(ResourceKey type, TagKey tag) { - var oHolder = Registry.POINT_OF_INTEREST_TYPE.getHolder(type); - if (oHolder.isPresent()) { - setTag(oHolder.get().value(), tag); - didAddTagFor(oHolder.get(), tag); - } - } - - private static void setTag(PoiType type, TagKey tag) { - if ((Object) type instanceof PoiTypeExtension ext) { - ext.bcl_setTag(tag); - } - } - - @ApiStatus.Internal - public static void registerAll() { - PoiManager.setTag(PoiTypes.FISHERMAN, CommonPoiTags.FISHERMAN_WORKSTATION); - PoiManager.setTag(PoiTypes.FARMER, CommonPoiTags.FARMER_WORKSTATION); - } - - - private static final List> TYPES_WITH_TAGS = new ArrayList<>(4); - private static Map> ORIGINAL_BLOCK_STATES = null; - - private static void didAddTagFor(Holder type, TagKey tag) { - TYPES_WITH_TAGS.remove(type); - if (tag != null) TYPES_WITH_TAGS.add(type); - } - - - @ApiStatus.Internal - public static void updateStates() { - if (ORIGINAL_BLOCK_STATES == null) { - //We have not yet tainted the original states, so we will create a copy now - ORIGINAL_BLOCK_STATES = new HashMap<>(PoiTypes.TYPE_BY_STATE); - } else { - //restore unaltered state - PoiTypes.TYPE_BY_STATE.clear(); - PoiTypes.TYPE_BY_STATE.putAll(ORIGINAL_BLOCK_STATES); - } - - for (Holder type : TYPES_WITH_TAGS) { - if ((Object) type.value() instanceof PoiTypeExtension ex) { - TagKey tag = ex.bcl_getTag(); - if (tag != null) { - var registry = InternalBiomeAPI.worldRegistryAccess().registryOrThrow(tag.registry()); - for (var block : registry.getTagOrEmpty(tag)) { - for (var state : block.value().getStateDefinition().getPossibleStates()) { - PoiTypes.TYPE_BY_STATE.put(state, type); - } - } - } - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/poi/PoiTypeExtension.java b/src/main/java/org/betterx/bclib/api/v2/poi/PoiTypeExtension.java deleted file mode 100644 index 96063ee1..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/poi/PoiTypeExtension.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.api.v2.poi; - -import net.minecraft.tags.TagKey; -import net.minecraft.world.level.block.Block; - -public interface PoiTypeExtension { - void bcl_setTag(TagKey tag); - TagKey bcl_getTag(); -} diff --git a/src/main/java/org/betterx/bclib/api/v2/spawning/SpawnRuleBuilder.java b/src/main/java/org/betterx/bclib/api/v2/spawning/SpawnRuleBuilder.java deleted file mode 100644 index 367a2c40..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/spawning/SpawnRuleBuilder.java +++ /dev/null @@ -1,369 +0,0 @@ -package org.betterx.bclib.api.v2.spawning; - -import org.betterx.bclib.entity.BCLEntityWrapper; -import org.betterx.bclib.interfaces.SpawnRule; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.Difficulty; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.SpawnPlacements; -import net.minecraft.world.entity.SpawnPlacements.SpawnPredicate; -import net.minecraft.world.entity.SpawnPlacements.Type; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.levelgen.Heightmap.Types; -import net.minecraft.world.phys.AABB; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.*; -import java.util.function.Supplier; - -public class SpawnRuleBuilder { - private static final Map RULES_CACHE = Maps.newHashMap(); - private static final SpawnRuleBuilder INSTANCE = new SpawnRuleBuilder(); - private final List rules = Lists.newArrayList(); - private SpawnRuleEntry entryInstance; - private EntityType entityType; - - private SpawnRuleBuilder() { - } - - /** - * Starts new rule building process. - * - * @param entityType The entity you want to build a rule for - * @return prepared {@link SpawnRuleBuilder} instance. - */ - public static SpawnRuleBuilder start(EntityType entityType) { - INSTANCE.entityType = entityType; - INSTANCE.rules.clear(); - return INSTANCE; - } - - /** - * Starts new rule building process. - * - * @param wrapper The entity you want to build a rule for - * @return prepared {@link SpawnRuleBuilder} instance. - */ - public static SpawnRuleBuilder start(BCLEntityWrapper wrapper) { - SpawnRuleBuilder builder = start(wrapper.type()); - if (!wrapper.canSpawn()) { - builder.preventSpawn(); - } - return builder; - } - - /** - * Stop entity spawn entierly - * - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder preventSpawn() { - entryInstance = getFromCache("prevent", () -> { - return new SpawnRuleEntry(-1, (type, world, spawnReason, pos, random) -> false); - }); - rules.add(entryInstance); - return this; - } - - /** - * Stop entity spawn on peaceful {@link Difficulty} - * - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder notPeaceful() { - entryInstance = getFromCache("not_peaceful", () -> { - return new SpawnRuleEntry( - 0, - (type, world, spawnReason, pos, random) -> world.getDifficulty() != Difficulty.PEACEFUL - ); - }); - rules.add(entryInstance); - return this; - } - - /** - * Restricts entity spawn above world surface (flying mobs). - * - * @param minHeight minimal spawn height. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder aboveGround(int minHeight) { - entryInstance = getFromCache("above_ground", () -> { - return new SpawnRuleEntry(0, (type, world, spawnReason, pos, random) -> { - if (pos.getY() < world.getMinBuildHeight() + 2) { - return false; - } - return pos.getY() > world.getHeight(Types.WORLD_SURFACE, pos.getX(), pos.getZ()) + minHeight; - }); - }); - rules.add(entryInstance); - return this; - } - - /** - * Restricts entity spawn below world logical height (useful for Nether mobs). - * - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder belowMaxHeight() { - entryInstance = getFromCache("below_max_height", () -> { - return new SpawnRuleEntry( - 0, - (type, world, spawnReason, pos, random) -> pos.getY() < world.dimensionType() - .logicalHeight() - ); - }); - rules.add(entryInstance); - return this; - } - - /** - * Restricts spawning only to vanilla valid blocks. - * - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder onlyOnValidBlocks() { - entryInstance = getFromCache("only_on_valid_blocks", () -> { - return new SpawnRuleEntry(0, (type, world, spawnReason, pos, random) -> { - BlockPos below = pos.below(); - return world.getBlockState(below).isValidSpawn(world, below, type); - }); - }); - rules.add(entryInstance); - return this; - } - - /** - * Restricts spawning only to specified blocks. - * - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder onlyOnBlocks(Block... blocks) { - final Block[] floorBlocks = blocks; - Arrays.sort(floorBlocks, Comparator.comparing(Block::getDescriptionId)); - - StringBuilder builder = new StringBuilder("only_on_blocks"); - for (Block block : floorBlocks) { - builder.append('_'); - builder.append(block.getDescriptionId()); - } - - entryInstance = getFromCache(builder.toString(), () -> { - return new SpawnRuleEntry(0, (type, world, spawnReason, pos, random) -> { - Block below = world.getBlockState(pos.below()).getBlock(); - for (Block floor : floorBlocks) { - if (floor == below) { - return true; - } - } - return false; - }); - }); - - rules.add(entryInstance); - return this; - } - - /** - * Will spawn entity with 1 / chance probability (randomly). - * - * @param chance probability limit. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder withChance(int chance) { - entryInstance = getFromCache("with_chance_" + chance, () -> { - return new SpawnRuleEntry(1, (type, world, spawnReason, pos, random) -> random.nextInt(chance) == 0); - }); - rules.add(entryInstance); - return this; - } - - /** - * Will spawn entity only below specified brightness value. - * - * @param lightLevel light level upper limit. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder belowBrightness(int lightLevel) { - entryInstance = getFromCache("below_brightness_" + lightLevel, () -> { - return new SpawnRuleEntry( - 2, - (type, world, spawnReason, pos, random) -> world.getMaxLocalRawBrightness(pos) <= lightLevel - ); - }); - rules.add(entryInstance); - return this; - } - - /** - * Will spawn entity only above specified brightness value. - * - * @param lightLevel light level lower limit. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder aboveBrightness(int lightLevel) { - entryInstance = getFromCache("above_brightness_" + lightLevel, () -> { - return new SpawnRuleEntry( - 2, - (type, world, spawnReason, pos, random) -> world.getMaxLocalRawBrightness(pos) >= lightLevel - ); - }); - rules.add(entryInstance); - return this; - } - - /** - * Entity spawn will follow common vanilla spawn rules - spawn in darkness and not on peaceful level. - * - * @param lightLevel light level upper limit. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder hostile(int lightLevel) { - return notPeaceful().belowBrightness(lightLevel); - } - - /** - * Entity spawn will follow common vanilla spawn rules - spawn in darkness (below light level 7) and not on peaceful level. - * - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder vanillaHostile() { - return hostile(7); - } - - /** - * Will spawn entity only if count of nearby entities will be lower than specified. - * - * @param selectorType selector {@link EntityType} to search. - * @param count max entity count. - * @param side side of box to search in. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder maxNearby(EntityType selectorType, int count, int side) { - final Class baseClass = selectorType.getBaseClass(); - entryInstance = getFromCache("max_nearby_" + selectorType.getDescriptionId() + "_" + count + "_" + side, () -> { - return new SpawnRuleEntry(3, (type, world, spawnReason, pos, random) -> { - try { - final AABB box = new AABB(pos).inflate(side, world.getHeight(), side); - final List list = world.getEntitiesOfClass(baseClass, box, (entity) -> true); - return list.size() < count; - } catch (Exception e) { - return true; - } - }); - }); - rules.add(entryInstance); - return this; - } - - /** - * Will spawn entity only if count of nearby entities with same type will be lower than specified. - * - * @param count max entity count. - * @param side side of box to search in. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder maxNearby(int count, int side) { - return maxNearby(entityType, count, side); - } - - /** - * Will spawn entity only if count of nearby entities with same type will be lower than specified. - * - * @param count max entity count. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder maxNearby(int count) { - return maxNearby(entityType, count, 256); - } - - /** - * Allows to add custom spawning rule for specific entities. - * - * @param rule {@link SpawnRule} rule, can be a lambda expression. - * @return same {@link SpawnRuleBuilder} instance. - */ - public SpawnRuleBuilder customRule(SpawnRule rule) { - rules.add(new SpawnRuleEntry(7, rule)); - return this; - } - - /** - * Finalize spawning rule creation. - * - * @param spawnType {@link Type} of spawn. - * @param heightmapType {@link Types} heightmap type. - */ - public void build(Type spawnType, Types heightmapType) { - final List rulesCopy = Lists.newArrayList(this.rules); - Collections.sort(rulesCopy); - - SpawnPredicate predicate = (entityType, serverLevelAccessor, mobSpawnType, blockPos, random) -> { - for (SpawnRuleEntry rule : rulesCopy) { - if (!rule.canSpawn(entityType, serverLevelAccessor, mobSpawnType, blockPos, random)) { - return false; - } - } - return true; - }; - - SpawnPlacements.register(entityType, spawnType, heightmapType, predicate); - } - - /** - * Finalize spawning rule creation with No Restrictions spawn type, useful for flying entities. - * - * @param heightmapType {@link Types} heightmap type. - */ - public void buildNoRestrictions(Types heightmapType) { - build(Type.NO_RESTRICTIONS, heightmapType); - } - - /** - * Finalize spawning rule creation with On Ground spawn type, useful for common entities. - * - * @param heightmapType {@link Types} heightmap type. - */ - public void buildOnGround(Types heightmapType) { - build(Type.ON_GROUND, heightmapType); - } - - /** - * Finalize spawning rule creation with In Water spawn type, useful for water entities. - * - * @param heightmapType {@link Types} heightmap type. - */ - public void buildInWater(Types heightmapType) { - build(Type.IN_WATER, heightmapType); - } - - /** - * Finalize spawning rule creation with In Lava spawn type, useful for lava entities. - * - * @param heightmapType {@link Types} heightmap type. - */ - public void buildInLava(Types heightmapType) { - build(Type.IN_LAVA, heightmapType); - } - - /** - * Internal function, will take entry from cache or create it if necessary. - * - * @param name {@link String} entry internal name. - * @param supplier {@link Supplier} for {@link SpawnRuleEntry}. - * @return new or existing {@link SpawnRuleEntry}. - */ - private static SpawnRuleEntry getFromCache(String name, Supplier supplier) { - SpawnRuleEntry entry = RULES_CACHE.get(name); - if (entry == null) { - entry = supplier.get(); - RULES_CACHE.put(name, entry); - } - return entry; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v2/spawning/SpawnRuleEntry.java b/src/main/java/org/betterx/bclib/api/v2/spawning/SpawnRuleEntry.java deleted file mode 100644 index 2d24e893..00000000 --- a/src/main/java/org/betterx/bclib/api/v2/spawning/SpawnRuleEntry.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.betterx.bclib.api.v2.spawning; - -import org.betterx.bclib.interfaces.SpawnRule; - -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.level.LevelAccessor; - -import org.jetbrains.annotations.NotNull; - -public class SpawnRuleEntry implements Comparable { - private final SpawnRule rule; - private final byte priority; - - public SpawnRuleEntry(int priority, SpawnRule rule) { - this.priority = (byte) priority; - this.rule = rule; - } - - protected boolean canSpawn( - EntityType type, - LevelAccessor world, - MobSpawnType spawnReason, - BlockPos pos, - RandomSource random - ) { - return rule.canSpawn(type, world, spawnReason, pos, random); - } - - @Override - public int compareTo(@NotNull SpawnRuleEntry entry) { - return Integer.compare(priority, entry.priority); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLConfigureFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLConfigureFeature.java deleted file mode 100644 index e3442c50..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLConfigureFeature.java +++ /dev/null @@ -1,107 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; -import net.minecraft.world.level.levelgen.feature.configurations.RandomPatchConfiguration; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -public class BCLConfigureFeature, FC extends FeatureConfiguration> { - private static final Map>, BCLConfigureFeature> KNOWN = new HashMap<>(); - - public final ResourceLocation id; - public final Holder> configuredFeature; - public final boolean registered; - - BCLConfigureFeature(ResourceLocation id, Holder> configuredFeature, boolean registered) { - this.id = id; - this.configuredFeature = configuredFeature; - this.registered = registered; - } - - public F getFeature() { - return configuredFeature.value().feature(); - } - - public FC getConfiguration() { - return configuredFeature.value().config(); - } - - - public BCLPlacedFeatureBuilder place() { - return place(this.id); - } - - public BCLPlacedFeatureBuilder place(ResourceLocation id) { - return BCLPlacedFeatureBuilder.place(id, this); - } - - static , FC extends FeatureConfiguration> BCLConfigureFeature create(Holder> registeredFeature) { - return (BCLConfigureFeature) KNOWN.computeIfAbsent( - (Holder>) (Object) registeredFeature, - holder -> new BCLConfigureFeature<>(holder.unwrapKey().orElseThrow() - .location(), registeredFeature, false) - ); - } - - public boolean placeInWorld(ServerLevel level, BlockPos pos, RandomSource random) { - return placeInWorld(getFeature(), getConfiguration(), level, pos, random); - } - - private static boolean placeUnboundInWorld( - Feature feature, - FeatureConfiguration config, - ServerLevel level, - BlockPos pos, - RandomSource random - ) { - if (config instanceof RandomPatchConfiguration rnd) { - var configured = rnd.feature().value().feature().value(); - feature = configured.feature(); - config = configured.config(); - } - - if (feature instanceof UserGrowableFeature growable) { - return growable.grow(level, pos, random, config); - } - - FeaturePlaceContext context = new FeaturePlaceContext( - Optional.empty(), - level, - level.getChunkSource().getGenerator(), - random, - pos, - config - ); - return feature.place(context); - } - - public static boolean placeInWorld( - Feature feature, - ServerLevel level, - BlockPos pos, - RandomSource random - ) { - return placeUnboundInWorld(feature, FeatureConfiguration.NONE, level, pos, random); - } - - public static boolean placeInWorld( - Feature feature, - FC config, - ServerLevel level, - BlockPos pos, - RandomSource random - ) { - return placeUnboundInWorld(feature, config, level, pos, random); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLFeature.java deleted file mode 100644 index dd784b5d..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLFeature.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v3.levelgen.features.config.*; -import org.betterx.bclib.api.v3.levelgen.features.features.*; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -import org.jetbrains.annotations.ApiStatus; - -public class BCLFeature, FC extends FeatureConfiguration> { - public static final Feature PLACE_BLOCK = register( - BCLib.makeID("place_block"), - new PlaceBlockFeature<>(PlaceFacingBlockConfig.CODEC) - ); - - - public static final Feature TEMPLATE = register( - BCLib.makeID("template"), - new TemplateFeature( - TemplateFeatureConfig.CODEC) - ); - - public static final Feature MARK_POSTPROCESSING = register( - BCLib.makeID( - "mark_postprocessing"), - new MarkPostProcessingFeature() - ); - - public static final Feature SEQUENCE = register( - BCLib.makeID("sequence"), - new SequenceFeature() - ); - - public static final Feature CONDITION = register( - BCLib.makeID("condition"), - new ConditionFeature() - ); - - public static final Feature PILLAR = register( - BCLib.makeID("pillar"), - new PillarFeature() - ); - public final BCLConfigureFeature configuredFeature; - public final Holder placedFeature; - public final GenerationStep.Decoration decoration; - - @ApiStatus.Internal - BCLFeature( - BCLConfigureFeature configuredFeature, - Holder placed, - GenerationStep.Decoration decoration - ) { - this.configuredFeature = configuredFeature; - this.placedFeature = placed; - this.decoration = decoration; - } - - /** - * Get raw feature. - * - * @return {@link Feature}. - */ - public F getFeature() { - return configuredFeature.getFeature(); - } - - /** - * Get configured feature. - * - * @return {@link PlacedFeature}. - */ - public Holder getPlacedFeature() { - return placedFeature; - } - - /** - * Get feature decoration step. - * - * @return {@link GenerationStep.Decoration}. - */ - public GenerationStep.Decoration getDecoration() { - return decoration; - } - - public FC getConfiguration() { - return configuredFeature.getConfiguration(); - } - - - public static > F register( - ResourceLocation location, - F feature - ) { - return Registry.register(Registry.FEATURE, location, feature); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLFeatureBuilder.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLFeatureBuilder.java deleted file mode 100644 index 2ff8f691..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLFeatureBuilder.java +++ /dev/null @@ -1,949 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.levelgen.structures.StructurePlacementType; -import org.betterx.bclib.api.v2.levelgen.structures.StructureWorldNBT; -import org.betterx.bclib.api.v2.poi.BCLPoiType; -import org.betterx.bclib.api.v3.levelgen.features.config.PillarFeatureConfig; -import org.betterx.bclib.api.v3.levelgen.features.config.PlaceFacingBlockConfig; -import org.betterx.bclib.api.v3.levelgen.features.config.SequenceFeatureConfig; -import org.betterx.bclib.api.v3.levelgen.features.config.TemplateFeatureConfig; -import org.betterx.bclib.api.v3.levelgen.features.features.PillarFeature; -import org.betterx.bclib.api.v3.levelgen.features.features.PlaceBlockFeature; -import org.betterx.bclib.api.v3.levelgen.features.features.SequenceFeature; -import org.betterx.bclib.api.v3.levelgen.features.features.TemplateFeature; -import org.betterx.bclib.blocks.BlockProperties; -import org.betterx.bclib.util.Triple; - -import net.minecraft.core.Direction; -import net.minecraft.core.Holder; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.random.SimpleWeightedRandomList; -import net.minecraft.util.valueproviders.ConstantInt; -import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.feature.*; -import net.minecraft.world.level.levelgen.feature.configurations.*; -import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; -import net.minecraft.world.level.levelgen.feature.stateproviders.SimpleStateProvider; -import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraft.world.level.levelgen.structure.templatesystem.BlockMatchTest; -import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTest; - -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.function.BiFunction; -import org.jetbrains.annotations.NotNull; - -@SuppressWarnings("unused") -public abstract class BCLFeatureBuilder, FC extends FeatureConfiguration> { - private final ResourceLocation featureID; - private final F feature; - - private BCLFeatureBuilder(ResourceLocation featureID, F feature) { - this.featureID = featureID; - this.feature = feature; - } - - /** - * Starts a new {@link BCLFeature} builder. - * - * @param featureID {@link ResourceLocation} feature identifier. - * @param feature {@link Feature} to construct. - * @return {@link BCLFeatureBuilder} instance. - */ - public static , FC extends FeatureConfiguration> WithConfiguration start( - ResourceLocation featureID, - F feature - ) { - return new WithConfiguration<>(featureID, feature); - } - - public static ForSimpleBlock start( - ResourceLocation featureID, - Block block - ) { - return start(featureID, BlockStateProvider.simple(block)); - } - - public static ForSimpleBlock start( - ResourceLocation featureID, - BlockState state - ) { - return start(featureID, BlockStateProvider.simple(state)); - } - - public static ForSimpleBlock start( - ResourceLocation featureID, - BlockStateProvider provider - ) { - return new ForSimpleBlock( - featureID, - (SimpleBlockFeature) Feature.SIMPLE_BLOCK, - provider - ); - } - - public static WeightedBlock startWeighted( - ResourceLocation featureID - ) { - return new WeightedBlock( - featureID, - (SimpleBlockFeature) Feature.SIMPLE_BLOCK - ); - } - - public static RandomPatch startRandomPatch( - ResourceLocation featureID, - Holder featureToPlace - ) { - return new RandomPatch( - featureID, - (RandomPatchFeature) Feature.RANDOM_PATCH, - featureToPlace - ); - } - - public static AsRandomSelect startRandomSelect( - ResourceLocation featureID - ) { - return new AsRandomSelect( - featureID, - (RandomSelectorFeature) Feature.RANDOM_SELECTOR - ); - } - - public static AsMultiPlaceRandomSelect startRandomSelect( - ResourceLocation featureID, - AsMultiPlaceRandomSelect.Placer placementModFunction - ) { - return new AsMultiPlaceRandomSelect( - featureID, - (RandomSelectorFeature) Feature.RANDOM_SELECTOR, - placementModFunction - ); - } - - public static NetherForrestVegetation startNetherVegetation( - ResourceLocation featureID - ) { - return new NetherForrestVegetation( - featureID, - (NetherForestVegetationFeature) Feature.NETHER_FOREST_VEGETATION - ); - } - - - public static WithTemplates startWithTemplates( - ResourceLocation featureID - ) { - return new WithTemplates( - featureID, - (TemplateFeature) org.betterx.bclib.api.v3.levelgen.features.BCLFeature.TEMPLATE - ); - } - - public static AsBlockColumn startColumn( - ResourceLocation featureID - ) { - return new AsBlockColumn<>( - featureID, - (BlockColumnFeature) Feature.BLOCK_COLUMN - ); - } - - public static AsPillar startPillar( - ResourceLocation featureID, - PillarFeatureConfig.KnownTransformers transformer - ) { - return new AsPillar( - featureID, - (PillarFeature) BCLFeature.PILLAR, - transformer - ); - } - - public static AsSequence startSequence( - ResourceLocation featureID - ) { - return new AsSequence( - featureID, - (SequenceFeature) BCLFeature.SEQUENCE - ); - } - - public static AsOre startOre( - ResourceLocation featureID - ) { - return new AsOre( - featureID, - (OreFeature) Feature.ORE - ); - } - - public static FacingBlock startFacing( - ResourceLocation featureID - ) { - return new FacingBlock( - featureID, - (PlaceBlockFeature) BCLFeature.PLACE_BLOCK - ); - } - - /** - * Internally used by the builder. Normally you should not have to call this method directly as it is - * handled by {@link #buildAndRegister()} - * - * @param id The ID to register this feature with - * @param cFeature The configured Feature - * @param The Feature Class - * @param The FeatureConfiguration Class - * @return The Holder for the new Feature - */ - public static , FC extends FeatureConfiguration> Holder> register( - ResourceLocation id, - ConfiguredFeature cFeature - ) { - return (Holder>) (Object) BuiltinRegistries.register( - BuiltinRegistries.CONFIGURED_FEATURE, - id, - cFeature - ); - } - - public abstract FC createConfiguration(); - - protected BCLConfigureFeature buildAndRegister(BiFunction, Holder>> holderBuilder) { - FC config = createConfiguration(); - if (config == null) { - throw new IllegalStateException("Feature configuration for " + featureID + " can not be null!"); - } - ConfiguredFeature cFeature = new ConfiguredFeature<>(feature, config); - Holder> holder = holderBuilder.apply(featureID, cFeature); - return new BCLConfigureFeature<>(featureID, holder, true); - } - - public BCLConfigureFeature buildAndRegister() { - return buildAndRegister(BCLFeatureBuilder::register); - } - - public BCLConfigureFeature build() { - return buildAndRegister((id, cFeature) -> Holder.direct(cFeature)); - } - - public BCLInlinePlacedBuilder inlinePlace() { - BCLConfigureFeature f = build(); - return BCLInlinePlacedBuilder.place(f); - } - - public Holder inlinePlace(BCLInlinePlacedBuilder placer) { - BCLConfigureFeature f = build(); - return placer.build(f); - } - - public static class AsOre extends BCLFeatureBuilder { - private final List targetStates = new LinkedList<>(); - private int size = 6; - private float discardChanceOnAirExposure = 0; - - private AsOre(ResourceLocation featureID, OreFeature feature) { - super(featureID, feature); - } - - public AsOre add(Block containedIn, Block ore) { - return this.add(containedIn, ore.defaultBlockState()); - } - - public AsOre add(Block containedIn, BlockState ore) { - return this.add(new BlockMatchTest(containedIn), ore); - } - - public AsOre add(RuleTest containedIn, Block ore) { - return this.add(containedIn, ore.defaultBlockState()); - } - - public AsOre add(RuleTest containedIn, BlockState ore) { - targetStates.add(OreConfiguration.target( - containedIn, - ore - )); - return this; - } - - public AsOre veinSize(int size) { - this.size = size; - return this; - } - - public AsOre discardChanceOnAirExposure(float chance) { - this.discardChanceOnAirExposure = chance; - return this; - } - - @Override - public OreConfiguration createConfiguration() { - return new OreConfiguration(targetStates, size, discardChanceOnAirExposure); - } - } - - public static class AsPillar extends BCLFeatureBuilder { - private IntProvider maxHeight; - private IntProvider minHeight; - private BlockStateProvider stateProvider; - - private final PillarFeatureConfig.KnownTransformers transformer; - private Direction direction = Direction.UP; - private BlockPredicate allowedPlacement = BlockPredicate.ONLY_IN_AIR_PREDICATE; - - private AsPillar( - ResourceLocation featureID, - PillarFeature feature, - PillarFeatureConfig.KnownTransformers transformer - ) { - super(featureID, feature); - this.transformer = transformer; - } - - public AsPillar allowedPlacement(BlockPredicate predicate) { - this.allowedPlacement = predicate; - return this; - } - - public AsPillar direction(Direction v) { - this.direction = v; - return this; - } - - public AsPillar blockState(Block v) { - return blockState(BlockStateProvider.simple(v.defaultBlockState())); - } - - public AsPillar blockState(BlockState v) { - return blockState(BlockStateProvider.simple(v)); - } - - public AsPillar blockState(BlockStateProvider v) { - this.stateProvider = v; - return this; - } - - public AsPillar maxHeight(int v) { - this.maxHeight = ConstantInt.of(v); - return this; - } - - public AsPillar maxHeight(IntProvider v) { - this.maxHeight = v; - return this; - } - - public AsPillar minHeight(int v) { - this.minHeight = ConstantInt.of(v); - return this; - } - - public AsPillar minHeight(IntProvider v) { - this.minHeight = v; - return this; - } - - - @Override - public PillarFeatureConfig createConfiguration() { - if (stateProvider == null) { - throw new IllegalStateException("A Pillar Features need a stateProvider"); - } - if (maxHeight == null) { - throw new IllegalStateException("A Pillar Features need a height"); - } - if (minHeight == null) minHeight = ConstantInt.of(0); - return new PillarFeatureConfig( - minHeight, - maxHeight, - direction, - allowedPlacement, - stateProvider, - transformer - ); - } - } - - public static class AsSequence extends BCLFeatureBuilder { - private final List> features = new LinkedList<>(); - - private AsSequence(ResourceLocation featureID, SequenceFeature feature) { - super(featureID, feature); - } - - - public AsSequence add(org.betterx.bclib.api.v3.levelgen.features.BCLFeature p) { - return add(p.placedFeature); - } - - public AsSequence add(Holder p) { - features.add(p); - return this; - } - - @Override - public SequenceFeatureConfig createConfiguration() { - return new SequenceFeatureConfig(features); - } - } - - public static class AsBlockColumn> extends BCLFeatureBuilder { - private final List layers = new LinkedList<>(); - private Direction direction = Direction.UP; - private BlockPredicate allowedPlacement = BlockPredicate.ONLY_IN_AIR_PREDICATE; - private boolean prioritizeTip = false; - - private AsBlockColumn(ResourceLocation featureID, FF feature) { - super(featureID, feature); - } - - public AsBlockColumn add(int height, Block block) { - return add(ConstantInt.of(height), BlockStateProvider.simple(block)); - } - - public AsBlockColumn add(int height, BlockState state) { - return add(ConstantInt.of(height), BlockStateProvider.simple(state)); - } - - public AsBlockColumn add(int height, BlockStateProvider state) { - return add(ConstantInt.of(height), state); - } - - protected static SimpleWeightedRandomList buildWeightedList(BlockState state) { - return SimpleWeightedRandomList - .builder() - .add(state, 1) - .build(); - } - - public final AsBlockColumn addRandom(int height, BlockState... states) { - return this.addRandom(ConstantInt.of(height), states); - } - - public final AsBlockColumn addRandom(IntProvider height, BlockState... states) { - var builder = SimpleWeightedRandomList.builder(); - for (BlockState state : states) builder.add(state, 1); - return add(height, new WeightedStateProvider(builder.build())); - } - - public AsBlockColumn add(IntProvider height, Block block) { - return add(height, BlockStateProvider.simple(block)); - } - - public AsBlockColumn add(IntProvider height, BlockState state) { - return add(height, BlockStateProvider.simple(state)); - } - - public AsBlockColumn add(IntProvider height, BlockStateProvider state) { - layers.add(new BlockColumnConfiguration.Layer(height, state)); - return this; - } - - public AsBlockColumn addTripleShape(BlockState state, IntProvider midHeight) { - return this - .add(1, state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.BOTTOM)) - .add(midHeight, state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.MIDDLE)) - .add(1, state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.TOP)); - } - - public AsBlockColumn addTripleShapeUpsideDown(BlockState state, IntProvider midHeight) { - return this - .add(1, state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.TOP)) - .add(midHeight, state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.MIDDLE)) - .add(1, state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.BOTTOM)); - } - - public AsBlockColumn addBottomShapeUpsideDown(BlockState state, IntProvider midHeight) { - return this - .add(midHeight, state.setValue(BlockProperties.BOTTOM, false)) - .add(1, state.setValue(BlockProperties.BOTTOM, true)); - } - - public AsBlockColumn addBottomShape(BlockState state, IntProvider midHeight) { - return this - .add(1, state.setValue(BlockProperties.BOTTOM, true)) - .add(midHeight, state.setValue(BlockProperties.BOTTOM, false)); - } - - public AsBlockColumn addTopShapeUpsideDown(BlockState state, IntProvider midHeight) { - return this - .add(1, state.setValue(BlockProperties.TOP, true)) - .add(midHeight, state.setValue(BlockProperties.TOP, false)); - } - - public AsBlockColumn addTopShape(BlockState state, IntProvider midHeight) { - return this - .add(midHeight, state.setValue(BlockProperties.TOP, false)) - .add(1, state.setValue(BlockProperties.TOP, true)); - } - - public AsBlockColumn direction(Direction dir) { - direction = dir; - return this; - } - - public AsBlockColumn prioritizeTip() { - return this.prioritizeTip(true); - } - - public AsBlockColumn prioritizeTip(boolean v) { - prioritizeTip = v; - return this; - } - - public AsBlockColumn allowedPlacement(BlockPredicate v) { - allowedPlacement = v; - return this; - } - - @Override - public BlockColumnConfiguration createConfiguration() { - return new BlockColumnConfiguration(layers, direction, allowedPlacement, prioritizeTip); - } - } - - public static class WithTemplates extends BCLFeatureBuilder, TemplateFeatureConfig> { - private final List templates = new LinkedList<>(); - - private WithTemplates(ResourceLocation featureID, TemplateFeature feature) { - super(featureID, feature); - } - - public WithTemplates add( - ResourceLocation location, - int offsetY, - StructurePlacementType type, - float chance - ) { - templates.add(TemplateFeatureConfig.cfg(location, offsetY, type, chance)); - return this; - } - - @Override - public TemplateFeatureConfig createConfiguration() { - return new TemplateFeatureConfig(templates); - } - } - - public static class NetherForrestVegetation extends BCLFeatureBuilder { - private SimpleWeightedRandomList.Builder blocks; - private WeightedStateProvider stateProvider; - private int spreadWidth = 8; - private int spreadHeight = 4; - - private NetherForrestVegetation(ResourceLocation featureID, NetherForestVegetationFeature feature) { - super(featureID, feature); - } - - public NetherForrestVegetation spreadWidth(int v) { - spreadWidth = v; - return this; - } - - public NetherForrestVegetation spreadHeight(int v) { - spreadHeight = v; - return this; - } - - public NetherForrestVegetation addAllStates(Block block, int weight) { - Set states = BCLPoiType.getBlockStates(block); - states.forEach(s -> add(block.defaultBlockState(), Math.max(1, weight / states.size()))); - return this; - } - - public NetherForrestVegetation addAllStatesFor(IntegerProperty prop, Block block, int weight) { - Collection values = prop.getPossibleValues(); - values.forEach(s -> add(block.defaultBlockState().setValue(prop, s), Math.max(1, weight / values.size()))); - return this; - } - - public NetherForrestVegetation add(Block block, int weight) { - return add(block.defaultBlockState(), weight); - } - - public NetherForrestVegetation add(BlockState state, int weight) { - if (stateProvider != null) { - throw new IllegalStateException("You can not add new state once a WeightedStateProvider was built. (" + state + ", " + weight + ")"); - } - if (blocks == null) { - blocks = SimpleWeightedRandomList.builder(); - } - blocks.add(state, weight); - return this; - } - - public NetherForrestVegetation provider(WeightedStateProvider provider) { - if (blocks != null) { - throw new IllegalStateException( - "You can not set a WeightedStateProvider after states were added manually."); - } - stateProvider = provider; - return this; - } - - @Override - public NetherForestVegetationConfig createConfiguration() { - if (stateProvider == null && blocks == null) { - throw new IllegalStateException("NetherForestVegetationConfig needs at least one BlockState"); - } - if (stateProvider == null) stateProvider = new WeightedStateProvider(blocks.build()); - return new NetherForestVegetationConfig(stateProvider, spreadWidth, spreadHeight); - } - } - - public static class RandomPatch extends BCLFeatureBuilder { - private final Holder featureToPlace; - private int tries = 96; - private int xzSpread = 7; - private int ySpread = 3; - - private RandomPatch( - @NotNull ResourceLocation featureID, - @NotNull RandomPatchFeature feature, - @NotNull Holder featureToPlace - ) { - super(featureID, feature); - this.featureToPlace = featureToPlace; - } - - public RandomPatch likeDefaultNetherVegetation() { - return likeDefaultNetherVegetation(8, 4); - } - - public RandomPatch likeDefaultNetherVegetation(int xzSpread, int ySpread) { - this.xzSpread = xzSpread; - this.ySpread = ySpread; - tries = xzSpread * xzSpread; - return this; - } - - public RandomPatch tries(int v) { - tries = v; - return this; - } - - public RandomPatch spreadXZ(int v) { - xzSpread = v; - return this; - } - - public RandomPatch spreadY(int v) { - ySpread = v; - return this; - } - - - @Override - public RandomPatchConfiguration createConfiguration() { - return new RandomPatchConfiguration(tries, xzSpread, ySpread, featureToPlace); - } - } - - public static class WithConfiguration, FC extends FeatureConfiguration> extends BCLFeatureBuilder { - private FC configuration; - - private WithConfiguration(@NotNull ResourceLocation featureID, @NotNull F feature) { - super(featureID, feature); - } - - public WithConfiguration configuration(FC config) { - this.configuration = config; - return this; - } - - - @Override - public FC createConfiguration() { - if (configuration == null) return (FC) NoneFeatureConfiguration.NONE; - return configuration; - } - } - - public static class FacingBlock extends BCLFeatureBuilder, PlaceFacingBlockConfig> { - private final SimpleWeightedRandomList.Builder stateBuilder = SimpleWeightedRandomList.builder(); - BlockState firstState; - private int count = 0; - private List directions = PlaceFacingBlockConfig.HORIZONTAL; - - private FacingBlock(ResourceLocation featureID, PlaceBlockFeature feature) { - super(featureID, feature); - } - - - public FacingBlock allHorizontal() { - directions = PlaceFacingBlockConfig.HORIZONTAL; - return this; - } - - public FacingBlock allVertical() { - directions = PlaceFacingBlockConfig.VERTICAL; - return this; - } - - public FacingBlock allDirections() { - directions = PlaceFacingBlockConfig.ALL; - return this; - } - - public FacingBlock add(Block block) { - return add(block, 1); - } - - public FacingBlock add(BlockState state) { - return this.add(state, 1); - } - - public FacingBlock add(Block block, int weight) { - return add(block.defaultBlockState(), weight); - } - - public FacingBlock add(BlockState state, int weight) { - if (firstState == null) firstState = state; - count++; - stateBuilder.add(state, weight); - return this; - } - - public FacingBlock addAllStates(Block block, int weight) { - Set states = BCLPoiType.getBlockStates(block); - states.forEach(s -> add(block.defaultBlockState(), Math.max(1, weight / states.size()))); - return this; - } - - public FacingBlock addAllStatesFor(IntegerProperty prop, Block block, int weight) { - Collection values = prop.getPossibleValues(); - values.forEach(s -> add(block.defaultBlockState().setValue(prop, s), Math.max(1, weight / values.size()))); - return this; - } - - - @Override - public PlaceFacingBlockConfig createConfiguration() { - BlockStateProvider provider = null; - if (count == 1) { - provider = SimpleStateProvider.simple(firstState); - } else { - SimpleWeightedRandomList list = stateBuilder.build(); - if (!list.isEmpty()) { - provider = new WeightedStateProvider(list); - } - } - - if (provider == null) { - throw new IllegalStateException("Facing Blocks need a State Provider."); - } - return new PlaceFacingBlockConfig(provider, directions); - } - } - - public static class ForSimpleBlock extends BCLFeatureBuilder { - private final BlockStateProvider provider; - - private ForSimpleBlock( - @NotNull ResourceLocation featureID, - @NotNull SimpleBlockFeature feature, - @NotNull BlockStateProvider provider - ) { - super(featureID, feature); - this.provider = provider; - } - - @Override - public SimpleBlockConfiguration createConfiguration() { - return new SimpleBlockConfiguration(provider); - } - } - - public static class WeightedBlock extends BCLFeatureBuilder { - SimpleWeightedRandomList.Builder stateBuilder = SimpleWeightedRandomList.builder(); - - private WeightedBlock( - @NotNull ResourceLocation featureID, - @NotNull SimpleBlockFeature feature - ) { - super(featureID, feature); - } - - public WeightedBlock add(Block block, int weight) { - return add(block.defaultBlockState(), weight); - } - - public WeightedBlock add(BlockState state, int weight) { - stateBuilder.add(state, weight); - return this; - } - - public WeightedBlock addAllStates(Block block, int weight) { - Set states = BCLPoiType.getBlockStates(block); - states.forEach(s -> add(block.defaultBlockState(), Math.max(1, weight / states.size()))); - return this; - } - - public WeightedBlock addAllStatesFor(IntegerProperty prop, Block block, int weight) { - Collection values = prop.getPossibleValues(); - values.forEach(s -> add(block.defaultBlockState().setValue(prop, s), Math.max(1, weight / values.size()))); - return this; - } - - @Override - public SimpleBlockConfiguration createConfiguration() { - return new SimpleBlockConfiguration(new WeightedStateProvider(stateBuilder.build())); - } - } - - public static class AsRandomSelect extends BCLFeatureBuilder { - private final List features = new LinkedList<>(); - private Holder defaultFeature; - - private AsRandomSelect(ResourceLocation featureID, RandomSelectorFeature feature) { - super(featureID, feature); - } - - - public AsRandomSelect add(Holder feature, float weight) { - features.add(new WeightedPlacedFeature(feature, weight)); - return this; - } - - public AsRandomSelect defaultFeature(Holder feature) { - defaultFeature = feature; - return this; - } - - @Override - public RandomFeatureConfiguration createConfiguration() { - return new RandomFeatureConfiguration(features, defaultFeature); - } - } - - public static class AsMultiPlaceRandomSelect extends BCLFeatureBuilder { - public interface Placer { - Holder place( - BCLInlinePlacedBuilder placer, - int id - ); - } - - private final List> features = new LinkedList<>(); - - private final Placer modFunction; - - private AsMultiPlaceRandomSelect( - ResourceLocation featureID, - RandomSelectorFeature feature, - Placer mod - ) { - super(featureID, feature); - this.modFunction = mod; - } - - private static int featureCounter = 0; - private static int lastID = 0; - - public AsMultiPlaceRandomSelect addAllStates(Block block, int weight) { - return addAllStates(block, weight, lastID + 1); - } - - public AsMultiPlaceRandomSelect addAll(int weight, Block... blocks) { - return addAll(weight, lastID + 1, blocks); - } - - public AsMultiPlaceRandomSelect addAllStatesFor(IntegerProperty prop, Block block, int weight) { - return addAllStatesFor(prop, block, weight, lastID + 1); - } - - public AsMultiPlaceRandomSelect add(Block block, float weight) { - return add(BlockStateProvider.simple(block), weight); - } - - public AsMultiPlaceRandomSelect add(BlockState state, float weight) { - return add(BlockStateProvider.simple(state), weight); - } - - public AsMultiPlaceRandomSelect add(BlockStateProvider provider, float weight) { - return add(provider, weight, lastID + 1); - } - - - public AsMultiPlaceRandomSelect addAllStates(Block block, int weight, int id) { - Set states = BCLPoiType.getBlockStates(block); - SimpleWeightedRandomList.Builder builder = SimpleWeightedRandomList.builder(); - states.forEach(s -> builder.add(block.defaultBlockState(), 1)); - - this.add(new WeightedStateProvider(builder.build()), weight, id); - return this; - } - - public AsMultiPlaceRandomSelect addAll(int weight, int id, Block... blocks) { - SimpleWeightedRandomList.Builder builder = SimpleWeightedRandomList.builder(); - for (Block block : blocks) { - builder.add(block.defaultBlockState(), 1); - } - - this.add(new WeightedStateProvider(builder.build()), weight, id); - return this; - } - - public AsMultiPlaceRandomSelect addAllStatesFor(IntegerProperty prop, Block block, int weight, int id) { - Collection values = prop.getPossibleValues(); - SimpleWeightedRandomList.Builder builder = SimpleWeightedRandomList.builder(); - values.forEach(s -> builder.add(block.defaultBlockState().setValue(prop, s), 1)); - this.add(new WeightedStateProvider(builder.build()), weight, id); - return this; - } - - public AsMultiPlaceRandomSelect add(Block block, float weight, int id) { - return add(BlockStateProvider.simple(block), weight, id); - } - - public AsMultiPlaceRandomSelect add(BlockState state, float weight, int id) { - return add(BlockStateProvider.simple(state), weight, id); - } - - public AsMultiPlaceRandomSelect add(BlockStateProvider provider, float weight, int id) { - features.add(new Triple<>(provider, weight, id)); - lastID = Math.max(lastID, id); - return this; - } - - private Holder place(BlockStateProvider p, int id) { - var builder = BCLFeatureBuilder - .start(BCLib.makeID("temp_select_feature" + (featureCounter++)), p) - .inlinePlace(); - return modFunction.place(builder, id); - } - - @Override - public RandomFeatureConfiguration createConfiguration() { - if (modFunction == null) { - throw new IllegalStateException("AsMultiPlaceRandomSelect needs a placement.modification Function"); - } - float sum = this.features.stream().map(p -> p.second).reduce(0.0f, Float::sum); - List features = this.features.stream() - .map(p -> new WeightedPlacedFeature( - this.place(p.first, p.third), - p.second / sum - )) - .toList(); - - - return new RandomFeatureConfiguration( - features.subList(0, features.size() - 1), - features.get(features.size() - 1).feature - ); - } - } -} - - diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLInlinePlacedBuilder.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLInlinePlacedBuilder.java deleted file mode 100644 index ecb6a80f..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLInlinePlacedBuilder.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features; - -import net.minecraft.core.Holder; -import net.minecraft.data.worldgen.placement.PlacementUtils; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; - -public class BCLInlinePlacedBuilder, FC extends FeatureConfiguration> extends CommonPlacedFeatureBuilder> { - private final BCLConfigureFeature cFeature; - - private BCLInlinePlacedBuilder(BCLConfigureFeature cFeature) { - this.cFeature = cFeature; - } - - /** - * Starts a new {@link BCLFeature} builder. - * - * @param holder {@link Feature} the configured Feature to start from. - * @return {@link CommonPlacedFeatureBuilder} instance. - */ - public static , FC extends FeatureConfiguration> BCLInlinePlacedBuilder place( - ResourceLocation featureID, - Holder> holder - ) { - return place(BCLConfigureFeature.create(holder)); - } - - - /** - * Starts a new {@link BCLFeature} builder. - * - * @param cFeature {@link Feature} the configured Feature to start from. - * @return {@link CommonPlacedFeatureBuilder} instance. - */ - static , FC extends FeatureConfiguration> BCLInlinePlacedBuilder place( - BCLConfigureFeature cFeature - ) { - return new BCLInlinePlacedBuilder(cFeature); - } - - /** - * Builds a new inline (not registered) {@link PlacedFeature}. - * - * @return created {@link PlacedFeature} instance. - */ - @Override - public Holder build() { - return build(cFeature); - } - - /** - * Builds a new inline (not registered) {@link PlacedFeature}. - * - * @return created {@link PlacedFeature} instance. - */ - public Holder build(BCLConfigureFeature feature) { - return build(feature.configuredFeature); - } - - /** - * Builds a new inline (not registered) {@link PlacedFeature}. - * - * @return created {@link PlacedFeature} instance. - */ - public Holder build(Holder> feature) { - PlacementModifier[] modifiers = modifications.toArray(new PlacementModifier[modifications.size()]); - return PlacementUtils.inlinePlaced(feature, modifiers); - } - - /** - * Builds a new inline (not registered) {@link PlacedFeature}. - * - * @return created {@link PlacedFeature} instance. - */ - public Holder build(F feature, FC configuration) { - PlacementModifier[] modifiers = modifications.toArray(new PlacementModifier[modifications.size()]); - return PlacementUtils.inlinePlaced(feature, configuration, modifiers); - } - - -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLPlacedFeatureBuilder.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLPlacedFeatureBuilder.java deleted file mode 100644 index 83658080..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/BCLPlacedFeatureBuilder.java +++ /dev/null @@ -1,88 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features; - -import net.minecraft.core.Holder; -import net.minecraft.data.worldgen.placement.PlacementUtils; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -public class BCLPlacedFeatureBuilder, FC extends FeatureConfiguration> extends CommonPlacedFeatureBuilder> { - private final ResourceLocation featureID; - private GenerationStep.Decoration decoration = GenerationStep.Decoration.VEGETAL_DECORATION; - private final BCLConfigureFeature cFeature; - - private BCLPlacedFeatureBuilder(ResourceLocation featureID, BCLConfigureFeature cFeature) { - this.featureID = featureID; - this.cFeature = cFeature; - } - - - /** - * Set generation step for the feature. Default is {@code VEGETAL_DECORATION}. - * - * @param decoration {@link GenerationStep.Decoration} step. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public BCLPlacedFeatureBuilder decoration(GenerationStep.Decoration decoration) { - this.decoration = decoration; - return this; - } - - /** - * Starts a new {@link BCLFeature} builder. - * - * @param featureID {@link ResourceLocation} feature identifier. - * @param holder {@link Feature} the configured Feature to start from. - * @return {@link CommonPlacedFeatureBuilder} instance. - */ - public static , FC extends FeatureConfiguration> BCLPlacedFeatureBuilder place( - ResourceLocation featureID, - Holder> holder - ) { - return place(featureID, BCLConfigureFeature.create(holder)); - } - - - /** - * Starts a new {@link BCLFeature} builder. - * - * @param featureID {@link ResourceLocation} feature identifier. - * @param cFeature {@link Feature} the configured Feature to start from. - * @return {@link CommonPlacedFeatureBuilder} instance. - */ - static , FC extends FeatureConfiguration> BCLPlacedFeatureBuilder place( - ResourceLocation featureID, - BCLConfigureFeature cFeature - ) { - return new BCLPlacedFeatureBuilder(featureID, cFeature); - } - - /** - * Builds a new {@link BCLFeature} instance. - * - * @return created {@link BCLFeature} instance. - */ - public Holder build() { - Holder p = PlacementUtils.register( - featureID.toString(), - cFeature.configuredFeature, - modifications - ); - return p; - } - - - /** - * Builds a new {@link BCLFeature} instance. - * Features will be registered during this process. - * - * @return created {@link BCLFeature} instance. - */ - public BCLFeature buildAndRegister() { - Holder p = build(); - return new BCLFeature(cFeature, p, decoration); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/CommonPlacedFeatureBuilder.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/CommonPlacedFeatureBuilder.java deleted file mode 100644 index d26524db..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/CommonPlacedFeatureBuilder.java +++ /dev/null @@ -1,423 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features; - -import org.betterx.bclib.api.v3.levelgen.features.blockpredicates.BlockPredicates; -import org.betterx.bclib.api.v3.levelgen.features.config.PlaceFacingBlockConfig; -import org.betterx.bclib.api.v3.levelgen.features.placement.*; -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.core.Direction; -import net.minecraft.core.Holder; -import net.minecraft.core.Vec3i; -import net.minecraft.data.worldgen.placement.PlacementUtils; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.level.levelgen.Noises; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.placement.*; -import net.minecraft.world.level.material.Material; - -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; - -abstract class CommonPlacedFeatureBuilder, FC extends FeatureConfiguration, T extends CommonPlacedFeatureBuilder> { - protected final List modifications = new LinkedList<>(); - - - /** - * Add feature placement modifier. Used as a condition for feature how to generate. - * - * @param modifiers {@link PlacementModifier}s to add. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T modifier(PlacementModifier... modifiers) { - for (var m : modifiers) - modifications.add(m); - return (T) this; - } - - /** - * Add feature placement modifier. Used as a condition for feature how to generate. - * - * @param modifiers {@link PlacementModifier}s to add. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T modifier(List modifiers) { - modifications.addAll(modifiers); - return (T) this; - } - - /** - * Generate feature in certain iterations (per chunk). - * - * @param count how many times feature will be generated in chunk. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T count(int count) { - return modifier(CountPlacement.of(count)); - } - - /** - * Generate feature in certain iterations (per chunk). Count can be between 0 and max value. - * - * @param count maximum amount of iterations per chunk. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T countMax(int count) { - return modifier(CountPlacement.of(UniformInt.of(0, count))); - } - - public T countRange(int min, int max) { - return modifier(CountPlacement.of(UniformInt.of(min, max))); - } - - /** - * Generate points for every xz-Coordinate in a chunk. Be carefuller, this is quite expensive! - * - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T all() { - return modifier(All.simple()); - } - - public T stencil() { - return modifier(Stencil.all()); - } - - public T stencilOneIn4() { - return modifier(Stencil.oneIn4()); - } - - - /** - * Generate feature in certain iterations (per chunk). - * Feature will be generated on all layers (example - Nether plants). - * - * @param count how many times feature will be generated in chunk layers. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - @SuppressWarnings("deprecation") - public T onEveryLayer(int count) { - return modifier(CountOnEveryLayerPlacement.of(count)); - } - - /** - * Generate feature in certain iterations (per chunk). Count can be between 0 and max value. - * Feature will be generated on all layers (example - Nether plants). - * - * @param count maximum amount of iterations per chunk layers. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - @SuppressWarnings("deprecation") - public T onEveryLayerMax(int count) { - return modifier(CountOnEveryLayerPlacement.of(UniformInt.of(0, count))); - } - - public T onEveryLayer() { - return modifier(OnEveryLayer.simple()); - } - - public T onEveryLayerMin4() { - return modifier(OnEveryLayer.min4()); - } - - public T underEveryLayer() { - return modifier(UnderEveryLayer.simple()); - } - - public T underEveryLayerMin4() { - return modifier(UnderEveryLayer.min4()); - } - - /** - * Will place feature once every n-th attempts (in average). - * - * @param n amount of attempts. - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T onceEvery(int n) { - return modifier(RarityFilter.onAverageOnceEvery(n)); - } - - /** - * Restricts feature generation only to biome where feature was added. - * - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T onlyInBiome() { - return modifier(BiomeFilter.biome()); - } - - public T noiseIn(double min, double max, float scaleXZ, float scaleY) { - return modifier(new NoiseFilter(Noises.GRAVEL, min, max, scaleXZ, scaleY)); - } - - public T noiseAbove(double value, float scaleXZ, float scaleY) { - return modifier(new NoiseFilter(Noises.GRAVEL, value, Double.MAX_VALUE, scaleXZ, scaleY)); - } - - public T noiseBelow(double value, float scaleXZ, float scaleY) { - return modifier(new NoiseFilter(Noises.GRAVEL, -Double.MAX_VALUE, value, scaleXZ, scaleY)); - } - - /** - * Randomize the xz-Coordinates - * - * @return same {@link CommonPlacedFeatureBuilder} instance. - */ - public T squarePlacement() { - return modifier(InSquarePlacement.spread()); - } - - - /** - * Select random height that is 10 above min Build height and 10 below max generation height - * - * @return The instance it was called on - */ - public T randomHeight10FromFloorCeil() { - return modifier(PlacementUtils.RANGE_10_10); - } - - /** - * Select random height that is 4 above min Build height and 10 below max generation height - * - * @return The instance it was called on - */ - public T randomHeight4FromFloorCeil() { - return modifier(PlacementUtils.RANGE_4_4); - } - - /** - * Select random height that is 8 above min Build height and 10 below max generation height - * - * @return The instance it was called on - */ - public T randomHeight8FromFloorCeil() { - return modifier(PlacementUtils.RANGE_8_8); - } - - /** - * Select random height that is above min Build height and 10 below max generation height - * - * @return The instance it was called on - */ - public T randomHeight() { - return modifier(PlacementUtils.FULL_RANGE); - } - - public T spreadHorizontal(IntProvider p) { - return modifier(RandomOffsetPlacement.horizontal(p)); - } - - public T spreadVertical(IntProvider p) { - return modifier(RandomOffsetPlacement.horizontal(p)); - } - - public T spread(IntProvider horizontal, IntProvider vertical) { - return modifier(RandomOffsetPlacement.of(horizontal, vertical)); - } - - public T offset(Direction dir) { - return modifier(Offset.inDirection(dir)); - } - - public T offset(Vec3i dir) { - return modifier(new Offset(dir)); - } - - /** - * Cast a downward ray with max {@code distance} length to find the next solid Block. - * - * @param distance The maximum search Distance - * @return The instance it was called on - * @see #findSolidSurface(Direction, int) for Details - */ - public T findSolidFloor(int distance) { - return modifier(FindSolidInDirection.down(distance)); - } - - public T noiseBasedCount(float noiseLevel, int belowNoiseCount, int aboveNoiseCount) { - return modifier(NoiseThresholdCountPlacement.of(noiseLevel, belowNoiseCount, aboveNoiseCount)); - } - - public T extendDown(int min, int max) { - return modifier(new Extend(Direction.DOWN, UniformInt.of(min, max))); - } - - public T inBasinOf(BlockPredicate... predicates) { - return modifier(new IsBasin(BlockPredicate.anyOf(predicates))); - } - - public T inOpenBasinOf(BlockPredicate... predicates) { - return modifier(IsBasin.openTop(BlockPredicate.anyOf(predicates))); - } - - public T is(BlockPredicate... predicates) { - return modifier(new Is(BlockPredicate.anyOf(predicates), Optional.empty())); - } - - public T isAbove(BlockPredicate... predicates) { - return modifier(new Is(BlockPredicate.anyOf(predicates), Optional.of(Direction.DOWN.getNormal()))); - } - - public T isUnder(BlockPredicate... predicates) { - return modifier(new Is(BlockPredicate.anyOf(predicates), Optional.of(Direction.UP.getNormal()))); - } - - public T findSolidCeil(int distance) { - return modifier(FindSolidInDirection.up(distance)); - } - - /** - * Cast a ray with max {@code distance} length to find the next solid Block. The ray will travel through replaceable - * Blocks (see {@link Material#isReplaceable()}) and will be accepted if it hits a block with the - * {@link CommonBlockTags#TERRAIN}-tag - * - * @param dir The direction the ray is cast - * @param distance The maximum search Distance - * @return The instance it was called on - * @see #findSolidSurface(Direction, int) for Details - */ - public T findSolidSurface(Direction dir, int distance) { - return modifier(new FindSolidInDirection(dir, distance, 0)); - } - - public T findSolidSurface(List dir, int distance, boolean randomSelect) { - return modifier(new FindSolidInDirection(dir, distance, randomSelect, 0)); - } - - public T onWalls(int distance, int depth) { - return modifier(new FindSolidInDirection(PlaceFacingBlockConfig.HORIZONTAL, distance, false, depth)); - } - - public T heightmap() { - return modifier(PlacementUtils.HEIGHTMAP); - } - - public T heightmapTopSolid() { - return modifier(PlacementUtils.HEIGHTMAP_TOP_SOLID); - } - - public T heightmapWorldSurface() { - return modifier(PlacementUtils.HEIGHTMAP_WORLD_SURFACE); - } - - public T extendXZ(int xzSpread) { - IntProvider xz = UniformInt.of(0, xzSpread); - return (T) modifier( - new ForAll(List.of( - new Extend(Direction.NORTH, xz), - new Extend(Direction.SOUTH, xz), - new Extend(Direction.EAST, xz), - new Extend(Direction.WEST, xz) - )), - new ForAll(List.of( - new Extend(Direction.EAST, xz), - new Extend(Direction.WEST, xz), - new Extend(Direction.NORTH, xz), - new Extend(Direction.SOUTH, xz) - )) - ); - } - - public T extendXYZ(int xzSpread, int ySpread) { - IntProvider xz = UniformInt.of(0, xzSpread); - return (T) extendXZ(xzSpread).extendDown(1, ySpread); - } - - public T isEmpty() { - return modifier(BlockPredicateFilter.forPredicate(BlockPredicate.ONLY_IN_AIR_PREDICATE)); - } - - - public T is(BlockPredicate predicate) { - return modifier(BlockPredicateFilter.forPredicate(predicate)); - } - - public T isNextTo(BlockPredicate predicate) { - return modifier(new IsNextTo(predicate)); - } - - public T belowIsNextTo(BlockPredicate predicate) { - return modifier(new IsNextTo(predicate, Direction.DOWN.getNormal())); - } - - public T isNextTo(BlockPredicate predicate, Vec3i offset) { - return modifier(new IsNextTo(predicate, offset)); - } - - public T isOn(BlockPredicate predicate) { - return modifier(Is.below(predicate)); - } - - public T isEmptyAndOn(BlockPredicate predicate) { - return (T) this.isEmpty().isOn(predicate); - } - - public T isEmptyAndOnNylium() { - return isEmptyAndOn(BlockPredicates.ONLY_NYLIUM); - } - - public T isEmptyAndOnNetherGround() { - return isEmptyAndOn(BlockPredicates.ONLY_NETHER_GROUND); - } - - public T isUnder(BlockPredicate predicate) { - return modifier(Is.above(predicate)); - } - - public T isEmptyAndUnder(BlockPredicate predicate) { - return (T) this.isEmpty().isUnder(predicate); - } - - public T isEmptyAndUnderNylium() { - return isEmptyAndUnder(BlockPredicates.ONLY_NYLIUM); - } - - public T isEmptyAndUnderNetherGround() { - return isEmptyAndUnder(BlockPredicates.ONLY_NETHER_GROUND); - } - - public T vanillaNetherGround(int countPerLayer) { - return (T) this.onEveryLayer(countPerLayer).onlyInBiome(); - } - - public T betterNetherGround(int countPerLayer) { - return (T) this.count(countPerLayer).squarePlacement().onEveryLayerMin4().onlyInBiome(); - } - - public T betterNetherCeiling(int countPerLayer) { - return (T) this.count(countPerLayer).squarePlacement().underEveryLayerMin4().onlyInBiome(); - } - - public T betterNetherOnWall(int countPerLayer) { - return (T) this.count(countPerLayer) - .squarePlacement() - .randomHeight4FromFloorCeil() - .onlyInBiome() - .onWalls(16, 0); - } - - public T betterNetherInWall(int countPerLayer) { - return (T) this.count(countPerLayer) - .squarePlacement() - .randomHeight4FromFloorCeil() - .onlyInBiome() - .onWalls(16, 1); - } - - /** - * Builds a new inline (not registered) {@link PlacedFeature}. - * - * @return created {@link PlacedFeature} instance. - */ - abstract Holder build(); - - public BCLFeatureBuilder.RandomPatch inRandomPatch(ResourceLocation id) { - return BCLFeatureBuilder.startRandomPatch(id, build()); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/UserGrowableFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/UserGrowableFeature.java deleted file mode 100644 index 09335bff..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/UserGrowableFeature.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features; - -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; - -public interface UserGrowableFeature { - boolean grow( - ServerLevelAccessor level, - BlockPos pos, - RandomSource random, - FC configuration - ); -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/blockpredicates/BlockPredicates.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/blockpredicates/BlockPredicates.java deleted file mode 100644 index 28cd01fa..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/blockpredicates/BlockPredicates.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.blockpredicates; - -import org.betterx.bclib.BCLib; -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import com.mojang.serialization.Codec; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicateType; -import net.minecraft.world.level.material.Fluids; - -public class BlockPredicates { - public static final BlockPredicate ONLY_NYLIUM = BlockPredicate.matchesTag(BlockTags.NYLIUM); - public static final BlockPredicate ONLY_MYCELIUM = BlockPredicate.matchesTag(CommonBlockTags.MYCELIUM); - public static final BlockPredicate ONLY_GRAVEL_OR_SAND = BlockPredicate.matchesBlocks( - Blocks.GRAVEL, - Blocks.SAND, - Blocks.RED_SAND - ); - public static final BlockPredicate ONLY_SOUL_GROUND = BlockPredicate.matchesTag(CommonBlockTags.SOUL_GROUND); - public static final BlockPredicate ONLY_NETHER_GROUND = BlockPredicate.matchesTag(CommonBlockTags.NETHER_TERRAIN); - public static final BlockPredicate ONLY_NETHER_GROUND_AND_BASALT = BlockPredicate.anyOf( - ONLY_NETHER_GROUND, - BlockPredicate.matchesBlocks(Blocks.BASALT) - ); - public static final BlockPredicate ONLY_GROUND = BlockPredicate.matchesTag(CommonBlockTags.TERRAIN); - - public static final BlockPredicate ONLY_LAVA = BlockPredicate.matchesFluids(Fluids.LAVA); - public static final BlockPredicate ONLY_GROUND_OR_LAVA = BlockPredicate.anyOf( - BlockPredicate.matchesTag(CommonBlockTags.TERRAIN), - BlockPredicate.matchesFluids(Fluids.LAVA) - ); - public static final BlockPredicateType FULL_SHAPE = register( - BCLib.makeID("full_shape"), - IsFullShape.CODEC - ); - - public static

BlockPredicateType

register(ResourceLocation location, Codec

codec) { - return Registry.register(Registry.BLOCK_PREDICATE_TYPES, location, () -> codec); - } - - public static void ensureStaticInitialization() { - - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/blockpredicates/IsFullShape.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/blockpredicates/IsFullShape.java deleted file mode 100644 index 10dc7e21..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/blockpredicates/IsFullShape.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.blockpredicates; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Vec3i; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicateType; - -public class IsFullShape implements BlockPredicate { - public static final IsFullShape HERE = new IsFullShape(); - public static final Codec CODEC = RecordCodecBuilder.create( - instance -> instance - .group( - Vec3i.offsetCodec(16).optionalFieldOf("offset", Vec3i.ZERO).forGetter((p) -> p.offset) - ).apply(instance, IsFullShape::new)); - - protected final Vec3i offset; - - private IsFullShape() { - this(Vec3i.ZERO); - } - - public IsFullShape(Vec3i offset) { - super(); - this.offset = offset; - } - - - public BlockPredicateType type() { - return BlockPredicates.FULL_SHAPE; - } - - @Override - public boolean test(WorldGenLevel worldGenLevel, BlockPos blockPos) { - BlockState state = worldGenLevel.getBlockState(blockPos.offset(this.offset)); - return state.isCollisionShapeFullBlock(worldGenLevel, blockPos); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/ConditionFeatureConfig.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/ConditionFeatureConfig.java deleted file mode 100644 index 35b91261..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/ConditionFeatureConfig.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.config; - -import org.betterx.bclib.api.v3.levelgen.features.BCLFeature; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Holder; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraft.world.level.levelgen.placement.PlacementFilter; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; - -import java.util.Optional; -import org.jetbrains.annotations.NotNull; - -public class ConditionFeatureConfig implements FeatureConfiguration { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> - instance.group( - PlacementModifier.CODEC.fieldOf("filter").forGetter(p -> p.filter), - PlacedFeature.CODEC.fieldOf("filter_pass").forGetter(p -> p.okFeature), - PlacedFeature.CODEC.optionalFieldOf("filter_fail").forGetter(p -> p.failFeature) - ).apply(instance, ConditionFeatureConfig::new) - ); - - public final PlacementModifier filter; - public final Holder okFeature; - public final Optional> failFeature; - - public ConditionFeatureConfig( - @NotNull PlacementFilter filter, - @NotNull BCLFeature okFeature - ) { - this(filter, okFeature.getPlacedFeature(), Optional.empty()); - - } - - public ConditionFeatureConfig( - @NotNull PlacementFilter filter, - @NotNull BCLFeature okFeature, - @NotNull BCLFeature failFeature - ) { - this(filter, okFeature.getPlacedFeature(), Optional.of(failFeature.getPlacedFeature())); - } - - public ConditionFeatureConfig( - @NotNull PlacementFilter filter, - @NotNull Holder okFeature - ) { - this(filter, okFeature, Optional.empty()); - - } - - public ConditionFeatureConfig( - @NotNull PlacementFilter filter, - @NotNull Holder okFeature, - @NotNull Holder failFeature - ) { - this(filter, okFeature, Optional.of(failFeature)); - } - - protected ConditionFeatureConfig( - @NotNull PlacementModifier filter, - @NotNull Holder okFeature, - @NotNull Optional> failFeature - ) { - this.filter = filter; - this.okFeature = okFeature; - this.failFeature = failFeature; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PillarFeatureConfig.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PillarFeatureConfig.java deleted file mode 100644 index 030387ed..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PillarFeatureConfig.java +++ /dev/null @@ -1,136 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.config; - -import org.betterx.bclib.blocks.BlockProperties; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.util.StringRepresentable; -import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; - -public class PillarFeatureConfig implements FeatureConfiguration { - @FunctionalInterface - public interface StateTransform { - BlockState apply(int height, int maxHeight, BlockState inputState, BlockPos pos, RandomSource rnd); - } - - @FunctionalInterface - public interface PlacePredicate { - PlacePredicate ALLWAYS = (min, max, start, above, level, allow, rnd) -> true; - boolean at( - int minHeight, - int maxHeight, - BlockPos startPos, - BlockPos abovePos, - WorldGenLevel level, - BlockPredicate allowedPlacement, - RandomSource rnd - ); - } - - public enum KnownTransformers implements StringRepresentable { - SIZE_DECREASE( - "size_decrease", - (height, maxHeight, state, pos, rnd) -> state - .setValue(BlockProperties.SIZE, Math.max(0, Math.min(7, maxHeight - height))) - ), - SIZE_INCREASE( - "size_increase", - (height, maxHeight, state, pos, rnd) -> state - .setValue(BlockProperties.SIZE, Math.max(0, Math.min(7, height))) - ), - BOTTOM_GROW( - "bottom_grow", - (height, maxHeight, state, pos, rnd) -> state - .setValue(BlockProperties.BOTTOM, height == maxHeight) - ), - TRIPLE_SHAPE_FILL( - "triple_shape_fill", - (height, maxHeight, state, pos, rnd) -> { - if (height == 0) - return state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.BOTTOM); - if (height == maxHeight) - return state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.TOP); - return state.setValue(BlockProperties.TRIPLE_SHAPE, BlockProperties.TripleShape.MIDDLE); - }, - (minHeight, maxHeight, startPos, abovePos, level, allow, rnd) -> !allow.test(level, abovePos) - ); - - - public static final StringRepresentable.EnumCodec CODEC = StringRepresentable - .fromEnum(KnownTransformers::values); - - - public final String name; - public final StateTransform stateTransform; - public final PlacePredicate canPlace; - - KnownTransformers(String name, StateTransform stateTransform) { - this(name, stateTransform, PlacePredicate.ALLWAYS); - } - - KnownTransformers(String name, StateTransform stateTransform, PlacePredicate canPlace) { - this.name = name; - this.stateTransform = stateTransform; - this.canPlace = canPlace; - } - - @Override - public String toString() { - return this.name; - } - - @Override - public String getSerializedName() { - return this.name; - } - } - - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - IntProvider.CODEC.fieldOf("min_height").forGetter(o -> o.minHeight), - IntProvider.CODEC.fieldOf("max_height").forGetter(o -> o.maxHeight), - Direction.CODEC.fieldOf("direction").orElse(Direction.UP).forGetter(o -> o.direction), - BlockPredicate.CODEC.fieldOf("allowed_placement").forGetter(o -> o.allowedPlacement), - BlockStateProvider.CODEC.fieldOf("state").forGetter(o -> o.stateProvider), - KnownTransformers.CODEC.fieldOf("transform").forGetter(o -> o.transformer) - ) - .apply(instance, PillarFeatureConfig::new)); - - public final IntProvider maxHeight; - public final IntProvider minHeight; - public final BlockStateProvider stateProvider; - - public final KnownTransformers transformer; - public final Direction direction; - public final BlockPredicate allowedPlacement; - - - public PillarFeatureConfig( - IntProvider minHeight, - IntProvider maxHeight, - Direction direction, - BlockPredicate allowedPlacement, - BlockStateProvider stateProvider, - KnownTransformers transformer - ) { - this.minHeight = minHeight; - this.maxHeight = maxHeight; - this.stateProvider = stateProvider; - this.transformer = transformer; - this.direction = direction; - this.allowedPlacement = allowedPlacement; - } - - public BlockState transform(int currentHeight, int maxHeight, BlockPos pos, RandomSource rnd) { - BlockState state = stateProvider.getState(rnd, pos); - return transformer.stateTransform.apply(currentHeight, maxHeight, state, pos, rnd); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PlaceBlockFeatureConfig.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PlaceBlockFeatureConfig.java deleted file mode 100644 index 8341bbfd..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PlaceBlockFeatureConfig.java +++ /dev/null @@ -1,78 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.config; - -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.util.random.SimpleWeightedRandomList; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; -import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider; - -import java.util.List; - -public abstract class PlaceBlockFeatureConfig implements FeatureConfiguration { - - protected static RecordCodecBuilder blockStateCodec() { - return BlockStateProvider.CODEC - .fieldOf("entries") - .forGetter((T o) -> o.stateProvider); - } - - protected final BlockStateProvider stateProvider; - - - protected static SimpleWeightedRandomList buildWeightedList(List states) { - var builder = SimpleWeightedRandomList.builder(); - for (BlockState s : states) builder.add(s, 1); - return builder.build(); - } - - protected static SimpleWeightedRandomList buildWeightedList(BlockState state) { - return SimpleWeightedRandomList - .builder() - .add(state, 1) - .build(); - } - - public PlaceBlockFeatureConfig(Block block) { - this(block.defaultBlockState()); - } - - public PlaceBlockFeatureConfig(BlockState state) { - this(BlockStateProvider.simple(state)); - } - - - public PlaceBlockFeatureConfig(List states) { - this(buildWeightedList(states)); - } - - public PlaceBlockFeatureConfig(SimpleWeightedRandomList blocks) { - this.stateProvider = new WeightedStateProvider(blocks); - } - - public PlaceBlockFeatureConfig(BlockStateProvider blocks) { - this.stateProvider = blocks; - } - - public BlockState getRandomBlock(RandomSource random, BlockPos pos) { - return this.stateProvider.getState(random, pos); - } - - public boolean place(FeaturePlaceContext ctx) { - BlockState state = getRandomBlock(ctx.random(), ctx.origin()); - return placeBlock(ctx, ctx.level(), ctx.origin(), state); - } - - - protected abstract boolean placeBlock( - FeaturePlaceContext ctx, - WorldGenLevel level, - BlockPos pos, - BlockState targetState - ); -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PlaceFacingBlockConfig.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PlaceFacingBlockConfig.java deleted file mode 100644 index feaa9325..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/PlaceFacingBlockConfig.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.config; - -import org.betterx.bclib.util.BlocksHelper; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.util.random.SimpleWeightedRandomList; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.HorizontalDirectionalBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; -import net.minecraft.world.level.levelgen.feature.stateproviders.WeightedStateProvider; - -import java.util.List; - -public class PlaceFacingBlockConfig extends PlaceBlockFeatureConfig { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - blockStateCodec(), - ExtraCodecs.nonEmptyList(Direction.CODEC.listOf()) - .fieldOf("dir") - .orElse(List.of(Direction.NORTH)) - .forGetter(a -> a.directions) - ).apply(instance, PlaceFacingBlockConfig::new) - ); - public static final List HORIZONTAL = List.of( - Direction.NORTH, - Direction.EAST, - Direction.WEST, - Direction.SOUTH - ); - public static final List VERTICAL = List.of(Direction.UP, Direction.DOWN); - public static final List ALL = List.of( - Direction.NORTH, - Direction.EAST, - Direction.SOUTH, - Direction.WEST, - Direction.UP, - Direction.DOWN - ); - - private final List directions; - - public PlaceFacingBlockConfig(Block block, List dir) { - this(block.defaultBlockState(), dir); - } - - public PlaceFacingBlockConfig(BlockState state, List dir) { - this(BlockStateProvider.simple(state), dir); - } - - public PlaceFacingBlockConfig(List states, List dir) { - this(buildWeightedList(states), dir); - } - - public PlaceFacingBlockConfig(SimpleWeightedRandomList blocks, List dir) { - this(new WeightedStateProvider(blocks), dir); - } - - public PlaceFacingBlockConfig(BlockStateProvider blocks, List dir) { - super(blocks); - directions = dir; - } - - @Override - public boolean placeBlock( - FeaturePlaceContext ctx, - WorldGenLevel level, - BlockPos pos, - BlockState targetState - ) { - BlockState lookupState; - BlockPos testPos; - for (Direction dir : directions) { - testPos = pos.relative(dir); - lookupState = targetState.setValue(HorizontalDirectionalBlock.FACING, dir); - if (level.getBlockState(testPos).isAir() && lookupState.canSurvive(level, testPos)) { - lookupState.canSurvive(level, testPos); - BlocksHelper.setWithoutUpdate(level, testPos, lookupState); - return true; - } - } - - return false; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/SequenceFeatureConfig.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/SequenceFeatureConfig.java deleted file mode 100644 index f0e5f300..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/SequenceFeatureConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.config; - -import org.betterx.bclib.api.v3.levelgen.features.BCLFeature; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Holder; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -import java.util.List; - -public class SequenceFeatureConfig implements FeatureConfiguration { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> - instance.group( - ExtraCodecs.nonEmptyList(PlacedFeature.CODEC.listOf()) - .fieldOf("features") - .forGetter(a -> a.features) - ).apply(instance, SequenceFeatureConfig::new) - ); - - private final List> features; - - public static SequenceFeatureConfig createSequence(List> features) { - return new SequenceFeatureConfig(features.stream().map(f -> f.getPlacedFeature()).toList()); - } - - public SequenceFeatureConfig(List> features) { - this.features = features; - } - - public boolean placeAll(FeaturePlaceContext ctx) { - boolean placed = false; - for (Holder f : features) { - placed |= f.value().place(ctx.level(), ctx.chunkGenerator(), ctx.random(), ctx.origin()); - } - return placed; - - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/TemplateFeatureConfig.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/TemplateFeatureConfig.java deleted file mode 100644 index 73b47c8e..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/config/TemplateFeatureConfig.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.config; - -import org.betterx.bclib.api.v2.levelgen.structures.StructurePlacementType; -import org.betterx.bclib.api.v2.levelgen.structures.StructureWorldNBT; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; - -import java.util.List; - -public class TemplateFeatureConfig implements FeatureConfiguration { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance - .group( - ExtraCodecs.nonEmptyList(StructureWorldNBT.CODEC.listOf()) - .fieldOf("structures") - .forGetter((TemplateFeatureConfig cfg) -> cfg.structures) - ) - .apply(instance, TemplateFeatureConfig::new) - ); - - public final List structures; - - public static StructureWorldNBT cfg( - ResourceLocation location, - int offsetY, - StructurePlacementType type, - float chance - ) { - return StructureWorldNBT.create(location, offsetY, type, chance); - } - - public TemplateFeatureConfig(ResourceLocation location, int offsetY, StructurePlacementType type) { - this(List.of(cfg(location, offsetY, type, 1.0f))); - } - - public TemplateFeatureConfig(List structures) { - this.structures = structures; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/ConditionFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/ConditionFeature.java deleted file mode 100644 index 8ceb7de2..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/ConditionFeature.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.features; - -import org.betterx.bclib.api.v3.levelgen.features.config.ConditionFeatureConfig; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraft.world.level.levelgen.placement.PlacementContext; - -import java.util.Optional; -import java.util.stream.Stream; - -public class ConditionFeature extends Feature { - public ConditionFeature() { - super(ConditionFeatureConfig.CODEC); - } - - @Override - public boolean place(FeaturePlaceContext ctx) { - final ConditionFeatureConfig cfg = ctx.config(); - final WorldGenLevel level = ctx.level(); - final RandomSource random = ctx.random(); - final BlockPos pos = ctx.origin(); - - final PlacementContext c = new PlacementContext(level, ctx.chunkGenerator(), Optional.empty()); - - Stream stream = cfg.filter.getPositions(c, ctx.random(), pos); - Holder state = (stream.findFirst().isPresent() ? cfg.okFeature : cfg.failFeature.orElse(null)); - if (state != null) { - return state.value().place(level, ctx.chunkGenerator(), random, pos); - } - return false; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/MarkPostProcessingFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/MarkPostProcessingFeature.java deleted file mode 100644 index 888a8103..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/MarkPostProcessingFeature.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.features; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; - -public class MarkPostProcessingFeature extends Feature { - public MarkPostProcessingFeature() { - super(NoneFeatureConfiguration.CODEC); - } - - @Override - public boolean place(FeaturePlaceContext ctx) { - BlockPos pos = ctx.origin(); - ctx.level().getChunk(pos.getX() >> 4, pos.getZ() >> 4) - .markPosForPostprocessing(new BlockPos(pos.getX() & 15, pos.getY(), pos.getZ() & 15)); - return true; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/PillarFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/PillarFeature.java deleted file mode 100644 index 2675fb52..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/PillarFeature.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.features; - -import org.betterx.bclib.api.v3.levelgen.features.config.PillarFeatureConfig; -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; - -public class PillarFeature extends Feature { - public PillarFeature() { - super(PillarFeatureConfig.CODEC); - } - - - @Override - public boolean place(FeaturePlaceContext featurePlaceContext) { - int height; - final WorldGenLevel level = featurePlaceContext.level(); - final PillarFeatureConfig config = featurePlaceContext.config(); - final RandomSource rnd = featurePlaceContext.random(); - int maxHeight = config.maxHeight.sample(rnd); - int minHeight = config.minHeight.sample(rnd); - BlockPos.MutableBlockPos posnow = featurePlaceContext.origin().mutable(); - posnow.move(config.direction); - - for (height = 1; height < maxHeight; ++height) { - if (!config.allowedPlacement.test(level, posnow)) { - maxHeight = height; - break; - } - posnow.move(config.direction); - } - if (maxHeight < minHeight) return false; - - if (!config.transformer.canPlace.at( - minHeight, - maxHeight, - featurePlaceContext.origin(), - posnow, - level, - config.allowedPlacement, - rnd - )) { - return false; - } - posnow = featurePlaceContext.origin().mutable(); - for (height = 0; height < maxHeight; ++height) { - BlockState state = config.transform(height, maxHeight - 1, posnow, rnd); - BlocksHelper.setWithoutUpdate(level, posnow, state); - posnow.move(config.direction); - } - - return true; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/PlaceBlockFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/PlaceBlockFeature.java deleted file mode 100644 index 257bf0d2..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/PlaceBlockFeature.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.features; - -import org.betterx.bclib.api.v3.levelgen.features.config.PlaceBlockFeatureConfig; - -import com.mojang.serialization.Codec; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; - -public class PlaceBlockFeature extends Feature { - public PlaceBlockFeature(Codec codec) { - super(codec); - } - - @Override - public boolean place(FeaturePlaceContext ctx) { - return ctx.config().place(ctx); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/SequenceFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/SequenceFeature.java deleted file mode 100644 index c42735c7..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/SequenceFeature.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.features; - -import org.betterx.bclib.api.v3.levelgen.features.config.SequenceFeatureConfig; - -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; - -public class SequenceFeature extends Feature { - public SequenceFeature() { - super(SequenceFeatureConfig.CODEC); - } - - @Override - public boolean place(FeaturePlaceContext featurePlaceContext) { - return featurePlaceContext.config().placeAll(featurePlaceContext); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/TemplateFeature.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/TemplateFeature.java deleted file mode 100644 index 91e28907..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/features/TemplateFeature.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.features; - -import org.betterx.bclib.api.v2.levelgen.structures.StructureNBT; -import org.betterx.bclib.api.v2.levelgen.structures.StructureWorldNBT; -import org.betterx.bclib.api.v3.levelgen.features.config.TemplateFeatureConfig; - -import com.mojang.serialization.Codec; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; - -public class TemplateFeature extends Feature { - public TemplateFeature(Codec codec) { - super(codec); - } - - protected StructureWorldNBT randomStructure(TemplateFeatureConfig cfg, RandomSource random) { - if (cfg.structures.size() > 1) { - final float chanceSum = cfg.structures.parallelStream().map(c -> c.chance).reduce(0.0f, (p, c) -> p + c); - float rnd = random.nextFloat() * chanceSum; - - for (StructureWorldNBT c : cfg.structures) { - rnd -= c.chance; - if (rnd <= 0) return c; - } - } else { - return cfg.structures.get(0); - } - - return null; - } - - @Override - public boolean place(FeaturePlaceContext ctx) { - StructureWorldNBT structure = randomStructure(ctx.config(), ctx.random()); - return structure.generateIfPlaceable( - ctx.level(), - ctx.origin(), - StructureNBT.getRandomRotation(ctx.random()), - StructureNBT.getRandomMirror(ctx.random()) - ); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/All.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/All.java deleted file mode 100644 index 05e3ba8c..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/All.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.stream.IntStream; -import java.util.stream.Stream; - -public class All extends PlacementModifier { - private static final All INSTANCE = new All(); - public static final Codec CODEC = Codec.unit(All::new); - - @Override - public Stream getPositions( - PlacementContext placementContext, - RandomSource randomSource, - BlockPos blockPos - ) { - return IntStream.range(0, 16 * 16 - 1).mapToObj(i -> blockPos.offset(i & 0xF, 0, i >> 4)); - } - - public static PlacementModifier simple() { - return INSTANCE; - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.ALL; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Debug.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Debug.java deleted file mode 100644 index be942fd1..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Debug.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.stream.Stream; - -public class Debug extends PlacementModifier { - public static final Debug INSTANCE = new Debug(); - public static final Codec CODEC = Codec.unit(Debug::new); - - @Override - public Stream getPositions( - PlacementContext placementContext, - RandomSource randomSource, - BlockPos blockPos - ) { - return Stream.of(blockPos); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.DEBUG; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Extend.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Extend.java deleted file mode 100644 index 21436043..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Extend.java +++ /dev/null @@ -1,57 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.stream.Stream; - -public class Extend extends PlacementModifier { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance - .group( - Direction.CODEC - .fieldOf("direction") - .orElse(Direction.DOWN) - .forGetter(cfg -> cfg.direction), - IntProvider.codec(0, 16) - .fieldOf("length") - .orElse(UniformInt.of(0, 3)) - .forGetter(cfg -> cfg.length) - ) - .apply(instance, Extend::new)); - - private final Direction direction; - private final IntProvider length; - - public Extend(Direction direction, IntProvider length) { - this.direction = direction; - this.length = length; - } - - @Override - public Stream getPositions( - PlacementContext placementContext, - RandomSource random, - BlockPos blockPos - ) { - var builder = Stream.builder(); - final int count = length.sample(random); - builder.add(blockPos); - for (int y = 1; y < count + 1; y++) { - builder.add(blockPos.relative(direction, y)); - } - return builder.build(); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.EXTEND; - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/FindSolidInDirection.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/FindSolidInDirection.java deleted file mode 100644 index 6ba80c04..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/FindSolidInDirection.java +++ /dev/null @@ -1,155 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import org.betterx.bclib.util.BlocksHelper; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.SectionPos; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.util.RandomSource; -import net.minecraft.util.valueproviders.IntProvider; -import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.List; -import java.util.stream.Stream; - -public class FindSolidInDirection extends PlacementModifier { - - public static final Codec CODEC = RecordCodecBuilder - .create((instance) -> instance.group( - ExtraCodecs.nonEmptyList(Direction.CODEC.listOf()) - .fieldOf("dir") - .orElse(List.of(Direction.DOWN)) - .forGetter(a -> a.direction), - Codec.intRange(1, 32).fieldOf("dist").orElse(12).forGetter((p) -> p.maxSearchDistance), - Codec.BOOL.fieldOf("random_select").orElse(true).forGetter(p -> p.randomSelect), - Codec.INT.fieldOf("offset_in_dir").orElse(0).forGetter(p -> p.offsetInDir) - ) - .apply( - instance, - FindSolidInDirection::new - )); - protected static final FindSolidInDirection DOWN = new FindSolidInDirection(Direction.DOWN, 6, 0); - protected static final FindSolidInDirection UP = new FindSolidInDirection(Direction.UP, 6, 0); - private final List direction; - private final int maxSearchDistance; - - private final int offsetInDir; - private final boolean randomSelect; - private final IntProvider provider; - - - public FindSolidInDirection(Direction direction, int maxSearchDistance, int offsetInDir) { - this(List.of(direction), maxSearchDistance, false, offsetInDir); - } - - public FindSolidInDirection(List direction, int maxSearchDistance, int offsetInDir) { - this(direction, maxSearchDistance, direction.size() > 1, offsetInDir); - } - - public FindSolidInDirection( - List direction, - int maxSearchDistance, - boolean randomSelect, - int offsetInDir - ) { - this.direction = direction; - this.maxSearchDistance = maxSearchDistance; - this.provider = UniformInt.of(0, direction.size() - 1); - this.randomSelect = randomSelect; - this.offsetInDir = offsetInDir; - } - - public static PlacementModifier down() { - return DOWN; - } - - public static PlacementModifier up() { - return UP; - } - - public static PlacementModifier down(int dist) { - if (dist == DOWN.maxSearchDistance && 0 == DOWN.offsetInDir) return DOWN; - return new FindSolidInDirection(Direction.DOWN, dist, 0); - } - - public static PlacementModifier up(int dist) { - if (dist == UP.maxSearchDistance && 0 == UP.offsetInDir) return UP; - return new FindSolidInDirection(Direction.UP, dist, 0); - } - - public static PlacementModifier down(int dist, int offset) { - if (dist == DOWN.maxSearchDistance && 0 == DOWN.offsetInDir) return DOWN; - return new FindSolidInDirection(Direction.DOWN, dist, offset); - } - - public static PlacementModifier up(int dist, int offset) { - if (dist == UP.maxSearchDistance && offset == UP.offsetInDir) return UP; - return new FindSolidInDirection(Direction.UP, dist, offset); - } - - public Direction randomDirection(RandomSource random) { - return direction.get(provider.sample(random)); - } - - @Override - public Stream getPositions( - PlacementContext placementContext, - RandomSource randomSource, - BlockPos blockPos - ) { - var builder = Stream.builder(); - if (randomSelect) { - submitSingle(placementContext, blockPos, builder, randomDirection(randomSource)); - } else { - for (Direction d : direction) { - submitSingle(placementContext, blockPos, builder, d); - } - } - - return builder.build(); - } - - private void submitSingle( - PlacementContext placementContext, - BlockPos blockPos, - Stream.Builder builder, - Direction d - ) { - int searchDist; - BlockPos.MutableBlockPos POS = blockPos.mutable(); - if (d == Direction.EAST) { //+x - searchDist = Math.min(maxSearchDistance, 15 - SectionPos.sectionRelative(blockPos.getX())); - } else if (d == Direction.WEST) { //-x - searchDist = Math.min(maxSearchDistance, SectionPos.sectionRelative(blockPos.getX())); - } else if (d == Direction.SOUTH) { //+z - searchDist = Math.min(maxSearchDistance, 15 - SectionPos.sectionRelative(blockPos.getZ())); - } else if (d == Direction.NORTH) { //-z - searchDist = Math.min(maxSearchDistance, SectionPos.sectionRelative(blockPos.getZ())); - } else { - searchDist = maxSearchDistance; - } - if (BlocksHelper.findOnSurroundingSurface( - placementContext.getLevel(), - POS, - d, - searchDist, - BlocksHelper::isTerrain - )) { - if (offsetInDir != 0) - builder.add(POS.move(d, offsetInDir)); - else - builder.add(POS); - } - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.SOLID_IN_DIR; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/ForAll.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/ForAll.java deleted file mode 100644 index 0a511a08..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/ForAll.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.List; -import java.util.stream.Stream; - -public class ForAll extends PlacementModifier { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - ExtraCodecs.nonEmptyList(PlacementModifier.CODEC.listOf()) - .fieldOf("modifiers") - .forGetter(a -> a.modifiers) - ) - .apply(instance, ForAll::new)); - - private final List modifiers; - - public ForAll(List modifiers) { - this.modifiers = modifiers; - } - - @Override - public Stream getPositions( - PlacementContext placementContext, - RandomSource randomSource, - BlockPos blockPos - ) { - Stream.Builder stream = Stream.builder(); - for (PlacementModifier p : modifiers) { - p.getPositions(placementContext, randomSource, blockPos).forEach(pp -> stream.add(pp)); - } - return stream.build(); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.FOR_ALL; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Is.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Is.java deleted file mode 100644 index 56f3066f..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Is.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Vec3i; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementFilter; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.Optional; - -public class Is extends PlacementFilter { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance - .group( - BlockPredicate.CODEC - .fieldOf("predicate") - .forGetter(cfg -> cfg.predicate), - Vec3i.CODEC - .optionalFieldOf("offset") - .forGetter(cfg -> cfg.offset) - ) - .apply(instance, Is::new)); - - private final BlockPredicate predicate; - private final Optional offset; - - public Is(BlockPredicate predicate, Optional offset) { - this.predicate = predicate; - this.offset = offset; - } - - public static Is simple(BlockPredicate predicate) { - return new Is(predicate, Optional.empty()); - } - - public static Is below(BlockPredicate predicate) { - return new Is(predicate, Optional.of(Direction.DOWN.getNormal())); - } - - public static Is above(BlockPredicate predicate) { - return new Is(predicate, Optional.of(Direction.UP.getNormal())); - } - - @Override - protected boolean shouldPlace(PlacementContext ctx, RandomSource random, BlockPos pos) { - WorldGenLevel level = ctx.getLevel(); - return predicate.test(level, offset.map(v -> pos.offset(v.getX(), v.getY(), v.getZ())).orElse(pos)); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.IS; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/IsBasin.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/IsBasin.java deleted file mode 100644 index a8d856a0..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/IsBasin.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementFilter; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.Optional; - -public class IsBasin extends PlacementFilter { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance - .group( - BlockPredicate.CODEC - .fieldOf("predicate") - .forGetter(cfg -> cfg.predicate), - BlockPredicate.CODEC - .optionalFieldOf("top_predicate") - .orElse(Optional.empty()) - .forGetter(cfg -> cfg.topPredicate) - ) - .apply(instance, IsBasin::new)); - - private final BlockPredicate predicate; - private final Optional topPredicate; - - public IsBasin(BlockPredicate predicate) { - this(predicate, Optional.empty()); - } - - public IsBasin(BlockPredicate predicate, Optional topPredicate) { - this.predicate = predicate; - this.topPredicate = topPredicate; - } - - public static PlacementFilter simple(BlockPredicate predicate) { - return new IsBasin(predicate); - } - - public static IsBasin openTop(BlockPredicate predicate) { - return new IsBasin(predicate, Optional.of(BlockPredicate.ONLY_IN_AIR_PREDICATE)); - } - - @Override - protected boolean shouldPlace(PlacementContext ctx, RandomSource random, BlockPos pos) { - WorldGenLevel level = ctx.getLevel(); - if (topPredicate.isPresent() && !topPredicate.get().test(level, pos.above())) return false; - - return predicate.test(level, pos.below()) - && predicate.test(level, pos.west()) - && predicate.test(level, pos.east()) - && predicate.test(level, pos.north()) - && predicate.test(level, pos.south()); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.IS_BASIN; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/IsNextTo.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/IsNextTo.java deleted file mode 100644 index fbb7c48f..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/IsNextTo.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Vec3i; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.levelgen.blockpredicates.BlockPredicate; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementFilter; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.Optional; -import org.jetbrains.annotations.NotNull; - -public class IsNextTo extends PlacementFilter { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance - .group( - BlockPredicate.CODEC - .fieldOf("predicate") - .forGetter(cfg -> cfg.predicate), - Vec3i.CODEC - .optionalFieldOf("offset") - .forGetter(cfg -> Optional.of(cfg.offset)) - ) - .apply(instance, IsNextTo::new)); - - private final BlockPredicate predicate; - private final Vec3i offset; - - public IsNextTo(BlockPredicate predicate) { - this(predicate, Optional.of(Vec3i.ZERO)); - } - - public IsNextTo(BlockPredicate predicate, Optional offset) { - this(predicate, offset.orElse(Vec3i.ZERO)); - } - - public IsNextTo(@NotNull BlockPredicate predicate, @NotNull Vec3i offset) { - this.predicate = predicate; - this.offset = offset; - } - - public static PlacementFilter simple(BlockPredicate predicate) { - return new IsBasin(predicate); - } - - @Override - protected boolean shouldPlace(PlacementContext ctx, RandomSource random, BlockPos pos) { - WorldGenLevel level = ctx.getLevel(); - - pos = pos.offset(this.offset); - return predicate.test(level, pos.west()) - || predicate.test(level, pos.east()) - || predicate.test(level, pos.north()) - || predicate.test(level, pos.south()); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.IS_NEXT_TO; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/NoiseFilter.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/NoiseFilter.java deleted file mode 100644 index cdf6c021..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/NoiseFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import org.betterx.bclib.noise.Noises; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementFilter; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; -import net.minecraft.world.level.levelgen.synth.NormalNoise; - -public class NoiseFilter extends PlacementFilter { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - ResourceKey.codec(Registry.NOISE_REGISTRY).fieldOf("noise").forGetter(o -> o.noise), - Codec.DOUBLE.fieldOf("min_noise_level").forGetter(o -> o.minNoiseLevel), - Codec.DOUBLE.fieldOf("max_noise_level").orElse(Double.MAX_VALUE).forGetter(o -> o.maxNoiseLevel), - Codec.FLOAT.fieldOf("scale_xz").orElse(1f).forGetter(o -> o.scaleXZ), - Codec.FLOAT.fieldOf("scale_y").orElse(1f).forGetter(o -> o.scaleY) - ) - .apply(instance, NoiseFilter::new)); - - private final ResourceKey noise; - - private final double minNoiseLevel; - private final double maxNoiseLevel; - private final float scaleXZ; - private final float scaleY; - - - public NoiseFilter( - ResourceKey noise, - double minNoiseLevel, - double maxNoiseLevel, - float scaleXZ, - float scaleY - ) { - this.noise = noise; - this.minNoiseLevel = minNoiseLevel; - this.maxNoiseLevel = maxNoiseLevel; - this.scaleXZ = scaleXZ; - this.scaleY = scaleY; - } - - @Override - protected boolean shouldPlace(PlacementContext ctx, RandomSource random, BlockPos pos) { - final NormalNoise normalNoise = Noises.getOrCreateNoise(ctx.getLevel().registryAccess(), random, this.noise); - final double v = normalNoise.getValue(pos.getX() * scaleXZ, pos.getY() * scaleY, pos.getZ() * scaleXZ); - return v > minNoiseLevel && v < maxNoiseLevel; - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.NOISE_FILTER; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Offset.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Offset.java deleted file mode 100644 index 69ba3ac5..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Offset.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Vec3i; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import com.google.common.collect.Maps; - -import java.util.Map; -import java.util.stream.Stream; - -public class Offset extends PlacementModifier { - private static final Map DIRECTIONS = Maps.newHashMap(); - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> instance - .group( - Vec3i.CODEC - .fieldOf("blocks") - .forGetter(cfg -> cfg.offset) - ) - .apply(instance, Offset::new)); - - private final Vec3i offset; - - public Offset(Vec3i offset) { - this.offset = offset; - } - - public static Offset inDirection(Direction dir) { - return DIRECTIONS.get(dir); - } - - @Override - public Stream getPositions( - PlacementContext placementContext, - RandomSource randomSource, - BlockPos blockPos - ) { - return Stream.of(blockPos.offset(offset)); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.OFFSET; - } - - static { - for (Direction d : Direction.values()) - DIRECTIONS.put(d, new Offset(d.getNormal())); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/OnEveryLayer.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/OnEveryLayer.java deleted file mode 100644 index 4a2ccb4b..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/OnEveryLayer.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import org.betterx.bclib.util.BlocksHelper; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.Heightmap; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.Optional; -import java.util.stream.Stream; - -public class OnEveryLayer - extends PlacementModifier { - private static final OnEveryLayer INSTANCE = new OnEveryLayer(Optional.empty(), Optional.empty()); - private static final OnEveryLayer INSTANCE_MIN_4 = new OnEveryLayer(Optional.of(4), Optional.empty()); - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - Codec.INT.optionalFieldOf("min").forGetter(o -> o.minHeight), - Codec.INT.optionalFieldOf("max").forGetter(o -> o.maxHeight) - ).apply(instance, OnEveryLayer::new)); - - - private final Optional minHeight; - private final Optional maxHeight; - - protected OnEveryLayer(Optional minHeight, Optional maxHeight) { - this.minHeight = minHeight; - - this.maxHeight = maxHeight; - } - - public static OnEveryLayer simple() { - return INSTANCE; - } - - public static OnEveryLayer min4() { - return INSTANCE_MIN_4; - } - - @Override - public Stream getPositions( - PlacementContext ctx, - RandomSource random, - BlockPos pos - ) { - - Stream.Builder builder = Stream.builder(); - - final int z = pos.getZ(); - final int x = pos.getX(); - final int levelHeight = ctx.getHeight(Heightmap.Types.MOTION_BLOCKING, x, z); - final int minLevelHeight = ctx.getMinBuildHeight(); - int y = maxHeight.map(h -> Math.min(levelHeight, h)).orElse(levelHeight); - final int minHeight = this.minHeight.map(h -> Math.max(minLevelHeight, h)).orElse(minLevelHeight); - - int layerY; - do { - layerY = OnEveryLayer.findOnGroundYPosition(ctx, x, y, z, minHeight); - if (layerY != Integer.MAX_VALUE) { - builder.add(new BlockPos(x, layerY, z)); - y = layerY - 1; - } - - } while (layerY != Integer.MAX_VALUE); - return builder.build(); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.ON_EVERY_LAYER; - } - - private static int findOnGroundYPosition(PlacementContext ctx, int x, int startY, int z, int minHeight) { - BlockPos.MutableBlockPos mPos = new BlockPos.MutableBlockPos(x, startY, z); - BlockState nowState = ctx.getBlockState(mPos); - for (int y = startY; y >= minHeight + 1; --y) { - mPos.setY(y - 1); - BlockState belowState = ctx.getBlockState(mPos); - if (BlocksHelper.isTerrain(belowState) && BlocksHelper.isFreeOrFluid(nowState) && !belowState.is(Blocks.BEDROCK)) { - return mPos.getY() + 1; - } - nowState = belowState; - } - return Integer.MAX_VALUE; - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/PlacementModifiers.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/PlacementModifiers.java deleted file mode 100644 index 62248abc..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/PlacementModifiers.java +++ /dev/null @@ -1,90 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import org.betterx.bclib.BCLib; - -import com.mojang.serialization.Codec; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -public class PlacementModifiers { - public static final PlacementModifierType STENCIL = register( - "stencil", - Stencil.CODEC - ); - public static final PlacementModifierType IS_NEXT_TO = register( - "is_next_to", - IsNextTo.CODEC - ); - public static final PlacementModifierType NOISE_FILTER = register( - "noise_filter", - NoiseFilter.CODEC - ); - public static final PlacementModifierType DEBUG = register( - "debug", - Debug.CODEC - ); - - public static final PlacementModifierType FOR_ALL = register( - "for_all", - ForAll.CODEC - ); - - public static final PlacementModifierType SOLID_IN_DIR = register( - "solid_in_dir", - FindSolidInDirection.CODEC - ); - - public static final PlacementModifierType ALL = register( - "all", - All.CODEC - ); - - public static final PlacementModifierType IS_BASIN = register( - "is_basin", - IsBasin.CODEC - ); - - public static final PlacementModifierType IS = register( - "is", - Is.CODEC - ); - - public static final PlacementModifierType OFFSET = register( - "offset", - Offset.CODEC - ); - - public static final PlacementModifierType EXTEND = register( - "extend", - Extend.CODEC - ); - - public static final PlacementModifierType ON_EVERY_LAYER = register( - "on_every_layer", - OnEveryLayer.CODEC - ); - - public static final PlacementModifierType UNDER_EVERY_LAYER = register( - "under_every_layer", - UnderEveryLayer.CODEC - ); - - - private static

PlacementModifierType

register(String path, Codec

codec) { - return register(BCLib.makeID(path), codec); - } - - public static

PlacementModifierType

register( - ResourceLocation location, - Codec

codec - ) { - return Registry.register(Registry.PLACEMENT_MODIFIERS, location, () -> codec); - } - - public static void ensureStaticInitialization() { - - } -} - diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Stencil.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Stencil.java deleted file mode 100644 index 64470958..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/Stencil.java +++ /dev/null @@ -1,345 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.util.ExtraCodecs; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Stream; - -public class Stencil extends PlacementModifier { - public static final Codec CODEC; - private static final Boolean[] BN_STENCIL; - private final List stencil; - private static final Stencil DEFAULT; - private static final Stencil DEFAULT4; - private final int selectOneIn; - - private static List convert(Boolean[] s) { - return Arrays.stream(s).toList(); - } - - public Stencil(Boolean[] stencil, int selectOneIn) { - this(convert(stencil), selectOneIn); - } - - public Stencil(List stencil, int selectOneIn) { - this.stencil = stencil; - this.selectOneIn = selectOneIn; - } - - public static Stencil all() { - return DEFAULT; - } - - public static Stencil oneIn4() { - return DEFAULT4; - } - - @Override - public Stream getPositions( - PlacementContext placementContext, - RandomSource randomSource, - BlockPos blockPos - ) { - List pos = new ArrayList<>(16 * 16); - for (int x = 0; x < 16; x++) { - for (int y = 0; y < 16; y++) { - if (stencil.get(x << 4 | y)) { - pos.add(blockPos.offset(x, 0, y)); - } - } - } - - return pos.stream(); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.STENCIL; - } - - static { - BN_STENCIL = new Boolean[]{ - false, - true, - false, - false, - false, - false, - false, - true, - false, - false, - false, - false, - true, - true, - false, - false, - false, - false, - false, - false, - false, - false, - false, - true, - false, - false, - false, - false, - true, - true, - false, - false, - true, - true, - true, - false, - false, - false, - true, - true, - false, - false, - false, - true, - false, - false, - true, - true, - true, - false, - false, - true, - true, - true, - true, - false, - true, - true, - true, - true, - false, - false, - false, - true, - true, - false, - false, - true, - true, - true, - false, - false, - false, - false, - false, - true, - false, - false, - false, - false, - true, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true, - false, - false, - false, - false, - false, - false, - false, - true, - true, - true, - true, - true, - false, - false, - false, - true, - true, - true, - true, - false, - false, - false, - true, - true, - false, - true, - true, - true, - true, - true, - true, - true, - false, - false, - true, - true, - false, - true, - true, - false, - false, - false, - true, - false, - false, - true, - false, - false, - false, - false, - false, - true, - true, - true, - false, - false, - false, - false, - true, - false, - false, - true, - false, - false, - false, - false, - false, - false, - true, - false, - false, - false, - false, - true, - false, - false, - false, - true, - true, - false, - false, - false, - false, - false, - true, - false, - false, - false, - false, - true, - false, - true, - false, - false, - false, - true, - false, - false, - false, - false, - true, - false, - false, - false, - false, - true, - false, - true, - true, - false, - false, - true, - false, - false, - false, - true, - true, - true, - true, - true, - true, - false, - true, - false, - true, - true, - true, - true, - true, - true, - true, - false, - false, - false, - false, - true, - false, - false, - false, - false, - true, - true, - false, - false, - false, - true, - false, - false, - false, - false, - false, - true, - true, - false, - false - }; - - DEFAULT = new Stencil(BN_STENCIL, 1); - DEFAULT4 = new Stencil(BN_STENCIL, 4); - CODEC = RecordCodecBuilder.create((instance) -> instance - .group( - ExtraCodecs.nonEmptyList(Codec.BOOL.listOf()) - .fieldOf("structures") - .orElse(convert(BN_STENCIL)) - .forGetter((Stencil a) -> a.stencil), - Codec.INT - .fieldOf("one_in") - .orElse(1) - .forGetter((Stencil a) -> a.selectOneIn) - ) - .apply(instance, Stencil::new) - ); - } -} diff --git a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/UnderEveryLayer.java b/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/UnderEveryLayer.java deleted file mode 100644 index eb4c7d57..00000000 --- a/src/main/java/org/betterx/bclib/api/v3/levelgen/features/placement/UnderEveryLayer.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.betterx.bclib.api.v3.levelgen.features.placement; - -import org.betterx.bclib.util.BlocksHelper; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.Heightmap; -import net.minecraft.world.level.levelgen.placement.PlacementContext; -import net.minecraft.world.level.levelgen.placement.PlacementModifier; -import net.minecraft.world.level.levelgen.placement.PlacementModifierType; - -import java.util.Optional; -import java.util.stream.Stream; - -public class UnderEveryLayer - extends PlacementModifier { - private static final UnderEveryLayer INSTANCE = new UnderEveryLayer(Optional.empty(), Optional.empty()); - private static final UnderEveryLayer INSTANCE_MIN_4 = new UnderEveryLayer(Optional.of(4), Optional.empty()); - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - Codec.INT.optionalFieldOf("min").forGetter(o -> o.minHeight), - Codec.INT.optionalFieldOf("max").forGetter(o -> o.maxHeight) - ).apply(instance, UnderEveryLayer::new)); - - - private final Optional minHeight; - private final Optional maxHeight; - - protected UnderEveryLayer(Optional minHeight, Optional maxHeight) { - this.minHeight = minHeight; - - this.maxHeight = maxHeight; - } - - public static UnderEveryLayer simple() { - return INSTANCE; - } - - public static UnderEveryLayer min4() { - return INSTANCE_MIN_4; - } - - @Override - public Stream getPositions( - PlacementContext ctx, - RandomSource random, - BlockPos pos - ) { - - Stream.Builder builder = Stream.builder(); - - final int z = pos.getZ(); - final int x = pos.getX(); - final int levelHeight = ctx.getHeight(Heightmap.Types.MOTION_BLOCKING, x, z); - final int minLevelHeight = ctx.getMinBuildHeight(); - int y = maxHeight.map(h -> Math.min(levelHeight, h)).orElse(levelHeight); - final int minHeight = this.minHeight.map(h -> Math.max(minLevelHeight, h)).orElse(minLevelHeight); - - int layerY; - do { - layerY = findUnderGroundYPosition(ctx, x, y, z, minHeight); - if (layerY != Integer.MAX_VALUE) { - builder.add(new BlockPos(x, layerY, z)); - y = layerY - 1; - } - - } while (layerY != Integer.MAX_VALUE); - return builder.build(); - } - - @Override - public PlacementModifierType type() { - return PlacementModifiers.UNDER_EVERY_LAYER; - } - - private static int findUnderGroundYPosition(PlacementContext ctx, int x, int startY, int z, int minHeight) { - BlockPos.MutableBlockPos mPos = new BlockPos.MutableBlockPos(x, startY, z); - BlockState nowState = ctx.getBlockState(mPos); - for (int y = startY; y >= minHeight + 1; --y) { - mPos.setY(y - 1); - BlockState belowState = ctx.getBlockState(mPos); - if (BlocksHelper.isTerrain(nowState) && BlocksHelper.isFreeOrFluid(belowState) && !nowState.is(Blocks.BEDROCK)) { - return mPos.getY(); - } - nowState = belowState; - } - return Integer.MAX_VALUE; - } -} diff --git a/src/main/java/org/betterx/bclib/blockentities/BaseBarrelBlockEntity.java b/src/main/java/org/betterx/bclib/blockentities/BaseBarrelBlockEntity.java deleted file mode 100644 index 1162c7bc..00000000 --- a/src/main/java/org/betterx/bclib/blockentities/BaseBarrelBlockEntity.java +++ /dev/null @@ -1,184 +0,0 @@ -package org.betterx.bclib.blockentities; - -import org.betterx.bclib.registry.BaseBlockEntities; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.NonNullList; -import net.minecraft.core.Vec3i; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.chat.Component; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.Container; -import net.minecraft.world.ContainerHelper; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.ChestMenu; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.BarrelBlock; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.entity.ContainerOpenersCounter; -import net.minecraft.world.level.block.entity.RandomizableContainerBlockEntity; -import net.minecraft.world.level.block.state.BlockState; - -public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { - private NonNullList inventory; - private ContainerOpenersCounter openersCounter = new ContainerOpenersCounter() { - - @Override - protected void onOpen(Level level, BlockPos blockPos, BlockState blockState) { - BaseBarrelBlockEntity.this.playSound(blockState, SoundEvents.BARREL_OPEN); - BaseBarrelBlockEntity.this.updateBlockState(blockState, true); - } - - @Override - protected void onClose(Level level, BlockPos blockPos, BlockState blockState) { - BaseBarrelBlockEntity.this.playSound(blockState, SoundEvents.BARREL_CLOSE); - BaseBarrelBlockEntity.this.updateBlockState(blockState, false); - } - - @Override - protected void openerCountChanged(Level level, BlockPos blockPos, BlockState blockState, int i, int j) { - } - - @Override - protected boolean isOwnContainer(Player player) { - if (player.containerMenu instanceof ChestMenu) { - Container container = ((ChestMenu) player.containerMenu).getContainer(); - return container == BaseBarrelBlockEntity.this; - } - return false; - } - }; - - private BaseBarrelBlockEntity(BlockEntityType type, BlockPos blockPos, BlockState blockState) { - super(type, blockPos, blockState); - this.inventory = NonNullList.withSize(27, ItemStack.EMPTY); - } - - public BaseBarrelBlockEntity(BlockPos blockPos, BlockState blockState) { - this(BaseBlockEntities.BARREL, blockPos, blockState); - } - - @Override - public void saveAdditional(CompoundTag tag) { - super.saveAdditional(tag); - if (!this.trySaveLootTable(tag)) { - ContainerHelper.saveAllItems(tag, this.inventory); - } - } - - @Override - public void load(CompoundTag tag) { - super.load(tag); - this.inventory = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); - if (!this.tryLoadLootTable(tag)) { - ContainerHelper.loadAllItems(tag, this.inventory); - } - } - - @Override - public int getContainerSize() { - return 27; - } - - @Override - protected NonNullList getItems() { - return this.inventory; - } - - @Override - protected void setItems(NonNullList list) { - this.inventory = list; - } - - @Override - protected Component getDefaultName() { - return Component.translatable("container.barrel"); - } - - @Override - protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { - return ChestMenu.threeRows(syncId, playerInventory, this); - } - - public void startOpen(Player player) { - if (!this.remove && !player.isSpectator()) { - this.openersCounter.incrementOpeners(player, this.getLevel(), this.getBlockPos(), this.getBlockState()); - } -// if (!player.isSpectator()) { -// if (viewerCount < 0) { -// viewerCount = 0; -// } -// -// ++viewerCount; -// BlockState blockState = this.getBlockState(); -// if (!blockState.getValue(BarrelBlock.OPEN)) { -// playSound(blockState, SoundEvents.BARREL_OPEN); -// updateBlockState(blockState, true); -// } -// -// if (level != null) { -// scheduleUpdate(); -// } -// } - } - - private void scheduleUpdate() { - level.scheduleTick(getBlockPos(), getBlockState().getBlock(), 5); - } - - public void tick() { -// if (level != null) { -// viewerCount = ChestBlockEntity.getOpenCount(level, worldPosition); -// if (viewerCount > 0) { -// scheduleUpdate(); -// } else { -// BlockState blockState = getBlockState(); -// if (!(blockState.getBlock() instanceof BaseBarrelBlock)) { -// setRemoved(); -// return; -// } -// if (blockState.getValue(BarrelBlock.OPEN)) { -// playSound(blockState, SoundEvents.BARREL_CLOSE); -// updateBlockState(blockState, false); -// } -// } -// } - } - - @Override - public void stopOpen(Player player) { - if (!this.remove && !player.isSpectator()) { - this.openersCounter.decrementOpeners(player, this.getLevel(), this.getBlockPos(), this.getBlockState()); - } - } - - public void recheckOpen() { - if (!this.remove) { - this.openersCounter.recheckOpeners(this.getLevel(), this.getBlockPos(), this.getBlockState()); - } - } - - private void updateBlockState(BlockState state, boolean open) { - if (level != null) { - level.setBlock(this.getBlockPos(), state.setValue(BarrelBlock.OPEN, open), 3); - } - } - - private void playSound(BlockState blockState, SoundEvent soundEvent) { - if (level != null) { - Vec3i facingDir = blockState.getValue(BarrelBlock.FACING).getNormal(); - double x = this.worldPosition.getX() + 0.5D + facingDir.getX() / 2.0D; - double y = this.worldPosition.getY() + 0.5D + facingDir.getY() / 2.0D; - double z = this.worldPosition.getZ() + 0.5D + facingDir.getZ() / 2.0D; - level.playSound( - null, x, y, z, - soundEvent, SoundSource.BLOCKS, 0.5F, this.level.random.nextFloat() * 0.1F + 0.9F - ); - } - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/blockentities/BaseChestBlockEntity.java b/src/main/java/org/betterx/bclib/blockentities/BaseChestBlockEntity.java deleted file mode 100644 index 258b113c..00000000 --- a/src/main/java/org/betterx/bclib/blockentities/BaseChestBlockEntity.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.betterx.bclib.blockentities; - -import org.betterx.bclib.registry.BaseBlockEntities; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.entity.ChestBlockEntity; -import net.minecraft.world.level.block.state.BlockState; - -public class BaseChestBlockEntity extends ChestBlockEntity { - public BaseChestBlockEntity(BlockPos blockPos, BlockState blockState) { - super(BaseBlockEntities.CHEST, blockPos, blockState); - } -} diff --git a/src/main/java/org/betterx/bclib/blockentities/BaseFurnaceBlockEntity.java b/src/main/java/org/betterx/bclib/blockentities/BaseFurnaceBlockEntity.java deleted file mode 100644 index 53e964e2..00000000 --- a/src/main/java/org/betterx/bclib/blockentities/BaseFurnaceBlockEntity.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.betterx.bclib.blockentities; - -import org.betterx.bclib.registry.BaseBlockEntities; - -import net.minecraft.core.BlockPos; -import net.minecraft.network.chat.Component; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.FurnaceMenu; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; -import net.minecraft.world.level.block.state.BlockState; - -public class BaseFurnaceBlockEntity extends AbstractFurnaceBlockEntity { - public BaseFurnaceBlockEntity(BlockPos blockPos, BlockState blockState) { - super(BaseBlockEntities.FURNACE, blockPos, blockState, RecipeType.SMELTING); - } - - protected Component getDefaultName() { - return Component.translatable("container.furnace"); - } - - protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { - return new FurnaceMenu(syncId, playerInventory, this, this.dataAccess); - } -} diff --git a/src/main/java/org/betterx/bclib/blockentities/BaseSignBlockEntity.java b/src/main/java/org/betterx/bclib/blockentities/BaseSignBlockEntity.java deleted file mode 100644 index e91c936b..00000000 --- a/src/main/java/org/betterx/bclib/blockentities/BaseSignBlockEntity.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.blockentities; - -import org.betterx.bclib.registry.BaseBlockEntities; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.entity.SignBlockEntity; -import net.minecraft.world.level.block.state.BlockState; - -public class BaseSignBlockEntity extends SignBlockEntity { - public BaseSignBlockEntity(BlockPos blockPos, BlockState blockState) { - super(blockPos, blockState); - } - - @Override - public BlockEntityType getType() { - return BaseBlockEntities.SIGN; - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/blockentities/DynamicBlockEntityType.java b/src/main/java/org/betterx/bclib/blockentities/DynamicBlockEntityType.java deleted file mode 100644 index 93a7afa9..00000000 --- a/src/main/java/org/betterx/bclib/blockentities/DynamicBlockEntityType.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.betterx.bclib.blockentities; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockState; - -import com.google.common.collect.Sets; - -import java.util.Collections; -import java.util.Set; -import org.jetbrains.annotations.Nullable; - -public class DynamicBlockEntityType extends BlockEntityType { - - private final Set validBlocks = Sets.newHashSet(); - private final BlockEntitySupplier factory; - - public DynamicBlockEntityType(BlockEntitySupplier supplier) { - super(null, Collections.emptySet(), null); - this.factory = supplier; - } - - @Override - @Nullable - public T create(BlockPos blockPos, BlockState blockState) { - return factory.create(blockPos, blockState); - } - - @Override - public boolean isValid(BlockState blockState) { - return validBlocks.contains(blockState.getBlock()); - } - - public void registerBlock(Block block) { - validBlocks.add(block); - } - - @FunctionalInterface - public interface BlockEntitySupplier { - T create(BlockPos blockPos, BlockState blockState); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseAnvilBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseAnvilBlock.java deleted file mode 100644 index 442293bb..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseAnvilBlock.java +++ /dev/null @@ -1,140 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.CustomItemProvider; -import org.betterx.bclib.items.BaseAnvilItem; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.PickaxeItem; -import net.minecraft.world.level.block.AnvilBlock; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider, CustomItemProvider { - public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; - public IntegerProperty durability; - - public BaseAnvilBlock(MaterialColor color) { - this(Properties.copy(Blocks.ANVIL).color(color)); - } - - public BaseAnvilBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - super.createBlockStateDefinition(builder); - if (getMaxDurability() != 3) { - durability = IntegerProperty.create("durability", 0, getMaxDurability()); - } else { - durability = BlockProperties.DEFAULT_ANVIL_DURABILITY; - } - builder.add(DESTRUCTION, durability); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return getBlockModel(blockId, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - int destruction = blockState.getValue(DESTRUCTION); - String name = blockId.getPath(); - Map textures = Maps.newHashMap(); - textures.put("%modid%", blockId.getNamespace()); - textures.put("%anvil%", name); - textures.put("%top%", name + "_top_" + destruction); - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_ANVIL, textures); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - int destruction = blockState.getValue(DESTRUCTION); - String modId = stateId.getNamespace(); - String modelId = "block/" + stateId.getPath() + "_top_" + destruction; - ResourceLocation modelLocation = new ResourceLocation(modId, modelId); - registerBlockModel(stateId, modelLocation, blockState, modelCache); - return ModelsHelper.createFacingModel(modelLocation, blockState.getValue(FACING), false, false); - } - - @Override - public BlockItem getCustomItem(ResourceLocation blockID, Item.Properties settings) { - return new BaseAnvilItem(this, settings); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - int destruction = state.getValue(DESTRUCTION); - int durability = state.getValue(getDurabilityProp()); - int value = destruction * getMaxDurability() + durability; - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.getItem() instanceof PickaxeItem) { - ItemStack itemStack = new ItemStack(this); - itemStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, value); - return Lists.newArrayList(itemStack); - } - return Collections.emptyList(); - } - - public IntegerProperty getDurabilityProp() { - return durability; - } - - public int getMaxDurability() { - return 3; - } - - public BlockState damageAnvilUse(BlockState state, RandomSource random) { - IntegerProperty durability = getDurabilityProp(); - int value = state.getValue(durability); - if (value < getMaxDurability() && random.nextInt(8) == 0) { - return state.setValue(durability, value + 1); - } - value = state.getValue(DESTRUCTION); - return value < 2 ? state.setValue(DESTRUCTION, value + 1).setValue(durability, 0) : null; - } - - public BlockState damageAnvilFall(BlockState state) { - int destruction = state.getValue(DESTRUCTION); - return destruction < 2 ? state.setValue(DESTRUCTION, destruction + 1) : null; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseAttachedBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseAttachedBlock.java deleted file mode 100644 index 3ba71ece..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseAttachedBlock.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.tags.BlockTags; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.block.state.properties.DirectionProperty; - -@SuppressWarnings("deprecation") -public abstract class BaseAttachedBlock extends BaseBlockNotFull { - public static final DirectionProperty FACING = BlockStateProperties.FACING; - - public BaseAttachedBlock(Properties settings) { - super(settings); - registerDefaultState(defaultBlockState().setValue(FACING, Direction.UP)); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(FACING); - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - BlockState blockState = defaultBlockState(); - LevelReader worldView = ctx.getLevel(); - BlockPos blockPos = ctx.getClickedPos(); - Direction[] directions = ctx.getNearestLookingDirections(); - for (Direction direction : directions) { - Direction direction2 = direction.getOpposite(); - blockState = blockState.setValue(FACING, direction2); - if (blockState.canSurvive(worldView, blockPos)) { - return blockState; - } - } - return null; - } - - @Override - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - Direction direction = state.getValue(FACING); - BlockPos blockPos = pos.relative(direction.getOpposite()); - return canSupportCenter(world, blockPos, direction) || world.getBlockState(blockPos).is(BlockTags.LEAVES); - } - - @Override - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) { - return Blocks.AIR.defaultBlockState(); - } else { - return state; - } - } - - - @Override - public BlockState rotate(BlockState state, Rotation rotation) { - return BlocksHelper.rotateHorizontal(state, rotation, FACING); - } - - @Override - public BlockState mirror(BlockState state, Mirror mirror) { - return BlocksHelper.mirrorHorizontal(state, mirror, FACING); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseBarkBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseBarkBlock.java deleted file mode 100644 index b4875661..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseBarkBlock.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.PatternsHelper; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; - -import java.util.Optional; - -public class BaseBarkBlock extends BaseRotatedPillarBlock { - public BaseBarkBlock(Properties settings) { - super(settings); - } - - @Override - protected Optional createBlockPattern(ResourceLocation blockId) { - blockId = Registry.BLOCK.getKey(this); - return PatternsHelper.createJson(BasePatterns.BLOCK_BASE, replacePath(blockId)); - } - - private ResourceLocation replacePath(ResourceLocation blockId) { - String newPath = blockId.getPath().replace("_bark", "_log_side"); - return new ResourceLocation(blockId.getNamespace(), newPath); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseBarrelBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseBarrelBlock.java deleted file mode 100644 index 5da62bd3..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseBarrelBlock.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.blockentities.BaseBarrelBlockEntity; -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.registry.BaseBlockEntities; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.stats.Stats; -import net.minecraft.util.RandomSource; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.monster.piglin.PiglinAi; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.BarrelBlock; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.RenderShape; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.phys.BlockHitResult; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { - public BaseBarrelBlock(Block source) { - this(Properties.copy(source).noOcclusion()); - } - - public BaseBarrelBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { - return BaseBlockEntities.BARREL.create(blockPos, blockState); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - List drop = super.getDrops(state, builder); - drop.add(new ItemStack(this.asItem())); - return drop; - } - - @Override - public InteractionResult use( - BlockState state, - Level level, - BlockPos pos, - Player player, - InteractionHand hand, - BlockHitResult hit - ) { - if (level.isClientSide) { - return InteractionResult.SUCCESS; - } else { - BlockEntity blockEntity = level.getBlockEntity(pos); - if (blockEntity instanceof BaseBarrelBlockEntity) { - player.openMenu((BaseBarrelBlockEntity) blockEntity); - player.awardStat(Stats.OPEN_BARREL); - PiglinAi.angerNearbyPiglins(player, true); - } - - return InteractionResult.CONSUME; - } - } - - @Override - public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - BlockEntity blockEntity = world.getBlockEntity(pos); - if (blockEntity instanceof BaseBarrelBlockEntity) { - ((BaseBarrelBlockEntity) blockEntity).recheckOpen(); - } - } - - @Override - public RenderShape getRenderShape(BlockState state) { - return RenderShape.MODEL; - } - - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { - if (itemStack.hasCustomHoverName()) { - BlockEntity blockEntity = world.getBlockEntity(pos); - if (blockEntity instanceof BaseBarrelBlockEntity) { - ((BaseBarrelBlockEntity) blockEntity).setCustomName(itemStack.getHoverName()); - } - } - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return getBlockModel(blockId, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - Optional pattern; - if (blockState.getValue(OPEN)) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BARREL_OPEN, blockId); - } else { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - String open = blockState.getValue(OPEN) ? "_open" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + open); - registerBlockModel(stateId, modelId, blockState, modelCache); - Direction facing = blockState.getValue(FACING); - BlockModelRotation rotation = BlockModelRotation.X0_Y0; - switch (facing) { - case NORTH: - rotation = BlockModelRotation.X90_Y0; - break; - case EAST: - rotation = BlockModelRotation.X90_Y90; - break; - case SOUTH: - rotation = BlockModelRotation.X90_Y180; - break; - case WEST: - rotation = BlockModelRotation.X90_Y270; - break; - case DOWN: - rotation = BlockModelRotation.X180_Y0; - break; - default: - break; - } - return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseBlock.java deleted file mode 100644 index 5482a865..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseBlock.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.level.storage.loot.LootContext; - - -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -/** - * Base class for a default Block. - *

- * This Block-Type will: - *

    - *
  • Drop itself
  • - *
  • Automatically create an Item-Model from the Block-Model
  • - *
- */ -public class BaseBlock extends Block implements BlockModelProvider { - /** - * Creates a new Block with the passed properties - * - * @param settings The properties of the Block. - */ - public BaseBlock(Properties settings) { - super(settings); - } - - /** - * {@inheritDoc} - *

- * This implementation will drop the Block itself - */ - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - /** - * {@inheritDoc} - *

- * This implementation will load the Block-Model and return it as the Item-Model - */ - @Override - public BlockModel getItemModel(ResourceLocation blockId) { - return getBlockModel(blockId, defaultBlockState()); - } - - /** - * This method is used internally. - *

- * It is called from Block-Contructors, to allow the augmentation of the blocks - * preset properties. - *

- * For example in {@link BaseLeavesBlock#BaseLeavesBlock(Block, MaterialColor, Consumer)} - * - * @param customizeProperties A {@link Consumer} to call with the preset properties - * @param settings The properties as created by the Block - * @return The reconfigured {@code settings} - */ - static Properties acceptAndReturn( - Consumer customizeProperties, - Properties settings - ) { - customizeProperties.accept(settings); - return settings; - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/blocks/BaseBlockNotFull.java b/src/main/java/org/betterx/bclib/blocks/BaseBlockNotFull.java deleted file mode 100644 index 22da4b48..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseBlockNotFull.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.state.BlockState; - -public class BaseBlockNotFull extends BaseBlock { - public BaseBlockNotFull(Properties settings) { - super(settings); - } - - public boolean canSuffocate(BlockState state, BlockGetter view, BlockPos pos) { - return false; - } - - public boolean isSimpleFullBlock(BlockState state, BlockGetter view, BlockPos pos) { - return false; - } - - public boolean allowsSpawning(BlockState state, BlockGetter view, BlockPos pos, EntityType type) { - return false; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseBlockWithEntity.java b/src/main/java/org/betterx/bclib/blocks/BaseBlockWithEntity.java deleted file mode 100644 index 5900b454..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseBlockWithEntity.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.BaseEntityBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import java.util.Collections; -import java.util.List; - -public class BaseBlockWithEntity extends BaseEntityBlock { - public BaseBlockWithEntity(Properties settings) { - super(settings); - } - - @Override - public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { - return null; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseBookshelfBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseBookshelfBlock.java deleted file mode 100644 index 32067e76..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseBookshelfBlock.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseBookshelfBlock extends BaseBlock { - public static class WithVanillaWood extends BaseBookshelfBlock { - public WithVanillaWood(Block source) { - super(source); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - Optional pattern = PatternsHelper.createJson( - BasePatterns.VANILLA_WOOD_BOOKSHELF, - replacePath(blockId) - ); - return ModelsHelper.fromPattern(pattern); - } - } - - public BaseBookshelfBlock(Block source) { - this(Properties.copy(source)); - } - - public BaseBookshelfBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null) { - int silk = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool); - if (silk > 0) { - return Collections.singletonList(new ItemStack(this)); - } - } - return Collections.singletonList(new ItemStack(Items.BOOK, 3)); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BOOKSHELF, replacePath(blockId)); - return ModelsHelper.fromPattern(pattern); - } - - protected ResourceLocation replacePath(ResourceLocation blockId) { - String newPath = blockId.getPath().replace("_bookshelf", ""); - return new ResourceLocation(blockId.getNamespace(), newPath); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseButtonBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseButtonBlock.java deleted file mode 100644 index 5c50bb4a..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseButtonBlock.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.ButtonBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.AttachFace; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelProvider { - private final Block parent; - - protected BaseButtonBlock(Block parent, Properties properties, boolean sensitive) { - super(sensitive, properties.noCollission()); - this.parent = parent; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_BUTTON, parentId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern = blockState.getValue(POWERED) - ? PatternsHelper.createJson( - BasePatterns.BLOCK_BUTTON_PRESSED, - parentId - ) - : PatternsHelper.createJson(BasePatterns.BLOCK_BUTTON, parentId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - String powered = blockState.getValue(POWERED) ? "_powered" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + powered); - registerBlockModel(stateId, modelId, blockState, modelCache); - AttachFace face = blockState.getValue(FACE); - boolean isCeiling = face == AttachFace.CEILING; - int x = 0, y = 0; - switch (face) { - case CEILING: - x = 180; - break; - case WALL: - x = 90; - break; - default: - break; - } - switch (blockState.getValue(FACING)) { - case NORTH: - if (isCeiling) { - y = 180; - } - break; - case EAST: - y = isCeiling ? 270 : 90; - break; - case SOUTH: - if (!isCeiling) { - y = 180; - } - break; - case WEST: - y = isCeiling ? 90 : 270; - break; - default: - break; - } - BlockModelRotation rotation = BlockModelRotation.by(x, y); - return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), face == AttachFace.WALL); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseChainBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseChainBlock.java deleted file mode 100644 index 89ea9d46..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseChainBlock.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.ChainBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseChainBlock extends ChainBlock implements BlockModelProvider, RenderLayerProvider { - public BaseChainBlock(MaterialColor color) { - this(Properties.copy(Blocks.CHAIN).color(color)); - } - - public BaseChainBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return ModelsHelper.createItemModel(blockId); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CHAIN, blockId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - Direction.Axis axis = blockState.getValue(AXIS); - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createRotatedModel(modelId, axis); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseChestBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseChestBlock.java deleted file mode 100644 index 577bcad9..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseChestBlock.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.registry.BaseBlockEntities; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.ChestBlock; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.List; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseChestBlock extends ChestBlock implements BlockModelProvider { - private final Block parent; - - public BaseChestBlock(Block source) { - super(Properties.copy(source).noOcclusion(), () -> BaseBlockEntities.CHEST); - this.parent = source; - } - - @Override - public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { - return BaseBlockEntities.CHEST.create(blockPos, blockState); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - List drop = super.getDrops(state, builder); - drop.add(new ItemStack(this.asItem())); - return drop; - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_CHEST, blockId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - return ModelsHelper.createBlockEmpty(parentId); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseComposterBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseComposterBlock.java deleted file mode 100644 index 6072e984..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseComposterBlock.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.ComposterBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseComposterBlock extends ComposterBlock implements BlockModelProvider { - public BaseComposterBlock(Block source) { - super(Properties.copy(source)); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this.asItem())); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_COMPOSTER, blockId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - - ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); - LEVEL.getPossibleValues().forEach(level -> { - if (level > 0) { - ResourceLocation contentId; - if (level > 7) { - contentId = new ResourceLocation("block/composter_contents_ready"); - } else { - contentId = new ResourceLocation("block/composter_contents" + level); - } - builder.part(contentId).setCondition(state -> state.getValue(LEVEL).equals(level)).add(); - } - }); - builder.part(modelId).add(); - - return builder.build(); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseCraftingTableBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseCraftingTableBlock.java deleted file mode 100644 index c5ca01ab..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseCraftingTableBlock.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.CraftingTableBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelProvider { - public BaseCraftingTableBlock(Block source) { - this(Properties.copy(source)); - } - - public BaseCraftingTableBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this.asItem())); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - String blockName = blockId.getPath(); - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SIDED, new HashMap() { - private static final long serialVersionUID = 1L; - - { - put("%modid%", blockId.getNamespace()); - put("%particle%", blockName + "_front"); - put("%down%", blockName + "_bottom"); - put("%up%", blockName + "_top"); - put("%north%", blockName + "_front"); - put("%south%", blockName + "_side"); - put("%west%", blockName + "_front"); - put("%east%", blockName + "_side"); - } - }); - return ModelsHelper.fromPattern(pattern); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseCropBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseCropBlock.java deleted file mode 100644 index 93803fa0..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseCropBlock.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.util.BlocksHelper; -import org.betterx.bclib.util.MHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.Mth; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import com.google.common.collect.Lists; - -import java.util.Collections; -import java.util.List; - -public class BaseCropBlock extends BasePlantBlock { - public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3); - private static final VoxelShape SHAPE = box(2, 0, 2, 14, 14, 14); - - private final Block[] terrain; - private final Item drop; - - public BaseCropBlock(Item drop, Block... terrain) { - this(basePlantSettings().randomTicks(), drop, terrain); - } - - protected BaseCropBlock(BlockBehaviour.Properties properties, Item drop, Block... terrain) { - super(properties); - this.drop = drop; - this.terrain = terrain; - this.registerDefaultState(defaultBlockState().setValue(AGE, 0)); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(AGE); - } - - @Override - protected boolean isTerrain(BlockState state) { - for (Block block : terrain) { - if (state.is(block)) { - return true; - } - } - return false; - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - if (state.getValue(AGE) < 3) { - return Collections.singletonList(new ItemStack(this)); - } - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.isCorrectToolForDrops(state)) { - int enchantment = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); - if (enchantment > 0) { - int countSeeds = MHelper.randRange(Mth.clamp(1 + enchantment, 1, 3), 3, MHelper.RANDOM_SOURCE); - int countDrops = MHelper.randRange(Mth.clamp(1 + enchantment, 1, 2), 2, MHelper.RANDOM_SOURCE); - return Lists.newArrayList(new ItemStack(this, countSeeds), new ItemStack(drop, countDrops)); - } - } - int countSeeds = MHelper.randRange(1, 3, MHelper.RANDOM_SOURCE); - int countDrops = MHelper.randRange(1, 2, MHelper.RANDOM_SOURCE); - return Lists.newArrayList(new ItemStack(this, countSeeds), new ItemStack(drop, countDrops)); - } - - @Override - public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) { - int age = state.getValue(AGE); - if (age < 3) { - BlocksHelper.setWithUpdate(level, pos, state.setValue(AGE, age + 1)); - } - } - - @Override - public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { - return state.getValue(AGE) < 3; - } - - @Override - public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { - return state.getValue(AGE) < 3; - } - - @Override - @SuppressWarnings("deprecation") - public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - super.tick(state, world, pos, random); - if (isBonemealSuccess(world, random, pos, state) && random.nextInt(8) == 0) { - performBonemeal(world, random, pos, state); - } - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPE; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseDoorBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseDoorBlock.java deleted file mode 100644 index ce346b18..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseDoorBlock.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.interfaces.TagProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; -import net.minecraft.tags.TagKey; -import net.minecraft.util.StringRepresentable; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.DoorBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.DoorHingeSide; -import net.minecraft.world.level.block.state.properties.DoubleBlockHalf; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseDoorBlock extends DoorBlock implements RenderLayerProvider, BlockModelProvider, TagProvider { - public BaseDoorBlock(Block source) { - this(Properties.copy(source).strength(3F, 3F).noOcclusion()); - } - - public BaseDoorBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - if (state.getValue(HALF) == DoubleBlockHalf.LOWER) - return Collections.singletonList(new ItemStack(this.asItem())); - else return Collections.emptyList(); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - DoorType doorType = getDoorType(blockState); - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_BOTTOM, resourceLocation); - switch (doorType) { - case TOP_HINGE: - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_TOP_HINGE, resourceLocation); - break; - case BOTTOM_HINGE: - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_BOTTOM_HINGE, resourceLocation); - break; - case TOP: - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_TOP, resourceLocation); - break; - default: - break; - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - Direction facing = blockState.getValue(FACING); - DoorType doorType = getDoorType(blockState); - boolean open = blockState.getValue(OPEN); - boolean hinge = doorType.isHinge(); - BlockModelRotation rotation = BlockModelRotation.X0_Y0; - switch (facing) { - case EAST: - if (hinge && open) { - rotation = BlockModelRotation.X0_Y90; - } else if (open) { - rotation = BlockModelRotation.X0_Y270; - } - break; - case SOUTH: - if (!hinge && !open || hinge && !open) { - rotation = BlockModelRotation.X0_Y90; - } else if (hinge) { - rotation = BlockModelRotation.X0_Y180; - } - break; - case WEST: - if (!hinge && !open || hinge && !open) { - rotation = BlockModelRotation.X0_Y180; - } else if (hinge) { - rotation = BlockModelRotation.X0_Y270; - } else { - rotation = BlockModelRotation.X0_Y90; - } - break; - case NORTH: - default: - if (!hinge && !open || hinge && !open) { - rotation = BlockModelRotation.X0_Y270; - } else if (!hinge) { - rotation = BlockModelRotation.X0_Y180; - } - break; - } - ResourceLocation modelId = new ResourceLocation( - stateId.getNamespace(), - "block/" + stateId.getPath() + "_" + doorType - ); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); - } - - protected DoorType getDoorType(BlockState blockState) { - boolean isHinge = isHinge(blockState.getValue(HINGE), blockState.getValue(OPEN)); - switch (blockState.getValue(HALF)) { - case UPPER: { - return isHinge ? DoorType.TOP_HINGE : DoorType.TOP; - } - case LOWER: { - return isHinge ? DoorType.BOTTOM_HINGE : DoorType.BOTTOM; - } - } - return DoorType.BOTTOM; - } - - private boolean isHinge(DoorHingeSide hingeSide, boolean open) { - boolean isHinge = hingeSide == DoorHingeSide.RIGHT; - return isHinge && !open || !isHinge && open; - } - - @Override - public void addTags(List> blockTags, List> itemTags) { - blockTags.add(BlockTags.DOORS); - itemTags.add(ItemTags.DOORS); - } - - protected enum DoorType implements StringRepresentable { - BOTTOM_HINGE("bottom_hinge"), TOP_HINGE("top_hinge"), BOTTOM("bottom"), TOP("top"); - - private final String name; - - DoorType(String name) { - this.name = name; - } - - public boolean isHinge() { - return this == BOTTOM_HINGE || this == TOP_HINGE; - } - - @Override - public String toString() { - return getSerializedName(); - } - - @Override - public String getSerializedName() { - return name; - } - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseDoublePlantBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseDoublePlantBlock.java deleted file mode 100644 index 1646c093..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseDoublePlantBlock.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.BonemealableBlock; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.BooleanProperty; -import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import com.google.common.collect.Lists; - -import java.util.List; - -public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { - private static final VoxelShape SHAPE = box(4, 2, 4, 12, 16, 12); - public static final IntegerProperty ROTATION = BlockProperties.ROTATION; - public static final BooleanProperty TOP = BooleanProperty.create("top"); - - public BaseDoublePlantBlock() { - this( - Properties.of(Material.PLANT) - .sound(SoundType.GRASS) - .noCollission() - .offsetType(BlockBehaviour.OffsetType.NONE) - ); - } - - public BaseDoublePlantBlock(int light) { - this( - Properties.of(Material.PLANT) - .sound(SoundType.GRASS) - .lightLevel((state) -> state.getValue(TOP) ? light : 0) - .noCollission() - .offsetType(BlockBehaviour.OffsetType.NONE) - ); - } - - public BaseDoublePlantBlock(BlockBehaviour.Properties properties) { - super(properties); - this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(TOP, ROTATION); - } - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - Vec3 vec3d = state.getOffset(view, pos); - return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); - } - - @Override - @SuppressWarnings("deprecation") - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - BlockState down = world.getBlockState(pos.below()); - BlockState up = world.getBlockState(pos.above()); - return state.getValue(TOP) ? down.getBlock() == this : isTerrain(down) && (up.getMaterial().isReplaceable()); - } - - public boolean canStayAt(BlockState state, LevelReader world, BlockPos pos) { - BlockState down = world.getBlockState(pos.below()); - BlockState up = world.getBlockState(pos.above()); - return state.getValue(TOP) ? down.getBlock() == this : isTerrain(down) && (up.getBlock() == this); - } - - protected abstract boolean isTerrain(BlockState state); - - @Override - @SuppressWarnings("deprecation") - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canStayAt(state, world, pos)) { - return Blocks.AIR.defaultBlockState(); - } else { - return state; - } - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - if (state.getValue(TOP)) { - return Lists.newArrayList(); - } - - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { - return Lists.newArrayList(new ItemStack(this)); - } else { - return Lists.newArrayList(); - } - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { - return true; - } - - @Override - public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { - return true; - } - - @Override - public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity( - level, - pos.getX() + 0.5, - pos.getY() + 0.5, - pos.getZ() + 0.5, - new ItemStack(this) - ); - level.addFreshEntity(item); - } - - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { - int rot = world.random.nextInt(4); - BlockState bs = this.defaultBlockState().setValue(ROTATION, rot); - BlocksHelper.setWithoutUpdate(world, pos, bs); - BlocksHelper.setWithoutUpdate(world, pos.above(), bs.setValue(TOP, true)); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseFenceBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseFenceBlock.java deleted file mode 100644 index 7b987c17..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseFenceBlock.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.FenceBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { - private final Block parent; - - public BaseFenceBlock(Block source) { - super(Properties.copy(source).noOcclusion()); - this.parent = source; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_FENCE, parentId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - String path = blockId.getPath(); - Optional pattern = Optional.empty(); - if (path.endsWith("_post")) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FENCE_POST, parentId); - } - if (path.endsWith("_side")) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FENCE_SIDE, parentId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post"); - ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side"); - registerBlockModel(postId, postId, blockState, modelCache); - registerBlockModel(sideId, sideId, blockState, modelCache); - - ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); - builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); - builder.part(sideId) - .setCondition(state -> state.getValue(EAST)) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideId) - .setCondition(state -> state.getValue(SOUTH)) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideId) - .setCondition(state -> state.getValue(WEST)) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()) - .setUVLock(true) - .add(); - builder.part(postId).add(); - - return builder.build(); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseFurnaceBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseFurnaceBlock.java deleted file mode 100644 index ba784476..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseFurnaceBlock.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.blockentities.BaseFurnaceBlockEntity; -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.registry.BaseBlockEntities; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.stats.Stats; -import net.minecraft.world.MenuProvider; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.FurnaceBlock; -import net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.entity.BlockEntityTicker; -import net.minecraft.world.level.block.entity.BlockEntityType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider, RenderLayerProvider { - public BaseFurnaceBlock(Block source) { - this(Properties.copy(source).lightLevel(state -> state.getValue(LIT) ? 13 : 0)); - } - - public BaseFurnaceBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { - return new BaseFurnaceBlockEntity(blockPos, blockState); - } - - @Override - protected void openContainer(Level world, BlockPos pos, Player player) { - BlockEntity blockEntity = world.getBlockEntity(pos); - if (blockEntity instanceof BaseFurnaceBlockEntity) { - player.openMenu((MenuProvider) blockEntity); - player.awardStat(Stats.INTERACT_WITH_FURNACE); - } - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - String blockName = blockId.getPath(); - Map textures = Maps.newHashMap(); - textures.put("%modid%", blockId.getNamespace()); - textures.put("%top%", blockName + "_top"); - textures.put("%side%", blockName + "_side"); - Optional pattern; - if (blockState.getValue(LIT)) { - textures.put("%front%", blockName + "_front_on"); - textures.put("%glow%", blockName + "_glow"); - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE_LIT, textures); - } else { - textures.put("%front%", blockName + "_front"); - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE, textures); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - String lit = blockState.getValue(LIT) ? "_lit" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + lit); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), false, true); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - List drop = Lists.newArrayList(new ItemStack(this)); - BlockEntity blockEntity = builder.getOptionalParameter(LootContextParams.BLOCK_ENTITY); - if (blockEntity instanceof BaseFurnaceBlockEntity) { - BaseFurnaceBlockEntity entity = (BaseFurnaceBlockEntity) blockEntity; - for (int i = 0; i < entity.getContainerSize(); i++) { - drop.add(entity.getItem(i)); - } - } - return drop; - } - - @Override - @Nullable - public BlockEntityTicker getTicker( - Level level, - BlockState blockState, - BlockEntityType blockEntityType - ) { - return createFurnaceTicker(level, blockEntityType, BaseBlockEntities.FURNACE); - } - - @Nullable - protected static BlockEntityTicker createFurnaceTicker( - Level level, - BlockEntityType blockEntityType, - BlockEntityType blockEntityType2 - ) { - return level.isClientSide ? null : createTickerHelper( - blockEntityType, - blockEntityType2, - AbstractFurnaceBlockEntity::serverTick - ); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseGateBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseGateBlock.java deleted file mode 100644 index 2ad552c0..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseGateBlock.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.FenceGateBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider { - private final Block parent; - - public BaseGateBlock(Block source) { - super(Properties.copy(source).noOcclusion()); - this.parent = source; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - boolean inWall = blockState.getValue(IN_WALL); - boolean isOpen = blockState.getValue(OPEN); - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern; - if (inWall) { - pattern = isOpen - ? PatternsHelper.createJson( - BasePatterns.BLOCK_GATE_OPEN_WALL, - parentId - ) - : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED_WALL, parentId); - } else { - pattern = isOpen - ? PatternsHelper.createJson( - BasePatterns.BLOCK_GATE_OPEN, - parentId - ) - : PatternsHelper.createJson(BasePatterns.BLOCK_GATE_CLOSED, parentId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - boolean inWall = blockState.getValue(IN_WALL); - boolean isOpen = blockState.getValue(OPEN); - String state = "" + (inWall ? "_wall" : "") + (isOpen ? "_open" : "_closed"); - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), true, false); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/blocks/BaseGlassBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseGlassBlock.java deleted file mode 100644 index 751e9684..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseGlassBlock.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.interfaces.tools.AddMineablePickaxe; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; - -public class BaseGlassBlock extends BaseBlockNotFull implements AddMineablePickaxe, RenderLayerProvider { - public BaseGlassBlock(Block block) { - this(block, 0.3f); - } - - public BaseGlassBlock(Block block, float resistance) { - super(Properties.copy(block) - .explosionResistance(resistance) - .noOcclusion() - .isSuffocating((arg1, arg2, arg3) -> false) - .isViewBlocking((arg1, arg2, arg3) -> false)); - } - - @Environment(EnvType.CLIENT) - public float getShadeBrightness(BlockState state, BlockGetter view, BlockPos pos) { - return 1.0F; - } - - @Override - public boolean propagatesSkylightDown(BlockState state, BlockGetter view, BlockPos pos) { - return true; - } - - @Environment(EnvType.CLIENT) - public boolean skipRendering(BlockState state, BlockState neighbor, Direction facing) { - return neighbor.getBlock() == this || super.skipRendering(state, neighbor, facing); - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { - return Collections.singletonList(new ItemStack(this)); - } - return Collections.emptyList(); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.TRANSLUCENT; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseLadderBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseLadderBlock.java deleted file mode 100644 index 6db903be..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseLadderBlock.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.LadderBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseLadderBlock extends LadderBlock implements RenderLayerProvider, BlockModelProvider { - public BaseLadderBlock(Block block) { - this(Properties.copy(block).noOcclusion()); - } - - public BaseLadderBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return ModelsHelper.createBlockItem(blockId); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_LADDER, blockId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), false, true); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseLeavesBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseLeavesBlock.java deleted file mode 100644 index 69018546..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseLeavesBlock.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.interfaces.TagProvider; -import org.betterx.bclib.interfaces.tools.AddMineableHoe; -import org.betterx.bclib.interfaces.tools.AddMineableShears; -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.MHelper; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.LeavesBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; - -import com.google.common.collect.Lists; - -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, RenderLayerProvider, TagProvider, AddMineableShears, AddMineableHoe { - protected final Block sapling; - - private static BlockBehaviour.Properties makeLeaves(MaterialColor color) { - return BlockBehaviour.Properties - .copy(Blocks.OAK_LEAVES) - .color(color) - //.requiresTool() - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false); - } - - public BaseLeavesBlock( - Block sapling, - MaterialColor color, - Consumer customizeProperties - ) { - super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color))); - this.sapling = sapling; - } - - public BaseLeavesBlock( - Block sapling, - MaterialColor color, - int light, - Consumer customizeProperties - ) { - super(BaseBlock.acceptAndReturn(customizeProperties, makeLeaves(color).lightLevel(state -> light))); - this.sapling = sapling; - } - - public BaseLeavesBlock(Block sapling, MaterialColor color) { - super(makeLeaves(color)); - this.sapling = sapling; - } - - public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { - super(makeLeaves(color).lightLevel(state -> light)); - this.sapling = sapling; - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return BaseLeavesBlock.getLeaveDrops(this, this.sapling, builder, 16, 16); - } - - public static List getLeaveDrops( - ItemLike leaveBlock, - Block sapling, - LootContext.Builder builder, - int fortuneRate, - int dropRate - ) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null) { - if (BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { - return Collections.singletonList(new ItemStack(leaveBlock)); - } - int fortune = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); - if (MHelper.RANDOM.nextInt(fortuneRate) <= fortune) { - return Lists.newArrayList(new ItemStack(sapling)); - } - return Lists.newArrayList(); - } - return MHelper.RANDOM.nextInt(dropRate) == 0 - ? Lists.newArrayList(new ItemStack(sapling)) - : Lists.newArrayList(); - } - - @Override - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - public void addTags(List> blockTags, List> itemTags) { - blockTags.add(BlockTags.LEAVES); - itemTags.add(ItemTags.LEAVES); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseMetalBarsBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseMetalBarsBlock.java deleted file mode 100644 index fd201df5..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseMetalBarsBlock.java +++ /dev/null @@ -1,129 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.IronBarsBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, RenderLayerProvider { - public BaseMetalBarsBlock(Block source) { - this(Properties.copy(source).strength(5.0F, 6.0F).noOcclusion()); - } - - public BaseMetalBarsBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - public Optional getModelString(String block) { - ResourceLocation blockId = Registry.BLOCK.getKey(this); - if (block.contains("item")) { - return PatternsHelper.createJson(BasePatterns.ITEM_BLOCK, blockId); - } - if (block.contains("post")) { - return PatternsHelper.createJson(BasePatterns.BLOCK_BARS_POST, blockId); - } else { - return PatternsHelper.createJson(BasePatterns.BLOCK_BARS_SIDE, blockId); - } - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createBlockItem(resourceLocation); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - ResourceLocation thisId = Registry.BLOCK.getKey(this); - String path = blockId.getPath(); - Optional pattern = Optional.empty(); - if (path.endsWith("_post")) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BARS_POST, thisId); - } - if (path.endsWith("_side")) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_BARS_SIDE, thisId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post"); - ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side"); - registerBlockModel(postId, postId, blockState, modelCache); - registerBlockModel(sideId, sideId, blockState, modelCache); - - ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); - builder.part(postId) - .setCondition(state -> !state.getValue(NORTH) && !state.getValue(EAST) && !state.getValue(SOUTH) && !state - .getValue(WEST)) - .add(); - builder.part(sideId).setCondition(state -> state.getValue(NORTH)).setUVLock(true).add(); - builder.part(sideId) - .setCondition(state -> state.getValue(EAST)) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideId) - .setCondition(state -> state.getValue(SOUTH)) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideId) - .setCondition(state -> state.getValue(WEST)) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()) - .setUVLock(true) - .add(); - - return builder.build(); - } - - @Environment(EnvType.CLIENT) - public boolean skipRendering(BlockState state, BlockState stateFrom, Direction direction) { - if (direction.getAxis().isVertical() && stateFrom.getBlock() == this && !stateFrom.equals(state)) { - return false; - } - return super.skipRendering(state, stateFrom, direction); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseOreBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseOreBlock.java deleted file mode 100644 index 57cd86ee..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseOreBlock.java +++ /dev/null @@ -1,148 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.TagProvider; -import org.betterx.bclib.util.LootUtil; -import org.betterx.bclib.util.MHelper; -import org.betterx.worlds.together.tag.v3.MineableTags; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.TagKey; -import net.minecraft.util.Mth; -import net.minecraft.util.valueproviders.UniformInt; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TieredItem; -import net.minecraft.world.item.Tiers; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.DropExperienceBlock; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; - -import java.util.Collections; -import java.util.List; -import java.util.function.Supplier; - -public class BaseOreBlock extends DropExperienceBlock implements BlockModelProvider, TagProvider { - private final Supplier dropItem; - private final int minCount; - private final int maxCount; - private final int miningLevel; - - public BaseOreBlock(Supplier drop, int minCount, int maxCount, int experience) { - this(drop, minCount, maxCount, experience, 0); - } - - public BaseOreBlock(Supplier drop, int minCount, int maxCount, int experience, int miningLevel) { - this( - Properties - .of(Material.STONE, MaterialColor.SAND) - .requiresCorrectToolForDrops() - .destroyTime(3F) - .explosionResistance(9F) - .sound(SoundType.STONE), - drop, minCount, maxCount, experience, miningLevel - ); - } - - public BaseOreBlock(Properties properties, Supplier drop, int minCount, int maxCount, int experience) { - this(properties, drop, minCount, maxCount, experience, 0); - } - - public BaseOreBlock( - Properties properties, - Supplier drop, - int minCount, - int maxCount, - int experience, - int miningLevel - ) { - super(properties, UniformInt.of(experience > 0 ? 1 : 0, experience)); - this.dropItem = drop; - this.minCount = minCount; - this.maxCount = maxCount; - this.miningLevel = miningLevel; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return LootUtil - .getDrops(this, state, builder) - .orElseGet( - () -> BaseOreBlock.getDroppedItems( - this, - dropItem.get(), - maxCount, - minCount, - miningLevel, - state, - builder - ) - ); - } - - public static List getDroppedItems( - ItemLike block, - Item dropItem, - int maxCount, - int minCount, - int miningLevel, - BlockState state, - LootContext.Builder builder - ) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && tool.isCorrectToolForDrops(state)) { - boolean canMine = miningLevel == 0; - if (tool.getItem() instanceof TieredItem tired) { - canMine = tired.getTier().getLevel() >= miningLevel; - } - if (canMine) { - if (EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { - return Collections.singletonList(new ItemStack(block)); - } - int count; - int enchantment = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); - if (enchantment > 0) { - int min = Mth.clamp(minCount + enchantment, minCount, maxCount); - int max = maxCount + (enchantment / Enchantments.BLOCK_FORTUNE.getMaxLevel()); - if (min == max) { - return Collections.singletonList(new ItemStack(dropItem, max)); - } - count = MHelper.randRange(min, max, MHelper.RANDOM_SOURCE); - } else { - count = MHelper.randRange(minCount, maxCount, MHelper.RANDOM_SOURCE); - } - return Collections.singletonList(new ItemStack(dropItem, count)); - } - } - return Collections.emptyList(); - } - - @Override - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - public void addTags(List> blockTags, List> itemTags) { - if (this.miningLevel == Tiers.STONE.getLevel()) { - blockTags.add(BlockTags.NEEDS_STONE_TOOL); - } else if (this.miningLevel == Tiers.IRON.getLevel()) { - blockTags.add(BlockTags.NEEDS_IRON_TOOL); - } else if (this.miningLevel == Tiers.DIAMOND.getLevel()) { - blockTags.add(BlockTags.NEEDS_DIAMOND_TOOL); - } else if (this.miningLevel == Tiers.NETHERITE.getLevel()) { - blockTags.add(MineableTags.NEEDS_NETHERITE_TOOL); - } - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BasePathBlock.java b/src/main/java/org/betterx/bclib/blocks/BasePathBlock.java deleted file mode 100644 index 409b78ea..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BasePathBlock.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Maps; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BasePathBlock extends BaseBlockNotFull { - private static final VoxelShape SHAPE = box(0, 0, 0, 16, 15, 16); - - private Block baseBlock; - - public BasePathBlock(Block source) { - super(Properties.copy(source).isValidSpawn((state, world, pos, type) -> false)); - this.baseBlock = Blocks.DIRT; - if (source instanceof BaseTerrainBlock) { - BaseTerrainBlock terrain = (BaseTerrainBlock) source; - this.baseBlock = terrain.getBaseBlock(); - terrain.setPathBlock(this); - } - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { - return Collections.singletonList(new ItemStack(this)); - } - return Collections.singletonList(new ItemStack(Blocks.END_STONE)); - } - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPE; - } - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getCollisionShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPE; - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return getBlockModel(blockId, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - String name = blockId.getPath(); - ResourceLocation bottomId = Registry.BLOCK.getKey(baseBlock); - String bottom = bottomId.getNamespace() + ":block/" + bottomId.getPath(); - Map textures = Maps.newHashMap(); - textures.put("%modid%", blockId.getNamespace()); - textures.put("%top%", name + "_top"); - textures.put("%side%", name.replace("_path", "") + "_side"); - textures.put("%bottom%", bottom); - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PATH, textures); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createRandomTopModel(modelId); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BasePlantBlock.java b/src/main/java/org/betterx/bclib/blocks/BasePlantBlock.java deleted file mode 100644 index fdcc3cc4..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BasePlantBlock.java +++ /dev/null @@ -1,206 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.interfaces.SettingsExtender; -import org.betterx.bclib.items.tool.BaseShearsItem; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.BonemealableBlock; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; - -import java.util.List; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { - public static Properties basePlantSettings() { - return basePlantSettings(false, 0); - } - - public static Properties basePlantSettings(int light) { - return basePlantSettings(false, light); - } - - public static Properties basePlantSettings(boolean replaceable) { - return basePlantSettings(replaceable, 0); - } - - public static Properties basePlantSettings(boolean replaceable, int light) { - return basePlantSettings(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT, light); - } - - public static Properties basePlantSettings(Material mat, int light) { - Properties props = Properties - .of(mat) - .sound(SoundType.GRASS) - .noCollission() - .offsetType(BlockBehaviour.OffsetType.XZ); - if (light > 0) props.lightLevel(s -> light); - return props; - } - - private static final VoxelShape SHAPE = box(4, 0, 4, 12, 14, 12); - - public BasePlantBlock() { - this(basePlantSettings()); - } - - public BasePlantBlock(int light) { - this(basePlantSettings(light)); - } - - @Deprecated(forRemoval = true) - public BasePlantBlock(int light, SettingsExtender propMod) { - this(false, light, propMod); - } - - public BasePlantBlock(boolean replaceable) { - this(basePlantSettings(replaceable)); - } - - @Deprecated(forRemoval = true) - public BasePlantBlock(boolean replaceable, SettingsExtender propMod) { - this(replaceable, 0, propMod); - } - - - public BasePlantBlock(boolean replaceable, int light) { - this(basePlantSettings(replaceable, light)); - } - - @Deprecated(forRemoval = true) - public BasePlantBlock(boolean replaceable, int light, SettingsExtender propMod) { - this( - propMod.amend(Properties - .of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) - .lightLevel((state)->light) - .sound(SoundType.GRASS) - .noCollission() - .offsetType(BlockBehaviour.OffsetType.XZ) - ) - ); - } - - protected BasePlantBlock(Properties settings) { - super(settings); - } - - protected abstract boolean isTerrain(BlockState state); - - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - Vec3 vec3d = state.getOffset(view, pos); - return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); - } - - @Override - @SuppressWarnings("deprecation") - public boolean canSurvive(BlockState state, LevelReader level, BlockPos pos) { - BlockState down = level.getBlockState(pos.below()); - return isTerrain(down); - } - - @Override - @SuppressWarnings("deprecation") - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) { - return Blocks.AIR.defaultBlockState(); - } else { - return state; - } - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { - return Lists.newArrayList(new ItemStack(this)); - } else { - return Lists.newArrayList(); - } - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { - return true; - } - - @Override - public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { - return true; - } - - @Override - public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity( - level, - pos.getX() + 0.5, - pos.getY() + 0.5, - pos.getZ() + 0.5, - new ItemStack(this) - ); - level.addFreshEntity(item); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createBlockItem(resourceLocation); - } - - @Override - @Nullable - @Environment(EnvType.CLIENT) - public BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS, resourceLocation); - return ModelsHelper.fromPattern(pattern); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BasePlantWithAgeBlock.java b/src/main/java/org/betterx/bclib/blocks/BasePlantWithAgeBlock.java deleted file mode 100644 index d1b56fa2..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BasePlantWithAgeBlock.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.IntegerProperty; - -import java.util.function.Function; - -public abstract class BasePlantWithAgeBlock extends BasePlantBlock { - public static final IntegerProperty AGE = BlockProperties.AGE; - - public BasePlantWithAgeBlock() { - this(p -> p); - } - - @Deprecated(forRemoval = true) - public BasePlantWithAgeBlock(Function propMod) { - this(propMod.apply(basePlantSettings().randomTicks())); - } - - protected BasePlantWithAgeBlock(Properties settings) { - super(settings); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(AGE); - } - - public abstract void growAdult(WorldGenLevel world, RandomSource random, BlockPos pos); - - @Override - public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) { - int age = state.getValue(AGE); - if (age < 3) { - level.setBlockAndUpdate(pos, state.setValue(AGE, age + 1)); - } else { - growAdult(level, random, pos); - } - } - - @Override - public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { - return true; - } - - @Override - @SuppressWarnings("deprecation") - public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - super.tick(state, world, pos, random); - if (random.nextInt(8) == 0) { - performBonemeal(world, random, pos, state); - } - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BasePressurePlateBlock.java b/src/main/java/org/betterx/bclib/blocks/BasePressurePlateBlock.java deleted file mode 100644 index 8f851e52..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BasePressurePlateBlock.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.PressurePlateBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelProvider { - private final Block parent; - - public BasePressurePlateBlock(Sensitivity rule, Block source) { - super(rule, Properties.copy(source).noCollission().noOcclusion().strength(0.5F)); - this.parent = source; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern; - if (blockState.getValue(POWERED)) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); - } else { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - String state = blockState.getValue(POWERED) ? "_down" : "_up"; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createBlockSimple(modelId); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseRotatedPillarBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseRotatedPillarBlock.java deleted file mode 100644 index 7731088d..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseRotatedPillarBlock.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.RotatedPillarBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelProvider { - public BaseRotatedPillarBlock(Properties settings) { - super(settings); - } - - public BaseRotatedPillarBlock(Block block) { - this(Properties.copy(block)); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return getBlockModel(blockId, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - Optional pattern = createBlockPattern(blockId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createRotatedModel(modelId, blockState.getValue(AXIS)); - } - - protected Optional createBlockPattern(ResourceLocation blockId) { - return PatternsHelper.createBlockPillar(blockId); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseSignBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseSignBlock.java deleted file mode 100644 index 57a3a1bd..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseSignBlock.java +++ /dev/null @@ -1,199 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.blockentities.BaseSignBlockEntity; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.CustomItemProvider; -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.network.protocol.game.ClientboundOpenSignEditorPacket; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.block.state.properties.BooleanProperty; -import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraft.world.level.block.state.properties.WoodType; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import org.jetbrains.annotations.Nullable; - -@SuppressWarnings("deprecation") -public class BaseSignBlock extends SignBlock implements BlockModelProvider, CustomItemProvider { - public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16; - public static final BooleanProperty FLOOR = BooleanProperty.create("floor"); - private static final VoxelShape[] WALL_SHAPES = new VoxelShape[]{ - Block.box(0.0D, 4.5D, 14.0D, 16.0D, 12.5D, 16.0D), - Block.box(0.0D, 4.5D, 0.0D, 2.0D, 12.5D, 16.0D), - Block.box(0.0D, 4.5D, 0.0D, 16.0D, 12.5D, 2.0D), - Block.box(14.0D, 4.5D, 0.0D, 16.0D, 12.5D, 16.0D) - }; - - private final Block parent; - - public BaseSignBlock(Block source) { - super(Properties.copy(source).strength(1.0F, 1.0F).noCollission().noOcclusion(), WoodType.OAK); - this.registerDefaultState(this.stateDefinition.any() - .setValue(ROTATION, 0) - .setValue(FLOOR, false) - .setValue(WATERLOGGED, false)); - this.parent = source; - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder builder) { - builder.add(ROTATION, FLOOR, WATERLOGGED); - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return state.getValue(FLOOR) ? SHAPE : WALL_SHAPES[state.getValue(ROTATION) >> 2]; - } - - @Override - public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { - return new BaseSignBlockEntity(blockPos, blockState); - } - - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { - if (placer instanceof Player) { - BaseSignBlockEntity sign = (BaseSignBlockEntity) world.getBlockEntity(pos); - if (sign != null) { - if (!world.isClientSide) { - sign.setAllowedPlayerEditor(placer.getUUID()); - ((ServerPlayer) placer).connection.send(new ClientboundOpenSignEditorPacket(pos)); - } else { - sign.setEditable(true); - } - } - } - } - - @Override - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (state.getValue(WATERLOGGED)) { - world.scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); - } - if (!canSurvive(state, world, pos)) { - return state.getValue(WATERLOGGED) - ? state.getFluidState().createLegacyBlock() - : Blocks.AIR.defaultBlockState(); - } - return super.updateShape(state, facing, neighborState, world, pos, neighborPos); - } - - @Override - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - if (!state.getValue(FLOOR)) { - int index = (((state.getValue(ROTATION) >> 2) + 2)) & 3; - return world.getBlockState(pos.relative(BlocksHelper.HORIZONTAL[index])).getMaterial().isSolid(); - } else { - return world.getBlockState(pos.below()).getMaterial().isSolid(); - } - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - if (ctx.getClickedFace() == Direction.UP) { - FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); - return this - .defaultBlockState() - .setValue(FLOOR, true) - .setValue(ROTATION, Mth.floor((180.0 + ctx.getRotation() * 16.0 / 360.0) + 0.5 - 12) & 15) - .setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); - } else if (ctx.getClickedFace() != Direction.DOWN) { - BlockState blockState = this.defaultBlockState(); - FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); - LevelReader worldView = ctx.getLevel(); - BlockPos blockPos = ctx.getClickedPos(); - Direction[] directions = ctx.getNearestLookingDirections(); - - for (Direction direction : directions) { - if (direction.getAxis().isHorizontal()) { - Direction dir = direction.getOpposite(); - int rot = Mth.floor((180.0 + dir.toYRot() * 16.0 / 360.0) + 0.5 + 4) & 15; - blockState = blockState.setValue(ROTATION, rot); - if (blockState.canSurvive(worldView, blockPos)) { - return blockState.setValue(FLOOR, false) - .setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); - } - } - } - } - - return null; - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - return ModelsHelper.createBlockEmpty(parentId); - } - - @Override - public BlockState rotate(BlockState state, Rotation rotation) { - return state.setValue(ROTATION, rotation.rotate(state.getValue(ROTATION), 16)); - } - - @Override - public BlockState mirror(BlockState state, Mirror mirror) { - return state.setValue(ROTATION, mirror.mirror(state.getValue(ROTATION), 16)); - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { - return super.canPlaceLiquid(world, pos, state, fluid); - } - - @Override - public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { - return super.placeLiquid(world, pos, state, fluidState); - } - - @Override - public BlockItem getCustomItem(ResourceLocation blockID, Item.Properties settings) { - return new BlockItem(this, settings.stacksTo(16)); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/blocks/BaseSlabBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseSlabBlock.java deleted file mode 100644 index 96631d99..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseSlabBlock.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.CustomItemProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.SlabBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.SlabType; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseSlabBlock extends SlabBlock implements BlockModelProvider, CustomItemProvider { - private final Block parent; - public final boolean fireproof; - - public BaseSlabBlock(Block source) { - this(source, false); - } - - public BaseSlabBlock(Block source, boolean fireproof) { - super(Properties.copy(source)); - this.parent = source; - this.fireproof = fireproof; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - int count = state.getValue(TYPE) == SlabType.DOUBLE ? 2 : 1; - return Collections.singletonList(new ItemStack(this, count)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern; - if (blockState.getValue(TYPE) == SlabType.DOUBLE) { - pattern = PatternsHelper.createBlockSimple(parentId); - } else { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_SLAB, parentId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - SlabType type = blockState.getValue(TYPE); - ResourceLocation modelId = new ResourceLocation( - stateId.getNamespace(), - "block/" + stateId.getPath() + "_" + type - ); - registerBlockModel(stateId, modelId, blockState, modelCache); - if (type == SlabType.TOP) { - return ModelsHelper.createMultiVariant(modelId, BlockModelRotation.X180_Y0.getRotation(), true); - } - return ModelsHelper.createBlockSimple(modelId); - } - - @Override - public BlockItem getCustomItem(ResourceLocation blockID, Item.Properties settings) { - if (fireproof) settings = settings.fireResistant(); - return new BlockItem(this, settings); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseStairsBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseStairsBlock.java deleted file mode 100644 index 06342f76..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseStairsBlock.java +++ /dev/null @@ -1,120 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.CustomItemProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.StairBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.Half; -import net.minecraft.world.level.block.state.properties.StairsShape; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseStairsBlock extends StairBlock implements BlockModelProvider, CustomItemProvider { - private final Block parent; - public final boolean fireproof; - - public BaseStairsBlock(Block source) { - this(source, false); - } - - public BaseStairsBlock(Block source, boolean fireproof) { - super(source.defaultBlockState(), Properties.copy(source)); - this.parent = source; - this.fireproof = fireproof; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern = PatternsHelper.createJson(switch (blockState.getValue(SHAPE)) { - case STRAIGHT -> BasePatterns.BLOCK_STAIR; - case INNER_LEFT, INNER_RIGHT -> BasePatterns.BLOCK_STAIR_INNER; - case OUTER_LEFT, OUTER_RIGHT -> BasePatterns.BLOCK_STAIR_OUTER; - }, parentId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - String state; - StairsShape shape = blockState.getValue(SHAPE); - state = switch (shape) { - case INNER_LEFT, INNER_RIGHT -> "_inner"; - case OUTER_LEFT, OUTER_RIGHT -> "_outer"; - default -> ""; - }; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); - registerBlockModel(stateId, modelId, blockState, modelCache); - - boolean isTop = blockState.getValue(HALF) == Half.TOP; - boolean isLeft = shape == StairsShape.INNER_LEFT || shape == StairsShape.OUTER_LEFT; - boolean isRight = shape == StairsShape.INNER_RIGHT || shape == StairsShape.OUTER_RIGHT; - int y = 0; - int x = isTop ? 180 : 0; - switch (blockState.getValue(FACING)) { - case NORTH: - if (isTop && !isRight) y = 270; - else if (!isTop) y = isLeft ? 180 : 270; - break; - case EAST: - if (isTop && isRight) y = 90; - else if (!isTop && isLeft) y = 270; - break; - case SOUTH: - if (isTop) y = isRight ? 180 : 90; - else if (!isLeft) y = 90; - break; - case WEST: - default: - y = (isTop && isRight) ? 270 : (!isTop && isLeft) ? 90 : 180; - break; - } - BlockModelRotation rotation = BlockModelRotation.by(x, y); - return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), true); - } - - @Override - public BlockItem getCustomItem(ResourceLocation blockID, Item.Properties settings) { - if (fireproof) settings = settings.fireResistant(); - return new BlockItem(this, settings); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseStoneButtonBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseStoneButtonBlock.java deleted file mode 100644 index 901f4469..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseStoneButtonBlock.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.level.block.Block; - - -public class BaseStoneButtonBlock extends BaseButtonBlock { - public BaseStoneButtonBlock(Block source) { - super(source, Properties.copy(source).noOcclusion(), false); - } - - @Override - protected SoundEvent getSound(boolean clicked) { - return clicked ? SoundEvents.STONE_BUTTON_CLICK_ON : SoundEvents.STONE_BUTTON_CLICK_OFF; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseStripableLogBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseStripableLogBlock.java deleted file mode 100644 index 46863349..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseStripableLogBlock.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.worlds.together.tag.v3.MineableTags; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.RotatedPillarBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.phys.BlockHitResult; - - -public class BaseStripableLogBlock extends BaseRotatedPillarBlock { - private final Block striped; - - public BaseStripableLogBlock(MaterialColor color, Block striped) { - super(Properties.copy(striped).color(color)); - this.striped = striped; - } - - @Override - @SuppressWarnings("deprecation") - public InteractionResult use( - BlockState state, - Level world, - BlockPos pos, - Player player, - InteractionHand hand, - BlockHitResult hit - ) { - if (TagManager.isToolWithMineableTag(player.getMainHandItem(), MineableTags.AXE)) { - world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); - if (!world.isClientSide) { - world.setBlock( - pos, - striped.defaultBlockState() - .setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), - 11 - ); - if (!player.isCreative()) { - player.getMainHandItem().hurt(1, world.random, (ServerPlayer) player); - } - } - return InteractionResult.SUCCESS; - } - return InteractionResult.FAIL; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseTerrainBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseTerrainBlock.java deleted file mode 100644 index 912fd404..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseTerrainBlock.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.sound.BlockSounds; -import org.betterx.worlds.together.tag.v3.MineableTags; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.util.RandomSource; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.SnowLayerBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.lighting.LayerLightEngine; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.BlockHitResult; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Maps; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -@SuppressWarnings("deprecation") -public class BaseTerrainBlock extends BaseBlock { - private final Block baseBlock; - private Block pathBlock; - - public BaseTerrainBlock(Block baseBlock, MaterialColor color) { - super(Properties - .copy(baseBlock) - .color(color) - .sound(BlockSounds.TERRAIN_SOUND) - .randomTicks() - ); - this.baseBlock = baseBlock; - } - - public void setPathBlock(Block roadBlock) { - this.pathBlock = roadBlock; - } - - public Block getBaseBlock() { - return baseBlock; - } - - @Override - public InteractionResult use( - BlockState state, - Level world, - BlockPos pos, - Player player, - InteractionHand hand, - BlockHitResult hit - ) { - if (pathBlock != null && TagManager.isToolWithMineableTag(player.getMainHandItem(), MineableTags.SHOVEL)) { - world.playSound(player, pos, SoundEvents.SHOVEL_FLATTEN, SoundSource.BLOCKS, 1.0F, 1.0F); - if (!world.isClientSide) { - world.setBlockAndUpdate(pos, pathBlock.defaultBlockState()); - if (!player.isCreative()) { - player.getMainHandItem().hurt(1, world.random, (ServerPlayer) player); - } - } - return InteractionResult.SUCCESS; - } - return InteractionResult.FAIL; - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { - return Collections.singletonList(new ItemStack(this)); - } - return Collections.singletonList(new ItemStack(getBaseBlock())); - } - - @Override - public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - if (random.nextInt(16) == 0 && !canStay(state, world, pos)) { - world.setBlockAndUpdate(pos, getBaseBlock().defaultBlockState()); - } - } - - public boolean canStay(BlockState state, LevelReader worldView, BlockPos pos) { - BlockPos blockPos = pos.above(); - BlockState blockState = worldView.getBlockState(blockPos); - if (blockState.is(Blocks.SNOW) && blockState.getValue(SnowLayerBlock.LAYERS) == 1) { - return true; - } else if (blockState.getFluidState().getAmount() == 8) { - return false; - } else { - int i = LayerLightEngine.getLightBlockInto( - worldView, - state, - pos, - blockState, - blockPos, - Direction.UP, - blockState.getLightBlock(worldView, blockPos) - ); - return i < 5; - } - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return getBlockModel(blockId, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - ResourceLocation baseId = Registry.BLOCK.getKey(getBaseBlock()); - String modId = blockId.getNamespace(); - String path = blockId.getPath(); - String bottom = baseId.getNamespace() + ":block/" + baseId.getPath(); - Map textures = Maps.newHashMap(); - textures.put("%top%", modId + ":block/" + path + "_top"); - textures.put("%side%", modId + ":block/" + path + "_side"); - textures.put("%bottom%", bottom); - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TOP_SIDE_BOTTOM, textures); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createRandomTopModel(modelId); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseTrapdoorBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseTrapdoorBlock.java deleted file mode 100644 index a105cc81..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseTrapdoorBlock.java +++ /dev/null @@ -1,105 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.TrapDoorBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.Half; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.*; -import org.jetbrains.annotations.Nullable; - -public class BaseTrapdoorBlock extends TrapDoorBlock implements RenderLayerProvider, BlockModelProvider { - public BaseTrapdoorBlock(Block source) { - this(Properties.copy(source).strength(3.0F, 3.0F).noOcclusion()); - } - - public BaseTrapdoorBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - String name = resourceLocation.getPath(); - Optional pattern = PatternsHelper.createJson( - BasePatterns.BLOCK_TRAPDOOR, - new HashMap() { - private static final long serialVersionUID = 1L; - - { - put("%modid%", resourceLocation.getNamespace()); - put("%texture%", name); - put("%side%", name.replace("trapdoor", "door_side")); - } - } - ); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - boolean isTop = blockState.getValue(HALF) == Half.TOP; - boolean isOpen = blockState.getValue(OPEN); - int y = 0; - int x = (isTop && isOpen) ? 270 : isTop ? 180 : isOpen ? 90 : 0; - switch (blockState.getValue(FACING)) { - case EAST: - y = (isTop && isOpen) ? 270 : 90; - break; - case NORTH: - if (isTop && isOpen) y = 180; - break; - case SOUTH: - y = (isTop && isOpen) ? 0 : 180; - break; - case WEST: - y = (isTop && isOpen) ? 90 : 270; - break; - default: - break; - } - BlockModelRotation rotation = BlockModelRotation.by(x, y); - return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseUnderwaterWallPlantBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseUnderwaterWallPlantBlock.java deleted file mode 100644 index 389e9fdc..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseUnderwaterWallPlantBlock.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.LiquidBlockContainer; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.material.Fluids; - -public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock implements LiquidBlockContainer { - - public BaseUnderwaterWallPlantBlock() { - this(0); - } - - public BaseUnderwaterWallPlantBlock(int light) { - this( - UnderwaterPlantBlock.baseUnderwaterPlantSettings(light) - ); - } - - public BaseUnderwaterWallPlantBlock(Properties settings) { - super(settings); - } - - @Override - public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { - return false; - } - - @Override - public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { - return false; - } - - @Override - @SuppressWarnings("deprecation") - public FluidState getFluidState(BlockState state) { - return Fluids.WATER.getSource(false); - } - - @Override - public boolean canSurvive(BlockState state, LevelReader level, BlockPos pos) { - return level.getFluidState(pos).getType() == Fluids.WATER && super.canSurvive(state, level, pos); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseVineBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseVineBlock.java deleted file mode 100644 index 88755554..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseVineBlock.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.blocks.BlockProperties.TripleShape; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.tags.BlockTags; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.BonemealableBlock; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.EnumProperty; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import com.google.common.collect.Lists; - -import java.util.List; -import java.util.function.Function; - -@SuppressWarnings("deprecation") -public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { - public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; - private static final VoxelShape VOXEL_SHAPE = box(2, 0, 2, 14, 16, 14); - - public BaseVineBlock() { - this(0, false); - } - - public BaseVineBlock(int light) { - this(light, false); - } - - public BaseVineBlock(int light, boolean bottomOnly) { - this(light, bottomOnly, p -> p); - } - - public BaseVineBlock(int light, boolean bottomOnly, Function propMod) { - this( - propMod.apply(Properties - .of(Material.PLANT) - .sound(SoundType.GRASS) - .lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM - ? light - : 0 : light) - .noCollission() - .offsetType(BlockBehaviour.OffsetType.XZ)) - ); - } - - public BaseVineBlock(BlockBehaviour.Properties properties) { - super(properties.offsetType(BlockBehaviour.OffsetType.XZ)); - this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, TripleShape.BOTTOM)); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(SHAPE); - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - Vec3 vec3d = state.getOffset(view, pos); - return VOXEL_SHAPE.move(vec3d.x, vec3d.y, vec3d.z); - } - - public boolean canGenerate(BlockState state, LevelReader world, BlockPos pos) { - return isSupport(state, world, pos); - } - - @Override - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - return isSupport(state, world, pos); - } - - protected boolean isSupport(BlockState state, LevelReader world, BlockPos pos) { - BlockState up = world.getBlockState(pos.above()); - return up.is(this) || up.is(BlockTags.LEAVES) || canSupportCenter(world, pos.above(), Direction.DOWN); - } - - @Override - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) { - return Blocks.AIR.defaultBlockState(); - } else { - if (world.getBlockState(pos.below()).getBlock() != this) return state.setValue(SHAPE, TripleShape.BOTTOM); - else if (world.getBlockState(pos.above()).getBlock() != this) return state.setValue(SHAPE, TripleShape.TOP); - return state.setValue(SHAPE, TripleShape.MIDDLE); - } - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { - return Lists.newArrayList(new ItemStack(this)); - } else { - return Lists.newArrayList(); - } - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { - while (world.getBlockState(pos).getBlock() == this) { - pos = pos.below(); - } - return world.getBlockState(pos).isAir(); - } - - @Override - public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { - while (level.getBlockState(pos).getBlock() == this) { - pos = pos.below(); - } - return level.isEmptyBlock(pos); - } - - @Override - public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) { - while (level.getBlockState(pos).getBlock() == this) { - pos = pos.below(); - } - level.setBlockAndUpdate(pos, defaultBlockState()); - BlocksHelper.setWithoutUpdate(level, pos, defaultBlockState()); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseWallBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseWallBlock.java deleted file mode 100644 index f3d25754..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseWallBlock.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.WallBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.WallSide; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseWallBlock extends WallBlock implements BlockModelProvider { - private final Block parent; - - public BaseWallBlock(Block source) { - super(Properties.copy(source).noOcclusion()); - this.parent = source; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_WALL, parentId); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - String path = blockId.getPath(); - Optional pattern = Optional.empty(); - if (path.endsWith("_post")) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_WALL_POST, parentId); - } - if (path.endsWith("_side")) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_WALL_SIDE, parentId); - } - if (path.endsWith("_side_tall")) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_WALL_SIDE_TALL, parentId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation postId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_post"); - ResourceLocation sideId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + "_side"); - ResourceLocation sideTallId = new ResourceLocation( - stateId.getNamespace(), - "block/" + stateId.getPath() + "_side_tall" - ); - registerBlockModel(postId, postId, blockState, modelCache); - registerBlockModel(sideId, sideId, blockState, modelCache); - registerBlockModel(sideTallId, sideTallId, blockState, modelCache); - - ModelsHelper.MultiPartBuilder builder = ModelsHelper.MultiPartBuilder.create(stateDefinition); - builder.part(sideId).setCondition(state -> state.getValue(NORTH_WALL) == WallSide.LOW).setUVLock(true).add(); - builder.part(sideId) - .setCondition(state -> state.getValue(EAST_WALL) == WallSide.LOW) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideId) - .setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.LOW) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideId) - .setCondition(state -> state.getValue(WEST_WALL) == WallSide.LOW) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideTallId) - .setCondition(state -> state.getValue(NORTH_WALL) == WallSide.TALL) - .setUVLock(true) - .add(); - builder.part(sideTallId) - .setCondition(state -> state.getValue(EAST_WALL) == WallSide.TALL) - .setTransformation(BlockModelRotation.X0_Y90.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideTallId) - .setCondition(state -> state.getValue(SOUTH_WALL) == WallSide.TALL) - .setTransformation(BlockModelRotation.X0_Y180.getRotation()) - .setUVLock(true) - .add(); - builder.part(sideTallId) - .setCondition(state -> state.getValue(WEST_WALL) == WallSide.TALL) - .setTransformation(BlockModelRotation.X0_Y270.getRotation()) - .setUVLock(true) - .add(); - builder.part(postId).setCondition(state -> state.getValue(UP)).add(); - - return builder.build(); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseWallPlantBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseWallPlantBlock.java deleted file mode 100644 index 06bed55b..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseWallPlantBlock.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.DirectionProperty; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; - -import java.util.EnumMap; - -public abstract class BaseWallPlantBlock extends BasePlantBlock { - private static final EnumMap SHAPES = Maps.newEnumMap(ImmutableMap.of( - Direction.NORTH, box(1, 1, 8, 15, 15, 16), - Direction.SOUTH, box(1, 1, 0, 15, 15, 8), - Direction.WEST, box(8, 1, 1, 16, 15, 15), - Direction.EAST, box(0, 1, 1, 8, 15, 15) - )); - public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; - - public BaseWallPlantBlock() { - this(basePlantSettings()); - } - - public BaseWallPlantBlock(int light) { - this(basePlantSettings(light)); - } - - protected BaseWallPlantBlock(Properties settings) { - super(settings.offsetType(OffsetType.NONE)); - } - - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(FACING); - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPES.get(state.getValue(FACING)); - } - - @Override - public boolean canSurvive(BlockState state, LevelReader level, BlockPos pos) { - Direction direction = state.getValue(FACING); - BlockPos blockPos = pos.relative(direction.getOpposite()); - BlockState blockState = level.getBlockState(blockPos); - return isSupport(level, blockPos, blockState, direction); - } - - public boolean isSupport(LevelReader world, BlockPos pos, BlockState blockState, Direction direction) { - return blockState.getMaterial().isSolid() && blockState.isFaceSturdy(world, pos, direction); - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - BlockState blockState = this.defaultBlockState(); - LevelReader worldView = ctx.getLevel(); - BlockPos blockPos = ctx.getClickedPos(); - Direction[] directions = ctx.getNearestLookingDirections(); - for (Direction direction : directions) { - if (direction.getAxis().isHorizontal()) { - Direction direction2 = direction.getOpposite(); - blockState = blockState.setValue(FACING, direction2); - if (blockState.canSurvive(worldView, blockPos)) { - return blockState; - } - } - } - return null; - } - - @Override - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) { - return Blocks.AIR.defaultBlockState(); - } else { - return state; - } - } - - @Override - @SuppressWarnings("deprecation") - public BlockState rotate(BlockState state, Rotation rotation) { - return BlocksHelper.rotateHorizontal(state, rotation, FACING); - } - - @Override - @SuppressWarnings("deprecation") - public BlockState mirror(BlockState state, Mirror mirror) { - return BlocksHelper.mirrorHorizontal(state, mirror, FACING); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseWeightedPlateBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseWeightedPlateBlock.java deleted file mode 100644 index 3bc48542..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseWeightedPlateBlock.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.BlockModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.WeightedPressurePlateBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelProvider { - private final Block parent; - - public BaseWeightedPlateBlock(Block source) { - super( - 15, - Properties.copy(source) - .noCollission() - .noOcclusion() - .requiresCorrectToolForDrops() - .strength(0.5F) - ); - this.parent = source; - } - - @Override - @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return getBlockModel(resourceLocation, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - ResourceLocation parentId = Registry.BLOCK.getKey(parent); - Optional pattern; - if (blockState.getValue(POWER) > 0) { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); - } else { - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_UP, parentId); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - String state = blockState.getValue(POWER) > 0 ? "_down" : "_up"; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + state); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createBlockSimple(modelId); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BaseWoodenButtonBlock.java b/src/main/java/org/betterx/bclib/blocks/BaseWoodenButtonBlock.java deleted file mode 100644 index 73569534..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BaseWoodenButtonBlock.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.sounds.SoundEvent; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.level.block.Block; - - -public class BaseWoodenButtonBlock extends BaseButtonBlock { - public BaseWoodenButtonBlock(Block source) { - super(source, Properties.copy(source).strength(0.5F, 0.5F).noOcclusion(), true); - } - - @Override - protected SoundEvent getSound(boolean clicked) { - return clicked ? SoundEvents.WOODEN_BUTTON_CLICK_ON : SoundEvents.WOODEN_BUTTON_CLICK_OFF; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/BlockProperties.java b/src/main/java/org/betterx/bclib/blocks/BlockProperties.java deleted file mode 100644 index 50a02974..00000000 --- a/src/main/java/org/betterx/bclib/blocks/BlockProperties.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.util.StringRepresentable; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.block.state.properties.BooleanProperty; -import net.minecraft.world.level.block.state.properties.EnumProperty; -import net.minecraft.world.level.block.state.properties.IntegerProperty; - -public class BlockProperties { - public static final EnumProperty TRIPLE_SHAPE = EnumProperty.create("shape", TripleShape.class); - public static final EnumProperty PENTA_SHAPE = EnumProperty.create("shape", PentaShape.class); - - public static final BooleanProperty TRANSITION = BooleanProperty.create("transition"); - public static final BooleanProperty HAS_LIGHT = BooleanProperty.create("has_light"); - public static final BooleanProperty IS_FLOOR = BooleanProperty.create("is_floor"); - public static final BooleanProperty NATURAL = BooleanProperty.create("natural"); - public static final BooleanProperty ACTIVE = BooleanProperty.create("active"); - public static final BooleanProperty SMALL = BooleanProperty.create("small"); - - public static final IntegerProperty DEFAULT_ANVIL_DURABILITY = IntegerProperty.create("durability", 0, 3); - public static final IntegerProperty DESTRUCTION = IntegerProperty.create("destruction", 0, 2); - public static final IntegerProperty ROTATION = IntegerProperty.create("rotation", 0, 3); - public static final IntegerProperty FULLNESS = IntegerProperty.create("fullness", 0, 3); - public static final IntegerProperty COLOR = IntegerProperty.create("color", 0, 7); - public static final IntegerProperty SIZE = IntegerProperty.create("size", 0, 7); - public static final IntegerProperty AGE = BlockStateProperties.AGE_3; - public static final IntegerProperty AGE_THREE = BlockStateProperties.AGE_2; - public static final BooleanProperty BOTTOM = BooleanProperty.create("bottom"); - public static final BooleanProperty TOP = BooleanProperty.create("top"); - - public enum TripleShape implements StringRepresentable { - TOP("top", 0), MIDDLE("middle", 1), BOTTOM("bottom", 2); - - private final String name; - private final int index; - - TripleShape(String name, int index) { - this.name = name; - this.index = index; - } - - @Override - public String getSerializedName() { - return name; - } - - @Override - public String toString() { - return name; - } - - public int getIndex() { - return index; - } - - public static TripleShape fromIndex(int index) { - return index > 1 ? BOTTOM : index == 1 ? MIDDLE : TOP; - } - } - - public enum PentaShape implements StringRepresentable { - BOTTOM("bottom"), PRE_BOTTOM("pre_bottom"), MIDDLE("middle"), PRE_TOP("pre_top"), TOP("top"); - - private final String name; - - PentaShape(String name) { - this.name = name; - } - - @Override - public String getSerializedName() { - return name; - } - - @Override - public String toString() { - return name; - } - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/FeatureHangingSaplingBlock.java b/src/main/java/org/betterx/bclib/blocks/FeatureHangingSaplingBlock.java deleted file mode 100644 index b42a8bce..00000000 --- a/src/main/java/org/betterx/bclib/blocks/FeatureHangingSaplingBlock.java +++ /dev/null @@ -1,47 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -public abstract class FeatureHangingSaplingBlock, FC extends FeatureConfiguration> extends FeatureSaplingBlock { - - private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); - - public FeatureHangingSaplingBlock(FeatureSupplier featureSupplier) { - super(featureSupplier); - } - - public FeatureHangingSaplingBlock( - FeatureSupplier featureSupplier, - int light - ) { - super(light, featureSupplier); - } - - public FeatureHangingSaplingBlock( - BlockBehaviour.Properties properties, - FeatureSupplier featureSupplier - ) { - super(properties, featureSupplier); - } - - @Override - public boolean canSurvive(BlockState blockState, LevelReader levelReader, BlockPos blockPos) { - final BlockPos target = blockPos.above(); - return this.mayPlaceOn(levelReader.getBlockState(target), levelReader, target); - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPE; - } - -} diff --git a/src/main/java/org/betterx/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/org/betterx/bclib/blocks/FeatureSaplingBlock.java deleted file mode 100644 index 075d4736..00000000 --- a/src/main/java/org/betterx/bclib/blocks/FeatureSaplingBlock.java +++ /dev/null @@ -1,151 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.api.v3.levelgen.features.BCLConfigureFeature; -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.RenderLayerProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.SaplingBlock; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.configurations.FeatureConfiguration; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class FeatureSaplingBlock, FC extends FeatureConfiguration> extends SaplingBlock implements RenderLayerProvider, BlockModelProvider { - - @FunctionalInterface - public interface FeatureSupplier, FC extends FeatureConfiguration> { - BCLConfigureFeature get(BlockState state); - } - - private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); - private final FeatureSupplier feature; - - public FeatureSaplingBlock(FeatureSupplier featureSupplier) { - this( - BlockBehaviour.Properties.of(Material.PLANT) - .noCollission() - .instabreak() - .sound(SoundType.GRASS) - .randomTicks(), - featureSupplier - ); - } - - public FeatureSaplingBlock(int light, FeatureSupplier featureSupplier) { - this( - BlockBehaviour.Properties.of(Material.PLANT) - .noCollission() - .lightLevel(state -> light) - .instabreak() - .sound(SoundType.GRASS) - .randomTicks(), - featureSupplier - ); - } - - public FeatureSaplingBlock( - BlockBehaviour.Properties properties, - FeatureSupplier featureSupplier - ) { - super(null, properties); - this.feature = featureSupplier; - } - - protected BCLConfigureFeature getConfiguredFeature(BlockState state) { - return feature != null ? feature.get(state) : null; - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - return Collections.singletonList(new ItemStack(this)); - } - - @Override - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) return Blocks.AIR.defaultBlockState(); - else return state; - } - - @Override - public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { - return random.nextInt(16) == 0; - } - - @Override - public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, RandomSource random) { - BCLConfigureFeature conf = getConfiguredFeature(blockState); - conf.placeInWorld(world, pos, random); - } - - @Override - public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - this.tick(state, world, pos, random); - } - - @Override - public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - super.tick(state, world, pos, random); - if (isBonemealSuccess(world, random, pos, state)) { - performBonemeal(world, random, pos, state); - } - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createBlockItem(resourceLocation); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS, resourceLocation); - return ModelsHelper.fromPattern(pattern); - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPE; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/LeveledAnvilBlock.java b/src/main/java/org/betterx/bclib/blocks/LeveledAnvilBlock.java deleted file mode 100644 index a8129594..00000000 --- a/src/main/java/org/betterx/bclib/blocks/LeveledAnvilBlock.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.client.Minecraft; -import net.minecraft.core.Registry; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.util.FormattedCharSequence; -import net.minecraft.world.item.Tiers; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.material.MaterialColor; - -import java.util.List; - -public class LeveledAnvilBlock extends BaseAnvilBlock { - protected final int level; - - public LeveledAnvilBlock(MaterialColor color, int level) { - super(color); - this.level = level; - } - - public static int getAnvilCraftingLevel(Block anvil) { - if (anvil instanceof LeveledAnvilBlock l) return l.getCraftingLevel(); - if (anvil == Blocks.ANVIL || anvil == Blocks.CHIPPED_ANVIL || anvil == Blocks.DAMAGED_ANVIL) - return Tiers.IRON.getLevel() - 1; - return 0; - } - - public static boolean canHandle(Block anvil, int level) { - return getAnvilCraftingLevel(anvil) >= level; - } - - public static List getAnvils() { - return Registry.BLOCK - .stream() - .filter(b -> b instanceof LeveledAnvilBlock || b == Blocks.ANVIL) - .toList(); - } - - public static List getNamesForLevel(int level) { - MutableComponent names = getAnvils() - .stream() - .filter(b -> canHandle(b, level)) - .map(Block::getName) - .reduce( - null, - (p, c) -> p == null ? c : p.append(net.minecraft.network.chat.Component.literal(", ")).append(c) - ); - if (names == null) return List.of(); - return Minecraft.getInstance().font.split(names, 200); - } - - public int getCraftingLevel() { - return level; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/org/betterx/bclib/blocks/SimpleLeavesBlock.java deleted file mode 100644 index 81441e7e..00000000 --- a/src/main/java/org/betterx/bclib/blocks/SimpleLeavesBlock.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.interfaces.TagProvider; -import org.betterx.bclib.interfaces.tools.AddMineableHoe; -import org.betterx.bclib.interfaces.tools.AddMineableShears; - -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.material.MaterialColor; - -import java.util.List; - -public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerProvider, TagProvider, AddMineableShears, AddMineableHoe { - public SimpleLeavesBlock(MaterialColor color) { - this( - Properties - .of(Material.LEAVES) - .strength(0.2F) - .color(color) - .sound(SoundType.GRASS) - .noOcclusion() - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false) - ); - } - - public SimpleLeavesBlock(MaterialColor color, int light) { - this( - Properties - .of(Material.LEAVES) - .lightLevel(ignored->light) - .color(color) - .strength(0.2F) - .sound(SoundType.GRASS) - .noOcclusion() - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false) - ); - } - - public SimpleLeavesBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - public void addTags(List> blockTags, List> itemTags) { - blockTags.add(BlockTags.LEAVES); - itemTags.add(ItemTags.LEAVES); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/blocks/StalactiteBlock.java b/src/main/java/org/betterx/bclib/blocks/StalactiteBlock.java deleted file mode 100644 index 9e524f52..00000000 --- a/src/main/java/org/betterx/bclib/blocks/StalactiteBlock.java +++ /dev/null @@ -1,263 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.LiquidBlockContainer; -import net.minecraft.world.level.block.SimpleWaterloggedBlock; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.BlockStateProperties; -import net.minecraft.world.level.block.state.properties.BooleanProperty; -import net.minecraft.world.level.block.state.properties.IntegerProperty; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -@SuppressWarnings("deprecation") -public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, RenderLayerProvider { - public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; - public static final BooleanProperty IS_FLOOR = BlockProperties.IS_FLOOR; - public static final IntegerProperty SIZE = BlockProperties.SIZE; - private static final VoxelShape[] SHAPES; - - public StalactiteBlock(Block source) { - this(Properties.copy(source).noOcclusion()); - } - - public StalactiteBlock(BlockBehaviour.Properties properties) { - super(properties); - this.registerDefaultState(getStateDefinition().any() - .setValue(SIZE, 0) - .setValue(IS_FLOOR, true) - .setValue(WATERLOGGED, false)); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(WATERLOGGED, IS_FLOOR, SIZE); - } - - @Override - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPES[state.getValue(SIZE)]; - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - LevelReader world = ctx.getLevel(); - BlockPos pos = ctx.getClickedPos(); - Direction dir = ctx.getClickedFace(); - boolean water = world.getFluidState(pos).getType() == Fluids.WATER; - - if (dir == Direction.DOWN) { - if (isThis(world, pos.above()) || canSupportCenter(world, pos.above(), Direction.DOWN)) { - return defaultBlockState().setValue(IS_FLOOR, false).setValue(WATERLOGGED, water); - } else if (isThis(world, pos.below()) || canSupportCenter(world, pos.below(), Direction.UP)) { - return defaultBlockState().setValue(IS_FLOOR, true).setValue(WATERLOGGED, water); - } else { - return null; - } - } else { - if (isThis(world, pos.below()) || canSupportCenter(world, pos.below(), Direction.UP)) { - return defaultBlockState().setValue(IS_FLOOR, true).setValue(WATERLOGGED, water); - } else if (isThis(world, pos.above()) || canSupportCenter(world, pos.above(), Direction.DOWN)) { - return defaultBlockState().setValue(IS_FLOOR, false).setValue(WATERLOGGED, water); - } else { - return null; - } - } - } - - @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { - boolean hasUp = isThis(world, pos.above()); - boolean hasDown = isThis(world, pos.below()); - MutableBlockPos mut = new MutableBlockPos(); - if (hasUp && hasDown) { - boolean floor = state.getValue(IS_FLOOR); - BlockPos second = floor ? pos.above() : pos.below(); - BlockState bState = world.getBlockState(second); - world.setBlockAndUpdate(pos, state.setValue(SIZE, 1).setValue(IS_FLOOR, floor)); - world.setBlockAndUpdate(second, bState.setValue(SIZE, 1).setValue(IS_FLOOR, !floor)); - - bState = state; - int startSize = floor ? 1 : 2; - mut.set(pos.getX(), pos.getY() + 1, pos.getZ()); - for (int i = 0; i < 8 && isThis(bState); i++) { - world.setBlockAndUpdate(mut, bState.setValue(SIZE, startSize++).setValue(IS_FLOOR, false)); - mut.setY(mut.getY() + 1); - bState = world.getBlockState(mut); - } - - bState = state; - startSize = floor ? 2 : 1; - mut.set(pos.getX(), pos.getY() - 1, pos.getZ()); - for (int i = 0; i < 8 && isThis(bState); i++) { - world.setBlockAndUpdate(mut, bState.setValue(SIZE, startSize++).setValue(IS_FLOOR, true)); - mut.setY(mut.getY() - 1); - bState = world.getBlockState(mut); - } - } else if (hasDown) { - mut.setX(pos.getX()); - mut.setZ(pos.getZ()); - for (int i = 1; i < 8; i++) { - mut.setY(pos.getY() - i); - if (isThis(world, mut)) { - BlockState state2 = world.getBlockState(mut); - int size = state2.getValue(SIZE); - if (size < i) { - world.setBlockAndUpdate(mut, state2.setValue(SIZE, i).setValue(IS_FLOOR, true)); - } else { - break; - } - } else { - break; - } - } - } else if (hasUp) { - mut.setX(pos.getX()); - mut.setZ(pos.getZ()); - for (int i = 1; i < 8; i++) { - mut.setY(pos.getY() + i); - if (isThis(world, mut)) { - BlockState state2 = world.getBlockState(mut); - int size = state2.getValue(SIZE); - if (size < i) { - world.setBlockAndUpdate(mut, state2.setValue(SIZE, i).setValue(IS_FLOOR, false)); - } else { - break; - } - } else { - break; - } - } - } - } - - private boolean isThis(LevelReader world, BlockPos pos) { - return isThis(world.getBlockState(pos)); - } - - private boolean isThis(BlockState state) { - return state.getBlock() instanceof StalactiteBlock; - } - - @Override - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) { - return Blocks.AIR.defaultBlockState(); - } - return state; - } - - @Override - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - int size = state.getValue(SIZE); - return checkUp(world, pos, size) || checkDown(world, pos, size); - } - - private boolean checkUp(BlockGetter world, BlockPos pos, int size) { - BlockPos p = pos.above(); - BlockState state = world.getBlockState(p); - return (isThis(state) && state.getValue(SIZE) >= size) || state.isCollisionShapeFullBlock(world, p); - } - - private boolean checkDown(BlockGetter world, BlockPos pos, int size) { - BlockPos p = pos.below(); - BlockState state = world.getBlockState(p); - return (isThis(state) && state.getValue(SIZE) >= size) || state.isCollisionShapeFullBlock(world, p); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_CROSS_SHADED, resourceLocation); - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - BlockModelRotation rotation = blockState.getValue(IS_FLOOR) - ? BlockModelRotation.X0_Y0 - : BlockModelRotation.X180_Y0; - ResourceLocation modelId = new ResourceLocation( - stateId.getNamespace(), - stateId.getPath() + "_" + blockState.getValue(SIZE) - ); - registerBlockModel(modelId, modelId, blockState, modelCache); - return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); - } - - @Override - public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { - return false; - } - - @Override - public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { - return false; - } - - @Override - public FluidState getFluidState(BlockState state) { - return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : Fluids.EMPTY.defaultFluidState(); - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - static { - float end = 2F / 8F; - float start = 5F / 8F; - SHAPES = new VoxelShape[8]; - for (int i = 0; i < 8; i++) { - int side = Mth.floor(Mth.lerp(i / 7F, start, end) * 8F + 0.5F); - SHAPES[i] = box(side, 0, side, 16 - side, 16, 16 - side); - } - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/blocks/StonePressurePlateBlock.java b/src/main/java/org/betterx/bclib/blocks/StonePressurePlateBlock.java deleted file mode 100644 index 9cd3ba24..00000000 --- a/src/main/java/org/betterx/bclib/blocks/StonePressurePlateBlock.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.world.level.block.Block; - -public class StonePressurePlateBlock extends BasePressurePlateBlock { - public StonePressurePlateBlock(Block source) { - super(Sensitivity.MOBS, source); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/StripableBarkBlock.java b/src/main/java/org/betterx/bclib/blocks/StripableBarkBlock.java deleted file mode 100644 index 2b0f8b84..00000000 --- a/src/main/java/org/betterx/bclib/blocks/StripableBarkBlock.java +++ /dev/null @@ -1,55 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.worlds.together.tag.v3.MineableTags; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.sounds.SoundEvents; -import net.minecraft.sounds.SoundSource; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.phys.BlockHitResult; - - -public class StripableBarkBlock extends BaseBarkBlock { - private final Block striped; - - public StripableBarkBlock(MaterialColor color, Block striped) { - super(Properties.copy(striped).color(color)); - this.striped = striped; - } - - @Override - @SuppressWarnings("deprecation") - public InteractionResult use( - BlockState state, - Level world, - BlockPos pos, - Player player, - InteractionHand hand, - BlockHitResult hit - ) { - if (TagManager.isToolWithMineableTag(player.getMainHandItem(), MineableTags.AXE)) { - world.playSound(player, pos, SoundEvents.AXE_STRIP, SoundSource.BLOCKS, 1.0F, 1.0F); - if (!world.isClientSide) { - world.setBlock( - pos, - striped.defaultBlockState() - .setValue(AXIS, state.getValue(AXIS)), - 11 - ); - if (!player.isCreative()) { - player.getMainHandItem().hurt(1, world.random, (ServerPlayer) player); - } - } - return InteractionResult.SUCCESS; - } - return InteractionResult.FAIL; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/TripleTerrainBlock.java b/src/main/java/org/betterx/bclib/blocks/TripleTerrainBlock.java deleted file mode 100644 index 92001f98..00000000 --- a/src/main/java/org/betterx/bclib/blocks/TripleTerrainBlock.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.blocks.BlockProperties.TripleShape; -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.renderer.block.model.MultiVariant; -import net.minecraft.client.renderer.block.model.Variant; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.EnumProperty; -import net.minecraft.world.level.material.MaterialColor; -import net.minecraft.world.phys.BlockHitResult; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public class TripleTerrainBlock extends BaseTerrainBlock { - public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; - - public TripleTerrainBlock(Block baseBlock) { - super(baseBlock, baseBlock.defaultMaterialColor()); - this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM)); - } - - public TripleTerrainBlock(Block baseBlock, MaterialColor color) { - super(baseBlock, color); - this.registerDefaultState(defaultBlockState().setValue(SHAPE, TripleShape.BOTTOM)); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(SHAPE); - } - - @Override - public BlockState getStateForPlacement(BlockPlaceContext ctx) { - Direction dir = ctx.getClickedFace(); - TripleShape shape = dir == Direction.UP - ? TripleShape.BOTTOM - : dir == Direction.DOWN ? TripleShape.TOP : TripleShape.MIDDLE; - return defaultBlockState().setValue(SHAPE, shape); - } - - @Override - public InteractionResult use( - BlockState state, - Level world, - BlockPos pos, - Player player, - InteractionHand hand, - BlockHitResult hit - ) { - TripleShape shape = state.getValue(SHAPE); - if (shape == TripleShape.BOTTOM) { - return super.use(state, world, pos, player, hand, hit); - } - return InteractionResult.FAIL; - } - - @Override - public void randomTick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - TripleShape shape = state.getValue(SHAPE); - if (shape == TripleShape.BOTTOM) { - super.randomTick(state, world, pos, random); - } else if (random.nextInt(16) == 0) { - boolean bottom = canStayBottom(world, pos); - if (shape == TripleShape.TOP) { - if (!bottom) { - world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); - } - } else { - boolean top = canStay(state, world, pos) || isMiddle(world.getBlockState(pos.above())); - if (!top && !bottom) { - world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); - } else if (top && !bottom) { - world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.BOTTOM)); - } else if (!top) { - world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.TOP)); - } - } - } - } - - protected boolean canStayBottom(LevelReader world, BlockPos pos) { - BlockPos blockPos = pos.below(); - BlockState blockState = world.getBlockState(blockPos); - if (isMiddle(blockState)) { - return true; - } else if (blockState.getFluidState().getAmount() == 8) { - return false; - } else { - return !blockState.isFaceSturdy(world, blockPos, Direction.UP); - } - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation blockId) { - return getBlockModel(blockId, defaultBlockState()); - } - - @Override - @Environment(EnvType.CLIENT) - public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { - String path = blockId.getPath(); - Optional pattern; - if (isMiddle(blockState)) { - ResourceLocation topId = new ResourceLocation(blockId.getNamespace(), path + "_top"); - pattern = PatternsHelper.createBlockSimple(topId); - } else { - Map textures = Maps.newHashMap(); - textures.put("%top%", "betterend:block/" + path + "_top"); - textures.put("%side%", "betterend:block/" + path + "_side"); - textures.put("%bottom%", "minecraft:block/end_stone"); - pattern = PatternsHelper.createJson(BasePatterns.BLOCK_TOP_SIDE_BOTTOM, textures); - } - return ModelsHelper.fromPattern(pattern); - } - - @Override - @Environment(EnvType.CLIENT) - public UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - boolean isMiddle = isMiddle(blockState); - String middle = isMiddle ? "_middle" : ""; - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath() + middle); - registerBlockModel(stateId, modelId, blockState, modelCache); - if (isMiddle) { - List variants = Lists.newArrayList(); - for (BlockModelRotation rotation : BlockModelRotation.values()) { - variants.add(new Variant(modelId, rotation.getRotation(), false, 1)); - } - return new MultiVariant(variants); - } else if (blockState.getValue(SHAPE) == TripleShape.TOP) { - return new MultiVariant(Lists.newArrayList( - new Variant( - modelId, - BlockModelRotation.X180_Y0.getRotation(), - false, - 1 - ), - new Variant(modelId, BlockModelRotation.X180_Y90.getRotation(), false, 1), - new Variant(modelId, BlockModelRotation.X180_Y180.getRotation(), false, 1), - new Variant(modelId, BlockModelRotation.X180_Y270.getRotation(), false, 1) - )); - } - return ModelsHelper.createRandomTopModel(modelId); - } - - protected boolean isMiddle(BlockState blockState) { - return blockState.is(this) && blockState.getValue(SHAPE) == TripleShape.MIDDLE; - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/UnderwaterPlantBlock.java b/src/main/java/org/betterx/bclib/blocks/UnderwaterPlantBlock.java deleted file mode 100644 index a02eb4cd..00000000 --- a/src/main/java/org/betterx/bclib/blocks/UnderwaterPlantBlock.java +++ /dev/null @@ -1,191 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.items.tool.BaseShearsItem; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.item.ItemEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.BonemealableBlock; -import net.minecraft.world.level.block.LiquidBlockContainer; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Fluid; -import net.minecraft.world.level.material.FluidState; -import net.minecraft.world.level.material.Fluids; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.Vec3; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; - -import com.google.common.collect.Lists; - -import java.util.List; -import java.util.function.Function; - -public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock, LiquidBlockContainer { - public static Properties baseUnderwaterPlantSettings() { - return baseUnderwaterPlantSettings(false, 0); - } - - public static Properties baseUnderwaterPlantSettings(int light) { - return baseUnderwaterPlantSettings(false, light); - } - - public static Properties baseUnderwaterPlantSettings(boolean replaceable) { - return baseUnderwaterPlantSettings(replaceable, 0); - } - - public static Properties baseUnderwaterPlantSettings(boolean replaceable, int light) { - return baseUnderwaterPlantSettings( - replaceable ? Material.REPLACEABLE_WATER_PLANT : Material.WATER_PLANT, - light - ); - } - - public static Properties baseUnderwaterPlantSettings(Material mat, int light) { - Properties props = FabricBlockSettings - .of(mat) - .sound(SoundType.WET_GRASS) - .noCollission() - .offsetType(BlockBehaviour.OffsetType.XZ); - if (light > 0) props.lightLevel(s -> light); - return props; - } - - private static final VoxelShape SHAPE = box(4, 0, 4, 12, 14, 12); - - public UnderwaterPlantBlock() { - this(p -> p); - } - - @Deprecated(forRemoval = true) - public UnderwaterPlantBlock(Function propMod) { - this( - propMod.apply(baseUnderwaterPlantSettings()) - ); - } - - public UnderwaterPlantBlock(int light) { - this(light, p -> p); - } - - @Deprecated(forRemoval = true) - public UnderwaterPlantBlock(int light, Function propMod) { - this( - propMod.apply(baseUnderwaterPlantSettings(light)) - ); - } - - public UnderwaterPlantBlock(Properties settings) { - super(settings); - } - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - Vec3 vec3d = state.getOffset(view, pos); - return SHAPE.move(vec3d.x, vec3d.y, vec3d.z); - } - - @Override - @SuppressWarnings("deprecation") - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - BlockState down = world.getBlockState(pos.below()); - state = world.getBlockState(pos); - return isTerrain(down) && state.getFluidState().getType().equals(Fluids.WATER.getSource()); - } - - protected abstract boolean isTerrain(BlockState state); - - @Override - @SuppressWarnings("deprecation") - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) { - world.destroyBlock(pos, true); - return Blocks.WATER.defaultBlockState(); - } else { - return state; - } - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { - return Lists.newArrayList(new ItemStack(this)); - } else { - return Lists.newArrayList(); - } - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { - return true; - } - - @Override - public boolean isBonemealSuccess(Level level, RandomSource random, BlockPos pos, BlockState state) { - return true; - } - - @Override - public void performBonemeal(ServerLevel level, RandomSource random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity( - level, - pos.getX() + 0.5, - pos.getY() + 0.5, - pos.getZ() + 0.5, - new ItemStack(this) - ); - level.addFreshEntity(item); - } - - @Override - public boolean canPlaceLiquid(BlockGetter world, BlockPos pos, BlockState state, Fluid fluid) { - return false; - } - - @Override - public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { - return false; - } - - @Override - @SuppressWarnings("deprecation") - public FluidState getFluidState(BlockState state) { - return Fluids.WATER.getSource(false); - } - -} diff --git a/src/main/java/org/betterx/bclib/blocks/UnderwaterPlantWithAgeBlock.java b/src/main/java/org/betterx/bclib/blocks/UnderwaterPlantWithAgeBlock.java deleted file mode 100644 index 56acdc8e..00000000 --- a/src/main/java/org/betterx/bclib/blocks/UnderwaterPlantWithAgeBlock.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; -import net.minecraft.world.level.block.state.properties.IntegerProperty; - -public abstract class UnderwaterPlantWithAgeBlock extends UnderwaterPlantBlock { - public static final IntegerProperty AGE = BlockProperties.AGE; - - public UnderwaterPlantWithAgeBlock() { - super(baseUnderwaterPlantSettings().randomTicks()); - } - - @Override - protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { - stateManager.add(AGE); - } - - public abstract void grow(WorldGenLevel world, RandomSource random, BlockPos pos); - - @Override - public void performBonemeal(ServerLevel world, RandomSource random, BlockPos pos, BlockState state) { - if (random.nextInt(4) == 0) { - int age = state.getValue(AGE); - if (age < 3) { - world.setBlockAndUpdate(pos, state.setValue(AGE, age + 1)); - } else { - grow(world, random, pos); - } - } - } - - @Override - @SuppressWarnings("deprecation") - public void tick(BlockState state, ServerLevel world, BlockPos pos, RandomSource random) { - super.tick(state, world, pos, random); - if (isBonemealSuccess(world, random, pos, state)) { - performBonemeal(world, random, pos, state); - } - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/UpDownPlantBlock.java b/src/main/java/org/betterx/bclib/blocks/UpDownPlantBlock.java deleted file mode 100644 index 67f759ca..00000000 --- a/src/main/java/org/betterx/bclib/blocks/UpDownPlantBlock.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.betterx.bclib.blocks; - -import org.betterx.bclib.client.render.BCLRenderLayer; -import org.betterx.bclib.interfaces.RenderLayerProvider; -import org.betterx.bclib.interfaces.tools.AddMineableHoe; -import org.betterx.bclib.interfaces.tools.AddMineableShears; -import org.betterx.bclib.items.tool.BaseShearsItem; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.EnchantmentHelper; -import net.minecraft.world.item.enchantment.Enchantments; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.entity.BlockEntity; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - - -import com.google.common.collect.Lists; - -import java.util.List; - -public abstract class UpDownPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, AddMineableShears, AddMineableHoe { - private static final VoxelShape SHAPE = box(4, 0, 4, 12, 16, 12); - - public UpDownPlantBlock() { - this(Properties - .of(Material.PLANT) - .sound(SoundType.GRASS) - .noCollission() - ); - } - - public UpDownPlantBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - protected abstract boolean isTerrain(BlockState state); - - @Override - @SuppressWarnings("deprecation") - public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { - return SHAPE; - } - - @Override - @SuppressWarnings("deprecation") - public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { - BlockState down = world.getBlockState(pos.below()); - BlockState up = world.getBlockState(pos.above()); - return (isTerrain(down) || down.getBlock() == this) && (isSupport(up, world, pos) || up.getBlock() == this); - } - - protected boolean isSupport(BlockState state, LevelReader world, BlockPos pos) { - return canSupportCenter(world, pos.above(), Direction.UP); - } - - @Override - @SuppressWarnings("deprecation") - public BlockState updateShape( - BlockState state, - Direction facing, - BlockState neighborState, - LevelAccessor world, - BlockPos pos, - BlockPos neighborPos - ) { - if (!canSurvive(state, world, pos)) { - return Blocks.AIR.defaultBlockState(); - } else { - return state; - } - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && BaseShearsItem.isShear(tool) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { - return Lists.newArrayList(new ItemStack(this)); - } else { - return Lists.newArrayList(); - } - } - - @Override - public BCLRenderLayer getRenderLayer() { - return BCLRenderLayer.CUTOUT; - } - - @Override - public void playerDestroy( - Level world, - Player player, - BlockPos pos, - BlockState state, - BlockEntity blockEntity, - ItemStack stack - ) { - super.playerDestroy(world, player, pos, state, blockEntity, stack); - world.neighborChanged(pos, Blocks.AIR, pos.below()); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/WallMushroomBlock.java b/src/main/java/org/betterx/bclib/blocks/WallMushroomBlock.java deleted file mode 100644 index 10e5867e..00000000 --- a/src/main/java/org/betterx/bclib/blocks/WallMushroomBlock.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.SoundType; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.LootContext; - -import com.google.common.collect.Lists; - -import java.util.List; - -public abstract class WallMushroomBlock extends BaseWallPlantBlock { - public WallMushroomBlock(int light) { - super(basePlantSettings(light).destroyTime(0.2F).sound(SoundType.WOOD)); - } - - protected WallMushroomBlock(BlockBehaviour.Properties properties) { - super(properties); - } - - @Override - public List getDrops(BlockState state, LootContext.Builder builder) { - return Lists.newArrayList(new ItemStack(this)); - } - - @Override - public boolean isSupport(LevelReader world, BlockPos pos, BlockState blockState, Direction direction) { - return blockState.getMaterial().isSolid() && blockState.isFaceSturdy(world, pos, direction); - } -} diff --git a/src/main/java/org/betterx/bclib/blocks/WoodenPressurePlateBlock.java b/src/main/java/org/betterx/bclib/blocks/WoodenPressurePlateBlock.java deleted file mode 100644 index 2a64768a..00000000 --- a/src/main/java/org/betterx/bclib/blocks/WoodenPressurePlateBlock.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.blocks; - -import net.minecraft.world.level.block.Block; - -public class WoodenPressurePlateBlock extends BasePressurePlateBlock { - public WoodenPressurePlateBlock(Block source) { - super(Sensitivity.EVERYTHING, source); - } -} diff --git a/src/main/java/org/betterx/bclib/client/BCLibClient.java b/src/main/java/org/betterx/bclib/client/BCLibClient.java deleted file mode 100644 index 26f4bae0..00000000 --- a/src/main/java/org/betterx/bclib/client/BCLibClient.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.betterx.bclib.client; - -import org.betterx.bclib.api.v2.ModIntegrationAPI; -import org.betterx.bclib.api.v2.PostInitAPI; -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; -import org.betterx.bclib.client.models.CustomModelBakery; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.registry.BaseBlockEntityRenders; -import org.betterx.bclib.registry.PresetsRegistryClient; -import org.betterx.worlds.together.WorldsTogether; -import org.betterx.worlds.together.client.WorldsTogetherClient; - -import net.minecraft.client.resources.model.ModelResourceLocation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.fabric.api.client.model.*; - -import org.jetbrains.annotations.Nullable; - -public class BCLibClient implements ClientModInitializer, ModelResourceProvider, ModelVariantProvider { - public static CustomModelBakery modelBakery; - - @Override - public void onInitializeClient() { - WorldsTogetherClient.onInitializeClient(); - ModIntegrationAPI.registerAll(); - BaseBlockEntityRenders.register(); - DataExchangeAPI.prepareClientside(); - PostInitAPI.postInit(true); - modelBakery = new CustomModelBakery(); - ModelLoadingRegistry.INSTANCE.registerResourceProvider(rm -> this); - ModelLoadingRegistry.INSTANCE.registerVariantProvider(rm -> this); - - PresetsRegistryClient.onLoad(); - WorldsTogether.SURPRESS_EXPERIMENTAL_DIALOG = Configs.CLIENT_CONFIG.suppressExperimentalDialog(); - //dumpDatapack(); - } - - @Override - public @Nullable UnbakedModel loadModelResource( - ResourceLocation resourceId, - ModelProviderContext context - ) throws ModelProviderException { - return modelBakery.getBlockModel(resourceId); - } - - @Override - public @Nullable UnbakedModel loadModelVariant( - ModelResourceLocation modelId, - ModelProviderContext context - ) throws ModelProviderException { - return modelId.getVariant().equals("inventory") - ? modelBakery.getItemModel(modelId) - : modelBakery.getBlockModel(modelId); - } - - -} diff --git a/src/main/java/org/betterx/bclib/client/gui/modmenu/EntryPoint.java b/src/main/java/org/betterx/bclib/client/gui/modmenu/EntryPoint.java deleted file mode 100644 index 485ec9c5..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/modmenu/EntryPoint.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.betterx.bclib.client.gui.modmenu; - -import org.betterx.bclib.integration.modmenu.ModMenuIntegration; - -@Deprecated() -public class EntryPoint extends ModMenuIntegration { - public static final Object entrypointObject = createEntrypoint(new EntryPoint()); - - public EntryPoint() { - super(MainScreen::new); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/modmenu/MainScreen.java b/src/main/java/org/betterx/bclib/client/gui/modmenu/MainScreen.java deleted file mode 100644 index 44bf419b..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/modmenu/MainScreen.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.betterx.bclib.client.gui.modmenu; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.ConfigKeeper; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.config.NamedPathConfig; -import org.betterx.bclib.config.NamedPathConfig.ConfigTokenDescription; -import org.betterx.bclib.config.NamedPathConfig.DependendConfigToken; -import org.betterx.ui.layout.components.*; -import org.betterx.ui.vanilla.LayoutScreenWithIcon; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Supplier; -import org.jetbrains.annotations.Nullable; - -public class MainScreen extends LayoutScreenWithIcon { - static final ResourceLocation BCLIB_LOGO_LOCATION = new ResourceLocation(BCLib.MOD_ID, "icon.png"); - - public MainScreen(@Nullable Screen parent) { - super(parent, BCLIB_LOGO_LOCATION, Component.translatable("title.bclib.modmenu.main"), 10, 10, 20); - } - - protected Component getComponent(NamedPathConfig config, ConfigTokenDescription option, String type) { - return Component.translatable(type + ".config." + config.configID + option.getPath()); - } - - Map> dependentWidgets = new HashMap<>(); - - protected void updateEnabledState() { - dependentWidgets.forEach((cb, supl) -> cb.setEnabled(supl.get())); - } - - @SuppressWarnings("unchecked") - protected void addRow(VerticalStack grid, NamedPathConfig config, ConfigTokenDescription option) { - if (ConfigKeeper.BooleanEntry.class.isAssignableFrom(option.token.type)) { - addCheckbox(grid, config, (ConfigTokenDescription) option); - } else if (ConfigKeeper.FloatEntry.class.isAssignableFrom(option.token.type)) { - addFloat(grid, config, (ConfigTokenDescription) option); - } - - grid.addSpacer(2); - } - - protected void addFloat(VerticalStack grid, NamedPathConfig config, ConfigTokenDescription option) { - if (option.topPadding > 0) { - grid.addSpacer(option.topPadding); - } - HorizontalStack row = grid.addRow(); - if (option.leftPadding > 0) { - row.addSpacer(option.leftPadding); - } - Range cb = row.addRange( - fixed(200), fit(), - getComponent(config, option, "title"), - option.minRange, - option.maxRange, - config.getRaw(option.token) - ).onChange( - (caller, state) -> { - config.set(option.token, state); - } - ); - } - - protected void addCheckbox(VerticalStack grid, NamedPathConfig config, ConfigTokenDescription option) { - if (option.topPadding > 0) { - grid.addSpacer(option.topPadding); - } - HorizontalStack row = grid.addRow(); - if (option.leftPadding > 0) { - row.addSpacer(option.leftPadding); - } - Checkbox cb = row.addCheckbox( - fit(), fit(), - getComponent(config, option, "title"), - config.getRaw(option.token) - ).onChange( - (caller, state) -> { - config.set(option.token, state); - updateEnabledState(); - } - ); - - if (option.token instanceof DependendConfigToken) { - dependentWidgets.put(cb, () -> option.token.dependenciesTrue(config)); - cb.setEnabled(option.token.dependenciesTrue(config)); - } - } - - @Override - public boolean shouldCloseOnEsc() { - return false; - } - - - @Override - protected LayoutComponent initContent() { - - VerticalStack content = new VerticalStack(fit(), fit()).setDebugName("content"); - - Configs.GENERATOR_CONFIG.getAllOptions() - .stream() - .filter(o -> !o.hidden) - .forEach(o -> addRow(content, Configs.GENERATOR_CONFIG, o)); - content.addSpacer(12); - Configs.MAIN_CONFIG.getAllOptions() - .stream() - .filter(o -> !o.hidden) - .forEach(o -> addRow(content, Configs.MAIN_CONFIG, o)); - content.addSpacer(12); - Configs.CLIENT_CONFIG.getAllOptions() - .stream() - .filter(o -> !o.hidden) - .forEach(o -> addRow(content, Configs.CLIENT_CONFIG, o)); - - - VerticalStack grid = new VerticalStack(fill(), fill()).setDebugName("main grid"); - grid.addScrollable(content); - grid.addSpacer(8); - grid.addButton(fit(), fit(), CommonComponents.GUI_DONE).onPress((button) -> { - Configs.CLIENT_CONFIG.saveChanges(); - Configs.GENERATOR_CONFIG.saveChanges(); - Configs.MAIN_CONFIG.saveChanges(); - onClose(); - }).alignRight(); - return grid; - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/modmenu/TestScreen.java b/src/main/java/org/betterx/bclib/client/gui/modmenu/TestScreen.java deleted file mode 100644 index 11d23aae..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/modmenu/TestScreen.java +++ /dev/null @@ -1,181 +0,0 @@ -package org.betterx.bclib.client.gui.modmenu; - -import org.betterx.bclib.BCLib; -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.*; -import org.betterx.ui.layout.values.Size; -import org.betterx.ui.vanilla.LayoutScreen; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class TestScreen extends LayoutScreen { - public TestScreen(Component component) { - super(component); - } - - public TestScreen(Screen parent, Component component) { - super(parent, component); - } - - @Override - protected LayoutComponent initContent() { - VerticalStack page1 = new VerticalStack(fill(), fit()); - page1.addText(fit(), fit(), Component.literal("Page 1")).alignLeft().centerVertical(); - page1.addButton(fit(), fit(), Component.literal("A1")).onPress((bt) -> System.out.println("A1")) - .centerHorizontal(); - page1.addButton(fit(), fit(), Component.literal("A2")).onPress((bt) -> System.out.println("A2")) - .centerHorizontal(); - page1.addButton(fit(), fit(), Component.literal("A3")).onPress((bt) -> System.out.println("A3")) - .centerHorizontal(); - page1.addButton(fit(), fit(), Component.literal("A4")).onPress((bt) -> System.out.println("A4")) - .centerHorizontal(); - page1.addRange(fixed(100), fit(), Component.literal("N1"), 0, 10, 5); - - VerticalStack page2 = new VerticalStack(fill(), fit()); - page2.addText(fit(), fit(), Component.literal("Page 2")).alignRight().centerVertical(); - page2.addButton(fit(), fit(), Component.literal("B1")).onPress((bt) -> System.out.println("B1")) - .centerHorizontal(); - page2.addButton(fit(), fit(), Component.literal("B2")).onPress((bt) -> System.out.println("B2")) - .centerHorizontal(); - page2.addButton(fit(), fit(), Component.literal("B3")).onPress((bt) -> System.out.println("B3")) - .centerHorizontal(); - page2.addButton(fit(), fit(), Component.literal("B4")).onPress((bt) -> System.out.println("B4")) - .centerHorizontal(); - page2.addRange(fixed(100), fit(), Component.literal("N2"), 0, 10, 5); - - - Container c = new Container(fill(), fixed(40)); - c.addChild(new Button(fit(), fit(), Component.literal("Containerd")).onPress(bt -> { - System.out.println("Containerd"); - }).centerHorizontal().centerVertical()); - c.setBackgroundColor(0x77000000); - VerticalStack rows = new VerticalStack(fit(), fitOrFill()); - - rows.addFiller(); - rows.add(new Text( - fitOrFill(), fixed(20), - Component.literal("Some Text") - ).alignRight() - ); - rows.add(new Text( - fitOrFill(), fixed(20), - Component.literal("Some other, longer Text") - ).centerHorizontal() - ); - rows.addHorizontalSeparator(16).alignTop(); - rows.add(new Tabs(fixed(300), fixed(80)).addPage( - Component.literal("PAGE 1"), - VerticalScroll.create(page1) - ) - .addPage( - Component.literal("PAGE 2"), - VerticalScroll.create(page2) - )); - rows.add(new Input(fitOrFill(), fit(), Component.literal("Input"), "0xff00ff")); - rows.add(new ColorSwatch(fit(), fit(), ColorUtil.LIGHT_PURPLE).centerHorizontal()); - rows.add(new ColorPicker( - fill(), - fit(), - Component.literal("Color"), - ColorUtil.GREEN - ).centerHorizontal()); - rows.add(new Text( - fitOrFill(), fixed(20), - Component.literal("Some blue text") - ).centerHorizontal().setColor(ColorUtil.BLUE) - ); - rows.addHLine(fixed(32), fixed(16)); - rows.add(c); - rows.addCheckbox( - fitOrFill(), - fit(), - Component.literal("Hide"), - false - ).onChange( - (cb, state) -> c.setVisible(!state) - ); - rows.addSpacer(16); - rows.add(new Image( - fixed(24), fixed(24), - BCLib.makeID("icon.png"), - new Size(512, 512) - ).centerHorizontal() - ); - rows.add(new MultiLineText( - fill(), fit(), - Component.literal( - "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.") - ).setColor(ColorUtil.LIGHT_PURPLE).centerHorizontal() - ); - - rows.addHorizontalLine(16); - rows.add(new Range<>( - fill(), fit(), - Component.literal("Integer"), - 10, 90, 20 - ).onChange( - (slider, value) -> { - System.out.println(value); - } - )); - rows.addSpacer(8); - rows.add(new Range<>( - fill(), fit(), - Component.literal("Float"), - 10f, 90f, 20f - ).onChange( - (slider, value) -> { - System.out.println(value); - } - )); - rows.addSpacer(16); - Checkbox cb1 = new Checkbox( - fit(), fit(), - Component.literal("Some Sub-State"), - false, true - ).onChange( - (checkbox, value) -> { - System.out.println(value); - } - ); - rows.add(new Checkbox( - fit(), fit(), - Component.literal("Some Selectable State"), - false, true - ).onChange( - (checkbox, value) -> { - System.out.println(value); - cb1.setEnabled(value); - } - )); - rows.add(cb1); - rows.addSpacer(16); - rows.add(new Button( - fit(), fit(), - Component.literal("test") - ).onPress( - (bt) -> { - System.out.println("clicked test"); - } - ).centerHorizontal() - ); - rows.addSpacer(8); - rows.add(new Button( - fit(), fit(), - Component.literal("Hello World") - ).onPress( - (bt) -> { - System.out.println("clicked hello"); - } - ).centerHorizontal() - ); - rows.addFiller(); - - return HorizontalStack.centered(VerticalScroll.create(fit(), relative(1), rows)); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/AtomicProgressListener.java b/src/main/java/org/betterx/bclib/client/gui/screens/AtomicProgressListener.java deleted file mode 100644 index 91754da1..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/AtomicProgressListener.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import net.minecraft.network.chat.Component; - -public interface AtomicProgressListener { - void incAtomic(int maxProgress); - void resetAtomic(); - void stop(); - void progressStage(Component component); -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/BCLibLayoutScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/BCLibLayoutScreen.java deleted file mode 100644 index ecf28cf9..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/BCLibLayoutScreen.java +++ /dev/null @@ -1,38 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.bclib.BCLib; -import org.betterx.ui.vanilla.LayoutScreenWithIcon; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; - -import org.jetbrains.annotations.Nullable; - -public abstract class BCLibLayoutScreen extends LayoutScreenWithIcon { - static final ResourceLocation BCLIB_LOGO_LOCATION = new ResourceLocation(BCLib.MOD_ID, "icon.png"); - static final ResourceLocation BCLIB_LOGO_WHITE_LOCATION = new ResourceLocation(BCLib.MOD_ID, "icon_bright.png"); - - public BCLibLayoutScreen( - Component component - ) { - super(BCLIB_LOGO_LOCATION, component); - } - - public BCLibLayoutScreen( - @Nullable Screen parent, - Component component - ) { - super(parent, BCLIB_LOGO_LOCATION, component); - } - - public BCLibLayoutScreen( - @Nullable Screen parent, - Component component, - int topPadding, - int bottomPadding, - int sidePadding - ) { - super(parent, BCLIB_LOGO_LOCATION, component, topPadding, bottomPadding, sidePadding); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/ConfirmFixScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/ConfirmFixScreen.java deleted file mode 100644 index cfd74fd3..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/ConfirmFixScreen.java +++ /dev/null @@ -1,67 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - - -import org.betterx.ui.layout.components.Checkbox; -import org.betterx.ui.layout.components.HorizontalStack; -import org.betterx.ui.layout.components.LayoutComponent; -import org.betterx.ui.layout.components.VerticalStack; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import org.jetbrains.annotations.Nullable; - -@Environment(EnvType.CLIENT) -public class ConfirmFixScreen extends BCLibLayoutScreen { - protected final ConfirmFixScreen.Listener listener; - private final Component description; - protected int id; - - public ConfirmFixScreen(@Nullable Screen parent, ConfirmFixScreen.Listener listener) { - super(parent, Component.translatable("bclib.datafixer.backupWarning.title")); - this.listener = listener; - - this.description = Component.translatable("bclib.datafixer.backupWarning.message"); - } - - public boolean shouldCloseOnEsc() { - return true; - } - - @Override - protected LayoutComponent initContent() { - VerticalStack grid = new VerticalStack(fill(), fill()); - grid.addFiller(); - grid.addMultilineText(fill(), fit(), this.description).centerHorizontal(); - grid.addSpacer(8); - Checkbox backup = grid.addCheckbox( - fit(), fit(), - Component.translatable("bclib.datafixer.backupWarning.backup"), - true - ); - grid.addSpacer(4); - Checkbox fix = grid.addCheckbox( - fit(), fit(), - Component.translatable("bclib.datafixer.backupWarning.fix"), - true - ); - grid.addSpacer(20); - - HorizontalStack row = grid.addRow().centerHorizontal(); - row.addButton(fit(), fit(), CommonComponents.GUI_CANCEL).onPress((button) -> onClose()); - row.addSpacer(4); - row.addButton(fit(), fit(), CommonComponents.GUI_PROCEED) - .onPress((button) -> this.listener.proceed(backup.isChecked(), fix.isChecked())); - - return grid; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(boolean createBackup, boolean applyPatches); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/ConfirmRestartScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/ConfirmRestartScreen.java deleted file mode 100644 index 04cc6777..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/ConfirmRestartScreen.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.ui.layout.components.LayoutComponent; -import org.betterx.ui.layout.components.VerticalStack; -import org.betterx.ui.layout.values.Value; - -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - - -@Environment(EnvType.CLIENT) -public class ConfirmRestartScreen extends BCLibLayoutScreen { - private final Component description; - private final ConfirmRestartScreen.Listener listener; - - public ConfirmRestartScreen(ConfirmRestartScreen.Listener listener) { - this(listener, null); - } - - public ConfirmRestartScreen(ConfirmRestartScreen.Listener listener, Component message) { - super(Component.translatable("title.bclib.confirmrestart")); - - this.description = message == null ? Component.translatable("message.bclib.confirmrestart") : message; - this.listener = listener; - } - - public boolean shouldCloseOnEsc() { - return false; - } - - @Override - protected LayoutComponent initContent() { - VerticalStack grid = new VerticalStack(fill(), fill()); - grid.addFiller(); - grid.addMultilineText(Value.relative(0.9), fit(), this.description).centerHorizontal(); - grid.addSpacer(10); - grid.addButton(fit(), fit(), CommonComponents.GUI_PROCEED) - .onPress((button) -> listener.proceed()) - .centerHorizontal(); - grid.addFiller(); - - return grid; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/LevelFixErrorScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/LevelFixErrorScreen.java deleted file mode 100644 index 3235c9cc..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/LevelFixErrorScreen.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.HorizontalStack; -import org.betterx.ui.layout.components.LayoutComponent; -import org.betterx.ui.layout.components.VerticalStack; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class LevelFixErrorScreen extends BCLibLayoutScreen { - private final String[] errors; - final Listener onContinue; - - public LevelFixErrorScreen(Screen parent, String[] errors, Listener onContinue) { - super(parent, Component.translatable("title.bclib.datafixer.error"), 10, 10, 10); - this.errors = errors; - this.onContinue = onContinue; - } - - - @Override - protected LayoutComponent initContent() { - VerticalStack grid = new VerticalStack(fill(), fill()); - grid.addSpacer(4); - grid.addMultilineText(fill(), fit(), Component.translatable("message.bclib.datafixer.error")) - .centerHorizontal(); - grid.addSpacer(8); - - HorizontalStack row = new HorizontalStack(fill(), fit()); - row.addSpacer(10); - VerticalStack col = row.addColumn(fixed(300), fit()); - grid.addScrollable(row); - - for (String error : errors) { - Component dash = Component.literal("-"); - row = col.addRow(); - row.addText(fit(), fit(), dash); - - row.addSpacer(4); - row.addText(fit(), fit(), Component.literal(error)).setColor(ColorUtil.RED); - } - grid.addSpacer(8); - - row = grid.addRow().centerHorizontal(); - row.addButton( - fit(), fit(), - Component.translatable("title.bclib.datafixer.error.continue") - ).setAlpha(0.5f).onPress((n) -> { - onClose(); - onContinue.doContinue(true); - }); - row.addSpacer(4); - row.addButton( - fit(), fit(), - CommonComponents.GUI_CANCEL - ).onPress((n) -> { - this.minecraft.setScreen(null); - }); - - - return grid; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void doContinue(boolean markFixed); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/ModListScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/ModListScreen.java deleted file mode 100644 index 149d4a9d..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/ModListScreen.java +++ /dev/null @@ -1,268 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.HelloClient; -import org.betterx.bclib.util.Triple; -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.HorizontalStack; -import org.betterx.ui.layout.components.LayoutComponent; -import org.betterx.ui.layout.components.Text; -import org.betterx.ui.layout.components.VerticalStack; -import org.betterx.worlds.together.util.ModUtil; -import org.betterx.worlds.together.util.PathUtil; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.loader.api.metadata.ModEnvironment; - -import java.util.*; -import java.util.stream.Collectors; - -@Environment(EnvType.CLIENT) -public class ModListScreen extends BCLibLayoutScreen { - private final List mods; - private final HelloClient.IServerModMap serverInfo; - private final Component description; - private final Component buttonTitle; - - private static List extractModList(Map mods) { - List list = new LinkedList(); - ModUtil.getMods().forEach((id, info) -> list.add(info)); - return list; - } - - public ModListScreen( - Screen parent, - Component title, - Component description, - Map mods, - HelloClient.IServerModMap serverInfo - ) { - this(parent, title, description, CommonComponents.GUI_BACK, mods, serverInfo); - } - - public ModListScreen( - Screen parent, - Component title, - Component description, - List mods, - HelloClient.IServerModMap serverInfo - ) { - this(parent, title, description, CommonComponents.GUI_BACK, mods, serverInfo); - } - - public ModListScreen( - Screen parent, - Component title, - Component description, - Component button, - Map mods, - HelloClient.IServerModMap serverInfo - ) { - this(parent, title, description, button, extractModList(mods), serverInfo); - } - - public ModListScreen( - Screen parent, - Component title, - Component description, - Component button, - List mods, - HelloClient.IServerModMap serverInfo - ) { - super(parent, title); - this.mods = mods; - this.serverInfo = serverInfo; - this.description = description; - this.buttonTitle = button; - } - - public static List localMissing(HelloClient.IServerModMap serverInfo) { - return serverInfo.keySet() - .stream() - .filter(modid -> !ModUtil.getMods() - .keySet() - .stream() - .filter(mod -> mod.equals(modid)) - .findFirst() - .isPresent()).collect(Collectors.toList()); - } - - public static List serverMissing(HelloClient.IServerModMap serverInfo) { - return ModUtil.getMods().entrySet() - .stream() - .filter(entry -> entry.getValue().metadata.getEnvironment() != ModEnvironment.CLIENT) - .map(entry -> entry.getKey()) - .filter(modid -> !serverInfo.keySet() - .stream() - .filter(mod -> mod.equals(modid)) - .findFirst() - .isPresent()).collect(Collectors.toList()); - } - - - public static void addModDesc( - VerticalStack grid, - java.util.List mods, - HelloClient.IServerModMap serverInfo - ) { - final int STATE_OK = 6; - final int STATE_SERVER_MISSING_CLIENT_MOD = 5; - final int STATE_MISSING_NOT_OFFERED = 4; - final int STATE_VERSION_CLIENT_ONLY = 7; - final int STATE_VERSION_NOT_OFFERED = 3; - final int STATE_VERSION = 2; - final int STATE_SERVER_MISSING = 1; - final int STATE_MISSING = 0; - - - List> items = new LinkedList<>(); - if (serverInfo != null) { - serverInfo.keySet() - .stream() - .filter(modid -> !mods.stream() - .filter(mod -> mod.metadata.getId().equals(modid)) - .findFirst() - .isPresent()) - .forEach(modid -> { - HelloClient.OfferedModInfo nfo = serverInfo.get(modid); - String stateString = nfo.version(); - if (nfo.size() > 0) { - stateString = "Version: " + stateString + ", Size: " + PathUtil.humanReadableFileSize(nfo.size()); - } - if (nfo.canDownload()) { - stateString += ", offered by server"; - } - - items.add(new Triple<>( - modid, - nfo.canDownload() ? STATE_MISSING : STATE_MISSING_NOT_OFFERED, - stateString - )); - }); - } - - mods.forEach(mod -> { - String serverVersion = null; - int serverSize = 0; - int state = STATE_OK; - if (serverInfo != null) { - final String modID = mod.metadata.getId(); - - - HelloClient.OfferedModInfo data = serverInfo.get(modID); - if (data != null) { - final String modVer = data.version(); - final int size = data.size(); - if (!modVer.equals(mod.getVersion())) { - if (mod.metadata.getEnvironment() == ModEnvironment.CLIENT) - state = STATE_VERSION_CLIENT_ONLY; - else - state = data.canDownload() ? STATE_VERSION : STATE_VERSION_NOT_OFFERED; - serverVersion = modVer; - serverSize = size; - } - } else if (mod.metadata.getEnvironment() == ModEnvironment.CLIENT) { - state = STATE_SERVER_MISSING_CLIENT_MOD; - } else { - state = STATE_SERVER_MISSING; - } - } - - String stateString = mod.metadata.getVersion().toString(); - if (serverVersion != null) { - stateString = "Client: " + stateString; - stateString += ", Server: " + serverVersion; - if (serverSize > 0) { - stateString += ", Size: " + PathUtil.humanReadableFileSize(serverSize); - } - } - if (mod.metadata.getEnvironment() == ModEnvironment.CLIENT) { - stateString += ", client-only"; - } else if (mod.metadata.getEnvironment() == ModEnvironment.SERVER) { - stateString += ", server-only"; - } - items.add(new Triple<>(mod.metadata.getName(), state, stateString)); - }); - - items.stream() - .filter(t -> t.second != STATE_SERVER_MISSING) - .sorted(Comparator.comparing(a -> a.second + a.first.toLowerCase(Locale.ROOT))) - .forEach(t -> { - final String name = t.first; - final int state = t.second; - final String stateString = t.third; - - int color = ColorUtil.RED; - final String typeText; - if (state == STATE_VERSION || state == STATE_VERSION_NOT_OFFERED || state == STATE_VERSION_CLIENT_ONLY) { - typeText = "[VERSION]"; - if (state == STATE_VERSION_NOT_OFFERED) { - color = ColorUtil.YELLOW; - } else if (state == STATE_VERSION_CLIENT_ONLY) { - color = ColorUtil.DARK_GREEN; - } - } else if (state == STATE_MISSING || state == STATE_MISSING_NOT_OFFERED) { - typeText = "[MISSING]"; - if (state == STATE_MISSING_NOT_OFFERED) { - color = ColorUtil.YELLOW; - } - } else if (state == STATE_SERVER_MISSING || state == STATE_SERVER_MISSING_CLIENT_MOD) { - if (state == STATE_SERVER_MISSING_CLIENT_MOD) { - color = ColorUtil.AQUA; - typeText = "[OK]"; - } else { - typeText = "[NOT ON SERVER]"; - } - } else { - color = ColorUtil.DARK_GREEN; - typeText = "[OK]"; - } - Component dash = Component.literal("-"); - Component typeTextComponent = Component.literal(typeText); - HorizontalStack row = grid.addRow(); - - Text dashText = row.addText(fit(), fit(), dash); - - row.addSpacer(4); - row.addText(fit(), fit(), Component.literal(name)); - - row.addSpacer(4); - row.addText(fit(), fit(), typeTextComponent).setColor(color); - - if (!stateString.isEmpty()) { - row = grid.addRow(); - row.addSpacer(4 + dashText.getContentWidth()); - row.addText(fit(), fit(), Component.literal(stateString)) - .setColor(ColorUtil.GRAY); - } - - grid.addSpacer(4); - }); - } - - - @Override - protected LayoutComponent initContent() { - VerticalStack grid = new VerticalStack(fill(), fill()); - if (description != null) { - grid.addSpacer(4); - grid.addMultilineText(fill(), fit(), description).centerHorizontal(); - grid.addSpacer(8); - } - - HorizontalStack row = new HorizontalStack(fill(), fit()); - row.addSpacer(10); - VerticalStack col = row.addColumn(fixed(200), fit()); - addModDesc(col, mods, serverInfo); - grid.addScrollable(row); - - grid.addSpacer(8); - grid.addButton(fit(), fit(), buttonTitle).onPress((n) -> onClose()).centerHorizontal(); - - return grid; - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/ProgressScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/ProgressScreen.java deleted file mode 100644 index 9da0a397..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/ProgressScreen.java +++ /dev/null @@ -1,233 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.bclib.BCLib; -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.*; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; -import org.betterx.ui.vanilla.LayoutScreen; - -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.ProgressListener; - -import java.util.concurrent.atomic.AtomicInteger; -import org.jetbrains.annotations.Nullable; - -class ProgressLogoRender extends CustomRenderComponent { - public static final int SIZE = 64; - public static final int LOGO_SIZE = 512; - public static final int PIXELATED_SIZE = 512; - float percentage = 0; - double time = 0; - - protected ProgressLogoRender() { - super(Value.fixed(SIZE), Value.fixed(SIZE)); - } - - @Override - public int getContentWidth() { - return SIZE; - } - - @Override - public int getContentHeight() { - return SIZE; - } - - @Override - protected void customRender( - PoseStack poseStack, - int x, - int y, - float deltaTicks, - Rectangle transform, - Rectangle clipRect - ) { - //time += 0.03; - time += deltaTicks * 0.1; - - RenderSystem.setShader(GameRenderer::getPositionTexShader); - RenderSystem.enableBlend(); - RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); - RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, 1.0f); - - final int yBarLocal = (int) (transform.height * percentage); - final int yBar = yBarLocal; - - final float fScale = (float) (0.3 * ((Math.sin(time) + 1.0) * 0.5) + 0.7); - int height = (int) (transform.height * fScale); - int width = (int) (transform.width * fScale); - width -= ((transform.width - width) % 2); - height -= ((transform.height - height) % 2); - - final int yOffset = (transform.height - height) / 2; - final int xOffset = (transform.width - width) / 2; - - - final int yBarImage = Math.max(0, Math.min(height, yBarLocal - yOffset)); - final float relativeY = ((float) yBarImage / height); - - if (yBarImage > 0) { - final int uvTopLogo = (int) (relativeY * LOGO_SIZE); - RenderSystem.setShaderTexture(0, BCLibLayoutScreen.BCLIB_LOGO_LOCATION); - GuiComponent.blit(poseStack, - xOffset, - yOffset, - width, - yBarImage, - 0, 0, LOGO_SIZE, uvTopLogo, - LOGO_SIZE, LOGO_SIZE - ); - } - - if (yBarImage < height) { - final int uvTopPixelated = (int) (relativeY * PIXELATED_SIZE); - RenderSystem.setShaderTexture(0, ProgressScreen.BCLIB_LOGO_PIXELATED_LOCATION); - GuiComponent.blit(poseStack, - xOffset, - yOffset + yBarImage, - width, - height - yBarImage, - 0, uvTopPixelated, PIXELATED_SIZE, PIXELATED_SIZE - uvTopPixelated, - PIXELATED_SIZE, PIXELATED_SIZE - ); - } - - if (percentage > 0 && percentage < 1.0) { - GuiComponent.fill( - poseStack, - 0, - yBar, - transform.width, - yBar + 1, - 0x3FFFFFFF - ); - } - } -} - -public class ProgressScreen extends LayoutScreen implements ProgressListener, AtomicProgressListener { - - static final ResourceLocation BCLIB_LOGO_PIXELATED_LOCATION = new ResourceLocation( - BCLib.MOD_ID, - "iconpixelated.png" - ); - - public ProgressScreen(@Nullable Screen parent, Component title, Component description) { - super(parent, title); - this.description = description; - } - - - Component description; - private Component stageComponent; - private MultiLineText stage; - private HorizontalStack stageRow; - private Text progress; - private ProgressLogoRender progressImage; - private int currentProgress = 0; - private AtomicInteger atomicCounter; - - @Override - public void incAtomic(int maxProgress) { - if (atomicCounter != null) { - progressStagePercentage((100 * atomicCounter.incrementAndGet()) / maxProgress); - } - } - - @Override - public void resetAtomic() { - progressStagePercentage(0); - atomicCounter = new AtomicInteger(0); - } - - public boolean shouldCloseOnEsc() { - return false; - } - - public Component getProgressComponent() { - return getProgressComponent(currentProgress); - } - - private Component getProgressComponent(int pg) { - return Component.translatable("title.bclib.progress").append(": " + pg + "%"); - } - - - @Override - public void progressStartNoAbort(Component text) { - this.progressStage(text); - } - - @Override - public void progressStart(Component text) { - this.progressStage(text); - this.progressStagePercentage(0); - } - - @Override - public void progressStage(Component text) { - stageComponent = text; - if (stage != null) stage.setText(text); - if (stageRow != null) stageRow.reCalculateLayout(); - } - - @Override - public void progressStagePercentage(int progress) { - if (progress != currentProgress) { - currentProgress = progress; - if (progressImage != null) progressImage.percentage = currentProgress / 100.0f; - if (this.progress != null) this.progress.setText(getProgressComponent()); - } - } - - @Override - public void stop() { - - } - - @Override - protected LayoutComponent addTitle(LayoutComponent content) { - return content; - } - - @Override - protected LayoutComponent initContent() { - VerticalStack grid = new VerticalStack(fill(), fill()).setDebugName("grid"); - grid.addFiller(); - grid.add(buildTitle()); - grid.addSpacer(4); - - HorizontalStack contentRow = grid.addRow(fit(), fit()) - .centerHorizontal() - .setDebugName("contentRow"); - - progressImage = new ProgressLogoRender(); - progressImage.percentage = currentProgress / 100.0f; - contentRow.add(progressImage); - contentRow.addSpacer(8); - - VerticalStack textCol = contentRow.addColumn(fit(), fit()).setDebugName("textCol").centerVertical(); - textCol.addText(fit(), fit(), description); - textCol.addSpacer(4); - progress = textCol.addText(fit(), fit(), getProgressComponent()).setColor(ColorUtil.GRAY); - - - grid.addSpacer(20); - stageRow = grid.addRow(fill(), fit()); - stage = stageRow.addMultilineText( - fill(), fit(), - stageComponent != null ? stageComponent : Component.literal("") - ).centerHorizontal(); - grid.addFiller(); - - return grid; - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/SyncFilesScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/SyncFilesScreen.java deleted file mode 100644 index 64dd76ea..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/SyncFilesScreen.java +++ /dev/null @@ -1,144 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.HelloClient; -import org.betterx.ui.layout.components.Checkbox; -import org.betterx.ui.layout.components.HorizontalStack; -import org.betterx.ui.layout.components.LayoutComponent; -import org.betterx.ui.layout.components.VerticalStack; -import org.betterx.worlds.together.util.ModUtil; - -import net.minecraft.client.Minecraft; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class SyncFilesScreen extends BCLibLayoutScreen { - private final Component description; - private final SyncFilesScreen.Listener listener; - private final boolean hasConfigFiles; - private final boolean hasFiles; - private final boolean hasMods; - private final boolean shouldDelete; - private final HelloClient.IServerModMap serverInfo; - - public SyncFilesScreen( - int modFiles, - int configFiles, - int singleFiles, - int folderFiles, - int deleteFiles, - HelloClient.IServerModMap serverInfo, - Listener listener - ) { - super(Component.translatable("title.bclib.syncfiles")); - - this.serverInfo = serverInfo; - this.description = Component.translatable("message.bclib.syncfiles"); - this.listener = listener; - - this.hasConfigFiles = configFiles > 0; - this.hasFiles = singleFiles + folderFiles > 0; - this.hasMods = modFiles > 0; - this.shouldDelete = deleteFiles > 0; - } - - - public boolean shouldCloseOnEsc() { - return false; - } - - @Override - protected LayoutComponent initContent() { - VerticalStack grid = new VerticalStack(fill(), fill()); - final int BUTTON_HEIGHT = 20; - - grid.addMultilineText(fill(), fit(), this.description).centerHorizontal(); - - grid.addSpacer(10); - - HorizontalStack row; - - final Checkbox mods; - row = grid.addRow(); - mods = row.addCheckbox( - fit(), fit(), - Component.translatable("message.bclib.syncfiles.mods"), - hasMods - ); - mods.setEnabled(hasMods); - - row.addSpacer(4); - row.addButton( - fit(), fit(), - Component.translatable("title.bclib.syncfiles.modInfo") - ).onPress((button) -> { - ModListScreen scr = new ModListScreen( - this, - Component.translatable("title.bclib.syncfiles.modlist"), - Component.translatable("message.bclib.syncfiles.modlist"), - ModUtil.getMods(), - serverInfo - ); - Minecraft.getInstance().setScreen(scr); - }); - - grid.addSpacer(4); - - - final Checkbox configs; - row = grid.addRow(); - configs = row.addCheckbox( - fit(), fit(), - Component.translatable("message.bclib.syncfiles.configs"), - hasConfigFiles - ); - configs.setEnabled(hasConfigFiles); - - grid.addSpacer(4); - - row = grid.addRow(); - - final Checkbox folder; - folder = row.addCheckbox( - fit(), fit(), - Component.translatable("message.bclib.syncfiles.folders"), - hasFiles - ); - folder.setEnabled(hasFiles); - row.addSpacer(4); - - Checkbox delete; - delete = row.addCheckbox( - fit(), fit(), - Component.translatable("message.bclib.syncfiles.delete"), - shouldDelete - ); - delete.setEnabled(shouldDelete); - - - grid.addSpacer(30); - row = grid.addRow().centerHorizontal(); - row.addButton(fit(), fit(), CommonComponents.GUI_NO).onPress((button) -> { - listener.proceed(false, false, false, false); - }); - row.addSpacer(4); - row.addButton(fit(), fit(), CommonComponents.GUI_YES).onPress((button) -> { - listener.proceed( - mods.isChecked(), - configs.isChecked(), - folder.isChecked(), - delete.isChecked() - ); - }); - - return grid; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(boolean downloadMods, boolean downloadConfigs, boolean downloadFiles, boolean removeFiles); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/UpdatesScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/UpdatesScreen.java deleted file mode 100644 index 4ba093ec..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/UpdatesScreen.java +++ /dev/null @@ -1,131 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.networking.VersionChecker; -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.HorizontalStack; -import org.betterx.ui.layout.components.LayoutComponent; -import org.betterx.ui.layout.components.VerticalStack; -import org.betterx.ui.layout.values.Size; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.Style; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; -import net.fabricmc.loader.api.metadata.CustomValue; - -@Environment(EnvType.CLIENT) -public class UpdatesScreen extends BCLibLayoutScreen { - public static final String DONATION_URL = "https://www.paypal.com/donate/?hosted_button_id=7VTXYRXBHZQZJ"; - static final ResourceLocation UPDATE_LOGO_LOCATION = new ResourceLocation(BCLib.MOD_ID, "icon_updater.png"); - - public UpdatesScreen(Screen parent) { - super(parent, Component.translatable("bclib.updates.title"), 10, 10, 10); - } - - public ResourceLocation getUpdaterIcon(String modID) { - if (modID.equals(BCLib.MOD_ID)) { - return UPDATE_LOGO_LOCATION; - } - ModContainer nfo = FabricLoader.getInstance().getModContainer(modID).orElse(null); - if (nfo != null) { - CustomValue element = nfo.getMetadata().getCustomValue("bclib"); - if (element != null) { - CustomValue.CvObject obj = element.getAsObject(); - if (obj != null) { - CustomValue icon = obj.get("updater_icon"); - return new ResourceLocation(modID, icon.getAsString()); - } - } - } - return null; - } - - @Override - protected LayoutComponent initContent() { - VerticalStack rows = new VerticalStack(relative(1), fit()).centerHorizontal(); - rows.addMultilineText(fill(), fit(), Component.translatable("bclib.updates.description")) - .centerHorizontal(); - - rows.addSpacer(8); - - VersionChecker.forEachUpdate((mod, cur, updated) -> { - ModContainer nfo = FabricLoader.getInstance().getModContainer(mod).orElse(null); - ResourceLocation icon = getUpdaterIcon(mod); - HorizontalStack row = rows.addRow(fixed(320), fit()).centerHorizontal(); - if (icon != null) { - row.addImage(Value.fit(), Value.fit(), icon, Size.of(32)); - row.addSpacer(4); - } else { - row.addSpacer(36); - } - if (nfo != null) { - row.addText(fit(), fit(), Component.literal(nfo.getMetadata().getName())) - .setColor(ColorUtil.WHITE); - } else { - row.addText(fit(), fit(), Component.literal(mod)).setColor(ColorUtil.WHITE); - } - row.addSpacer(4); - row.addText(fit(), fit(), Component.literal(cur)); - row.addText(fit(), fit(), Component.literal(" -> ")); - row.addText(fit(), fit(), Component.literal(updated)).setColor(ColorUtil.GREEN); - row.addFiller(); - if (nfo != null && nfo.getMetadata().getContact().get("homepage").isPresent()) { - row.addButton(fit(), fit(), Component.translatable("bclib.updates.curseforge_link")) - .onPress((bt) -> { - this.openLink(nfo.getMetadata().getContact().get("homepage").get()); - }).centerVertical(); - } - }); - - VerticalStack layout = new VerticalStack(relative(1), fill()).centerHorizontal(); - //layout.addSpacer(8); - layout.addScrollable(rows); - layout.addSpacer(8); - - - HorizontalStack footer = layout.addRow(fill(), fit()); - if (Configs.CLIENT_CONFIG.isDonor()) { - footer.addButton( - fit(), - fit(), - Component.translatable("bclib.updates.donate").setStyle(Style.EMPTY.withColor(ColorUtil.YELLOW)) - ) - .onPress((bt) -> openLink(DONATION_URL)); - footer.addSpacer(2); - footer.addMultilineText(fit(), fit(), Component.translatable("bclib.updates.donate_pre")) - .alignBottom(); - } - - footer.addFiller(); - footer.addCheckbox( - fit(), fit(), - Component.translatable("Disable Check"), - !Configs.CLIENT_CONFIG.checkVersions() - ) - .onChange((cb, state) -> { - Configs.CLIENT_CONFIG.setCheckVersions(!state); - Configs.CLIENT_CONFIG.saveChanges(); - }); - footer.addSpacer(4); - footer.addButton(fit(), fit(), CommonComponents.GUI_DONE).onPress((bt -> { - onClose(); - })); - return layout; - } - - @Override - protected void renderBackground(PoseStack poseStack, int i, int j, float f) { - GuiComponent.fill(poseStack, 0, 0, width, height, 0xBD343444); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/WarnBCLibVersionMismatch.java b/src/main/java/org/betterx/bclib/client/gui/screens/WarnBCLibVersionMismatch.java deleted file mode 100644 index 1127a24d..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/WarnBCLibVersionMismatch.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.ui.layout.components.HorizontalStack; -import org.betterx.ui.layout.components.LayoutComponent; -import org.betterx.ui.layout.components.VerticalStack; - -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class WarnBCLibVersionMismatch extends BCLibLayoutScreen { - private final Component description; - private final Listener listener; - - public WarnBCLibVersionMismatch(Listener listener) { - super(Component.translatable("title.bclib.bclibmissmatch")); - - this.description = Component.translatable("message.bclib.bclibmissmatch"); - this.listener = listener; - } - - public boolean shouldCloseOnEsc() { - return false; - } - - @Override - protected LayoutComponent initContent() { - VerticalStack grid = new VerticalStack(fill(), fill()); - grid.addFiller(); - grid.addMultilineText(fill(), fit(), this.description).centerHorizontal(); - grid.addSpacer(20); - - HorizontalStack row = grid.addRow().centerHorizontal(); - row.addButton(fit(), fit(), CommonComponents.GUI_NO).onPress((button) -> listener.proceed(false)); - row.addSpacer(4); - row.addButton(fit(), fit(), CommonComponents.GUI_YES).onPress((button) -> listener.proceed(true)); - - grid.addFiller(); - return grid; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(boolean download); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/WelcomeScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/WelcomeScreen.java deleted file mode 100644 index b840e28a..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/WelcomeScreen.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.networking.VersionChecker; -import org.betterx.bclib.registry.PresetsRegistry; -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.*; -import org.betterx.ui.layout.values.Size; -import org.betterx.worlds.together.WorldsTogether; -import org.betterx.worlds.together.worldPreset.WorldPresets; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.Style; -import net.minecraft.resources.ResourceLocation; - -public class WelcomeScreen extends BCLibLayoutScreen { - static final ResourceLocation BETTERX_LOCATION = new ResourceLocation(BCLib.MOD_ID, "betterx.png"); - static final ResourceLocation BACKGROUND = new ResourceLocation(BCLib.MOD_ID, "header.jpg"); - static final ResourceLocation ICON_BETTERNETHER = new ResourceLocation(BCLib.MOD_ID, "icon_betternether.png"); - static final ResourceLocation ICON_BETTEREND = new ResourceLocation(BCLib.MOD_ID, "icon_betterend.png"); - - public WelcomeScreen(Screen parent) { - super(parent, translatable("bclib.welcome.title")); - } - - @Override - protected LayoutComponent initContent() { - VerticalStack content = new VerticalStack(fill(), fit()).setDebugName("content"); - - content.addImage(fill(), fit(), BACKGROUND, new Size(427, 100)); - content.addHorizontalLine(1).setColor(ColorUtil.BLACK); - content.addSpacer(16); - HorizontalStack headerRow = content.addRow(fit(), fit()).setDebugName("title bar").centerHorizontal(); - headerRow.addIcon(icon, Size.of(512)).setDebugName("icon"); - headerRow.addSpacer(4); - headerRow.addText(fit(), fit(), title).centerHorizontal().setColor(ColorUtil.WHITE).setDebugName("title"); - headerRow.addImage(fixed(178 / 2), fixed(40 / 2), BETTERX_LOCATION, Size.of(178, 40)).setDebugName("betterx"); - content.addSpacer(16); - - content.addMultilineText(fill(), fit(), MultiLineText.parse(translatable("bclib.welcome.description"))) - .centerHorizontal(); - - Container padContainer = new Container(fill(), fit()).setPadding(10, 0, 10, 10).setDebugName("padContainer"); - VerticalStack innerContent = new VerticalStack(fill(), fit()).setDebugName("innerContent"); - padContainer.addChild(innerContent); - content.add(padContainer); - if (Configs.CLIENT_CONFIG.isDonor()) { - addSeparator(innerContent, ICON_BETTEREND); - HorizontalStack donationRow = innerContent.addRow(relative(0.9), fit()) - .setDebugName("donationRow") - .centerHorizontal(); - - donationRow.addMultilineText(fill(), fit(), translatable("bclib.welcome.donation")) - .alignLeft() - .alignRight(); - donationRow.addSpacer(4); - donationRow.addButton( - fit(), fit(), - Component.translatable("bclib.updates.donate").setStyle(Style.EMPTY.withColor(ColorUtil.YELLOW)) - ) - .onPress((bt) -> openLink(UpdatesScreen.DONATION_URL)).centerVertical(); - } - - addSeparator(innerContent, ICON_BETTERNETHER); - - // Do Update Checks - Checkbox check = innerContent.addCheckbox( - fit(), - fit(), - translatable("title.config.bclib.client.version.check"), - Configs.CLIENT_CONFIG.checkVersions() - ) - .onChange((cb, state) -> { - Configs.CLIENT_CONFIG.setCheckVersions(state); - }); - innerContent.addSpacer(2); - HorizontalStack dscBox = innerContent.indent(24); - dscBox.addMultilineText(fill(), fit(), translatable("description.config.bclib.client.version.check")) - .setColor(ColorUtil.GRAY); - dscBox.addSpacer(8); - - // Hide Experimental Dialog - innerContent.addSpacer(8); - Checkbox experimental = innerContent.addCheckbox( - fit(), - fit(), - translatable("title.config.bclib.client.ui.suppressExperimentalDialogOnLoad"), - Configs.CLIENT_CONFIG.suppressExperimentalDialog() - ) - .onChange((cb, state) -> { - Configs.CLIENT_CONFIG.setSuppressExperimentalDialog(state); - }); - innerContent.addSpacer(2); - dscBox = innerContent.indent(24); - dscBox.addMultilineText( - fill(), - fit(), - translatable("description.config.bclib.client.ui.suppressExperimentalDialogOnLoad") - ) - .setColor(ColorUtil.GRAY); - dscBox.addSpacer(8); - - // Use BetterX WorldType - innerContent.addSpacer(8); - Checkbox betterx = innerContent.addCheckbox( - fit(), - fit(), - translatable("title.config.bclib.client.ui.forceBetterXPreset"), - Configs.CLIENT_CONFIG.forceBetterXPreset() - ) - .onChange((cb, state) -> { - Configs.CLIENT_CONFIG.setForceBetterXPreset(state); - }); - innerContent.addSpacer(2); - dscBox = innerContent.indent(24); - dscBox.addMultilineText( - fill(), fit(), - translatable("warning.config.bclib.client.ui.forceBetterXPreset") - .setStyle(Style.EMPTY - .withBold(true) - .withColor(ColorUtil.RED) - ) - .append(translatable( - "description.config.bclib.client.ui.forceBetterXPreset").setStyle( - Style.EMPTY - .withBold(false) - .withColor(ColorUtil.GRAY)) - ) - ) - .setColor(ColorUtil.GRAY); - dscBox.addSpacer(8); - - innerContent.addSpacer(16); - innerContent.addButton(fit(), fit(), CommonComponents.GUI_PROCEED).onPress((bt) -> { - Configs.CLIENT_CONFIG.setDidShowWelcomeScreen(); - Configs.CLIENT_CONFIG.setCheckVersions(check.isChecked()); - Configs.CLIENT_CONFIG.setSuppressExperimentalDialog(experimental.isChecked()); - Configs.CLIENT_CONFIG.setForceBetterXPreset(betterx.isChecked()); - Configs.CLIENT_CONFIG.saveChanges(); - - WorldsTogether.SURPRESS_EXPERIMENTAL_DIALOG = Configs.CLIENT_CONFIG.suppressExperimentalDialog(); - if (Configs.CLIENT_CONFIG.forceBetterXPreset()) - WorldPresets.setDEFAULT(PresetsRegistry.BCL_WORLD); - else - WorldPresets.setDEFAULT(net.minecraft.world.level.levelgen.presets.WorldPresets.NORMAL); - VersionChecker.startCheck(true); - onClose(); - }).alignRight(); - - return VerticalScroll.create(fill(), fill(), content).setScrollerPadding(0); - } - - private void addSeparator(VerticalStack innerContent, ResourceLocation image) { - final int sepWidth = (int) (427 / 1.181) / 2; - HorizontalStack separator = new HorizontalStack(fit(), fit()).centerHorizontal(); - separator.addHLine(fixed((sepWidth - 32) / 2), fixed(32)).centerVertical(); - separator.addSpacer(1); - separator.addImage(fixed(32), fixed(32), image, Size.of(64)).alignBottom(); - separator.addHLine(fixed((sepWidth - 32) / 2), fixed(32)).centerVertical(); - innerContent.addSpacer(16); - innerContent.add(separator); - innerContent.addSpacer(4); - } - - @Override - protected LayoutComponent addTitle(LayoutComponent content) { - return content; - } - - @Override - protected void renderBackground(PoseStack poseStack, int i, int j, float f) { - GuiComponent.fill(poseStack, 0, 0, width, height, 0xBD343444); -// Rectangle BANNER_UV = new Rectangle(0, 0, 427, 100); -// Size BANNER_RESOURCE_SIZE = BANNER_UV.size(); -// Size BANNER_SIZE = BANNER_UV.sizeFromWidth(this.width); -// -// RenderHelper.renderImage( -// poseStack, -// BANNER_SIZE.width(), -// BANNER_SIZE.height(), -// BACKGROUND, -// BANNER_UV, -// BANNER_RESOURCE_SIZE, -// 1.0f -// ); - } -} diff --git a/src/main/java/org/betterx/bclib/client/gui/screens/WorldSetupScreen.java b/src/main/java/org/betterx/bclib/client/gui/screens/WorldSetupScreen.java deleted file mode 100644 index a2e09292..00000000 --- a/src/main/java/org/betterx/bclib/client/gui/screens/WorldSetupScreen.java +++ /dev/null @@ -1,472 +0,0 @@ -package org.betterx.bclib.client.gui.screens; - -import org.betterx.bclib.api.v2.generator.BCLibEndBiomeSource; -import org.betterx.bclib.api.v2.generator.BCLibNetherBiomeSource; -import org.betterx.bclib.api.v2.generator.config.BCLEndBiomeSourceConfig; -import org.betterx.bclib.api.v2.generator.config.BCLNetherBiomeSourceConfig; -import org.betterx.bclib.api.v2.levelgen.LevelGenUtil; -import org.betterx.bclib.registry.PresetsRegistry; -import org.betterx.ui.layout.components.*; -import org.betterx.ui.layout.components.render.RenderHelper; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Size; -import org.betterx.ui.vanilla.LayoutScreen; -import org.betterx.worlds.together.worldPreset.TogetherWorldPreset; -import org.betterx.worlds.together.worldPreset.WorldGenSettingsComponentAccessor; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen; -import net.minecraft.client.gui.screens.worldselection.WorldCreationContext; -import net.minecraft.core.Holder; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.dimension.BuiltinDimensionTypes; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.presets.WorldPresets; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -@Environment(EnvType.CLIENT) -public class WorldSetupScreen extends LayoutScreen { - private final WorldCreationContext context; - private final CreateWorldScreen createWorldScreen; - private Range landBiomeSize; - private Range voidBiomeSize; - private Range centerBiomeSize; - private Range barrensBiomeSize; - private Range innerRadius; - - public WorldSetupScreen(@Nullable CreateWorldScreen parent, WorldCreationContext context) { - super(parent, Component.translatable("title.screen.bclib.worldgen.main"), 10, 10, 10); - this.context = context; - this.createWorldScreen = parent; - } - - - private Checkbox bclibEnd; - private Checkbox bclibNether; - Checkbox endLegacy; - Checkbox endCustomTerrain; - Checkbox generateEndVoid; - Checkbox netherLegacy; - - public LayoutComponent netherPage(BCLNetherBiomeSourceConfig netherConfig) { - VerticalStack content = new VerticalStack(fill(), fit()).centerHorizontal(); - content.addSpacer(8); - - bclibNether = content.addCheckbox( - fit(), fit(), - Component.translatable("title.screen.bclib.worldgen.custom_biome_source"), - netherConfig.mapVersion != BCLNetherBiomeSourceConfig.NetherBiomeMapType.VANILLA - ); - - netherLegacy = content.indent(20).addCheckbox( - fit(), fit(), - Component.translatable("title.screen.bclib.worldgen.legacy_square"), - netherConfig.mapVersion == BCLNetherBiomeSourceConfig.NetherBiomeMapType.SQUARE - ); - - - bclibNether.onChange((cb, state) -> { - netherLegacy.setEnabled(state); - }); - - content.addSpacer(8); - return content.setDebugName("Nether page"); - } - - public LayoutComponent endPage(BCLEndBiomeSourceConfig endConfig) { - VerticalStack content = new VerticalStack(fill(), fit()).centerHorizontal(); - content.addSpacer(8); - bclibEnd = content.addCheckbox( - fit(), fit(), - Component.translatable("title.screen.bclib.worldgen.custom_biome_source"), - endConfig.mapVersion != BCLEndBiomeSourceConfig.EndBiomeMapType.VANILLA - ); - - endLegacy = content.indent(20).addCheckbox( - fit(), fit(), - Component.translatable("title.screen.bclib.worldgen.legacy_square"), - endConfig.mapVersion == BCLEndBiomeSourceConfig.EndBiomeMapType.SQUARE - ); - - endCustomTerrain = content.indent(20).addCheckbox( - fit(), fit(), - Component.translatable("title.screen.bclib.worldgen.custom_end_terrain"), - endConfig.generatorVersion != BCLEndBiomeSourceConfig.EndBiomeGeneratorType.VANILLA - ); - - generateEndVoid = content.indent(20).addCheckbox( - fit(), fit(), - Component.translatable("title.screen.bclib.worldgen.end_void"), - endConfig.withVoidBiomes - ); - - content.addSpacer(12); - content.addText(fit(), fit(), Component.translatable("title.screen.bclib.worldgen.avg_biome_size")) - .centerHorizontal(); - content.addHorizontalSeparator(8).alignTop(); - - landBiomeSize = content.addRange( - fixed(200), - fit(), - Component.translatable("title.screen.bclib.worldgen.land_biome_size"), - 1, - 512, - endConfig.landBiomesSize / 16 - ); - - voidBiomeSize = content.addRange( - fixed(200), - fit(), - Component.translatable("title.screen.bclib.worldgen.void_biome_size"), - 1, - 512, - endConfig.voidBiomesSize / 16 - ); - - centerBiomeSize = content.addRange( - fixed(200), - fit(), - Component.translatable("title.screen.bclib.worldgen.center_biome_size"), - 1, - 512, - endConfig.centerBiomesSize / 16 - ); - - barrensBiomeSize = content.addRange( - fixed(200), - fit(), - Component.translatable("title.screen.bclib.worldgen.barrens_biome_size"), - 1, - 512, - endConfig.barrensBiomesSize / 16 - ); - - content.addSpacer(12); - content.addText(fit(), fit(), Component.translatable("title.screen.bclib.worldgen.other")) - .centerHorizontal(); - content.addHorizontalSeparator(8).alignTop(); - - innerRadius = content.addRange( - fixed(200), - fit(), - Component.translatable("title.screen.bclib.worldgen.central_radius"), - 1, - 512, - (int) Math.sqrt(endConfig.innerVoidRadiusSquared) / 16 - ); - - - bclibEnd.onChange((cb, state) -> { - endLegacy.setEnabled(state); - endCustomTerrain.setEnabled(state); - generateEndVoid.setEnabled(state); - - landBiomeSize.setEnabled(state && endCustomTerrain.isChecked()); - voidBiomeSize.setEnabled(state && endCustomTerrain.isChecked() && generateEndVoid.isChecked()); - centerBiomeSize.setEnabled(state && endCustomTerrain.isChecked()); - barrensBiomeSize.setEnabled(state && endCustomTerrain.isChecked()); - }); - - endCustomTerrain.onChange((cb, state) -> { - landBiomeSize.setEnabled(state); - voidBiomeSize.setEnabled(state && generateEndVoid.isChecked()); - centerBiomeSize.setEnabled(state); - barrensBiomeSize.setEnabled(state); - }); - - generateEndVoid.onChange((cb, state) -> { - voidBiomeSize.setEnabled(state && endCustomTerrain.isChecked()); - }); - - content.addSpacer(8); - return content.setDebugName("End Page"); - } - - private void updateSettings() { - Map, ChunkGenerator> betterxDimensions = TogetherWorldPreset.getDimensionsMap( - PresetsRegistry.BCL_WORLD); - Map, ChunkGenerator> vanillaDimensions = TogetherWorldPreset.getDimensionsMap( - WorldPresets.NORMAL); - BCLEndBiomeSourceConfig.EndBiomeMapType endVersion = BCLEndBiomeSourceConfig.DEFAULT.mapVersion; - - - if (bclibEnd.isChecked()) { - BCLEndBiomeSourceConfig endConfig = new BCLEndBiomeSourceConfig( - endLegacy.isChecked() - ? BCLEndBiomeSourceConfig.EndBiomeMapType.SQUARE - : BCLEndBiomeSourceConfig.EndBiomeMapType.HEX, - endCustomTerrain.isChecked() - ? BCLEndBiomeSourceConfig.EndBiomeGeneratorType.PAULEVS - : BCLEndBiomeSourceConfig.EndBiomeGeneratorType.VANILLA, - generateEndVoid.isChecked(), - (int) Math.pow(innerRadius.getValue() * 16, 2), - centerBiomeSize.getValue(), - voidBiomeSize.getValue(), - landBiomeSize.getValue(), - barrensBiomeSize.getValue() - ); - - ChunkGenerator endGenerator = betterxDimensions.get(LevelStem.END); - ((BCLibEndBiomeSource) endGenerator.getBiomeSource()).setTogetherConfig(endConfig); - - updateConfiguration(LevelStem.END, BuiltinDimensionTypes.END, endGenerator); - } else { - ChunkGenerator endGenerator = vanillaDimensions.get(LevelStem.END); - updateConfiguration(LevelStem.END, BuiltinDimensionTypes.END, endGenerator); - } - - if (bclibNether.isChecked()) { - BCLNetherBiomeSourceConfig netherConfig = new BCLNetherBiomeSourceConfig( - netherLegacy.isChecked() - ? BCLNetherBiomeSourceConfig.NetherBiomeMapType.SQUARE - : BCLNetherBiomeSourceConfig.NetherBiomeMapType.HEX, - BCLNetherBiomeSourceConfig.DEFAULT.biomeSize, - BCLNetherBiomeSourceConfig.DEFAULT.biomeSizeVertical, - BCLNetherBiomeSourceConfig.DEFAULT.useVerticalBiomes - ); - - ChunkGenerator netherGenerator = betterxDimensions.get(LevelStem.NETHER); - ((BCLibNetherBiomeSource) netherGenerator.getBiomeSource()).setTogetherConfig(netherConfig); - - updateConfiguration(LevelStem.NETHER, BuiltinDimensionTypes.NETHER, netherGenerator); - } else { - ChunkGenerator endGenerator = vanillaDimensions.get(LevelStem.NETHER); - updateConfiguration(LevelStem.NETHER, BuiltinDimensionTypes.NETHER, endGenerator); - } - - if (createWorldScreen.worldGenSettingsComponent instanceof WorldGenSettingsComponentAccessor acc - && acc.bcl_getPreset() - .isPresent() && acc.bcl_getPreset() - .get() - .value() instanceof TogetherWorldPreset worldPreset) { - acc.bcl_setPreset(Optional.of(Holder.direct( - worldPreset.withDimensions( - createWorldScreen - .worldGenSettingsComponent - .settings() - .worldGenSettings() - .dimensions() - ) - ))); - } - } - - - private void updateConfiguration( - ResourceKey dimensionKey, - ResourceKey dimensionTypeKey, - ChunkGenerator chunkGenerator - ) { - createWorldScreen.worldGenSettingsComponent.updateSettings( - (registryAccess, worldGenSettings) -> LevelGenUtil.replaceGenerator( - dimensionKey, - dimensionTypeKey, - registryAccess, - worldGenSettings, - chunkGenerator - ) - ); - } - - @Override - protected LayoutComponent addTitle(LayoutComponent content) { - VerticalStack rows = new VerticalStack(fill(), fill()).setDebugName("title stack"); - - if (topPadding > 0) rows.addSpacer(topPadding); - rows.add(content); - if (bottomPadding > 0) rows.addSpacer(bottomPadding); - - if (sidePadding <= 0) return rows; - - HorizontalStack cols = new HorizontalStack(fill(), fill()).setDebugName("padded side"); - cols.addSpacer(sidePadding); - cols.add(rows); - cols.addSpacer(sidePadding); - return cols; - } - - Button netherButton, endButton; - VerticalScroll scroller; - HorizontalStack title; - - @Override - protected LayoutComponent initContent() { - BCLEndBiomeSourceConfig endConfig = BCLEndBiomeSourceConfig.VANILLA; - BCLNetherBiomeSourceConfig netherConfig = BCLNetherBiomeSourceConfig.VANILLA; - if (createWorldScreen.worldGenSettingsComponent instanceof WorldGenSettingsComponentAccessor acc - && acc.bcl_getPreset() - .isPresent() && acc.bcl_getPreset() - .get() - .value() instanceof TogetherWorldPreset wp) { - - LevelStem endStem = wp.getDimension(LevelStem.END); - if (endStem != null && endStem.generator().getBiomeSource() instanceof BCLibEndBiomeSource bs) { - endConfig = bs.getTogetherConfig(); - } - LevelStem netherStem = wp.getDimension(LevelStem.NETHER); - if (netherStem != null && netherStem.generator().getBiomeSource() instanceof BCLibNetherBiomeSource bs) { - netherConfig = bs.getTogetherConfig(); - } - } - - var netherPage = netherPage(netherConfig); - var endPage = endPage(endConfig); - - Tabs main = new Tabs(fill(), fill()).setPadding(8, 0, 0, 0); - main.addPage(Component.translatable("title.bclib.the_nether"), VerticalScroll.create(netherPage)); - main.addSpacer(8); - main.addPage(Component.translatable("title.bclib.the_end"), scroller = VerticalScroll.create(endPage)); - netherButton = main.getButton(0); - endButton = main.getButton(1); - - title = new HorizontalStack(fit(), fit()).setDebugName("title bar").alignBottom(); - title.addImage(fixed(22), fixed(22), BCLibLayoutScreen.BCLIB_LOGO_WHITE_LOCATION, Size.of(256)) - .setDebugName("icon"); - title.addSpacer(4); - VerticalStack logos = title.addColumn(fit(), fit()); - logos.addImage(fixed(178 / 3), fixed(40 / 3), WelcomeScreen.BETTERX_LOCATION, Size.of(178, 40)); - logos.add(super.buildTitle()); - logos.addSpacer(2); - - main.addFiller(); - main.addComponent(title); - - - VerticalStack rows = new VerticalStack(fill(), fill()); - rows.add(main); - rows.addSpacer(4); - rows.addButton(fit(), fit(), CommonComponents.GUI_DONE).onPress((bt) -> { - updateSettings(); - onClose(); - }).alignRight(); - - main.onPageChange((tabs, idx) -> { - targetT = 1 - idx; - }); - - return rows; - } - - @Override - protected void renderBackground(PoseStack poseStack, int i, int j, float f) { - GuiComponent.fill(poseStack, 0, 0, width, height, 0xBD343444); - } - - record IconState(int left, int top, int size) { - //easing curves from https://easings.net/de - static double easeInOutQuint(double t) { - return t < 0.5 ? 16 * t * t * t * t * t : 1 - Math.pow(-2 * t + 2, 5) / 2; - } - - static double easeOutBounce(double x) { - final double n1 = 7.5625; - final double d1 = 2.75; - - if (x < 1 / d1) { - return n1 * x * x; - } else if (x < 2 / d1) { - return n1 * (x -= 1.5 / d1) * x + 0.75; - } else if (x < 2.5 / d1) { - return n1 * (x -= 2.25 / d1) * x + 0.9375; - } else { - return n1 * (x -= 2.625 / d1) * x + 0.984375; - } - } - - static int lerp(double t, int x0, int x1) { - return (int) ((1 - t) * x0 + t * x1); - } - } - - IconState netherOff, netherOn, endOff, endOn; - double iconT = 0.5; - double targetT = 1; - - @Override - public void render(PoseStack poseStack, int i, int j, float f) { - super.render(poseStack, i, j, f); - final double SPEED = 0.05; - if (targetT < iconT && iconT > 0) iconT = Math.max(0, iconT - f * SPEED); - else if (targetT > iconT && iconT < 1) iconT = Math.min(1, iconT + f * SPEED); - - final double t; - if (iconT > 0 && iconT < 1) { - if (targetT > iconT) { - t = IconState.easeOutBounce(iconT); - } else { - t = 1 - IconState.easeOutBounce(1 - iconT); - } - } else t = iconT; - - if (endButton != null) { - if (endOff == null) { - endOff = new IconState( - endButton.getScreenBounds().right() - 12, - endButton.getScreenBounds().top - 7, - 16 - ); - endOn = new IconState( - (title.getScreenBounds().left - endButton.getScreenBounds().right()) / 2 - + endButton.getScreenBounds().right() - - 14, - scroller.getScreenBounds().top - 16, - 32 - ); - } - poseStack.pushPose(); - poseStack.translate( - IconState.lerp(t, endOn.left, endOff.left), - IconState.lerp(t, endOn.top, endOff.top), - 0 - ); - int size = IconState.lerp(t, endOn.size, endOff.size); - RenderHelper.renderImage( - poseStack, 0, 0, - size, - size, - WelcomeScreen.ICON_BETTEREND, - Size.of(32), new Rectangle(0, 0, 32, 32), - (float) 1 - ); - poseStack.popPose(); - } - - if (netherButton != null) { - if (netherOff == null) { - netherOff = new IconState( - netherButton.getScreenBounds().right() - 12, - netherButton.getScreenBounds().top - 7, - 16 - ); - netherOn = endOn; - } - poseStack.pushPose(); - poseStack.translate( - IconState.lerp(t, netherOff.left, netherOn.left), - IconState.lerp(t, netherOff.top, netherOn.top), - 0 - ); - int size = IconState.lerp(t, netherOff.size, netherOn.size); - RenderHelper.renderImage( - poseStack, 0, 0, - size, - size, - WelcomeScreen.ICON_BETTERNETHER, - Size.of(32), new Rectangle(0, 0, 32, 32), - (float) 1 - ); - poseStack.popPose(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/BaseChestBlockModel.java b/src/main/java/org/betterx/bclib/client/models/BaseChestBlockModel.java deleted file mode 100644 index 6acde89a..00000000 --- a/src/main/java/org/betterx/bclib/client/models/BaseChestBlockModel.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.betterx.bclib.client.models; - -import net.minecraft.client.model.geom.ModelPart; -import net.minecraft.client.model.geom.PartPose; -import net.minecraft.client.model.geom.builders.*; - -public class BaseChestBlockModel { - public final ModelPart partA; - public final ModelPart partC; - public final ModelPart partB; - public final ModelPart partRightA; - public final ModelPart partRightC; - public final ModelPart partRightB; - public final ModelPart partLeftA; - public final ModelPart partLeftC; - public final ModelPart partLeftB; - - public static LayerDefinition getTexturedModelData() { - MeshDefinition modelData = new MeshDefinition(); - PartDefinition modelPartData = modelData.getRoot(); - CubeDeformation deformation_partC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partC", - CubeListBuilder.create().texOffs(0, 19).addBox(1.0f, 0.0f, 1.0f, 14.0f, 9.0f, 14.0f, deformation_partC), - PartPose.ZERO - ); - - CubeDeformation deformation_partA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partA", - CubeListBuilder.create().texOffs(0, 0).addBox(1.0f, 0.0f, 0.0f, 14.0f, 5.0f, 14.0f, deformation_partA), - PartPose.offset(0.0f, 9.0f, 1.0f) - ); - - CubeDeformation deformation_partB = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partB", - CubeListBuilder.create().texOffs(0, 0).addBox(7.0f, -1.0f, 15.0f, 2.0f, 4.0f, 1.0f, deformation_partB), - PartPose.offset(0.0f, 8.0f, 0.0f) - ); - - CubeDeformation deformation_partRightC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partRightC", - CubeListBuilder.create() - .texOffs(0, 19) - .addBox(1.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partRightC), - PartPose.ZERO - ); - - CubeDeformation deformation_partRightA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partRightA", - CubeListBuilder.create() - .texOffs(0, 0) - .addBox(1.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partRightA), - PartPose.offset(0.0f, 9.0f, 1.0f) - ); - - CubeDeformation deformation_partRightB = new CubeDeformation(0.0f); - PartDefinition partRightB = modelPartData.addOrReplaceChild( - "partRightB", - CubeListBuilder.create() - .texOffs(0, 0) - .addBox(15.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partRightB), - PartPose.offset(0.0f, 8.0f, 0.0f) - ); - - CubeDeformation deformation_partLeftC = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partLeftC", - CubeListBuilder.create() - .texOffs(0, 19) - .addBox(0.0f, 0.0f, 1.0f, 15.0f, 9.0f, 14.0f, deformation_partLeftC), - PartPose.ZERO - ); - - CubeDeformation deformation_partLeftA = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partLeftA", - CubeListBuilder.create() - .texOffs(0, 0) - .addBox(0.0f, 0.0f, 0.0f, 15.0f, 5.0f, 14.0f, deformation_partLeftA), - PartPose.offset(0.0f, 9.0f, 1.0f) - ); - - CubeDeformation deformation_partLeftB = new CubeDeformation(0.0f); - modelPartData.addOrReplaceChild( - "partLeftB", - CubeListBuilder.create() - .texOffs(0, 0) - .addBox(0.0f, -1.0f, 15.0f, 1.0f, 4.0f, 1.0f, deformation_partLeftB), - PartPose.offset(0.0f, 8.0f, 0.0f) - ); - - return LayerDefinition.create(modelData, 64, 64); - } - - public BaseChestBlockModel(ModelPart modelPart) { - super(); - - partC = modelPart.getChild("partC"); - partA = modelPart.getChild("partA"); - partB = modelPart.getChild("partB"); - partRightC = modelPart.getChild("partRightC"); - partRightA = modelPart.getChild("partRightA"); - partRightB = modelPart.getChild("partRightB"); - partLeftC = modelPart.getChild("partLeftC"); - partLeftA = modelPart.getChild("partLeftA"); - partLeftB = modelPart.getChild("partLeftB"); - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/BasePatterns.java b/src/main/java/org/betterx/bclib/client/models/BasePatterns.java deleted file mode 100644 index db14c841..00000000 --- a/src/main/java/org/betterx/bclib/client/models/BasePatterns.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.client.models; - -import org.betterx.bclib.BCLib; - -import net.minecraft.resources.ResourceLocation; - -public class BasePatterns { - //Block Models - public final static ResourceLocation BLOCK_EMPTY = BCLib.makeID("patterns/block/empty.json"); - public final static ResourceLocation BLOCK_BASE = BCLib.makeID("patterns/block/block.json"); - public final static ResourceLocation BLOCK_SIDED = BCLib.makeID("patterns/block/block_sided.json"); - public final static ResourceLocation BLOCK_BOTTOM_TOP = BCLib.makeID("patterns/block/block_bottom_top.json"); - public final static ResourceLocation BLOCK_SLAB = BCLib.makeID("patterns/block/slab.json"); - public final static ResourceLocation BLOCK_STAIR = BCLib.makeID("patterns/block/stairs.json"); - public final static ResourceLocation BLOCK_STAIR_INNER = BCLib.makeID("patterns/block/stairs_inner.json"); - public final static ResourceLocation BLOCK_STAIR_OUTER = BCLib.makeID("patterns/block/stairs_outer.json"); - public final static ResourceLocation BLOCK_WALL_POST = BCLib.makeID("patterns/block/wall_post.json"); - public final static ResourceLocation BLOCK_WALL_SIDE = BCLib.makeID("patterns/block/wall_side.json"); - public final static ResourceLocation BLOCK_WALL_SIDE_TALL = BCLib.makeID("patterns/block/wall_side_tall.json"); - public final static ResourceLocation BLOCK_FENCE_POST = BCLib.makeID("patterns/block/fence_post.json"); - public final static ResourceLocation BLOCK_FENCE_SIDE = BCLib.makeID("patterns/block/fence_side.json"); - public final static ResourceLocation BLOCK_BUTTON = BCLib.makeID("patterns/block/button.json"); - public final static ResourceLocation BLOCK_BUTTON_PRESSED = BCLib.makeID("patterns/block/button_pressed.json"); - public final static ResourceLocation BLOCK_PILLAR = BCLib.makeID("patterns/block/pillar.json"); - public final static ResourceLocation BLOCK_PLATE_UP = BCLib.makeID("patterns/block/pressure_plate_up.json"); - public final static ResourceLocation BLOCK_PLATE_DOWN = BCLib.makeID("patterns/block/pressure_plate_down.json"); - public final static ResourceLocation BLOCK_DOOR_TOP = BCLib.makeID("patterns/block/door_top.json"); - public final static ResourceLocation BLOCK_DOOR_TOP_HINGE = BCLib.makeID("patterns/block/door_top_hinge.json"); - public final static ResourceLocation BLOCK_DOOR_BOTTOM = BCLib.makeID("patterns/block/door_bottom.json"); - public final static ResourceLocation BLOCK_DOOR_BOTTOM_HINGE = BCLib.makeID("patterns/block/door_bottom_hinge.json"); - public final static ResourceLocation BLOCK_CROSS = BCLib.makeID("patterns/block/cross.json"); - public final static ResourceLocation BLOCK_CROSS_SHADED = BCLib.makeID("patterns/block/cross_shaded.json"); - public final static ResourceLocation BLOCK_GATE_CLOSED = BCLib.makeID("patterns/block/fence_gate_closed.json"); - public final static ResourceLocation BLOCK_GATE_CLOSED_WALL = BCLib.makeID("patterns/block/wall_gate_closed.json"); - public final static ResourceLocation BLOCK_GATE_OPEN = BCLib.makeID("patterns/block/fence_gate_open.json"); - public final static ResourceLocation BLOCK_GATE_OPEN_WALL = BCLib.makeID("patterns/block/wall_gate_open.json"); - public final static ResourceLocation BLOCK_TRAPDOOR = BCLib.makeID("patterns/block/trapdoor.json"); - public final static ResourceLocation BLOCK_LADDER = BCLib.makeID("patterns/block/ladder.json"); - public final static ResourceLocation BLOCK_BARREL_OPEN = BCLib.makeID("patterns/block/barrel_open.json"); - public final static ResourceLocation BLOCK_BOOKSHELF = BCLib.makeID("patterns/block/bookshelf.json"); - public final static ResourceLocation BLOCK_COMPOSTER = BCLib.makeID("patterns/block/composter.json"); - public final static ResourceLocation BLOCK_COLORED = BCLib.makeID("patterns/block/block_colored.json"); - public final static ResourceLocation BLOCK_BARS_POST = BCLib.makeID("patterns/block/bars_post.json"); - public final static ResourceLocation BLOCK_BARS_SIDE = BCLib.makeID("patterns/block/bars_side.json"); - public final static ResourceLocation BLOCK_ANVIL = BCLib.makeID("patterns/block/anvil.json"); - public final static ResourceLocation BLOCK_CHAIN = BCLib.makeID("patterns/block/chain.json"); - public final static ResourceLocation BLOCK_FURNACE = BCLib.makeID("patterns/block/furnace.json"); - public final static ResourceLocation BLOCK_FURNACE_LIT = BCLib.makeID("patterns/block/furnace_glow.json"); - public final static ResourceLocation BLOCK_TOP_SIDE_BOTTOM = BCLib.makeID("patterns/block/top_side_bottom.json"); - public final static ResourceLocation BLOCK_PATH = BCLib.makeID("patterns/block/path.json"); - - //Item Models - public final static ResourceLocation ITEM_WALL = BCLib.makeID("patterns/item/pattern_wall.json"); - public final static ResourceLocation ITEM_FENCE = BCLib.makeID("patterns/item/pattern_fence.json"); - public final static ResourceLocation ITEM_BUTTON = BCLib.makeID("patterns/item/pattern_button.json"); - public final static ResourceLocation ITEM_CHEST = BCLib.makeID("patterns/item/pattern_chest.json"); - public final static ResourceLocation ITEM_BLOCK = BCLib.makeID("patterns/item/pattern_block_item.json"); - public final static ResourceLocation ITEM_GENERATED = BCLib.makeID("patterns/item/pattern_item_generated.json"); - public final static ResourceLocation ITEM_HANDHELD = BCLib.makeID("patterns/item/pattern_item_handheld.json"); - public final static ResourceLocation ITEM_SPAWN_EGG = BCLib.makeID("patterns/item/pattern_item_spawn_egg.json"); - - public final static ResourceLocation VANILLA_WOOD_BOOKSHELF = BCLib.makeID( - "patterns/block/vanilla_wood_bookshelf.json"); -} diff --git a/src/main/java/org/betterx/bclib/client/models/CustomModelBakery.java b/src/main/java/org/betterx/bclib/client/models/CustomModelBakery.java deleted file mode 100644 index f820c5f8..00000000 --- a/src/main/java/org/betterx/bclib/client/models/CustomModelBakery.java +++ /dev/null @@ -1,156 +0,0 @@ -package org.betterx.bclib.client.models; - -import org.betterx.bclib.api.v2.ModIntegrationAPI; -import org.betterx.bclib.client.render.EmissiveTextureInfo; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.ItemModelProvider; -import org.betterx.bclib.models.RecordItemModelProvider; - -import com.mojang.datafixers.util.Pair; -import net.minecraft.client.renderer.block.BlockModelShaper; -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.renderer.block.model.multipart.MultiPart; -import net.minecraft.client.resources.model.Material; -import net.minecraft.client.resources.model.ModelResourceLocation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -public class CustomModelBakery { - private final Map models = Maps.newConcurrentMap(); - - public UnbakedModel getBlockModel(ResourceLocation location) { - return models.get(location); - } - - public UnbakedModel getItemModel(ResourceLocation location) { - ResourceLocation storageID = new ResourceLocation( - location.getNamespace(), - "models/item/" + location.getPath() + ".json" - ); - return models.get(location); - } - - public void loadCustomModels(ResourceManager resourceManager) { - Registry.BLOCK.stream().parallel().filter(block -> block instanceof BlockModelProvider).forEach(block -> { - ResourceLocation blockID = Registry.BLOCK.getKey(block); - ResourceLocation storageID = new ResourceLocation( - blockID.getNamespace(), - "blockstates/" + blockID.getPath() + ".json" - ); - if (resourceManager.getResource(storageID).isEmpty()) { - addBlockModel(blockID, block); - } - storageID = new ResourceLocation(blockID.getNamespace(), "models/item/" + blockID.getPath() + ".json"); - if (resourceManager.getResource(storageID).isEmpty()) { - addItemModel(blockID, (ItemModelProvider) block); - } - }); - - Registry.ITEM.stream() - .parallel() - .filter(item -> item instanceof ItemModelProvider || RecordItemModelProvider.has(item)) - .forEach(item -> { - ResourceLocation registryID = Registry.ITEM.getKey(item); - ResourceLocation storageID = new ResourceLocation( - registryID.getNamespace(), - "models/item/" + registryID.getPath() + ".json" - ); - final ItemModelProvider provider = (item instanceof ItemModelProvider) - ? (ItemModelProvider) item - : RecordItemModelProvider.get(item); - - if (resourceManager.getResource(storageID).isEmpty()) { - addItemModel(registryID, provider); - } - }); - } - - private void addBlockModel(ResourceLocation blockID, Block block) { - BlockModelProvider provider = (BlockModelProvider) block; - ImmutableList states = block.getStateDefinition().getPossibleStates(); - BlockState defaultState = block.defaultBlockState(); - - ResourceLocation defaultStateID = BlockModelShaper.stateToModelLocation(blockID, defaultState); - UnbakedModel defaultModel = provider.getModelVariant(defaultStateID, defaultState, models); - - if (defaultModel instanceof MultiPart) { - states.forEach(blockState -> { - ResourceLocation stateID = BlockModelShaper.stateToModelLocation(blockID, blockState); - models.put(stateID, defaultModel); - }); - } else { - states.forEach(blockState -> { - ResourceLocation stateID = BlockModelShaper.stateToModelLocation(blockID, blockState); - UnbakedModel model = stateID.equals(defaultStateID) - ? defaultModel - : provider.getModelVariant(stateID, blockState, models); - models.put(stateID, model); - }); - } - } - - private void addItemModel(ResourceLocation itemID, ItemModelProvider provider) { - ModelResourceLocation modelLocation = new ModelResourceLocation( - itemID.getNamespace(), - itemID.getPath(), - "inventory" - ); - if (models.containsKey(modelLocation)) { - return; - } - BlockModel model = provider.getItemModel(modelLocation); - models.put(modelLocation, model); - } - - public static void loadEmissiveModels(Map unbakedCache) { - if (!ModIntegrationAPI.hasCanvas()) { - return; - } - - Map cacheCopy = new HashMap<>(unbakedCache); - Set> strings = Sets.newConcurrentHashSet(); - Registry.BLOCK.keySet().forEach(blockID -> { - Block block = Registry.BLOCK.get(blockID); - ImmutableList states = block.getStateDefinition().getPossibleStates(); - boolean addBlock = false; - - for (BlockState state : states) { - ResourceLocation stateID = BlockModelShaper.stateToModelLocation(blockID, state); - UnbakedModel model = cacheCopy.get(stateID); - if (model == null) { - continue; - } - Collection materials = model.getMaterials(cacheCopy::get, strings); - if (materials == null) { - continue; - } - for (Material material : materials) { - if (EmissiveTextureInfo.isEmissiveTexture(material.texture())) { - addBlock = true; - break; - } - } - if (addBlock) { - break; - } - } - - if (addBlock) { - EmissiveTextureInfo.addBlock(blockID); - } - }); - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/CustomModelData.java b/src/main/java/org/betterx/bclib/client/models/CustomModelData.java deleted file mode 100644 index 35698fbf..00000000 --- a/src/main/java/org/betterx/bclib/client/models/CustomModelData.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.client.models; - -import net.minecraft.resources.ResourceLocation; - -import com.google.common.collect.Sets; - -import java.util.Set; - -public class CustomModelData { - private static final Set TRANSPARENT_EMISSION = Sets.newConcurrentHashSet(); - - public static void clear() { - TRANSPARENT_EMISSION.clear(); - } - - public static void addTransparent(ResourceLocation blockID) { - TRANSPARENT_EMISSION.add(blockID); - } - - public static boolean isTransparentEmissive(ResourceLocation rawLocation) { - String name = rawLocation.getPath().replace("materialmaps/block/", "").replace(".json", ""); - return TRANSPARENT_EMISSION.contains(new ResourceLocation(rawLocation.getNamespace(), name)); - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/ModelsHelper.java b/src/main/java/org/betterx/bclib/client/models/ModelsHelper.java deleted file mode 100644 index ec51963d..00000000 --- a/src/main/java/org/betterx/bclib/client/models/ModelsHelper.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.betterx.bclib.client.models; - -import com.mojang.math.Transformation; -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.renderer.block.model.MultiVariant; -import net.minecraft.client.renderer.block.model.Variant; -import net.minecraft.client.renderer.block.model.multipart.Condition; -import net.minecraft.client.renderer.block.model.multipart.MultiPart; -import net.minecraft.client.renderer.block.model.multipart.Selector; -import net.minecraft.client.resources.model.BlockModelRotation; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.StateDefinition; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; - -import java.util.List; -import java.util.Optional; -import java.util.function.Function; - -@Environment(EnvType.CLIENT) -public class ModelsHelper { - public static BlockModel fromPattern(Optional pattern) { - return pattern.map(BlockModel::fromString).orElse(null); - } - - public static BlockModel createItemModel(ResourceLocation resourceLocation) { - return fromPattern(PatternsHelper.createItemGenerated(resourceLocation)); - } - - public static BlockModel createHandheldItem(ResourceLocation resourceLocation) { - return fromPattern(PatternsHelper.createItemHandheld(resourceLocation)); - } - - public static BlockModel createBlockItem(ResourceLocation resourceLocation) { - Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_BLOCK, resourceLocation); - return fromPattern(pattern); - } - - public static BlockModel createBlockEmpty(ResourceLocation resourceLocation) { - Optional pattern = PatternsHelper.createJson(BasePatterns.BLOCK_EMPTY, resourceLocation); - return fromPattern(pattern); - } - - public static MultiVariant createMultiVariant( - ResourceLocation resourceLocation, - Transformation transform, - boolean uvLock - ) { - Variant variant = new Variant(resourceLocation, transform, uvLock, 1); - return new MultiVariant(Lists.newArrayList(variant)); - } - - public static MultiVariant createBlockSimple(ResourceLocation resourceLocation) { - return createMultiVariant(resourceLocation, Transformation.identity(), false); - } - - public static MultiVariant createFacingModel( - ResourceLocation resourceLocation, - Direction facing, - boolean uvLock, - boolean inverted - ) { - if (inverted) { - facing = facing.getOpposite(); - } - BlockModelRotation rotation = BlockModelRotation.by(0, (int) facing.toYRot()); - return createMultiVariant(resourceLocation, rotation.getRotation(), uvLock); - } - - public static MultiVariant createRotatedModel(ResourceLocation resourceLocation, Direction.Axis axis) { - BlockModelRotation rotation = BlockModelRotation.X0_Y0; - switch (axis) { - case X: - rotation = BlockModelRotation.X90_Y90; - break; - case Z: - rotation = BlockModelRotation.X90_Y0; - break; - default: - break; - } - return createMultiVariant(resourceLocation, rotation.getRotation(), false); - } - - public static MultiVariant createRandomTopModel(ResourceLocation resourceLocation) { - return new MultiVariant(Lists.newArrayList( - new Variant(resourceLocation, Transformation.identity(), false, 1), - new Variant(resourceLocation, BlockModelRotation.X0_Y90.getRotation(), false, 1), - new Variant(resourceLocation, BlockModelRotation.X0_Y180.getRotation(), false, 1), - new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1) - )); - } - - public static class MultiPartBuilder { - - //private final static MultiPartBuilder BUILDER = new MultiPartBuilder(); - - public static MultiPartBuilder create(StateDefinition stateDefinition) { - // BUILDER.stateDefinition = stateDefinition; - //BUILDER.modelParts.clear(); - // return BUILDER; - return new MultiPartBuilder(stateDefinition); - } - - private final List modelParts = Lists.newArrayList(); - private final StateDefinition stateDefinition; - - private MultiPartBuilder(StateDefinition stateDefinition) { - this.stateDefinition = stateDefinition; - } - - public ModelPart part(ResourceLocation modelId) { - ModelPart part = new ModelPart(modelId); - return part; - } - - public MultiPart build() { - if (modelParts.size() > 0) { - List selectors = Lists.newArrayList(); - modelParts.forEach(modelPart -> { - MultiVariant variant = createMultiVariant(modelPart.modelId, modelPart.transform, modelPart.uvLock); - selectors.add(new Selector(modelPart.condition, variant)); - }); - modelParts.clear(); - return new MultiPart(stateDefinition, selectors); - } - throw new IllegalStateException("At least one model part need to be created."); - } - - public class ModelPart { - private final ResourceLocation modelId; - private Transformation transform = Transformation.identity(); - private Condition condition = Condition.TRUE; - private boolean uvLock = false; - - private ModelPart(ResourceLocation modelId) { - this.modelId = modelId; - } - - public ModelPart setCondition(Function condition) { - this.condition = stateDefinition -> condition::apply; - return this; - } - - public ModelPart setTransformation(Transformation transform) { - this.transform = transform; - return this; - } - - public ModelPart setUVLock(boolean value) { - this.uvLock = value; - return this; - } - - public void add() { - modelParts.add(this); - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/OBJBlockModel.java b/src/main/java/org/betterx/bclib/client/models/OBJBlockModel.java deleted file mode 100644 index 40e5b60a..00000000 --- a/src/main/java/org/betterx/bclib/client/models/OBJBlockModel.java +++ /dev/null @@ -1,303 +0,0 @@ -package org.betterx.bclib.client.models; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.util.BlocksHelper; -import org.betterx.bclib.util.MHelper; - -import com.mojang.datafixers.util.Pair; -import com.mojang.math.Vector3f; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.block.model.ItemOverrides; -import net.minecraft.client.renderer.block.model.ItemTransforms; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.*; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.block.state.BlockState; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.*; -import java.util.function.Function; -import org.jetbrains.annotations.Nullable; - -@Environment(EnvType.CLIENT) -public class OBJBlockModel implements UnbakedModel, BakedModel { - private static final Vector3f[] POSITIONS = new Vector3f[]{new Vector3f(), new Vector3f(), new Vector3f()}; - - protected final Map> quadsUnbakedMap = Maps.newEnumMap(Direction.class); - protected final Map> quadsBakedMap = Maps.newEnumMap(Direction.class); - protected final List quadsUnbaked = Lists.newArrayList(); - protected final List quadsBaked = Lists.newArrayList(); - - protected TextureAtlasSprite[] sprites; - protected ItemTransforms transforms; - protected ItemOverrides overrides; - - protected List materials; - protected boolean useCulling; - protected boolean useShading; - protected byte particleIndex; - - public OBJBlockModel( - ResourceLocation location, - Vector3f offset, - boolean useCulling, - boolean useShading, - byte particleIndex, - ResourceLocation... textureIDs - ) { - for (Direction dir : BlocksHelper.DIRECTIONS) { - quadsUnbakedMap.put(dir, Lists.newArrayList()); - quadsBakedMap.put(dir, Lists.newArrayList()); - } - - transforms = ItemTransforms.NO_TRANSFORMS; - overrides = ItemOverrides.EMPTY; - materials = new ArrayList<>(textureIDs.length); - sprites = new TextureAtlasSprite[textureIDs.length]; - this.particleIndex = particleIndex; - this.useCulling = useCulling; - this.useShading = useShading; - loadModel(location, offset, (byte) (textureIDs.length - 1)); - - for (int i = 0; i < textureIDs.length; i++) { - materials.add(new Material(TextureAtlas.LOCATION_BLOCKS, textureIDs[i])); - } - } - - // UnbakedModel // - - @Override - public Collection getDependencies() { - return Collections.emptyList(); - } - - @Override - public Collection getMaterials( - Function function, - Set> set - ) { - return materials; - } - - @Nullable - @Override - public BakedModel bake( - ModelBakery modelBakery, - Function textureGetter, - ModelState modelState, - ResourceLocation resourceLocation - ) { - for (int i = 0; i < sprites.length; i++) { - sprites[i] = textureGetter.apply(materials.get(i)); - } - quadsBaked.clear(); - quadsUnbaked.forEach(quad -> quadsBaked.add(quad.bake(sprites, modelState))); - for (Direction dir : BlocksHelper.DIRECTIONS) { - List unbaked = quadsUnbakedMap.get(dir); - List baked = quadsBakedMap.get(dir); - baked.clear(); - unbaked.forEach(quad -> baked.add(quad.bake(sprites, modelState))); - } - return this; - } - - // Baked Model // - - @Override - public List getQuads( - @Nullable BlockState blockState, - @Nullable Direction direction, - RandomSource random - ) { - return direction == null ? quadsBaked : quadsBakedMap.get(direction); - } - - @Override - public boolean useAmbientOcclusion() { - return true; - } - - @Override - public boolean isGui3d() { - return true; - } - - @Override - public boolean usesBlockLight() { - return true; - } - - @Override - public boolean isCustomRenderer() { - return false; - } - - @Override - public TextureAtlasSprite getParticleIcon() { - return sprites[particleIndex]; - } - - @Override - public ItemTransforms getTransforms() { - return transforms; - } - - @Override - public ItemOverrides getOverrides() { - return overrides; - } - - private Resource getResource(ResourceLocation location) { - return Minecraft.getInstance().getResourceManager().getResource(location).orElse(null); - } - - private void loadModel(ResourceLocation location, Vector3f offset, byte maxIndex) { - Resource resource = getResource(location); - if (resource == null) { - return; - } - InputStream input = null; - try { - input = resource.open(); - } catch (IOException e) { - BCLib.LOGGER.error("Unable to load Model", e); - throw new RuntimeException(e); - } - - List vertecies = new ArrayList<>(12); - List uvs = new ArrayList<>(8); - - List vertexIndex = new ArrayList<>(4); - List uvIndex = new ArrayList<>(4); - - byte materialIndex = -1; - - try { - InputStreamReader streamReader = new InputStreamReader(input); - BufferedReader reader = new BufferedReader(streamReader); - String string; - - while ((string = reader.readLine()) != null) { - if (string.startsWith("usemtl")) { - materialIndex++; - if (materialIndex > maxIndex) { - materialIndex = maxIndex; - } - } else if (string.startsWith("vt")) { - String[] uv = string.split(" "); - uvs.add(Float.parseFloat(uv[1])); - uvs.add(Float.parseFloat(uv[2])); - } else if (string.startsWith("v")) { - String[] vert = string.split(" "); - for (int i = 1; i < 4; i++) { - vertecies.add(Float.parseFloat(vert[i])); - } - } else if (string.startsWith("f")) { - String[] members = string.split(" "); - if (members.length != 5) { - System.out.println("Only quads in OBJ are supported! Model [" + location + "] has n-gons or triangles!"); - continue; - } - vertexIndex.clear(); - uvIndex.clear(); - - for (int i = 1; i < members.length; i++) { - String member = members[i]; - - if (member.contains("/")) { - String[] sub = member.split("/"); - vertexIndex.add(Integer.parseInt(sub[0]) - 1); // Vertex - uvIndex.add(Integer.parseInt(sub[1]) - 1); // UV - } else { - vertexIndex.add(Integer.parseInt(member) - 1); // Vertex - } - } - - boolean hasUV = !uvIndex.isEmpty(); - UnbakedQuad quad = new UnbakedQuad(); - for (int i = 0; i < 4; i++) { - int index = vertexIndex.get(i) * 3; - int quadIndex = i * 5; - quad.addData(quadIndex++, vertecies.get(index++) + offset.x()); // X - quad.addData(quadIndex++, vertecies.get(index++) + offset.y()); // Y - quad.addData(quadIndex++, vertecies.get(index) + offset.z()); // Z - if (hasUV) { - index = uvIndex.get(i) * 2; - quad.addData(quadIndex++, uvs.get(index++) * 16F); // U - quad.addData(quadIndex, (1 - uvs.get(index)) * 16F); // V - } - } - quad.setSpriteIndex(materialIndex); - if (useShading) { - Direction dir = getNormalDirection(quad); - quad.setDirection(dir); - quad.setShading(true); - } - if (useCulling) { - Direction dir = getCullingDirection(quad); - if (dir == null) { - quadsUnbaked.add(quad); - } else { - quadsUnbakedMap.get(dir).add(quad); - } - } else { - quadsUnbaked.add(quad); - } - } - } - - reader.close(); - streamReader.close(); - input.close(); - } catch (IOException e) { - e.printStackTrace(); - } - - if (materialIndex < 0) { - quadsUnbaked.forEach(quad -> quad.setSpriteIndex(0)); - quadsUnbakedMap.values().forEach(list -> list.forEach(quad -> quad.setSpriteIndex(0))); - } - } - - private Direction getNormalDirection(UnbakedQuad quad) { - Vector3f pos = quad.getPos(0, POSITIONS[0]); - Vector3f dirA = quad.getPos(1, POSITIONS[1]); - Vector3f dirB = quad.getPos(2, POSITIONS[2]); - dirA.sub(pos); - dirB.sub(pos); - pos = MHelper.cross(dirA, dirB); - return Direction.getNearest(pos.x(), pos.y(), pos.z()); - } - - @Nullable - private Direction getCullingDirection(UnbakedQuad quad) { - Direction dir = null; - for (int i = 0; i < 4; i++) { - Vector3f pos = quad.getPos(i, POSITIONS[0]); - if (pos.x() < 1 && pos.x() > 0 && pos.y() < 1 && pos.y() > 0 && pos.z() < 1 && pos.z() > 0) { - return null; - } - Direction newDir = Direction.getNearest(pos.x() - 0.5F, pos.y() - 0.5F, pos.z() - 0.5F); - if (dir == null) { - dir = newDir; - } else if (newDir != dir) { - return null; - } - } - return dir; - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/OBJModelBuilder.java b/src/main/java/org/betterx/bclib/client/models/OBJModelBuilder.java deleted file mode 100644 index d08be7eb..00000000 --- a/src/main/java/org/betterx/bclib/client/models/OBJModelBuilder.java +++ /dev/null @@ -1,112 +0,0 @@ -package org.betterx.bclib.client.models; - -import com.mojang.math.Vector3f; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; - -import java.util.List; - -@Environment(EnvType.CLIENT) -public class OBJModelBuilder { - private static final OBJModelBuilder INSTANCE = new OBJModelBuilder(); - private final List textures = Lists.newArrayList(); - private final Vector3f offset = new Vector3f(); - private ResourceLocation modelLocation; - private ResourceLocation particles; - private boolean useCulling; - private boolean useShading; - - private OBJModelBuilder() { - } - - /** - * Start a new bodel building process, clears data of previous builder. - * - * @return {@link OBJModelBuilder} instance. - */ - public static OBJModelBuilder start(ResourceLocation modelLocation) { - INSTANCE.modelLocation = modelLocation; - INSTANCE.offset.set(0, 0, 0); - INSTANCE.useCulling = true; - INSTANCE.useShading = true; - INSTANCE.particles = null; - INSTANCE.textures.clear(); - return INSTANCE; - } - - /** - * Add texture to the model. All textures have indexes with same order as in source OBJ model. - * - * @param texture {@link ResourceLocation} texture ID. - * @return this {@link OBJModelBuilder}. - */ - public OBJModelBuilder addTexture(ResourceLocation texture) { - textures.add(texture); - return this; - } - - /** - * Culling used to remove block faces if they are on block faces or outside of the block to reduce faces count in rendering. - * Opaque blocks shoud have this as true to reduce geometry issues, block like plants should have this as false. - * Default value is {@code true}. - * - * @param useCulling {@link Boolean}. - * @return this {@link OBJModelBuilder}. - */ - public OBJModelBuilder useCulling(boolean useCulling) { - this.useCulling = useCulling; - return this; - } - - /** - * Shading tints block faces in shades of gray to immitate volume in MC rendering. - * Blocks like plants don't have shading, most full opaque blocks - have. - * Default value is {@code true}. - * - * @param useShading {@link Boolean}. - * @return this {@link OBJModelBuilder}. - */ - public OBJModelBuilder useShading(boolean useShading) { - this.useShading = useShading; - return this; - } - - /** - * Set particle texture for this model. - * Not required, if texture is not selected the first texture will be used instead of it. - * - * @param texture {@link ResourceLocation} texture ID. - * @return this {@link OBJModelBuilder}. - */ - public OBJModelBuilder setParticlesTexture(ResourceLocation texture) { - this.particles = texture; - return this; - } - - public OBJModelBuilder setOffset(float x, float y, float z) { - this.offset.set(x, y, z); - return this; - } - - /** - * Builds model from all required data. - * - * @return {@link OBJBlockModel}. - */ - public OBJBlockModel build() { - byte particleIndex = 0; - if (particles != null) { - particleIndex = (byte) textures.indexOf(particles); - if (particleIndex < 0) { - particleIndex = (byte) textures.size(); - textures.add(particles); - } - } - ResourceLocation[] sprites = textures.toArray(new ResourceLocation[textures.size()]); - return new OBJBlockModel(modelLocation, offset, useCulling, useShading, particleIndex, sprites); - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/PatternsHelper.java b/src/main/java/org/betterx/bclib/client/models/PatternsHelper.java deleted file mode 100644 index 0547df55..00000000 --- a/src/main/java/org/betterx/bclib/client/models/PatternsHelper.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.betterx.bclib.client.models; - -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; - -import com.google.common.collect.Maps; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; - -public class PatternsHelper { - private static final Map JSON_CACHE = Maps.newConcurrentMap(); - - public static Optional createItemGenerated(ResourceLocation itemId) { - return createJson(BasePatterns.ITEM_GENERATED, itemId); - } - - public static Optional createItemHandheld(ResourceLocation itemId) { - return createJson(BasePatterns.ITEM_HANDHELD, itemId); - } - - public static Optional createBlockSimple(ResourceLocation blockId) { - return createJson(BasePatterns.BLOCK_BASE, blockId); - } - - public static Optional createBlockEmpty(ResourceLocation blockId) { - return createJson(BasePatterns.BLOCK_EMPTY, blockId); - } - - public static Optional createBlockPillar(ResourceLocation blockId) { - return createJson(BasePatterns.BLOCK_PILLAR, blockId); - } - - public static Optional createBlockBottomTop(ResourceLocation blockId) { - return createJson(BasePatterns.BLOCK_BOTTOM_TOP, blockId); - } - - public static Optional createBlockColored(ResourceLocation blockId) { - return createJson(BasePatterns.BLOCK_COLORED, blockId); - } - - public static Optional createJson(ResourceLocation patternId, ResourceLocation blockId) { - Map textures = Maps.newHashMap(); - textures.put("%modid%", blockId.getNamespace()); - textures.put("%texture%", blockId.getPath()); - return createJson(patternId, textures); - } - - public static Optional createJson(ResourceLocation patternId, Map textures) { - ResourceManager resourceManager = Minecraft.getInstance().getResourceManager(); - Optional patternRes = resourceManager.getResource(patternId); - if (patternRes.isEmpty()) return Optional.empty(); - - try (InputStream input = patternRes.get().open()) { - String json = JSON_CACHE.get(patternId); - if (json == null) { - json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)).lines() - .collect(Collectors.joining()); - JSON_CACHE.put(patternId, json); - } - for (Map.Entry texture : textures.entrySet()) { - json = json.replace(texture.getKey(), texture.getValue()); - } - return Optional.of(json); - } catch (Exception ex) { - return Optional.empty(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/client/models/UnbakedQuad.java b/src/main/java/org/betterx/bclib/client/models/UnbakedQuad.java deleted file mode 100644 index 9978d8bd..00000000 --- a/src/main/java/org/betterx/bclib/client/models/UnbakedQuad.java +++ /dev/null @@ -1,69 +0,0 @@ -package org.betterx.bclib.client.models; - -import com.mojang.math.Matrix4f; -import com.mojang.math.Vector3f; -import com.mojang.math.Vector4f; -import net.minecraft.client.renderer.block.model.BakedQuad; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.core.Direction; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class UnbakedQuad { - private static final Vector4f POS = new Vector4f(); - private final float[] data = new float[20]; // 4 points with 3 positions and 2 uvs, 4 * (3 + 2) - private Direction dir = Direction.UP; - private boolean useShading = false; - private int spriteIndex; - - public void addData(int index, float value) { - data[index] = value; - } - - public void setSpriteIndex(int index) { - spriteIndex = index; - } - - public void setDirection(Direction dir) { - this.dir = dir; - } - - public void setShading(boolean useShading) { - this.useShading = useShading; - } - - public Vector3f getPos(int index, Vector3f result) { - int dataIndex = index * 5; - float x = data[dataIndex++]; - float y = data[dataIndex++]; - float z = data[dataIndex]; - result.set(x, y, z); - return result; - } - - public BakedQuad bake(TextureAtlasSprite[] sprites, ModelState modelState) { - Matrix4f matrix = modelState.getRotation().getMatrix(); - TextureAtlasSprite sprite = sprites[spriteIndex]; - int[] vertexData = new int[32]; - for (int i = 0; i < 4; i++) { - int index = i << 3; - int dataIndex = i * 5; - float x = data[dataIndex++]; // X - float y = data[dataIndex++]; // Y - float z = data[dataIndex++]; // Z - POS.set(x, y, z, 0); - POS.transform(matrix); - vertexData[index] = Float.floatToIntBits(POS.x()); // X - vertexData[index | 1] = Float.floatToIntBits(POS.y()); // Y - vertexData[index | 2] = Float.floatToIntBits(POS.z()); // Z - vertexData[index | 3] = -1; // Unknown constant - vertexData[index | 4] = Float.floatToIntBits(sprite.getU(data[dataIndex++])); // U - vertexData[index | 5] = Float.floatToIntBits(sprite.getV(data[dataIndex])); // V - } - // vertices, tint index, direction, sprite, shade - return new BakedQuad(vertexData, 0, dir, sprites[spriteIndex], useShading); - } -} diff --git a/src/main/java/org/betterx/bclib/client/render/BCLRenderLayer.java b/src/main/java/org/betterx/bclib/client/render/BCLRenderLayer.java deleted file mode 100644 index 8d21bb5b..00000000 --- a/src/main/java/org/betterx/bclib/client/render/BCLRenderLayer.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.betterx.bclib.client.render; - -public enum BCLRenderLayer { - CUTOUT, TRANSLUCENT -} diff --git a/src/main/java/org/betterx/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/org/betterx/bclib/client/render/BaseChestBlockEntityRenderer.java deleted file mode 100644 index ab1a3d59..00000000 --- a/src/main/java/org/betterx/bclib/client/render/BaseChestBlockEntityRenderer.java +++ /dev/null @@ -1,194 +0,0 @@ -package org.betterx.bclib.client.render; - -import org.betterx.bclib.blockentities.BaseChestBlockEntity; -import org.betterx.bclib.client.models.BaseChestBlockModel; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.math.Vector3f; -import net.minecraft.client.model.geom.ModelPart; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; -import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; -import net.minecraft.client.renderer.blockentity.BrightnessCombiner; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.*; -import net.minecraft.world.level.block.DoubleBlockCombiner.NeighborCombineResult; -import net.minecraft.world.level.block.entity.ChestBlockEntity; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.ChestType; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Maps; -import it.unimi.dsi.fastutil.ints.Int2IntFunction; - -import java.util.HashMap; - -@Environment(EnvType.CLIENT) -public class BaseChestBlockEntityRenderer implements BlockEntityRenderer { - private static final HashMap LAYERS = Maps.newHashMap(); - private static final RenderType[] RENDER_TYPES; - - private static final int ID_NORMAL = 0; - private static final int ID_LEFT = 1; - private static final int ID_RIGHT = 2; - - private final BaseChestBlockModel chestModel; - - public BaseChestBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { - super(); - chestModel = new BaseChestBlockModel(BaseChestBlockModel.getTexturedModelData().bakeRoot()); - } - - public void render( - BaseChestBlockEntity entity, - float tickDelta, - PoseStack matrices, - MultiBufferSource vertexConsumers, - int light, - int overlay - ) { - Level world = entity.getLevel(); - boolean worldExists = world != null; - BlockState blockState = worldExists ? entity.getBlockState() : Blocks.CHEST.defaultBlockState() - .setValue( - ChestBlock.FACING, - Direction.SOUTH - ); - ChestType chestType = blockState.hasProperty(ChestBlock.TYPE) - ? blockState.getValue(ChestBlock.TYPE) - : ChestType.SINGLE; - Block block = blockState.getBlock(); - if (block instanceof AbstractChestBlock) { - AbstractChestBlock abstractChestBlock = (AbstractChestBlock) block; - boolean isDouble = chestType != ChestType.SINGLE; - float f = blockState.getValue(ChestBlock.FACING).toYRot(); - NeighborCombineResult propertySource; - - matrices.pushPose(); - matrices.translate(0.5D, 0.5D, 0.5D); - matrices.mulPose(Vector3f.YP.rotationDegrees(-f)); - matrices.translate(-0.5D, -0.5D, -0.5D); - - if (worldExists) { - propertySource = abstractChestBlock.combine(blockState, world, entity.getBlockPos(), true); - } else { - propertySource = DoubleBlockCombiner.Combiner::acceptNone; - } - - float pitch = propertySource.apply(ChestBlock.opennessCombiner(entity)).get( - tickDelta); - pitch = 1.0F - pitch; - pitch = 1.0F - pitch * pitch * pitch; - @SuppressWarnings({ - "unchecked", - "rawtypes" - }) int blockLight = ((Int2IntFunction) propertySource.apply(new BrightnessCombiner())).applyAsInt(light); - - VertexConsumer vertexConsumer = getConsumer(vertexConsumers, block, chestType); - - if (isDouble) { - if (chestType == ChestType.LEFT) { - renderParts( - matrices, - vertexConsumer, - chestModel.partLeftA, - chestModel.partLeftB, - chestModel.partLeftC, - pitch, - blockLight, - overlay - ); - } else { - renderParts( - matrices, - vertexConsumer, - chestModel.partRightA, - chestModel.partRightB, - chestModel.partRightC, - pitch, - blockLight, - overlay - ); - } - } else { - renderParts( - matrices, - vertexConsumer, - chestModel.partA, - chestModel.partB, - chestModel.partC, - pitch, - blockLight, - overlay - ); - } - - matrices.popPose(); - } - } - - private void renderParts( - PoseStack matrices, - VertexConsumer vertices, - ModelPart modelPart, - ModelPart modelPart2, - ModelPart modelPart3, - float pitch, - int light, - int overlay - ) { - modelPart.xRot = -(pitch * 1.5707964F); - modelPart2.xRot = modelPart.xRot; - modelPart.render(matrices, vertices, light, overlay); - modelPart2.render(matrices, vertices, light, overlay); - modelPart3.render(matrices, vertices, light, overlay); - } - - private static RenderType getChestTexture(ChestType type, RenderType[] layers) { - return switch (type) { - case LEFT -> layers[ID_LEFT]; - case RIGHT -> layers[ID_RIGHT]; - default -> layers[ID_NORMAL]; - }; - } - - public static VertexConsumer getConsumer(MultiBufferSource provider, Block block, ChestType chestType) { - RenderType[] layers = LAYERS.getOrDefault(block, RENDER_TYPES); - return provider.getBuffer(getChestTexture(chestType, layers)); - } - - public static void registerRenderLayer(Block block) { - ResourceLocation blockId = Registry.BLOCK.getKey(block); - String modId = blockId.getNamespace(); - String path = blockId.getPath(); - LAYERS.put( - block, - new RenderType[]{ - RenderType.entityCutout(new ResourceLocation(modId, "textures/entity/chest/" + path + ".png")), - RenderType.entityCutout(new ResourceLocation( - modId, - "textures/entity/chest/" + path + "_left.png" - )), - RenderType.entityCutout(new ResourceLocation( - modId, - "textures/entity/chest/" + path + "_right.png" - )) - } - ); - } - - static { - RENDER_TYPES = new RenderType[]{ - RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal.png")), - RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_left.png")), - RenderType.entityCutout(new ResourceLocation("textures/entity/chest/normal_right.png")) - }; - } -} diff --git a/src/main/java/org/betterx/bclib/client/render/BaseSignBlockEntityRenderer.java b/src/main/java/org/betterx/bclib/client/render/BaseSignBlockEntityRenderer.java deleted file mode 100644 index e379d15e..00000000 --- a/src/main/java/org/betterx/bclib/client/render/BaseSignBlockEntityRenderer.java +++ /dev/null @@ -1,195 +0,0 @@ -package org.betterx.bclib.client.render; - -import org.betterx.bclib.blockentities.BaseSignBlockEntity; -import org.betterx.bclib.blocks.BaseSignBlock; - -import com.mojang.blaze3d.platform.NativeImage; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.math.Vector3f; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.model.geom.ModelLayers; -import net.minecraft.client.player.LocalPlayer; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.Sheets; -import net.minecraft.client.renderer.blockentity.BlockEntityRenderer; -import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; -import net.minecraft.client.renderer.blockentity.SignRenderer; -import net.minecraft.client.resources.model.Material; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.FormattedCharSequence; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.item.DyeColor; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.SignBlock; -import net.minecraft.world.level.block.StandingSignBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.WoodType; -import net.minecraft.world.phys.Vec3; - -import com.google.common.collect.Maps; - -import java.util.HashMap; -import java.util.List; - -public class BaseSignBlockEntityRenderer implements BlockEntityRenderer { - private static final HashMap RENDER_TYPES = Maps.newHashMap(); - private static final int OUTLINE_RENDER_DISTANCE = Mth.square(16); - private static final RenderType RENDER_TYPE; - private final SignRenderer.SignModel model; - private final Font font; - - - public BaseSignBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { - super(); - this.font = ctx.getFont(); - model = new SignRenderer.SignModel(ctx.bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); - } - - public void render( - BaseSignBlockEntity signBlockEntity, - float tickDelta, - PoseStack matrixStack, - MultiBufferSource provider, - int light, - int overlay - ) { - BlockState state = signBlockEntity.getBlockState(); - - matrixStack.pushPose(); - - - matrixStack.translate(0.5D, 0.5D, 0.5D); - float angle = -((float) (state.getValue(StandingSignBlock.ROTATION) * 360) / 16.0F); - - BlockState blockState = signBlockEntity.getBlockState(); - if (blockState.getValue(BaseSignBlock.FLOOR)) { - matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle)); - model.stick.visible = true; - } else { - matrixStack.mulPose(Vector3f.YP.rotationDegrees(angle + 180)); - matrixStack.translate(0.0D, -0.3125D, -0.4375D); - model.stick.visible = false; - } - - matrixStack.pushPose(); - matrixStack.scale(0.6666667F, -0.6666667F, -0.6666667F); - VertexConsumer vertexConsumer = getConsumer(provider, state.getBlock()); - - model.root.render(matrixStack, vertexConsumer, light, overlay); - matrixStack.popPose(); - matrixStack.translate(0.0D, 0.3333333432674408D, 0.046666666865348816D); - matrixStack.scale(0.010416667F, -0.010416667F, 0.010416667F); - int m = signBlockEntity.getColor().getTextColor(); - int n = (int) (NativeImage.getR(m) * 0.4D); - int o = (int) (NativeImage.getG(m) * 0.4D); - int p = (int) (NativeImage.getB(m) * 0.4D); - int q = NativeImage.combine(0, p, o, n); - - FormattedCharSequence[] formattedCharSequences = signBlockEntity.getRenderMessages( - Minecraft.getInstance() - .isTextFilteringEnabled(), - (component) -> { - List list = this.font.split(component, 90); - return list.isEmpty() ? FormattedCharSequence.EMPTY : list.get(0); - } - ); - int drawColor; - boolean drawOutlined; - int drawLight; - if (signBlockEntity.hasGlowingText()) { - drawColor = signBlockEntity.getColor().getTextColor(); - drawOutlined = isOutlineVisible(signBlockEntity, drawColor); - drawLight = 15728880; - } else { - drawColor = m; - drawOutlined = false; - drawLight = light; - } - - for (int s = 0; s < 4; ++s) { - FormattedCharSequence formattedCharSequence = formattedCharSequences[s]; - float t = (float) (-this.font.width(formattedCharSequence) / 2); - if (drawOutlined) { - this.font.drawInBatch8xOutline( - formattedCharSequence, - t, - (float) (s * 10 - 20), - drawColor, - m, - matrixStack.last().pose(), - provider, - drawLight - ); - } else { - this.font.drawInBatch( - formattedCharSequence, - t, - (float) (s * 10 - 20), - drawColor, - false, - matrixStack.last().pose(), - provider, - false, - 0, - drawLight - ); - } - } - - - matrixStack.popPose(); - } - - - private static boolean isOutlineVisible(BaseSignBlockEntity signBlockEntity, int i) { - if (i == DyeColor.BLACK.getTextColor()) { - return true; - } else { - Minecraft minecraft = Minecraft.getInstance(); - LocalPlayer localPlayer = minecraft.player; - if (localPlayer != null && minecraft.options.getCameraType().isFirstPerson() && localPlayer.isScoping()) { - return true; - } else { - Entity entity = minecraft.getCameraEntity(); - return entity != null && entity.distanceToSqr(Vec3.atCenterOf(signBlockEntity.getBlockPos())) < (double) OUTLINE_RENDER_DISTANCE; - } - } - } - - public static WoodType getSignType(Block block) { - WoodType signType2; - if (block instanceof SignBlock) { - signType2 = ((SignBlock) block).type(); - } else { - signType2 = WoodType.OAK; - } - - return signType2; - } - - public static Material getModelTexture(Block block) { - return Sheets.getSignMaterial(getSignType(block)); - } - - public static VertexConsumer getConsumer(MultiBufferSource provider, Block block) { - return provider.getBuffer(RENDER_TYPES.getOrDefault(block, RENDER_TYPE)); - } - - public static void registerRenderLayer(Block block) { - ResourceLocation blockId = Registry.BLOCK.getKey(block); - RenderType layer = RenderType.entitySolid(new ResourceLocation( - blockId.getNamespace(), - "textures/entity/sign/" + blockId.getPath() + ".png" - )); - RENDER_TYPES.put(block, layer); - } - - static { - RENDER_TYPE = RenderType.entitySolid(new ResourceLocation("textures/entity/signs/oak.png")); - } -} diff --git a/src/main/java/org/betterx/bclib/client/render/BoatRenderer.java b/src/main/java/org/betterx/bclib/client/render/BoatRenderer.java deleted file mode 100644 index 0d144c54..00000000 --- a/src/main/java/org/betterx/bclib/client/render/BoatRenderer.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.betterx.bclib.client.render; - -import org.betterx.bclib.items.boat.BoatTypeOverride; -import org.betterx.bclib.items.boat.CustomBoatTypeOverride; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import com.mojang.math.Quaternion; -import com.mojang.math.Vector3f; -import net.minecraft.client.model.BoatModel; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.client.renderer.texture.OverlayTexture; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.Mth; -import net.minecraft.world.entity.vehicle.Boat; -import net.minecraft.world.entity.vehicle.ChestBoat; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(value = EnvType.CLIENT) -public class BoatRenderer { - - public static boolean render( - Boat boat, - float f, - float g, - PoseStack poseStack, - MultiBufferSource multiBufferSource, - int i - ) { - if (boat instanceof CustomBoatTypeOverride cbto) { - BoatTypeOverride type = cbto.bcl_getCustomType(); - if (type != null) { - boolean hasChest = boat instanceof ChestBoat; - float k; - poseStack.pushPose(); - poseStack.translate(0.0, 0.375, 0.0); - poseStack.mulPose(Vector3f.YP.rotationDegrees(180.0f - f)); - float h = (float) boat.getHurtTime() - g; - float j = boat.getDamage() - g; - if (j < 0.0f) { - j = 0.0f; - } - if (h > 0.0f) { - poseStack.mulPose(Vector3f.XP.rotationDegrees(Mth.sin(h) * h * j / 10.0f * (float) boat.getHurtDir())); - } - if (!Mth.equal(k = boat.getBubbleAngle(g), 0.0f)) { - poseStack.mulPose(new Quaternion(new Vector3f(1.0f, 0.0f, 1.0f), boat.getBubbleAngle(g), true)); - } - ResourceLocation resourceLocation = hasChest ? type.chestBoatTexture : type.boatTexture; - BoatModel boatModel = type.getBoatModel(hasChest); - poseStack.scale(-1.0f, -1.0f, 1.0f); - poseStack.mulPose(Vector3f.YP.rotationDegrees(90.0f)); - boatModel.setupAnim(boat, g, 0.0f, -0.1f, 0.0f, 0.0f); - VertexConsumer vertexConsumer = multiBufferSource.getBuffer(boatModel.renderType(resourceLocation)); - boatModel.renderToBuffer( - poseStack, vertexConsumer, i, - OverlayTexture.NO_OVERLAY, - 1.0f, 1.0f, 1.0f, 1.0f - ); - if (!boat.isUnderWater()) { - VertexConsumer vertexConsumer2 = multiBufferSource.getBuffer(RenderType.waterMask()); - boatModel.waterPatch().render(poseStack, vertexConsumer2, i, OverlayTexture.NO_OVERLAY); - } - poseStack.popPose(); - - return true; - } - - } - return false; - } -} diff --git a/src/main/java/org/betterx/bclib/client/render/CustomFogRenderer.java b/src/main/java/org/betterx/bclib/client/render/CustomFogRenderer.java deleted file mode 100644 index b4f122fd..00000000 --- a/src/main/java/org/betterx/bclib/client/render/CustomFogRenderer.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.betterx.bclib.client.render; - -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.util.BackgroundInfo; -import org.betterx.bclib.util.MHelper; - -import com.mojang.blaze3d.systems.RenderSystem; -import net.minecraft.client.Camera; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.util.Mth; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.effect.MobEffects; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.material.FogType; - -public class CustomFogRenderer { - private static final MutableBlockPos LAST_POS = new MutableBlockPos(0, -100, 0); - private static final MutableBlockPos MUT_POS = new MutableBlockPos(); - private static final float[] FOG_DENSITY = new float[8]; - private static final int GRID_SIZE = 32; - private static float fogStart = 0; - private static float fogEnd = 192; - - public static boolean applyFogDensity(Camera camera, float viewDistance, boolean thickFog) { - if (!Configs.CLIENT_CONFIG.renderCustomFog()) { - return false; - } - - FogType fogType = camera.getFluidInCamera(); - if (fogType != FogType.NONE) { - BackgroundInfo.fogDensity = 1; - return false; - } - Entity entity = camera.getEntity(); - - if (!isForcedDimension(entity.level) && shouldIgnoreArea( - entity.level, - (int) entity.getX(), - (int) entity.getEyeY(), - (int) entity.getZ() - )) { - BackgroundInfo.fogDensity = 1; - return false; - } - - float fog = getFogDensity( - entity.level, - entity.getX(), - entity.getEyeY(), - entity.getZ() - ) * Configs.CLIENT_CONFIG.fogDensity(); - BackgroundInfo.fogDensity = fog; - - if (thickFog(thickFog, entity.level)) { - fogStart = viewDistance * 0.05F / fog; - fogEnd = Math.min(viewDistance, 192.0F) * 0.5F / fog; - } else { - fogStart = viewDistance * 0.25F / fog; // In vanilla - 0 - fogEnd = viewDistance / fog; - } - - if (entity instanceof LivingEntity) { - LivingEntity livingEntity = (LivingEntity) entity; - MobEffectInstance effect = livingEntity.getEffect(MobEffects.BLINDNESS); - if (effect != null) { - int duration = effect.getDuration(); - if (duration > 20) { - fogStart = 0; - fogEnd *= 0.03F; - BackgroundInfo.blindness = 1; - } else { - float delta = (float) duration / 20F; - BackgroundInfo.blindness = delta; - fogStart = Mth.lerp(delta, fogStart, 0); - fogEnd = Mth.lerp(delta, fogEnd, fogEnd * 0.03F); - } - } else { - BackgroundInfo.blindness = 0; - } - } - RenderSystem.setShaderFogStart(fogStart); - RenderSystem.setShaderFogEnd(fogEnd); - - return true; - } - - private static boolean thickFog(boolean thickFog, Level level) { - if (!thickFog) { - return false; - } - if (level.dimension() == Level.NETHER) { - return Configs.CLIENT_CONFIG.netherThickFog(); - } - return true; - } - - private static boolean isForcedDimension(Level level) { - return level.dimension() == Level.END || level.dimension() == Level.NETHER; - } - - private static boolean shouldIgnoreArea(Level level, int x, int y, int z) { - for (int i = -8; i <= 8; i += 8) { - for (int j = -8; j <= 8; j += 8) { - if (!shouldIgnore(level, x + i, y, z + j)) { - return false; - } - } - } - return true; - } - - private static boolean shouldIgnore(Level level, int x, int y, int z) { - Biome biome = level.getBiome(MUT_POS.set(x, y, z)).value(); - return BiomeAPI.getRenderBiome(biome) == BCLBiomeRegistry.EMPTY_BIOME; - } - - private static float getFogDensityI(Level level, int x, int y, int z) { - Biome biome = level.getBiome(MUT_POS.set(x, y, z)).value(); - BCLBiome renderBiome = BiomeAPI.getRenderBiome(biome); - return renderBiome.getFogDensity(); - } - - private static float getFogDensity(Level level, double x, double y, double z) { - int x1 = MHelper.floor(x / GRID_SIZE) * GRID_SIZE; - int y1 = MHelper.floor(y / GRID_SIZE) * GRID_SIZE; - int z1 = MHelper.floor(z / GRID_SIZE) * GRID_SIZE; - float dx = (float) (x - x1) / GRID_SIZE; - float dy = (float) (y - y1) / GRID_SIZE; - float dz = (float) (z - z1) / GRID_SIZE; - - if (LAST_POS.getX() != x1 || LAST_POS.getY() != y1 || LAST_POS.getZ() != z1) { - int x2 = x1 + GRID_SIZE; - int y2 = y1 + GRID_SIZE; - int z2 = z1 + GRID_SIZE; - LAST_POS.set(x1, y1, z1); - FOG_DENSITY[0] = getFogDensityI(level, x1, y1, z1); - FOG_DENSITY[1] = getFogDensityI(level, x2, y1, z1); - FOG_DENSITY[2] = getFogDensityI(level, x1, y2, z1); - FOG_DENSITY[3] = getFogDensityI(level, x2, y2, z1); - FOG_DENSITY[4] = getFogDensityI(level, x1, y1, z2); - FOG_DENSITY[5] = getFogDensityI(level, x2, y1, z2); - FOG_DENSITY[6] = getFogDensityI(level, x1, y2, z2); - FOG_DENSITY[7] = getFogDensityI(level, x2, y2, z2); - } - - float a = Mth.lerp(dx, FOG_DENSITY[0], FOG_DENSITY[1]); - float b = Mth.lerp(dx, FOG_DENSITY[2], FOG_DENSITY[3]); - float c = Mth.lerp(dx, FOG_DENSITY[4], FOG_DENSITY[5]); - float d = Mth.lerp(dx, FOG_DENSITY[6], FOG_DENSITY[7]); - - a = Mth.lerp(dy, a, b); - b = Mth.lerp(dy, c, d); - - return Mth.lerp(dz, a, b); - } -} diff --git a/src/main/java/org/betterx/bclib/client/render/EmissiveTextureInfo.java b/src/main/java/org/betterx/bclib/client/render/EmissiveTextureInfo.java deleted file mode 100644 index e2acddae..00000000 --- a/src/main/java/org/betterx/bclib/client/render/EmissiveTextureInfo.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.client.render; - -import net.minecraft.resources.ResourceLocation; - -import com.google.common.collect.Sets; - -import java.util.Set; - -public class EmissiveTextureInfo { - private static final Set EMISSIVE_TEXTURES = Sets.newHashSet(); - private static final Set EMISSIVE_BLOCKS = Sets.newHashSet(); - - public static void clear() { - EMISSIVE_TEXTURES.clear(); - EMISSIVE_BLOCKS.clear(); - } - - public static void addTexture(ResourceLocation texture) { - EMISSIVE_TEXTURES.add(texture); - } - - public static void addBlock(ResourceLocation blockID) { - EMISSIVE_BLOCKS.add(blockID); - } - - public static boolean isEmissiveTexture(ResourceLocation texture) { - return EMISSIVE_TEXTURES.contains(texture); - } - - public static boolean isEmissiveBlock(ResourceLocation blockID) { - return EMISSIVE_BLOCKS.contains(blockID); - } -} diff --git a/src/main/java/org/betterx/bclib/client/sound/BlockSounds.java b/src/main/java/org/betterx/bclib/client/sound/BlockSounds.java deleted file mode 100644 index fd4f6b80..00000000 --- a/src/main/java/org/betterx/bclib/client/sound/BlockSounds.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.betterx.bclib.client.sound; - -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.level.block.SoundType; - -public class BlockSounds { - public static final SoundType TERRAIN_SOUND = new SoundType( - 1.0F, - 1.0F, - SoundEvents.STONE_BREAK, - SoundEvents.WART_BLOCK_STEP, - SoundEvents.STONE_PLACE, - SoundEvents.STONE_HIT, - SoundEvents.STONE_FALL - ); -} diff --git a/src/main/java/org/betterx/bclib/commands/CommandRegistry.java b/src/main/java/org/betterx/bclib/commands/CommandRegistry.java deleted file mode 100644 index 13177749..00000000 --- a/src/main/java/org/betterx/bclib/commands/CommandRegistry.java +++ /dev/null @@ -1,212 +0,0 @@ -package org.betterx.bclib.commands; - -import org.betterx.bclib.util.BlocksHelper; -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import com.mojang.brigadier.Command; -import com.mojang.brigadier.CommandDispatcher; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.commands.CommandBuildContext; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.commands.Commands; -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.core.Direction; -import net.minecraft.core.Holder; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.tags.BlockTags; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.Vec3; - -import net.fabricmc.fabric.api.command.v2.CommandRegistrationCallback; - -import java.util.HashMap; -import java.util.Map; - -public class CommandRegistry { - public static void register() { - CommandRegistrationCallback.EVENT.register(CommandRegistry::register); - } - - private static void register( - CommandDispatcher dispatcher, - CommandBuildContext commandBuildContext, - Commands.CommandSelection commandSelection - ) { - dispatcher.register( - Commands.literal("bclib") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .then(Commands.literal("request_garbage_collection") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .executes(ctx -> requestGC(ctx)) - ) - .then(Commands.literal("dump_datapack") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .executes(ctx -> DumpDatapack.dumpDatapack(ctx)) - ) - .then(Commands.literal("print") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .then(Commands.literal("dimensions") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .executes(ctx -> PrintInfo.printDimensions(ctx)) - ).then(Commands.literal("updates") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .executes(ctx -> PrintInfo.printUpdates(ctx, true)) - ) - ) - .then(Commands.literal("debug_ore") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .executes(ctx -> revealOre(ctx)) - ) - .then(Commands.literal("sliceZ") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .executes(ctx -> slice(ctx, true)) - ) - .then(Commands.literal("sliceX") - .requires(source -> source.hasPermission(Commands.LEVEL_OWNERS)) - .executes(ctx -> slice(ctx, false)) - ) - ); - } - - private static int requestGC(CommandContext ctx) { - System.gc(); - return Command.SINGLE_SUCCESS; - } - - private static final Map, BlockState> biomeMap = new HashMap<>(); - private static int biomeMapIdx = 0; - private static final BlockState[] states = { - Blocks.RED_STAINED_GLASS.defaultBlockState(), - Blocks.BLUE_STAINED_GLASS.defaultBlockState(), - Blocks.YELLOW_STAINED_GLASS.defaultBlockState(), - Blocks.LIME_STAINED_GLASS.defaultBlockState(), - Blocks.PINK_STAINED_GLASS.defaultBlockState(), - Blocks.GREEN_STAINED_GLASS.defaultBlockState(), - Blocks.WHITE_STAINED_GLASS.defaultBlockState(), - Blocks.BLACK_STAINED_GLASS.defaultBlockState(), - Blocks.ORANGE_STAINED_GLASS.defaultBlockState(), - Blocks.LIGHT_BLUE_STAINED_GLASS.defaultBlockState() - }; - private static final BlockState[] states2 = { - Blocks.RED_CONCRETE.defaultBlockState(), - Blocks.BLUE_CONCRETE.defaultBlockState(), - Blocks.YELLOW_CONCRETE.defaultBlockState(), - Blocks.LIME_CONCRETE.defaultBlockState(), - Blocks.PINK_CONCRETE.defaultBlockState(), - Blocks.GREEN_CONCRETE.defaultBlockState(), - Blocks.WHITE_CONCRETE.defaultBlockState(), - Blocks.BLACK_CONCRETE.defaultBlockState(), - Blocks.ORANGE_CONCRETE.defaultBlockState(), - Blocks.LIGHT_BLUE_CONCRETE.defaultBlockState() - }; - - private static int revealOre(CommandContext ctx) throws CommandSyntaxException { - final CommandSourceStack source = ctx.getSource(); - final ServerLevel level = source.getLevel(); - final Vec3 pos = source.getPosition(); - - MutableBlockPos bp = new MutableBlockPos(); - BlockState state; - BlockState fillState; - final BlockState AIR = Blocks.AIR.defaultBlockState(); - - for (int y = 1; y < level.getHeight(); y++) { - bp.setY(y); - for (int x = -64; x < 64; x++) { - bp.setX((int) pos.x + x); - for (int z = -64; z < 64; z++) { - bp.setZ((int) pos.z + z); - if (y == 1) { - Holder b = level.getBiome(bp); - fillState = biomeMap.computeIfAbsent(b, (bb) -> { - biomeMapIdx = (biomeMapIdx + 1) % states.length; - return states[biomeMapIdx]; - }); - } else { - fillState = AIR; - } - - state = level.getBlockState(bp); - if (y == 1 || !state.is(Blocks.AIR)) { - if (!(state.is(CommonBlockTags.NETHER_ORES) - || state.is(CommonBlockTags.END_ORES) - || state.is(BlockTags.COAL_ORES) - || state.is(BlockTags.COPPER_ORES) - || state.is(BlockTags.DIAMOND_ORES) - || state.is(BlockTags.EMERALD_ORES) - || state.is(BlockTags.GOLD_ORES) - || state.is(BlockTags.IRON_ORES) - || state.is(BlockTags.LAPIS_ORES) - || state.is(BlockTags.REDSTONE_ORES) - || state.is(Blocks.NETHER_QUARTZ_ORE) - || state.is(Blocks.NETHER_GOLD_ORE) - || state.is(Blocks.ANCIENT_DEBRIS))) { - BlocksHelper.setWithoutUpdate(level, bp, fillState); - } - } - } - } - } - return Command.SINGLE_SUCCESS; - } - - private static int slice(CommandContext ctx, boolean constX) throws CommandSyntaxException { - final CommandSourceStack source = ctx.getSource(); - final ServerLevel level = source.getLevel(); - final Vec3 pos = source.getPosition(); - - BlockState AIR = Blocks.AIR.defaultBlockState(); - MutableBlockPos bp = new MutableBlockPos(); - BlockState state; - BlockState fillState; - - - for (int y = 1; y < level.getHeight(); y++) { - bp.setY(y); - for (int x = constX ? 0 : -64; x < 64; x++) { - bp.setX((int) pos.x + x); - for (int z = constX ? -64 : 0; z < 64; z++) { - bp.setZ((int) pos.z + z); - if (y == 1) { - Holder b = level.getBiome(bp); - fillState = biomeMap.computeIfAbsent(b, (bb) -> { - biomeMapIdx = (biomeMapIdx + 1) % states.length; - return states[biomeMapIdx]; - }); - } else { - fillState = AIR; - } - - BlocksHelper.setWithoutUpdate(level, bp, fillState); - } - } - } - return Command.SINGLE_SUCCESS; - } - - private static int findSurface(CommandContext ctx) throws CommandSyntaxException { - final CommandSourceStack source = ctx.getSource(); - final ServerPlayer player = source.getPlayerOrException(); - Vec3 pos = source.getPosition(); - final ServerLevel level = source.getLevel(); - MutableBlockPos mPos = new BlockPos(pos).mutable(); - System.out.println("Staring at: " + mPos + " -> " + level.getBlockState(mPos)); - boolean found = org.betterx.bclib.util.BlocksHelper.findSurroundingSurface( - level, - mPos, - Direction.DOWN, - 12, - state -> BlocksHelper.isTerrain(state) - ); - System.out.println("Ending at: " + mPos + " -> " + level.getBlockState(mPos) + " = " + found); - org.betterx.bclib.util.BlocksHelper.setWithoutUpdate(level, new BlockPos(pos), Blocks.YELLOW_CONCRETE); - org.betterx.bclib.util.BlocksHelper.setWithoutUpdate(level, mPos, Blocks.LIGHT_BLUE_CONCRETE); - return Command.SINGLE_SUCCESS; - } -} - diff --git a/src/main/java/org/betterx/bclib/commands/DumpDatapack.java b/src/main/java/org/betterx/bclib/commands/DumpDatapack.java deleted file mode 100644 index 5a5eff21..00000000 --- a/src/main/java/org/betterx/bclib/commands/DumpDatapack.java +++ /dev/null @@ -1,483 +0,0 @@ -package org.betterx.bclib.commands; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeData; -import org.betterx.bclib.blocks.BaseStairsBlock; -import org.betterx.worlds.together.surfaceRules.AssignedSurfaceRule; -import org.betterx.worlds.together.surfaceRules.SurfaceRuleRegistry; - -import com.mojang.brigadier.Command; -import com.mojang.brigadier.context.CommandContext; -import com.mojang.serialization.Codec; -import com.mojang.serialization.JsonOps; -import com.mojang.serialization.codecs.KeyDispatchCodec; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.Style; -import net.minecraft.resources.RegistryOps; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.tags.TagEntry; -import net.minecraft.tags.TagFile; -import net.minecraft.util.KeyDispatchDataCodec; -import net.minecraft.world.effect.MobEffect; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.gameevent.GameEvent; -import net.minecraft.world.level.levelgen.DensityFunction; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; -import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.levelgen.flat.FlatLevelGeneratorPreset; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; -import net.minecraft.world.level.levelgen.presets.WorldPreset; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.StructureSet; -import net.minecraft.world.level.levelgen.structure.pools.StructureTemplatePool; -import net.minecraft.world.level.levelgen.structure.templatesystem.PosRuleTestType; -import net.minecraft.world.level.levelgen.structure.templatesystem.RuleTestType; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorList; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureProcessorType; -import net.minecraft.world.level.levelgen.synth.NormalNoise; -import net.minecraft.world.level.material.Fluid; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.awt.Taskbar.Feature; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -public class DumpDatapack { - private record Dumper, H extends Holder>( - Function codecFunction, - Function, T> contentTransform - ) { - Dumper(Function codecFunction) { - this(codecFunction, h -> h.value()); - } - } - - private static final Map DUMPERS = new HashMap<>(); - - static int dumpDatapack(CommandContext ctx) { - File base = new File(System.getProperty("user.dir"), "bclib_datapack_dump"); - dumpDatapack(base, ctx.getSource().getLevel().registryAccess(), ctx); - - - ctx.getSource().sendSuccess( - Component.literal("Succesfully written to:\n ").append( - Component.literal(base.toString()).setStyle(Style.EMPTY.withUnderlined(true)) - ), - false - ); - return Command.SINGLE_SUCCESS; - } - - public static void dumpDatapack(File base, RegistryAccess registryAccess, CommandContext ctx) { - final RegistryOps registryOps = RegistryOps.create(JsonOps.INSTANCE, registryAccess); - GsonBuilder gsonBuilder = new GsonBuilder(); - gsonBuilder = gsonBuilder.setPrettyPrinting(); - Gson gson = gsonBuilder.create(); - - registryAccess.registries().forEach(r -> dump(base, r, registryOps, gson)); - - BCLib.LOGGER.info("- Serializing Dimensions "); - - for (ServerLevel serverLevel : ctx.getSource().getLevel().getServer().getAllLevels()) { - File f1 = new File(base, serverLevel.dimension().location().getNamespace()); - f1 = new File(f1, "dimension"); - f1 = new File(f1, serverLevel.dimension().location().getPath() + ".json"); - f1.getParentFile().mkdirs(); - - try { - LevelStem stem = new LevelStem( - serverLevel.dimensionTypeRegistration(), - serverLevel.getChunkSource().getGenerator() - ); - Codec codec = LevelStem.CODEC; - var o = codec - .encodeStart(registryOps, stem) - .result() - .orElse(new JsonObject()); - - String content = gson.toJson(o); - try { - Files.writeString(f1.toPath(), content, StandardCharsets.UTF_8); - } catch (IOException e) { - BCLib.LOGGER.error(" ->> Unable to WRITE: " + e.getMessage()); - } - } catch (Exception e) { - BCLib.LOGGER.error(" ->> Unable to encode: " + e.getMessage()); - } - } - - } - - - private static void dump( - File base, RegistryAccess.RegistryEntry registry, - RegistryOps registryOps, - Gson gson - ) { - BCLib.LOGGER.info("- Serializing: " + registry.key().toString()); - DUMPERS.clear(); - DUMPERS.put(Registry.BIOME_REGISTRY.location(), new Dumper<>((Biome v) -> Biome.DIRECT_CODEC)); - DUMPERS.put( - Registry.CONFIGURED_FEATURE_REGISTRY.location(), - new Dumper<>((ConfiguredFeature v) -> ConfiguredFeature.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.WORLD_PRESET_REGISTRY.location(), - new Dumper<>((WorldPreset v) -> WorldPreset.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.NOISE_GENERATOR_SETTINGS_REGISTRY.location(), - new Dumper<>((NoiseGeneratorSettings v) -> NoiseGeneratorSettings.DIRECT_CODEC) - ); - DUMPERS.put(Registry.STRUCTURE_REGISTRY.location(), new Dumper<>((Structure v) -> Structure.DIRECT_CODEC)); - DUMPERS.put( - Registry.DIMENSION_TYPE_REGISTRY.location(), - new Dumper<>((DimensionType v) -> DimensionType.DIRECT_CODEC) - ); - DUMPERS.put(BCLBiomeRegistry.BCL_BIOMES_REGISTRY.location(), new Dumper<>((BCLBiome v) -> v.codec().codec())); - DUMPERS.put( - SurfaceRuleRegistry.SURFACE_RULES_REGISTRY.location(), - new Dumper<>((AssignedSurfaceRule v) -> AssignedSurfaceRule.CODEC) - ); - DUMPERS.put(Registry.SOUND_EVENT_REGISTRY.location(), new Dumper<>((SoundEvent v) -> SoundEvent.CODEC)); - DUMPERS.put( - Registry.CONFIGURED_CARVER_REGISTRY.location(), - new Dumper<>((ConfiguredWorldCarver v) -> ConfiguredWorldCarver.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.PROCESSOR_LIST_REGISTRY.location(), - new Dumper<>((StructureProcessorList v) -> StructureProcessorType.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.FLAT_LEVEL_GENERATOR_PRESET_REGISTRY.location(), - new Dumper<>((FlatLevelGeneratorPreset v) -> FlatLevelGeneratorPreset.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.DENSITY_FUNCTION_REGISTRY.location(), - new Dumper<>((DensityFunction v) -> DensityFunction.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.PLACED_FEATURE_REGISTRY.location(), - new Dumper<>((PlacedFeature v) -> PlacedFeature.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.NOISE_REGISTRY.location(), - new Dumper<>((NormalNoise.NoiseParameters v) -> NormalNoise.NoiseParameters.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.NOISE_REGISTRY.location(), - new Dumper<>((NormalNoise.NoiseParameters v) -> NormalNoise.NoiseParameters.DIRECT_CODEC) - ); - - - DUMPERS.put( - Registry.TEMPLATE_POOL_REGISTRY.location(), - new Dumper<>((StructureTemplatePool v) -> StructureTemplatePool.DIRECT_CODEC) - ); - DUMPERS.put( - Registry.STRUCTURE_SET_REGISTRY.location(), - new Dumper<>((StructureSet v) -> StructureSet.DIRECT_CODEC) - ); - - - Dumper d = DUMPERS.getOrDefault(registry.key().location(), new Dumper(v -> registry.value().byNameCodec())); - //Dumper d = DUMPERS.get(registry.key().location()); - if (d != null) - dump(base, registry, registryOps, gson, d.codecFunction, d.contentTransform); - else - BCLib.LOGGER.warning(" No Codec Found"); - - } - - private static void dump( - File base, RegistryAccess.RegistryEntry registry, - RegistryOps registryOps, - Gson gson, - Function> codecFunction, - Function, Object> contentTransform - ) { - BCLib.LOGGER.info(" - Serializing Tags"); - dumpTags(base, registry, registryOps, gson); - - BCLib.LOGGER.info(" - Serializing Content"); - int[] count = {0, 0}; - registry - .value() - .entrySet() - .stream() - .map(e -> e.getKey()).map(key -> registry.value().getHolder(key).get()) - .forEach(holder -> { - File f1 = new File(base, holder.unwrapKey().get().location().getNamespace()); - f1 = new File(f1, registry.key().location().getPath()); - f1.mkdirs(); - f1 = new File(f1, holder.unwrapKey().get().location().getPath() + ".json"); - f1.getParentFile().mkdirs(); - //BCLib.LOGGER.info(" - " + f1); - - Object obj = contentTransform.apply(holder); - try { - Codec codec = codecFunction.apply(obj); - var o = codec - .encodeStart(registryOps, obj) - .result() - .orElse(new JsonObject()); - - String content = gson.toJson(o); - try { - Files.writeString(f1.toPath(), content, StandardCharsets.UTF_8); - count[0]++; - } catch (IOException e) { - count[1]++; - BCLib.LOGGER.error(" ->> Unable to WRITE: " + e.getMessage()); - } - } catch (Exception e) { - count[1]++; - BCLib.LOGGER.error(" ->> Unable to encode: " + e.getMessage()); - } - }); - BCLib.LOGGER.info(" -> Wrote " + count[0] + " files (" + count[1] + " errors)"); - } - - - private static void dumpDatapackOld( - File base, - RegistryAccess.RegistryEntry registry, - RegistryOps registryOps, - Gson gson - ) { - BCLib.LOGGER.info(registry.key().toString()); - dumpTags(base, registry, registryOps, gson); - - registry - .value() - .entrySet() - .stream() - .map(e -> e.getKey()).map(key -> registry.value().getHolder(key).get()) - .forEach(holder -> { - File f1 = new File(base, holder.unwrapKey().get().location().getNamespace()); - f1 = new File(f1, registry.key().location().getPath()); - f1.mkdirs(); - f1 = new File(f1, holder.unwrapKey().get().location().getPath() + ".json"); - f1.getParentFile().mkdirs(); - - Codec[] codec = {null}; - - //BCLib.LOGGER.info(" - " + f1); - Object obj = holder; - - while (obj instanceof Holder) { - obj = ((Holder) obj).value(); - } - - if (obj instanceof BiomeSource || obj instanceof Feature) { - System.out.print(""); - } - System.out.println(obj.getClass()); - - if (obj instanceof Structure s) { - codec[0] = s.type().codec(); - } else if (obj instanceof BCLBiome s) { - codec[0] = BiomeData.CODEC; - } else if (obj instanceof StructureProcessorList s) { - codec[0] = StructureProcessorType.LIST_OBJECT_CODEC; - } else if (obj instanceof GameEvent) { - return; - } else if (obj instanceof Fluid) { - return; - } else if (obj instanceof MobEffect) { - return; - } else if (obj instanceof BaseStairsBlock) { - return; - } else if (obj instanceof RuleTestType) { - codec[0] = registry.value().byNameCodec(); - } else if (obj instanceof PosRuleTestType) { - codec[0] = registry.value().byNameCodec(); - } else if (obj instanceof WorldGenSettings) { - codec[0] = registry.value().byNameCodec(); - } else if (obj instanceof LevelStem) { - codec[0] = registry.value().byNameCodec(); - } - - if (codec[0] == null) { - for (Method m : obj.getClass().getMethods()) { - if (!Modifier.isStatic(m.getModifiers())) { - m.setAccessible(true); - if (m.getParameterTypes().length == 0) { - if (Codec.class.isAssignableFrom(m.getReturnType())) { - try { - codec[0] = (Codec) m.invoke(obj); - BCLib.LOGGER.debug(" Got Codec from " + m); - break; - } catch (Exception e) { - BCLib.LOGGER.error(" !!! Unable to get Codec from " + m); - } - } else if (KeyDispatchCodec.class.isAssignableFrom(m.getReturnType())) { - try { - codec[0] = ((KeyDispatchCodec) m.invoke(obj)).codec(); - BCLib.LOGGER.debug(" Got Codec from " + m); - break; - } catch (Exception e) { - BCLib.LOGGER.error(" !!! Unable to get Codec from " + m); - } - } else if (KeyDispatchDataCodec.class.isAssignableFrom(m.getReturnType())) { - try { - codec[0] = ((KeyDispatchDataCodec) m.invoke(obj)).codec(); - BCLib.LOGGER.debug(" Got Codec from " + m); - break; - } catch (Exception e) { - BCLib.LOGGER.error(" !!! Unable to get Codec from " + m); - } - } - } - } - } - } - - if (codec[0] == null) { - //Try to find DIRECT_CODEC field - for (Field f : obj.getClass().getFields()) { - if (Modifier.isStatic(f.getModifiers())) { - if ("DIRECT_CODEC".equals(f.getName())) { - f.setAccessible(true); - try { - codec[0] = (Codec) f.get(null); - BCLib.LOGGER.debug(" Got Codec from " + f); - } catch (Exception e) { - BCLib.LOGGER.error(" !!! Unable to get Codec from " + f); - } - } - } - } - } - - //Try to find CODEC field - if (codec[0] == null) { - for (Field f : obj.getClass().getFields()) { - if (Modifier.isStatic(f.getModifiers())) { - if ("CODEC".equals(f.getName())) { - try { - f.setAccessible(true); - codec[0] = (Codec) f.get(null); - BCLib.LOGGER.debug(" Got Codec from " + f); - } catch (Exception e) { - BCLib.LOGGER.error(" !!! Unable to get Codec from " + f); - } - } - } - } - } - - //Try to find any Codec field - if (codec[0] == null) { - for (Field f : obj.getClass().getFields()) { - if (Modifier.isStatic(f.getModifiers())) { - if (Codec.class.isAssignableFrom(f.getType())) { - f.setAccessible(true); - try { - codec[0] = (Codec) f.get(null); - BCLib.LOGGER.debug(" Got Codec from " + f); - } catch (Exception e) { - BCLib.LOGGER.error(" !!! Unable to get Codec from " + f); - } - } - } - } - } - - if (codec[0] == null) { - codec[0] = registry.value().byNameCodec(); - } - - if (codec[0] == null) { - codec[0] = registry.value().byNameCodec(); - } - - - if (codec[0] != null) { - try { - var o = codec[0] - .encodeStart(registryOps, obj) - .result() - .orElse(new JsonObject()); - - String content = gson.toJson(o); - try { - Files.writeString(f1.toPath(), content, StandardCharsets.UTF_8); - } catch (IOException e) { - BCLib.LOGGER.error(" ->> Unable to WRITE: " + e.getMessage()); - } - } catch (Exception e) { - BCLib.LOGGER.error(" ->> Unable to encode: " + e.getMessage()); - } - } else { - BCLib.LOGGER.error(" !!! Could not determine Codec: " + obj.getClass()); - } - }); - - } - - private static void dumpTags( - File base, - RegistryAccess.RegistryEntry registry, - RegistryOps registryOps, - Gson gson - ) { - // Tag Output - registry.value() - .getTagNames() - .map(tagKey -> registry.value().getTag(tagKey)) - .filter(tag -> tag.isPresent()) - .map(tag -> tag.get()) - .forEach(tag -> { - File f1 = new File(base, tag.key().location().getNamespace()); - f1 = new File(f1, "tags"); - f1 = new File(f1, registry.key().location().getPath()); - f1 = new File(f1, tag.key().location().getPath() + ".json"); - f1.getParentFile().mkdirs(); - - TagFile tf = new TagFile( - tag.stream() - .map(holder -> holder.unwrapKey()) - .filter(k -> k.isPresent()) - .map(k -> TagEntry.element(k.get().location())) - .toList(), - true - ); - var o = TagFile.CODEC - .encodeStart(registryOps, tf) - .result() - .orElse(new JsonObject()); - String content = gson.toJson(o); - try { - Files.writeString(f1.toPath(), content, StandardCharsets.UTF_8); - } catch (IOException e) { - BCLib.LOGGER.error(" ->> Unable to WRITE: " + e.getMessage()); - } - }); - } -} diff --git a/src/main/java/org/betterx/bclib/commands/PrintInfo.java b/src/main/java/org/betterx/bclib/commands/PrintInfo.java deleted file mode 100644 index c9aaba80..00000000 --- a/src/main/java/org/betterx/bclib/commands/PrintInfo.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.betterx.bclib.commands; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.client.gui.screens.UpdatesScreen; -import org.betterx.bclib.config.Configs; -import org.betterx.bclib.networking.VersionChecker; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.brigadier.Command; -import com.mojang.brigadier.context.CommandContext; -import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.commands.CommandSourceStack; -import net.minecraft.network.chat.ClickEvent; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.Style; -import net.minecraft.world.level.Level; - -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; - -public class PrintInfo { - static int printDimensions(CommandContext ctx) { - - MutableComponent result = Component.literal("World Dimensions: ") - .setStyle(Style.EMPTY.withBold(true).withColor(ChatFormatting.BLUE)); - - for (var serverLevel : ctx.getSource().getLevel().getServer().getAllLevels()) { - var generator = serverLevel.getChunkSource().getGenerator(); - String output = "\n - " + serverLevel.dimension().location().toString() + ": " + - "\n " + generator.toString().trim() + " " + - generator - .getBiomeSource() - .toString() - .replace("\n", "\n "); - var cl = ChatFormatting.LIGHT_PURPLE; - if (serverLevel.dimension().location().equals(Level.OVERWORLD.location())) - cl = ChatFormatting.WHITE; - else if (serverLevel.dimension().location().equals(Level.NETHER.location())) - cl = ChatFormatting.RED; - if (serverLevel.dimension().location().equals(Level.END.location())) - cl = ChatFormatting.YELLOW; - Component dimComponent = Component.literal(output) - .setStyle(Style.EMPTY.withBold(false).withColor(cl)); - result.append(dimComponent); - } - ctx.getSource().sendSuccess(result, false); - return Command.SINGLE_SUCCESS; - } - - static int printUpdates(CommandContext ctx, boolean withUI) { - boolean hasOne = false; - MutableComponent header = Component.literal("Mod Updates:") - .setStyle(Style.EMPTY.withBold(false) - .withColor(ChatFormatting.WHITE)); - ctx.getSource().sendSuccess(header, false); - - VersionChecker.forEachUpdate((mod, cur, updated) -> { - ModContainer nfo = FabricLoader.getInstance().getModContainer(mod).orElse(null); - MutableComponent result = Component.literal(" - ") - .setStyle(Style.EMPTY.withBold(false) - .withUnderlined(false) - .withColor(ChatFormatting.WHITE)); - if (nfo != null) - result.append(Component.literal(nfo.getMetadata().getName()) - .setStyle(Style.EMPTY.withBold(false).withColor(ChatFormatting.WHITE))); - else - result.append(Component.literal(mod) - .setStyle(Style.EMPTY.withBold(false).withColor(ChatFormatting.WHITE))); - result.append(Component.literal(": ") - .setStyle(Style.EMPTY.withBold(false).withColor(ChatFormatting.WHITE))); - result.append(Component.literal(cur).setStyle(Style.EMPTY.withBold(false).withColor(ChatFormatting.WHITE))); - result.append(Component.literal(" -> ") - .setStyle(Style.EMPTY.withBold(false).withColor(ChatFormatting.WHITE))); - if (nfo != null && nfo.getMetadata().getContact().get("homepage").isPresent()) { - var ce = new ClickEvent( - ClickEvent.Action.OPEN_URL, - nfo.getMetadata().getContact().get("homepage").get() - ); - - result.append(Component.literal(updated) - .setStyle(Style.EMPTY.withClickEvent(ce) - .withBold(false) - .withItalic(true) - .withColor(ChatFormatting.GREEN))); - result.append(Component.literal(" ") - .setStyle(Style.EMPTY.withClickEvent(ce).withBold(true).withItalic(false))); - - result = result.append(Component.literal("[CurseForge]") - .setStyle(Style.EMPTY.withClickEvent(ce) - .withBold(true) - .withColor(ChatFormatting.GREEN) - .withUnderlined(true))); - - } else { - result.append(Component.literal(updated) - .setStyle(Style.EMPTY.withBold(false) - .withItalic(true) - .withColor(ChatFormatting.WHITE))); - result.append(Component.literal(" ").setStyle(Style.EMPTY.withBold(true).withItalic(false))); - - } - ctx.getSource().sendSuccess(result, false); - }); - MutableComponent footer = Component.literal("\n") - .setStyle(Style.EMPTY.withBold(false) - .withUnderlined(true) - .withColor(ChatFormatting.WHITE)); - ctx.getSource().sendSuccess(footer, false); - - if (withUI && BCLib.isClient() && Configs.CLIENT_CONFIG.showUpdateInfo() && !VersionChecker.isEmpty()) { - if (!RenderSystem.isOnRenderThread()) { - RenderSystem.recordRenderCall(() -> Minecraft.getInstance() - .setScreen(new UpdatesScreen(Minecraft.getInstance().screen))); - } else { - Minecraft.getInstance().setScreen(new UpdatesScreen(Minecraft.getInstance().screen)); - } - } - return Command.SINGLE_SUCCESS; - } -} diff --git a/src/main/java/org/betterx/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/org/betterx/bclib/complexmaterials/ComplexMaterial.java deleted file mode 100644 index f622f428..00000000 --- a/src/main/java/org/betterx/bclib/complexmaterials/ComplexMaterial.java +++ /dev/null @@ -1,371 +0,0 @@ -package org.betterx.bclib.complexmaterials; - -import org.betterx.bclib.complexmaterials.entry.BlockEntry; -import org.betterx.bclib.complexmaterials.entry.ItemEntry; -import org.betterx.bclib.complexmaterials.entry.RecipeEntry; -import org.betterx.bclib.config.PathConfig; -import org.betterx.bclib.registry.BlockRegistry; -import org.betterx.bclib.registry.ItemRegistry; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockBehaviour; - - -import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -public abstract class ComplexMaterial { - private static final Map> RECIPE_ENTRIES = Maps.newHashMap(); - private static final Map> BLOCK_ENTRIES = Maps.newHashMap(); - private static final Map> ITEM_ENTRIES = Maps.newHashMap(); - private static final List MATERIALS = Lists.newArrayList(); - - private final List defaultRecipeEntries = Lists.newArrayList(); - private final List defaultBlockEntries = Lists.newArrayList(); - private final List defaultItemEntries = Lists.newArrayList(); - - private final Map> blockTags = Maps.newHashMap(); - private final Map> itemTags = Maps.newHashMap(); - private final Map blocks = Maps.newHashMap(); - private final Map items = Maps.newHashMap(); - - protected final String baseName; - protected final String modID; - protected final String receipGroupPrefix; - - public ComplexMaterial(String modID, String baseName, String receipGroupPrefix) { - this.baseName = baseName; - this.modID = modID; - this.receipGroupPrefix = receipGroupPrefix; - MATERIALS.add(this); - } - - /** - * Initialize and registers all content inside material, return material itself. - * - * @param blocksRegistry {@link BlockRegistry} instance to add blocks in; - * @param itemsRegistry {@link ItemRegistry} instance to add items in; - * @param recipeConfig {@link PathConfig} for recipes check. - * @return {@link ComplexMaterial}. - */ - public ComplexMaterial init(BlockRegistry blocksRegistry, ItemRegistry itemsRegistry, PathConfig recipeConfig) { - initTags(); - - final BlockBehaviour.Properties blockSettings = getBlockSettings(); - final Item.Properties itemSettings = getItemSettings(itemsRegistry); - initDefault(blockSettings, itemSettings); - - getBlockEntries().forEach(entry -> { - Block block = entry.init(this, blockSettings, blocksRegistry); - blocks.put(entry.getSuffix(), block); - }); - - getItemEntries().forEach(entry -> { - Item item = entry.init(this, itemSettings, itemsRegistry); - items.put(entry.getSuffix(), item); - }); - - initDefaultRecipes(); - getRecipeEntries().forEach(entry -> { - entry.init(this, recipeConfig); - }); - - initFlammable(FlammableBlockRegistry.getDefaultInstance()); - return this; - } - - /** - * Init default content for {@link ComplexMaterial} - blocks and items. - * - * @param blockSettings {@link BlockBehaviour.Properties} default block settings for this material; - * @param itemSettings {@link Item.Properties} default item settings for this material. - */ - - protected abstract void initDefault(BlockBehaviour.Properties blockSettings, Item.Properties itemSettings); - - /** - * Init custom tags for this {@link ComplexMaterial}, not required. - */ - protected void initTags() { - } - - /** - * Init default recipes for this {@link ComplexMaterial}, not required. - */ - protected void initDefaultRecipes() { - } - - /** - * Allows to add blocks into Fabric {@link FlammableBlockRegistry} for this {@link ComplexMaterial}, not required. - */ - protected void initFlammable(FlammableBlockRegistry registry) { - } - - /** - * Adds custom block tag for this {@link ComplexMaterial}, tag can be created with {@link TagManager} or you can use one of already created tags. - * - * @param tag {@link TagKey} for {@link Block} - */ - protected void addBlockTag(TagKey tag) { - String key = tag.location().getPath().replace(getBaseName() + "_", ""); - blockTags.put(key, tag); - } - - /** - * Adds custom item tag for this {@link ComplexMaterial}, tag can be created with {@link TagManager} or you can use one of already created tags. - * - * @param tag {@link TagKey} for {@link Item} - */ - protected void addItemTag(TagKey tag) { - String key = tag.location().getPath().replace(getBaseName() + "_", ""); - itemTags.put(key, tag); - } - - /** - * Get custom {@link Block} {@link TagKey} from this {@link ComplexMaterial}. - * - * @param key {@link String} tag name (path of its {@link ResourceLocation}), for inner tags created inside material its tag suffix. - * @return {@link TagKey} for {@link Block} or {@code null} if nothing is stored. - */ - @Nullable - public TagKey getBlockTag(String key) { - return blockTags.get(key); - } - - /** - * Get custom {@link Item} {@link TagKey} from this {@link ComplexMaterial}. - * - * @param key {@link String} tag name (path of its {@link ResourceLocation}), for inner tags created inside material its tag suffix. - * @return {@link TagKey} for {@link Item} or {@code null} if nothing is stored. - */ - @Nullable - public TagKey getItemTag(String key) { - return itemTags.get(key); - } - - /** - * Get initiated {@link Block} from this {@link ComplexMaterial}. - * - * @param key {@link String} block name suffix (example: "mod:custom_log" will have a "log" suffix if "custom" is a base name of this material) - * @return {@link Block} or {@code null} if nothing is stored. - */ - @Nullable - public Block getBlock(String key) { - return blocks.get(key); - } - - /** - * Get initiated {@link Item} from this {@link ComplexMaterial}. - * - * @param key {@link String} block name suffix (example: "mod:custom_apple" will have a "apple" suffix if "custom" is a base name of this material) - * @return {@link Item} or {@code null} if nothing is stored. - */ - @Nullable - public Item getItem(String key) { - return items.get(key); - } - - /** - * Get default block settings for this material. - * - * @return {@link BlockBehaviour.Properties} - */ - protected abstract BlockBehaviour.Properties getBlockSettings(); - /** - * Get default item settings for this material. - * - * @return {@link Item.Properties} - */ - protected Item.Properties getItemSettings(ItemRegistry registry) { - return registry.makeItemSettings(); - } - - private Collection getBlockEntries() { - List result = Lists.newArrayList(defaultBlockEntries); - List entries = BLOCK_ENTRIES.get(this.getMaterialID()); - if (entries != null) { - result.addAll(entries); - } - return result; - } - - private Collection getItemEntries() { - List result = Lists.newArrayList(defaultItemEntries); - List entries = ITEM_ENTRIES.get(this.getMaterialID()); - if (entries != null) { - result.addAll(entries); - } - return result; - } - - private Collection getRecipeEntries() { - List result = Lists.newArrayList(defaultRecipeEntries); - List entries = RECIPE_ENTRIES.get(this.getMaterialID()); - if (entries != null) { - result.addAll(entries); - } - return result; - } - - /** - * Get base name of this {@link ComplexMaterial}. - * - * @return {@link String} name - */ - public String getBaseName() { - return baseName; - } - - /** - * Get mod ID for this {@link ComplexMaterial}. - * - * @return {@link String} mod ID. - */ - public String getModID() { - return modID; - } - - /** - * Get a unique {@link ResourceLocation} for each material class. - * For example WoodenComplexMaterial will have a "bclib:Wooden_Complex_Material" {@link ResourceLocation}. - * This is used to add custom entries before mods init using Fabric "preLaunch" entry point. - * - * @return {@link ResourceLocation} for this material - * @see Fabric Documentation: Entrypoint - */ - public abstract ResourceLocation getMaterialID(); - - /** - * Get all initiated block from this {@link ComplexMaterial}. - * - * @return {@link Collection} of {@link Block}. - */ - public Collection getBlocks() { - return blocks.values(); - } - - /** - * Get all initiated items from this {@link ComplexMaterial}. - * - * @return {@link Collection} of {@link Item}. - */ - public Collection getItems() { - return items.values(); - } - - /** - * Adds a default {@link BlockEntry} to this {@link ComplexMaterial}. Used to initiate blocks later. - * - * @param entry {@link BlockEntry} - */ - protected void addBlockEntry(BlockEntry entry) { - defaultBlockEntries.add(entry); - } - - /** - * Replaces or Adds a default {@link BlockEntry} to this {@link ComplexMaterial}. Used to initiate blocks later. - *

- * If this {@link ComplexMaterial} does already contain an entry for the {@link ResourceLocation}, the entry will - * be removed first. - * - * @param entry {@link BlockEntry} - */ - protected void replaceOrAddBlockEntry(BlockEntry entry) { - int pos = defaultBlockEntries.indexOf(entry); - if (pos >= 0) defaultBlockEntries.remove(entry); - - addBlockEntry(entry); - } - - /** - * Adds a default {@link ItemEntry} to this {@link ComplexMaterial}. Used to initiate items later. - * - * @param entry {@link ItemEntry} - */ - protected void addItemEntry(ItemEntry entry) { - defaultItemEntries.add(entry); - } - - /** - * Adds a default {@link RecipeEntry} to this {@link ComplexMaterial}. Used to initiate items later. - * - * @param entry {@link RecipeEntry} - */ - protected void addRecipeEntry(RecipeEntry entry) { - defaultRecipeEntries.add(entry); - } - - /** - * Adds a custom {@link BlockEntry} for specified {@link ComplexMaterial} using its {@link ResourceLocation}. - * Used to add custom entry for all instances of {@link ComplexMaterial}. - * Should be called only using Fabric "preLaunch" entry point. - * - * @param materialName {@link ResourceLocation} id of {@link ComplexMaterial}; - * @param entry {@link BlockEntry}. - * @see Fabric Documentation: Entrypoint - */ - public static void addBlockEntry(ResourceLocation materialName, BlockEntry entry) { - List entries = BLOCK_ENTRIES.get(materialName); - if (entries == null) { - entries = Lists.newArrayList(); - BLOCK_ENTRIES.put(materialName, entries); - } - entries.add(entry); - } - - /** - * Adds a custom {@link ItemEntry} for specified {@link ComplexMaterial} using its {@link ResourceLocation}. - * Used to add custom entry for all instances of {@link ComplexMaterial}. - * Should be called only using Fabric "preLaunch" entry point. - * - * @param materialName {@link ResourceLocation} id of {@link ComplexMaterial}; - * @param entry {@link ItemEntry}. - * @see Fabric Documentation: Entrypoint - */ - public static void addItemEntry(ResourceLocation materialName, ItemEntry entry) { - List entries = ITEM_ENTRIES.get(materialName); - if (entries == null) { - entries = Lists.newArrayList(); - ITEM_ENTRIES.put(materialName, entries); - } - entries.add(entry); - } - - /** - * Adds a custom {@link RecipeEntry} for specified {@link ComplexMaterial} using its {@link ResourceLocation}. - * Used to add custom entry for all instances of {@link ComplexMaterial}. - * Should be called only using Fabric "preLaunch" entry point. - * - * @param materialName {@link ResourceLocation} id of {@link ComplexMaterial}; - * @param entry {@link RecipeEntry}. - * @see Fabric Documentation: Entrypoint - */ - public static void addRecipeEntry(ResourceLocation materialName, RecipeEntry entry) { - List entries = RECIPE_ENTRIES.get(materialName); - if (entries == null) { - entries = Lists.newArrayList(); - RECIPE_ENTRIES.put(materialName, entries); - } - entries.add(entry); - } - - /** - * Get all instances of all materials. - * - * @return {@link Collection} of {@link ComplexMaterial}. - */ - public static Collection getAllMaterials() { - return MATERIALS; - } -} diff --git a/src/main/java/org/betterx/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/org/betterx/bclib/complexmaterials/WoodenComplexMaterial.java deleted file mode 100644 index 0eceebdd..00000000 --- a/src/main/java/org/betterx/bclib/complexmaterials/WoodenComplexMaterial.java +++ /dev/null @@ -1,433 +0,0 @@ -package org.betterx.bclib.complexmaterials; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.blocks.*; -import org.betterx.bclib.complexmaterials.entry.BlockEntry; -import org.betterx.bclib.complexmaterials.entry.RecipeEntry; -import org.betterx.bclib.recipes.BCLRecipeBuilder; -import org.betterx.worlds.together.tag.v3.CommonBlockTags; -import org.betterx.worlds.together.tag.v3.CommonItemTags; -import org.betterx.worlds.together.tag.v3.CommonPoiTags; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.material.MaterialColor; - -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; - -public class WoodenComplexMaterial extends ComplexMaterial { - public static final ResourceLocation MATERIAL_ID = BCLib.makeID("wooden_material"); - - public static final String BLOCK_CRAFTING_TABLE = "crafting_table"; - public static final String BLOCK_STRIPPED_BARK = "stripped_bark"; - public static final String BLOCK_STRIPPED_LOG = "stripped_log"; - public static final String BLOCK_PRESSURE_PLATE = "plate"; - public static final String BLOCK_BOOKSHELF = "bookshelf"; - public static final String BLOCK_COMPOSTER = "composter"; - public static final String BLOCK_TRAPDOOR = "trapdoor"; - public static final String BLOCK_BARREL = "barrel"; - public static final String BLOCK_BUTTON = "button"; - public static final String BLOCK_LADDER = "ladder"; - public static final String BLOCK_PLANKS = "planks"; - public static final String BLOCK_STAIRS = "stairs"; - public static final String BLOCK_CHEST = "chest"; - public static final String BLOCK_FENCE = "fence"; - public static final String BLOCK_BARK = "bark"; - public static final String BLOCK_DOOR = "door"; - public static final String BLOCK_GATE = "gate"; - public static final String BLOCK_SIGN = "sign"; - public static final String BLOCK_SLAB = "slab"; - public static final String BLOCK_LOG = "log"; - - public static final String TAG_LOGS = "logs"; - - public final MaterialColor planksColor; - public final MaterialColor woodColor; - - public WoodenComplexMaterial( - String modID, - String baseName, - String receipGroupPrefix, - MaterialColor woodColor, - MaterialColor planksColor - ) { - super(modID, baseName, receipGroupPrefix); - this.planksColor = planksColor; - this.woodColor = woodColor; - } - - @Override - protected FabricBlockSettings getBlockSettings() { - return FabricBlockSettings.copyOf(Blocks.OAK_PLANKS) - .mapColor(planksColor); - } - - @Override - public ResourceLocation getMaterialID() { - return MATERIAL_ID; - } - - @Override - protected void initTags() { - addBlockTag(TagManager.BLOCKS.makeTag(getModID(), getBaseName() + "_logs")); - addItemTag(TagManager.ITEMS.makeTag(getModID(), getBaseName() + "_logs")); - } - - @Override - protected void initDefault(BlockBehaviour.Properties blockSettings, Item.Properties itemSettings) { - initBase(blockSettings, itemSettings); - initStorage(blockSettings, itemSettings); - initDecorations(blockSettings, itemSettings); - } - - final protected void initBase(BlockBehaviour.Properties blockSettings, Item.Properties itemSettings) { - TagKey tagBlockLog = getBlockTag(TAG_LOGS); - TagKey tagItemLog = getItemTag(TAG_LOGS); - - addBlockEntry( - new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> new BaseRotatedPillarBlock(settings)) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - addBlockEntry( - new BlockEntry(BLOCK_STRIPPED_BARK, (complexMaterial, settings) -> new BaseBarkBlock(settings)) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - - addBlockEntry( - new BlockEntry( - BLOCK_LOG, - (complexMaterial, settings) -> new BaseStripableLogBlock( - woodColor, - getBlock(BLOCK_STRIPPED_LOG) - ) - ) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - addBlockEntry( - new BlockEntry( - BLOCK_BARK, - (complexMaterial, settings) -> new StripableBarkBlock( - woodColor, - getBlock(BLOCK_STRIPPED_BARK) - ) - ) - .setBlockTags(BlockTags.LOGS, BlockTags.LOGS_THAT_BURN, tagBlockLog) - .setItemTags(ItemTags.LOGS, ItemTags.LOGS_THAT_BURN, tagItemLog) - ); - addBlockEntry(new BlockEntry(BLOCK_PLANKS, (complexMaterial, settings) -> new BaseBlock(settings)) - .setBlockTags(BlockTags.PLANKS) - .setItemTags(ItemTags.PLANKS)); - - addBlockEntry(new BlockEntry( - BLOCK_STAIRS, - (complexMaterial, settings) -> new BaseStairsBlock(getBlock(BLOCK_PLANKS), false) - ) - .setBlockTags(BlockTags.WOODEN_STAIRS, BlockTags.STAIRS) - .setItemTags(ItemTags.WOODEN_STAIRS, ItemTags.STAIRS)); - - addBlockEntry(new BlockEntry( - BLOCK_SLAB, - (complexMaterial, settings) -> new BaseSlabBlock(getBlock(BLOCK_PLANKS), false) - ) - .setBlockTags(BlockTags.WOODEN_SLABS, BlockTags.SLABS) - .setItemTags(ItemTags.WOODEN_SLABS, ItemTags.SLABS)); - - addBlockEntry(new BlockEntry( - BLOCK_FENCE, - (complexMaterial, settings) -> new BaseFenceBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.FENCES, BlockTags.WOODEN_FENCES) - .setItemTags(ItemTags.FENCES, ItemTags.WOODEN_FENCES)); - - addBlockEntry(new BlockEntry( - BLOCK_GATE, - (complexMaterial, settings) -> new BaseGateBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.FENCE_GATES)); - - addBlockEntry(new BlockEntry( - BLOCK_BUTTON, - (complexMaterial, settings) -> new BaseWoodenButtonBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.BUTTONS, BlockTags.WOODEN_BUTTONS) - .setItemTags(ItemTags.BUTTONS, ItemTags.WOODEN_BUTTONS)); - - addBlockEntry(new BlockEntry( - BLOCK_PRESSURE_PLATE, - (complexMaterial, settings) -> new WoodenPressurePlateBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.PRESSURE_PLATES, BlockTags.WOODEN_PRESSURE_PLATES) - .setItemTags(ItemTags.WOODEN_PRESSURE_PLATES)); - - addBlockEntry(new BlockEntry( - BLOCK_TRAPDOOR, - (complexMaterial, settings) -> new BaseTrapdoorBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.TRAPDOORS, BlockTags.WOODEN_TRAPDOORS) - .setItemTags(ItemTags.TRAPDOORS, ItemTags.WOODEN_TRAPDOORS)); - - addBlockEntry(new BlockEntry( - BLOCK_DOOR, - (complexMaterial, settings) -> new BaseDoorBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS) - .setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); - - addBlockEntry(new BlockEntry( - BLOCK_LADDER, - (complexMaterial, settings) -> new BaseLadderBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.CLIMBABLE)); - - addBlockEntry(new BlockEntry( - BLOCK_SIGN, - (complexMaterial, settings) -> new BaseSignBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(BlockTags.SIGNS) - .setItemTags(ItemTags.SIGNS)); - } - - final protected void initStorage(BlockBehaviour.Properties blockSettings, Item.Properties itemSettings) { - addBlockEntry(new BlockEntry( - BLOCK_CHEST, - (complexMaterial, settings) -> new BaseChestBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(CommonBlockTags.CHEST, CommonBlockTags.WOODEN_CHEST) - .setItemTags(CommonItemTags.CHEST, CommonItemTags.WOODEN_CHEST)); - - addBlockEntry(new BlockEntry( - BLOCK_BARREL, - (complexMaterial, settings) -> new BaseBarrelBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(CommonBlockTags.BARREL, CommonBlockTags.WOODEN_BARREL) - .setItemTags(CommonItemTags.BARREL, CommonItemTags.WOODEN_BARREL)); - } - - protected void initDecorations(BlockBehaviour.Properties blockSettings, Item.Properties itemSettings) { - addBlockEntry(new BlockEntry( - BLOCK_CRAFTING_TABLE, - (cmx, settings) -> new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(CommonBlockTags.WORKBENCHES) - .setItemTags(CommonItemTags.WORKBENCHES) - ); - - addBlockEntry(new BlockEntry( - BLOCK_BOOKSHELF, - (cmx, settings) -> new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(CommonBlockTags.BOOKSHELVES)); - - addBlockEntry(new BlockEntry( - BLOCK_COMPOSTER, - (complexMaterial, settings) -> new BaseComposterBlock(getBlock(BLOCK_PLANKS)) - ) - .setBlockTags(CommonPoiTags.FARMER_WORKSTATION)); - } - - @Override - protected void initFlammable(FlammableBlockRegistry registry) { - getBlocks().forEach(block -> { - registry.add(block, 5, 20); - }); - - registry.add(getBlock(BLOCK_LOG), 5, 5); - registry.add(getBlock(BLOCK_BARK), 5, 5); - registry.add(getBlock(BLOCK_STRIPPED_LOG), 5, 5); - registry.add(getBlock(BLOCK_STRIPPED_BARK), 5, 5); - } - - @Override - public void initDefaultRecipes() { - Block planks = getBlock(BLOCK_PLANKS); - addRecipeEntry(new RecipeEntry("planks", (material, config, id) -> { - Block log_stripped = getBlock(BLOCK_STRIPPED_LOG); - Block bark_stripped = getBlock(BLOCK_STRIPPED_BARK); - Block log = getBlock(BLOCK_LOG); - Block bark = getBlock(BLOCK_BARK); - BCLRecipeBuilder.crafting(id, planks) - .checkConfig(config) - .setOutputCount(4) - .setList("#") - .addMaterial('#', log, bark, log_stripped, bark_stripped) - .setGroup(receipGroupPrefix + "_planks") - .build(); - })); - addRecipeEntry(new RecipeEntry("stairs", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_STAIRS)) - .checkConfig(config) - .setOutputCount(4) - .setShape("# ", "## ", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_stairs") - .build(); - })); - addRecipeEntry(new RecipeEntry("slab", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_SLAB)) - .checkConfig(config) - .setOutputCount(6) - .setShape("###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_slabs") - .build(); - })); - addRecipeEntry(new RecipeEntry("fence", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_FENCE)) - .checkConfig(config) - .setOutputCount(3) - .setShape("#I#", "#I#") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix + "_planks_fences") - .build(); - })); - addRecipeEntry(new RecipeEntry("gate", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_GATE)) - .checkConfig(config) - .setShape("I#I", "I#I") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix + "_planks_gates") - .build(); - })); - addRecipeEntry(new RecipeEntry("button", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_BUTTON)) - .checkConfig(config) - .setList("#") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_buttons") - .build(); - })); - addRecipeEntry(new RecipeEntry("pressure_plate", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_PRESSURE_PLATE)) - .checkConfig(config) - .setShape("##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_plates") - .build(); - })); - addRecipeEntry(new RecipeEntry("trapdoor", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_TRAPDOOR)) - .checkConfig(config) - .setOutputCount(2) - .setShape("###", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_trapdoors") - .build(); - })); - addRecipeEntry(new RecipeEntry("door", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_DOOR)) - .checkConfig(config) - .setOutputCount(3) - .setShape("##", "##", "##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_doors") - .build(); - })); - addRecipeEntry(new RecipeEntry("crafting_table", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_CRAFTING_TABLE)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_tables") - .build(); - })); - addRecipeEntry(new RecipeEntry("ladder", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_LADDER)) - .checkConfig(config) - .setOutputCount(3) - .setShape("I I", "I#I", "I I") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix + "_ladders") - .build(); - })); - addRecipeEntry(new RecipeEntry("sign", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_SIGN)) - .checkConfig(config) - .setOutputCount(3) - .setShape("###", "###", " I ") - .addMaterial('#', planks) - .addMaterial('I', Items.STICK) - .setGroup(receipGroupPrefix + "_signs") - .build(); - })); - addRecipeEntry(new RecipeEntry("chest", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_CHEST)) - .checkConfig(config) - .setShape("###", "# #", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_chests") - .build(); - })); - addRecipeEntry(new RecipeEntry("barrel", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_BARREL)) - .checkConfig(config) - .setShape("#S#", "# #", "#S#") - .addMaterial('#', planks) - .addMaterial('S', getBlock(BLOCK_SLAB)) - .setGroup(receipGroupPrefix + "_barrels") - .build(); - })); - addRecipeEntry(new RecipeEntry("bookshelf", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_BOOKSHELF)) - .checkConfig(config) - .setShape("###", "PPP", "###") - .addMaterial('#', planks) - .addMaterial('P', Items.BOOK) - .setGroup(receipGroupPrefix + "_bookshelves") - .build(); - })); - addRecipeEntry(new RecipeEntry("bark", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_BARK)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_LOG)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("log", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_LOG)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_BARK)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("stripped_bark", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_STRIPPED_BARK)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_STRIPPED_LOG)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("stripped_log", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_STRIPPED_LOG)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_STRIPPED_BARK)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("composter", (material, config, id) -> { - BCLRecipeBuilder.crafting(id, getBlock(BLOCK_COMPOSTER)) - .checkConfig(config) - .setShape("# #", "# #", "###") - .addMaterial('#', getBlock(BLOCK_SLAB)) - .build(); - })); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/complexmaterials/entry/BlockEntry.java b/src/main/java/org/betterx/bclib/complexmaterials/entry/BlockEntry.java deleted file mode 100644 index bf5ccb41..00000000 --- a/src/main/java/org/betterx/bclib/complexmaterials/entry/BlockEntry.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.complexmaterials.entry; - -import org.betterx.bclib.complexmaterials.ComplexMaterial; -import org.betterx.bclib.registry.BlockRegistry; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockBehaviour; - -import java.util.function.BiFunction; - -public class BlockEntry extends ComplexMaterialEntry { - final BiFunction initFunction; - final boolean hasItem; - - TagKey[] blockTags; - TagKey[] itemTags; - - public BlockEntry(String suffix, BiFunction initFunction) { - this(suffix, true, initFunction); - } - - public BlockEntry( - String suffix, - boolean hasItem, - BiFunction initFunction - ) { - super(suffix); - this.initFunction = initFunction; - this.hasItem = hasItem; - } - - @SafeVarargs - public final BlockEntry setBlockTags(TagKey... blockTags) { - this.blockTags = blockTags; - return this; - } - - @SafeVarargs - public final BlockEntry setItemTags(TagKey... itemTags) { - this.itemTags = itemTags; - return this; - } - - public Block init(ComplexMaterial material, BlockBehaviour.Properties blockSettings, BlockRegistry registry) { - ResourceLocation location = getLocation(material.getModID(), material.getBaseName()); - Block block = initFunction.apply(material, blockSettings); - if (hasItem) { - registry.register(location, block); - if (itemTags != null) { - TagManager.ITEMS.add(block.asItem(), itemTags); - } - } else { - registry.registerBlockOnly(location, block); - } - if (blockTags != null) { - TagManager.BLOCKS.add(block, blockTags); - } - return block; - } -} diff --git a/src/main/java/org/betterx/bclib/complexmaterials/entry/ComplexMaterialEntry.java b/src/main/java/org/betterx/bclib/complexmaterials/entry/ComplexMaterialEntry.java deleted file mode 100644 index 9dea2b60..00000000 --- a/src/main/java/org/betterx/bclib/complexmaterials/entry/ComplexMaterialEntry.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.betterx.bclib.complexmaterials.entry; - -import net.minecraft.resources.ResourceLocation; - -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -public abstract class ComplexMaterialEntry { - @NotNull - private final String suffix; - - protected ComplexMaterialEntry(String suffix) { - this.suffix = suffix; - } - - public String getName(String baseName) { - return baseName + "_" + suffix; - } - - public ResourceLocation getLocation(String modID, String baseName) { - return new ResourceLocation(modID, getName(baseName)); - } - - public String getSuffix() { - return suffix; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ComplexMaterialEntry that = (ComplexMaterialEntry) o; - return suffix.equals(that.suffix); - } - - @Override - public int hashCode() { - return Objects.hash(suffix); - } -} diff --git a/src/main/java/org/betterx/bclib/complexmaterials/entry/ItemEntry.java b/src/main/java/org/betterx/bclib/complexmaterials/entry/ItemEntry.java deleted file mode 100644 index 37d91f27..00000000 --- a/src/main/java/org/betterx/bclib/complexmaterials/entry/ItemEntry.java +++ /dev/null @@ -1,37 +0,0 @@ -package org.betterx.bclib.complexmaterials.entry; - -import org.betterx.bclib.complexmaterials.ComplexMaterial; -import org.betterx.bclib.registry.ItemRegistry; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; - -import java.util.function.BiFunction; - -public class ItemEntry extends ComplexMaterialEntry { - final BiFunction initFunction; - - TagKey[] itemTags; - - public ItemEntry(String suffix, BiFunction initFunction) { - super(suffix); - this.initFunction = initFunction; - } - - public ItemEntry setItemTags(TagKey[] itemTags) { - this.itemTags = itemTags; - return this; - } - - public Item init(ComplexMaterial material, Item.Properties itemSettings, ItemRegistry registry) { - ResourceLocation location = getLocation(material.getModID(), material.getBaseName()); - Item item = initFunction.apply(material, itemSettings); - registry.register(location, item); - if (itemTags != null) { - TagManager.ITEMS.add(item, itemTags); - } - return item; - } -} diff --git a/src/main/java/org/betterx/bclib/complexmaterials/entry/RecipeEntry.java b/src/main/java/org/betterx/bclib/complexmaterials/entry/RecipeEntry.java deleted file mode 100644 index 8828f6af..00000000 --- a/src/main/java/org/betterx/bclib/complexmaterials/entry/RecipeEntry.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.betterx.bclib.complexmaterials.entry; - -import org.betterx.bclib.complexmaterials.ComplexMaterial; -import org.betterx.bclib.config.PathConfig; -import org.betterx.bclib.interfaces.TriConsumer; - -import net.minecraft.resources.ResourceLocation; - -public class RecipeEntry extends ComplexMaterialEntry { - final TriConsumer initFunction; - - public RecipeEntry(String suffix, TriConsumer initFunction) { - super(suffix); - this.initFunction = initFunction; - } - - public void init(ComplexMaterial material, PathConfig recipeConfig) { - initFunction.accept(material, recipeConfig, getLocation(material.getModID(), material.getBaseName())); - } -} diff --git a/src/main/java/org/betterx/bclib/config/BiomesConfig.java b/src/main/java/org/betterx/bclib/config/BiomesConfig.java deleted file mode 100644 index ea73ba70..00000000 --- a/src/main/java/org/betterx/bclib/config/BiomesConfig.java +++ /dev/null @@ -1,111 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; - -import java.util.*; - -public class BiomesConfig extends PathConfig { - - private Map> BIOME_INCLUDE_LIST = null; - private Map> BIOME_EXCLUDE_LIST = null; - - - public static final BiomeAPI.BiomeType[] endTypes = { - BiomeAPI.BiomeType.END_LAND, - BiomeAPI.BiomeType.END_VOID, - BiomeAPI.BiomeType.END_CENTER, - BiomeAPI.BiomeType.END_BARRENS - }; - - public static final BiomeAPI.BiomeType[] netherTypes = { - BiomeAPI.BiomeType.NETHER - }; - - private static final BiomeAPI.BiomeType[] includeTypes = all(); - private static final BiomeAPI.BiomeType[] excludeTypes = {BiomeAPI.BiomeType.NETHER, BiomeAPI.BiomeType.END}; - - public BiomesConfig() { - super(BCLib.MOD_ID, "biomes", true); - for (var type : includeTypes) { - keeper.registerEntry( - new ConfigKey(type.getName(), "force_include"), - new ConfigKeeper.StringArrayEntry(Collections.EMPTY_LIST) - ); - } - for (var type : excludeTypes) { - keeper.registerEntry( - new ConfigKey(type.getName(), "force_exclude"), - new ConfigKeeper.StringArrayEntry(Collections.EMPTY_LIST) - ); - } - } - - private static BiomeAPI.BiomeType[] all() { - BiomeAPI.BiomeType[] res = new BiomeAPI.BiomeType[endTypes.length + netherTypes.length]; - System.arraycopy(netherTypes, 0, res, 0, netherTypes.length); - System.arraycopy(endTypes, 0, res, netherTypes.length, endTypes.length); - return res; - } - - private List getBiomeIncludeList(BiomeAPI.BiomeType type) { - var entry = getEntry( - "force_include", - type.getName(), - ConfigKeeper.StringArrayEntry.class - ); - if (entry == null) - return List.of(); - return entry.getValue(); - } - - private List getBiomeExcludeList(BiomeAPI.BiomeType type) { - var entry = getEntry( - "force_exclude", - type.getName(), - ConfigKeeper.StringArrayEntry.class - ); - if (entry == null) - return List.of(); - return entry.getValue(); - } - - public List getIncludeMatching(BiomeAPI.BiomeType type) { - return getBiomeIncludeMap().entrySet() - .stream() - .filter(e -> e.getKey().is(type)) - .map(e -> e.getValue()) - .flatMap(Collection::stream) - .toList(); - } - - public List getExcludeMatching(BiomeAPI.BiomeType type) { - return getBiomeExcludeMap().entrySet() - .stream() - .filter(e -> e.getKey().is(type)) - .map(e -> e.getValue()) - .flatMap(Collection::stream) - .toList(); - } - - - public Map> getBiomeIncludeMap() { - if (BIOME_INCLUDE_LIST == null) { - BIOME_INCLUDE_LIST = new HashMap<>(); - for (BiomeAPI.BiomeType type : includeTypes) { - BIOME_INCLUDE_LIST.put(type, getBiomeIncludeList(type)); - } - } - return BIOME_INCLUDE_LIST; - } - - public Map> getBiomeExcludeMap() { - if (BIOME_EXCLUDE_LIST == null) { - BIOME_EXCLUDE_LIST = new HashMap<>(); - for (BiomeAPI.BiomeType type : excludeTypes) { - BIOME_EXCLUDE_LIST.put(type, getBiomeExcludeList(type)); - } - } - return BIOME_EXCLUDE_LIST; - } -} diff --git a/src/main/java/org/betterx/bclib/config/CachedConfig.java b/src/main/java/org/betterx/bclib/config/CachedConfig.java deleted file mode 100644 index 07604a0e..00000000 --- a/src/main/java/org/betterx/bclib/config/CachedConfig.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.networking.VersionChecker; - -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.Base64; - -public class CachedConfig extends NamedPathConfig { - - @ConfigUI(hide = true) - public static final ConfigToken LAST_CHECK_DATE = ConfigToken.String( - "never", - "last", - "version" - ); - - @ConfigUI(hide = true) - public static final ConfigToken LAST_JSON = ConfigToken.String( - "", - "cached", - "version" - ); - - public CachedConfig() { - super(BCLib.MOD_ID, "cache", false, false); - } - - public String lastVersionJson() { - byte[] decodedBytes = Base64.getUrlDecoder().decode(get(LAST_JSON)); - return new String(decodedBytes, StandardCharsets.UTF_8); - } - - public void setLastVersionJson(String json) { - set(LAST_JSON, Base64.getUrlEncoder().encodeToString(json.getBytes(StandardCharsets.UTF_8))); - } - - public Instant lastCheckDate() { - String d = get(LAST_CHECK_DATE); - if (d.trim().toLowerCase().equals("never")) { - return Instant.now().minus(VersionChecker.WAIT_FOR_DAYS + 1, ChronoUnit.DAYS); - } - return Instant.parse(d); - } - - public void setLastCheckDate() { - set(LAST_CHECK_DATE, Instant.now().toString()); - } - - @Override - public void saveChanges() { - synchronized (this) { - super.saveChanges(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/config/CategoryConfig.java b/src/main/java/org/betterx/bclib/config/CategoryConfig.java deleted file mode 100644 index 5fe67b2b..00000000 --- a/src/main/java/org/betterx/bclib/config/CategoryConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.betterx.bclib.config; - -public class CategoryConfig extends IdConfig { - - public CategoryConfig(String modID, String group) { - super(modID, group, (id, category) -> { - return new ConfigKey(id.getPath(), id.getNamespace(), category); - }); - } -} diff --git a/src/main/java/org/betterx/bclib/config/ClientConfig.java b/src/main/java/org/betterx/bclib/config/ClientConfig.java deleted file mode 100644 index dba7bfa8..00000000 --- a/src/main/java/org/betterx/bclib/config/ClientConfig.java +++ /dev/null @@ -1,192 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync; - -public class ClientConfig extends NamedPathConfig { - - @ConfigUI(hide = true) - public static final ConfigToken DID_SHOW_WELCOME = ConfigToken.Boolean( - false, - "didShowWelcome", - "version" - ); - @ConfigUI(topPadding = 12) - public static final ConfigToken CHECK_VERSIONS = ConfigToken.Boolean( - true, - "check", - "version" - ); - @ConfigUI(leftPadding = 8) - public static final ConfigToken SHOW_UPDATE_INFO = ConfigToken.Boolean( - true, - "showUpdateInfo", - "ui" - ); - - @ConfigUI(hide = true) - public static final ConfigToken FORCE_BETTERX_PRESET = ConfigToken.Boolean( - true, - "forceBetterXPreset", - "ui" - ); - public static final ConfigToken SUPPRESS_EXPERIMENTAL_DIALOG = ConfigToken.Boolean( - false, - "suppressExperimentalDialogOnLoad", - "ui" - ); - - - @ConfigUI(hide = true) - public static final ConfigToken NO_DONOR = ConfigToken.Boolean( - false, - "iAmNotTheDonorType", - "ui" - ); - - - @ConfigUI(topPadding = 12) - public static final ConfigToken ENABLED = ConfigToken.Boolean(true, "enabled", AutoSync.SYNC_CATEGORY); - - @ConfigUI(leftPadding = 8) - public static final DependendConfigToken ACCEPT_CONFIGS = DependendConfigToken.Boolean( - true, - "acceptConfigs", - AutoSync.SYNC_CATEGORY, - (config) -> config.get( - ENABLED) - ); - @ConfigUI(leftPadding = 8) - public static final DependendConfigToken ACCEPT_FILES = DependendConfigToken.Boolean( - true, - "acceptFiles", - AutoSync.SYNC_CATEGORY, - (config) -> config.get( - ENABLED) - ); - @ConfigUI(leftPadding = 8) - public static final DependendConfigToken ACCEPT_MODS = DependendConfigToken.Boolean( - true, - "acceptMods", - AutoSync.SYNC_CATEGORY, - (config) -> config.get(ENABLED) - ); - @ConfigUI(leftPadding = 8) - public static final DependendConfigToken DISPLAY_MOD_INFO = DependendConfigToken.Boolean( - true, - "displayModInfo", - AutoSync.SYNC_CATEGORY, - (config) -> config.get(ENABLED) - ); - - @ConfigUI(leftPadding = 8) - public static final ConfigToken DEBUG_HASHES = ConfigToken.Boolean( - false, - "debugHashes", - AutoSync.SYNC_CATEGORY - ); - - @ConfigUI(topPadding = 12) - public static final ConfigToken CUSTOM_FOG_RENDERING = ConfigToken.Boolean( - true, - "customFogRendering", - "rendering" - ); - @ConfigUI(leftPadding = 8) - public static final ConfigToken NETHER_THICK_FOG = DependendConfigToken.Boolean( - true, - "netherThickFog", - "rendering", - (config) -> config.get(CUSTOM_FOG_RENDERING) - ); - - @ConfigUI(leftPadding = 8, minValue = 0, maxValue = 2) - public static final ConfigToken FOG_DENSITY = DependendConfigToken.Float( - 1.0f, - "FogDensity", - "rendering", - (config) -> config.get(CUSTOM_FOG_RENDERING) - ); - - - public ClientConfig() { - super(BCLib.MOD_ID, "client", false); - } - - public boolean shouldPrintDebugHashes() { - return get(DEBUG_HASHES); - } - - public boolean isAllowingAutoSync() { - return get(ENABLED); - } - - public boolean isAcceptingMods() { - return get(ACCEPT_MODS) /*&& isAllowingAutoSync()*/; - } - - public boolean isAcceptingConfigs() { - return get(ACCEPT_CONFIGS) /*&& isAllowingAutoSync()*/; - } - - public boolean isAcceptingFiles() { - return get(ACCEPT_FILES) /*&& isAllowingAutoSync()*/; - } - - public boolean isShowingModInfo() { - return get(DISPLAY_MOD_INFO) /*&& isAllowingAutoSync()*/; - } - - public boolean suppressExperimentalDialog() { - return get(SUPPRESS_EXPERIMENTAL_DIALOG); - } - - public void setSuppressExperimentalDialog(boolean newValue) { - set(ClientConfig.SUPPRESS_EXPERIMENTAL_DIALOG, newValue); - } - - public boolean netherThickFog() { - return get(NETHER_THICK_FOG); - } - - public boolean renderCustomFog() { - return get(CUSTOM_FOG_RENDERING); - } - - public boolean showUpdateInfo() { - return get(SHOW_UPDATE_INFO); - } - - public boolean isDonor() { - return !get(NO_DONOR); - } - - public float fogDensity() { - return get(FOG_DENSITY); - } - - public boolean checkVersions() { - return get(ClientConfig.CHECK_VERSIONS); - } - - - public void setCheckVersions(boolean newValue) { - set(ClientConfig.CHECK_VERSIONS, newValue); - } - - public boolean didShowWelcomeScreen() { - return get(ClientConfig.DID_SHOW_WELCOME); - } - - public void setDidShowWelcomeScreen() { - set(ClientConfig.DID_SHOW_WELCOME, true); - } - - public boolean forceBetterXPreset() { - return get(FORCE_BETTERX_PRESET); - } - - public void setForceBetterXPreset(boolean v) { - set(FORCE_BETTERX_PRESET, v); - } -} diff --git a/src/main/java/org/betterx/bclib/config/Config.java b/src/main/java/org/betterx/bclib/config/Config.java deleted file mode 100644 index 45223139..00000000 --- a/src/main/java/org/betterx/bclib/config/Config.java +++ /dev/null @@ -1,239 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; -import org.betterx.bclib.api.v2.dataexchange.SyncFileHash; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSyncID; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.FileContentWrapper; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import org.jetbrains.annotations.Nullable; - -public abstract class Config { - protected final static Map AUTO_SYNC_CONFIGS = new HashMap<>(); - public static final String CONFIG_SYNC_PREFIX = "CONFIG_"; - protected final ConfigKeeper keeper; - protected final boolean autoSync; - public final String configID; - - protected abstract void registerEntries(); - - protected Config(String modID, String group) { - this(modID, group, true, false); - } - - protected Config(String modID, String group, boolean autoSync) { - this(modID, group, autoSync, false); - } - - protected Config(String modID, String group, boolean autoSync, boolean diffContent) { - configID = modID + "." + group; - this.keeper = new ConfigKeeper(modID, group); - this.registerEntries(); - this.autoSync = autoSync; - - if (autoSync) { - final String uid = CONFIG_SYNC_PREFIX + configID; - final AutoSyncID aid = new AutoSyncID(BCLib.MOD_ID, uid); - if (diffContent) - DataExchangeAPI.addAutoSyncFile(aid.modID, aid.uniqueID, keeper.getConfigFile(), this::compareForSync); - else - DataExchangeAPI.addAutoSyncFile(aid.modID, aid.uniqueID, keeper.getConfigFile()); - - AUTO_SYNC_CONFIGS.put(aid, this); - BCLib.LOGGER.info("Added Config " + configID + " to auto sync (" + (diffContent - ? "content diff" - : "file hash") + ")"); - } - } - - private boolean compareForSync(SyncFileHash clientHash, SyncFileHash serverHash, FileContentWrapper content) { - //identical hashes => nothing to do - if (clientHash.equals(serverHash)) { - return false; - } - - return keeper.compareAndUpdateForSync(content); - } - - public void saveChanges() { - this.keeper.save(); - } - - public static void reloadSyncedConfig(AutoSyncID aid, File file) { - Config cfg = AUTO_SYNC_CONFIGS.get(aid); - if (cfg != null) { - cfg.reload(); - } - } - - public void reload() { - this.keeper.reload(); - BCLib.LOGGER.info("Did Reload " + keeper.getConfigFile()); - } - - @Nullable - public > E getEntry(ConfigKey key, Class type) { - return this.keeper.getEntry(key, type); - } - - @Nullable - public > T getDefault(ConfigKey key, Class type) { - ConfigKeeper.Entry entry = keeper.getEntry(key, type); - return entry != null ? entry.getDefault() : null; - } - - protected String getString(ConfigKey key, String defaultValue) { - String str = keeper.getValue(key, ConfigKeeper.StringEntry.class); - if (str == null) { - ConfigKeeper.StringEntry entry = keeper.registerEntry(key, new ConfigKeeper.StringEntry(defaultValue)); - return entry.getValue(); - } - return str != null ? str : defaultValue; - } - - protected String getString(ConfigKey key) { - String str = keeper.getValue(key, ConfigKeeper.StringEntry.class); - return str != null ? str : ""; - } - - protected boolean setString(ConfigKey key, String value) { - try { - ConfigKeeper.StringEntry entry = keeper.getEntry(key, ConfigKeeper.StringEntry.class); - if (entry == null) return false; - entry.setValue(value); - return true; - } catch (NullPointerException ex) { - BCLib.LOGGER.catching(ex); - } - return false; - } - - protected int getInt(ConfigKey key, int defaultValue) { - Integer val = keeper.getValue(key, ConfigKeeper.IntegerEntry.class); - if (val == null) { - ConfigKeeper.IntegerEntry entry = keeper.registerEntry(key, new ConfigKeeper.IntegerEntry(defaultValue)); - return entry.getValue(); - } - return val != null ? val : defaultValue; - } - - protected int getInt(ConfigKey key) { - Integer val = keeper.getValue(key, ConfigKeeper.IntegerEntry.class); - return val != null ? val : 0; - } - - protected boolean setInt(ConfigKey key, int value) { - try { - ConfigKeeper.IntegerEntry entry = keeper.getEntry(key, ConfigKeeper.IntegerEntry.class); - if (entry == null) return false; - entry.setValue(value); - return true; - } catch (NullPointerException ex) { - BCLib.LOGGER.catching(ex); - } - return false; - } - - protected , RE extends ConfigKeeper.RangeEntry> boolean setRanged( - ConfigKey key, - T value, - Class type - ) { - try { - ConfigKeeper.RangeEntry entry = keeper.getEntry(key, type); - if (entry == null) return false; - entry.setValue(value); - return true; - } catch (NullPointerException | ClassCastException ex) { - BCLib.LOGGER.catching(ex); - } - return false; - } - - protected float getFloat(ConfigKey key, float defaultValue) { - Float val = keeper.getValue(key, ConfigKeeper.FloatEntry.class); - if (val == null) { - ConfigKeeper.FloatEntry entry = keeper.registerEntry(key, new ConfigKeeper.FloatEntry(defaultValue)); - return entry.getValue(); - } - return val; - } - - protected float getFloat(ConfigKey key) { - Float val = keeper.getValue(key, ConfigKeeper.FloatEntry.class); - return val != null ? val : 0.0F; - } - - protected boolean setFloat(ConfigKey key, float value) { - try { - ConfigKeeper.FloatEntry entry = keeper.getEntry(key, ConfigKeeper.FloatEntry.class); - if (entry == null) return false; - entry.setValue(value); - return true; - } catch (NullPointerException ex) { - BCLib.LOGGER.catching(ex); - } - return false; - } - - protected boolean getBoolean(ConfigKey key, boolean defaultValue) { - Boolean val = keeper.getValue(key, ConfigKeeper.BooleanEntry.class); - if (val == null) { - ConfigKeeper.BooleanEntry entry = keeper.registerEntry(key, new ConfigKeeper.BooleanEntry(defaultValue)); - return entry.getValue(); - } - return val; - } - - protected boolean getBoolean(ConfigKey key) { - Boolean val = keeper.getValue(key, ConfigKeeper.BooleanEntry.class); - return val != null ? val : false; - } - - protected boolean setBoolean(ConfigKey key, boolean value) { - try { - ConfigKeeper.BooleanEntry entry = keeper.getEntry(key, ConfigKeeper.BooleanEntry.class); - - if (entry == null) return false; - entry.setValue(value); - return true; - } catch (NullPointerException ex) { - BCLib.LOGGER.catching(ex); - } - return false; - } - - protected List getStringArray(ConfigKey key, List defaultValue) { - List str = keeper.getValue(key, ConfigKeeper.StringArrayEntry.class); - if (str == null) { - ConfigKeeper.StringArrayEntry entry = keeper.registerEntry( - key, - new ConfigKeeper.StringArrayEntry(defaultValue) - ); - return entry.getValue(); - } - return str != null ? str : defaultValue; - } - - protected List getStringArray(ConfigKey key) { - List str = keeper.getValue(key, ConfigKeeper.StringArrayEntry.class); - return str != null ? str : new ArrayList<>(0); - } - - protected boolean setStringArray(ConfigKey key, List value) { - try { - ConfigKeeper.StringArrayEntry entry = keeper.getEntry(key, ConfigKeeper.StringArrayEntry.class); - if (entry == null) return false; - entry.setValue(value); - return true; - } catch (NullPointerException ex) { - BCLib.LOGGER.catching(ex); - } - return false; - } -} diff --git a/src/main/java/org/betterx/bclib/config/ConfigKeeper.java b/src/main/java/org/betterx/bclib/config/ConfigKeeper.java deleted file mode 100644 index 6571b1f7..00000000 --- a/src/main/java/org/betterx/bclib/config/ConfigKeeper.java +++ /dev/null @@ -1,464 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.FileContentWrapper; -import org.betterx.bclib.util.JsonFactory; -import org.betterx.bclib.util.Pair; - -import net.minecraft.util.GsonHelper; - -import com.google.common.collect.Maps; -import com.google.common.reflect.TypeToken; -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.OutputStream; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Supplier; -import org.jetbrains.annotations.Nullable; - -public final class ConfigKeeper { - private final Map> configEntries = Maps.newHashMap(); - private final ConfigWriter writer; - - private JsonObject configObject; - private boolean changed = false; - - public ConfigKeeper(String modID, String group) { - this.writer = new ConfigWriter(modID, group); - this.configObject = writer.load(); - } - - public File getConfigFile() { - return this.writer.getConfigFile(); - } - - boolean compareAndUpdateForSync(FileContentWrapper content) { - ByteArrayInputStream inputStream = content.getInputStream(); - final JsonObject other = JsonFactory.getJsonObject(inputStream); - - boolean changed = this.compareAndUpdateForSync(other); - if (changed) { - OutputStream outStream = content.getEmptyOutputStream(); - JsonFactory.storeJson(outStream, this.configObject); - content.syncWithOutputStream(); - } - return changed; - } - - boolean compareAndUpdateForSync(JsonObject other) { - return compareAndUpdateForSync(this.configObject, other); - } - - private static Pair> find(JsonObject json, Pair key) { - String kk = key.first + key.second; - for (var entry : json.entrySet()) { - final Pair otherKey = ConfigKey.realKey(entry.getKey()); - if (kk.equals(entry)) return new Pair<>(entry.getValue(), otherKey); - } - -// for (var entry : json.entrySet()) { -// final Pair otherKey = ConfigKey.realKey(entry.getKey()); -// if (otherKey.first.equals(key.first)) return new Pair<>(entry.getValue(), otherKey); -// } - - return null; - } - - /** - * Called for content based auto-sync. - * - * @param me - When called in AutoSync this represents the content of the client. - * @param other - When called in AutoSync, this represents the content of the server - * @return {@code true} if content was changed - */ - static boolean compareAndUpdateForSync(JsonObject me, JsonObject other) { - boolean changed = false; - for (var otherEntry : other.entrySet()) { - final Pair otherKey = ConfigKey.realKey(otherEntry.getKey()); - final JsonElement otherValue = otherEntry.getValue(); - - Pair> temp = find(me, otherKey); - //we already have an entry - if (temp != null) { - final Pair myKey = temp.second; - final JsonElement myValue = temp.first; - - if ((otherValue.isJsonNull() && !myValue.isJsonNull()) || (otherValue.isJsonPrimitive() && !myValue.isJsonPrimitive()) || (otherValue.isJsonObject() && !myValue.isJsonObject()) || (otherValue.isJsonArray() && !myValue.isJsonArray())) { - //types are different => replace with "server"-version in other - changed = true; - me.add(myKey.first + myKey.second, otherValue); - } else if (otherValue.isJsonPrimitive() || otherValue.isJsonArray() || otherValue.isJsonNull()) { - if (!otherValue.equals(myValue)) { - changed = true; - me.add(myKey.first + myKey.second, otherValue); - } - } else if (otherValue.isJsonObject()) { - changed |= compareAndUpdateForSync(myValue.getAsJsonObject(), otherValue.getAsJsonObject()); - } - } else { //no entry, just copy the value from other - if (!otherValue.isJsonNull()) { - changed = true; - temp = find(me, otherKey); - me.add(otherKey.first + otherKey.second, otherValue); - } - } - } - - return changed; - } - - - public void save() { - if (!changed) return; - this.writer.save(); - this.changed = false; - } - - void reload() { - this.configObject = this.writer.reload(); - this.configEntries.clear(); - this.changed = false; - } - - private > void initializeEntry(ConfigKey key, E entry) { - if (configObject == null) { - return; - } - String[] path = key.getPath(); - JsonObject obj = configObject; - - if (!key.isRoot()) { - for (String group : path) { - JsonElement element = obj.get(group); - if (element == null || !element.isJsonObject()) { - element = new JsonObject(); - obj.add(group, element); - } - obj = element.getAsJsonObject(); - } - } - - String paramKey = key.getEntry(); - if (entry.hasDefaultInName()) { - paramKey += " [default: " + entry.getDefault() + "]"; - } - - this.changed |= entry.setLocation(obj, paramKey); - } - - private > void storeValue(E entry, T value) { - if (configObject == null) { - return; - } - T val = entry.getValue(); - if (value.equals(val)) return; - entry.toJson(value); - this.changed = true; - } - - private > T getValue(E entry) { - if (!entry.hasLocation()) { - return entry.getDefault(); - } - return entry.fromJson(); - } - - @Nullable - public > E getEntry(ConfigKey key, Class type) { - Entry entry = this.configEntries.get(key); - if (type.isInstance(entry)) { - return type.cast(entry); - } - return null; - } - - @Nullable - public > T getValue(ConfigKey key, Class type) { - Entry entry = this.getEntry(key, type); - if (entry == null) { - return null; - } - return entry.getValue(); - } - - public > E registerEntry(ConfigKey key, E entry) { - entry.setWriter(value -> this.storeValue(entry, value)); - entry.setReader(() -> { - return this.getValue(entry); - }); - this.initializeEntry(key, entry); - this.configEntries.put(key, entry); - return entry; - } - - public static class BooleanEntry extends Entry { - - public BooleanEntry(Boolean defaultValue) { - super(defaultValue); - } - - @Override - public Boolean fromJson() { - return GsonHelper.getAsBoolean(location, key, defaultValue); - } - - @Override - public void toJson(Boolean value) { - this.location.addProperty(key, value); - } - } - - public static class FloatEntry extends Entry { - - public FloatEntry(Float defaultValue) { - super(defaultValue); - } - - @Override - public Float fromJson() { - return GsonHelper.getAsFloat(location, key, defaultValue); - } - - @Override - public void toJson(Float value) { - this.location.addProperty(key, value); - } - } - - public static class FloatRange extends RangeEntry { - - public FloatRange(Float defaultValue, float minVal, float maxVal) { - super(defaultValue, minVal, maxVal); - } - - @Override - public Float fromJson() { - return GsonHelper.getAsFloat(location, key, defaultValue); - } - - @Override - public void toJson(Float value) { - this.location.addProperty(key, value); - } - } - - public static class IntegerEntry extends Entry { - - public IntegerEntry(Integer defaultValue) { - super(defaultValue); - } - - @Override - public Integer getDefault() { - return this.defaultValue; - } - - @Override - public Integer fromJson() { - return GsonHelper.getAsInt(location, key, defaultValue); - } - - @Override - public void toJson(Integer value) { - this.location.addProperty(key, value); - } - } - - public static class IntegerRange extends RangeEntry { - - public IntegerRange(Integer defaultValue, int minVal, int maxVal) { - super(defaultValue, minVal, maxVal); - } - - @Override - public Integer fromJson() { - return GsonHelper.getAsInt(location, key, defaultValue); - } - - @Override - public void toJson(Integer value) { - this.location.addProperty(key, value); - } - } - - public static class StringEntry extends Entry { - - public StringEntry(String defaultValue) { - super(defaultValue); - } - - @Override - public String fromJson() { - return GsonHelper.getAsString(location, key, defaultValue); - } - - @Override - public void toJson(String value) { - this.location.addProperty(key, value); - } - } - - public static abstract class ArrayEntry extends Entry> { - public ArrayEntry(List defaultValue) { - super(defaultValue); - } - - protected abstract T getValue(JsonElement element); - protected abstract void add(JsonArray array, T element); - - private JsonArray toArray(List input) { - final JsonArray array = new JsonArray(); - input.forEach(s -> add(array, s)); - return array; - } - - @Override - public List fromJson() { - final JsonArray resArray = GsonHelper.getAsJsonArray(location, key, toArray(defaultValue)); - final List res = new ArrayList<>(resArray.size()); - resArray.forEach(e -> res.add(getValue(e))); - - return res; - } - - @Override - public void toJson(List value) { - this.location.add(key, toArray(value)); - } - } - - public static class StringArrayEntry extends ArrayEntry { - public StringArrayEntry(List defaultValue) { - super(defaultValue); - } - - @Override - protected String getValue(JsonElement el) { - return el.getAsString(); - } - - protected void add(JsonArray array, String el) { - array.add(el); - } - - @Override - protected boolean hasDefaultInName() { - return false; - } - } - - public static class EnumEntry> extends Entry { - private final Type type; - - public EnumEntry(T defaultValue) { - super(defaultValue); - TypeToken token = new TypeToken() { - private static final long serialVersionUID = 1L; - }; - this.type = token.getType(); - } - - @Override - public T getDefault() { - return this.defaultValue; - } - - @Override - public T fromJson() { - return JsonFactory.GSON.fromJson(location.get(key), type); - } - - @Override - public void toJson(T value) { - location.addProperty(key, JsonFactory.GSON.toJson(value, type)); - } - } - - public static abstract class RangeEntry> extends Entry { - private final T min, max; - - public RangeEntry(T defaultValue, T minVal, T maxVal) { - super(defaultValue); - this.min = minVal; - this.max = maxVal; - } - - @Override - public void setValue(T value) { - super.setValue(value.compareTo(min) < 0 ? min : value.compareTo(max) > 0 ? max : value); - } - - public T minValue() { - return this.min; - } - - public T maxValue() { - return this.max; - } - } - - public static abstract class Entry { - protected final T defaultValue; - protected Consumer writer; - protected Supplier reader; - protected JsonObject location; - protected String key; - - public abstract T fromJson(); - - public abstract void toJson(T value); - - public Entry(T defaultValue) { - this.defaultValue = defaultValue; - } - - protected void setWriter(Consumer writer) { - this.writer = writer; - } - - protected void setReader(Supplier reader) { - this.reader = reader; - } - - protected boolean setLocation(JsonObject location, String key) { - this.location = location; - this.key = key; - if (!location.has(key)) { - this.toJson(defaultValue); - return true; - } - return false; - } - - protected boolean hasLocation() { - return this.location != null && this.key != null; - } - - public T getValue() { - return this.reader.get(); - } - - public void setValue(T value) { - this.writer.accept(value); - } - - public T getDefault() { - return this.defaultValue; - } - - public void setDefault() { - this.setValue(defaultValue); - } - - protected boolean hasDefaultInName() { - return true; - } - } -} diff --git a/src/main/java/org/betterx/bclib/config/ConfigKey.java b/src/main/java/org/betterx/bclib/config/ConfigKey.java deleted file mode 100644 index 53c16304..00000000 --- a/src/main/java/org/betterx/bclib/config/ConfigKey.java +++ /dev/null @@ -1,97 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.util.Pair; - -import net.minecraft.resources.ResourceLocation; - -import java.util.Arrays; -import org.jetbrains.annotations.NotNull; - -public class ConfigKey { - private final String[] path; - private final String entry; - private final boolean root; - - public ConfigKey(String entry, String... path) { - this.validate(entry); - this.path = path; - this.entry = entry; - this.root = path.length == 0 || (path.length == 1 && path[0].isEmpty()); - } - - public ConfigKey(String entry, ResourceLocation path) { - this(entry, path.getNamespace(), path.getPath()); - } - - public String[] getPath() { - return path; - } - - public String getEntry() { - return entry; - } - - public boolean isRoot() { - return root; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + Arrays.hashCode(path); - result = prime * result + entry.hashCode(); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof ConfigKey)) { - return false; - } - ConfigKey other = (ConfigKey) obj; - if (other.path.length != path.length) { - return false; - } - for (int i = 0; i < path.length; i++) { - if (!path[i].equals(other.path[i])) { - return false; - } - } - return entry.equals(other.entry); - } - - @Override - public String toString() { - if (root) { - return String.format("[root]:%s", entry); - } - String p = path[0]; - for (int i = 1; i < path.length; i++) { - p += "." + path[i]; - } - return String.format("%s:%s", p, entry); - } - - private void validate(String entry) { - if (entry == null) { - throw new NullPointerException("Config key must be not null!"); - } - if (entry.isEmpty()) { - throw new IndexOutOfBoundsException("Config key must be not empty!"); - } - } - - public static Pair realKey(@NotNull String key) { - String[] parts = key.split("\\[default:", 2); - if (parts.length == 1) { - return new Pair(parts[0].trim(), ""); - } else if (parts.length == 2) { - return new Pair(parts[0].trim(), " " + ("[default:" + parts[1]).trim()); - } - return new Pair(key, ""); - } -} diff --git a/src/main/java/org/betterx/bclib/config/ConfigUI.java b/src/main/java/org/betterx/bclib/config/ConfigUI.java deleted file mode 100644 index d2fc94ff..00000000 --- a/src/main/java/org/betterx/bclib/config/ConfigUI.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.config; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.FIELD}) -public @interface ConfigUI { - /** - * When {@code true}, this option will not generate UI-Elements. - */ - boolean hide() default false; - - /** - * When a Widget is generated for this option, it will be indented by this Value - */ - int leftPadding() default 0; - - /** - * When a Widget is generated for this option, it will be indented by this Value - */ - int topPadding() default 0; - - /** - * When a Slider is generated, this will be the minimum Value - */ - int minValue() default 0; - - /** - * When a Slider is generated, this will be the maximu Value - */ - int maxValue() default 0; -} diff --git a/src/main/java/org/betterx/bclib/config/ConfigWriter.java b/src/main/java/org/betterx/bclib/config/ConfigWriter.java deleted file mode 100644 index 951f0d3c..00000000 --- a/src/main/java/org/betterx/bclib/config/ConfigWriter.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.util.JsonFactory; - -import net.fabricmc.loader.api.FabricLoader; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.io.File; -import java.nio.file.Path; - -public class ConfigWriter { - private final static Path GAME_CONFIG_DIR = FabricLoader.getInstance().getConfigDir(); - - private final File configFile; - private JsonObject configObject; - - public ConfigWriter(String modID, String configFile) { - this.configFile = new File(GAME_CONFIG_DIR.resolve(modID).toFile(), configFile + ".json"); - File parent = this.configFile.getParentFile(); - if (!parent.exists()) { - parent.mkdirs(); - } - this.load(); - } - - File getConfigFile() { - return this.configFile; - } - - public JsonObject getConfig() { - return configObject; - } - - public void save() { - if (configObject == null) { - return; - } - save(configFile, configObject); - } - - JsonObject reload() { - configObject = load(configFile); - return configObject; - } - - public JsonObject load() { - if (configObject == null) { - configObject = load(configFile); - } - return configObject; - } - - public void save(JsonElement config) { - this.configObject = config.getAsJsonObject(); - save(configFile, config); - } - - public static JsonObject load(File configFile) { - return JsonFactory.getJsonObject(configFile); - } - - public static void save(File configFile, JsonElement config) { - JsonFactory.storeJson(configFile, config); - } - - public static String scrubFileName(String input) { - input = input.replaceAll("[/\\ ]+", "_"); - input = input.replaceAll("[,:&\"\\|\\<\\>\\?\\*]", "_"); - return input; - } -} diff --git a/src/main/java/org/betterx/bclib/config/Configs.java b/src/main/java/org/betterx/bclib/config/Configs.java deleted file mode 100644 index b83926b6..00000000 --- a/src/main/java/org/betterx/bclib/config/Configs.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public class Configs { - // Client and Server-Config must be the first entries. They are not part of the Auto-Sync process - // But will be needed by other Auto-Sync Config-Files - @Environment(EnvType.CLIENT) - public static final ClientConfig CLIENT_CONFIG = new ClientConfig(); - public static final ServerConfig SERVER_CONFIG = new ServerConfig(); - - public static final GeneratorConfig GENERATOR_CONFIG = new GeneratorConfig(); - public static final MainConfig MAIN_CONFIG = new MainConfig(); - public static final CachedConfig CACHED_CONFIG = new CachedConfig(); - - public static final PathConfig RECIPE_CONFIG = new PathConfig(BCLib.MOD_ID, "recipes"); - public static final BiomesConfig BIOMES_CONFIG = new BiomesConfig(); - - public static final String MAIN_PATCH_CATEGORY = "patches"; - - public static void save() { - MAIN_CONFIG.saveChanges(); - RECIPE_CONFIG.saveChanges(); - GENERATOR_CONFIG.saveChanges(); - BIOMES_CONFIG.saveChanges(); - } -} diff --git a/src/main/java/org/betterx/bclib/config/EntryConfig.java b/src/main/java/org/betterx/bclib/config/EntryConfig.java deleted file mode 100644 index 44276cfc..00000000 --- a/src/main/java/org/betterx/bclib/config/EntryConfig.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.config; - -public class EntryConfig extends IdConfig { - public EntryConfig(String modID, String group) { - super(modID, group, (id, entry) -> { - return new ConfigKey(entry, id); - }); - } -} diff --git a/src/main/java/org/betterx/bclib/config/GeneratorConfig.java b/src/main/java/org/betterx/bclib/config/GeneratorConfig.java deleted file mode 100644 index 250542b9..00000000 --- a/src/main/java/org/betterx/bclib/config/GeneratorConfig.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; - -public class GeneratorConfig extends NamedPathConfig { - public GeneratorConfig() { - super(BCLib.MOD_ID, "generator", true); - } - -} diff --git a/src/main/java/org/betterx/bclib/config/IdConfig.java b/src/main/java/org/betterx/bclib/config/IdConfig.java deleted file mode 100644 index c51afd5a..00000000 --- a/src/main/java/org/betterx/bclib/config/IdConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -package org.betterx.bclib.config; - -import net.minecraft.resources.ResourceLocation; - -import java.util.function.BiFunction; -import org.jetbrains.annotations.Nullable; - -public class IdConfig extends Config { - protected final BiFunction keyFactory; - - public IdConfig(String modID, String group, BiFunction keyFactory) { - super(modID, group); - this.keyFactory = keyFactory; - } - - @Override - protected void registerEntries() { - } - - protected ConfigKey createKey(ResourceLocation id, String key) { - return this.keyFactory.apply(id, key); - } - - @Nullable - public > E getEntry(ResourceLocation id, String key, Class type) { - return this.getEntry(createKey(id, key), type); - } - - @Nullable - public > T getDefault(ResourceLocation id, String key, Class type) { - return this.getDefault(createKey(id, key), type); - } - - public String getString(ResourceLocation id, String key, String defaultValue) { - return this.getString(createKey(id, key), defaultValue); - } - - public String getString(ResourceLocation id, String key) { - return this.getString(createKey(id, key)); - } - - public boolean setString(ResourceLocation id, String key, String value) { - return this.setString(createKey(id, key), value); - } - - public int getInt(ResourceLocation id, String key, int defaultValue) { - return this.getInt(createKey(id, key), defaultValue); - } - - public int getInt(ResourceLocation id, String key) { - return this.getInt(createKey(id, key)); - } - - public boolean setInt(ResourceLocation id, String key, int value) { - return this.setInt(createKey(id, key), value); - } - - public boolean setRangedInt(ResourceLocation id, String key, int value) { - return this.setRanged(createKey(id, key), value, ConfigKeeper.IntegerRange.class); - } - - public boolean setRangedFloat(ResourceLocation id, String key, float value) { - return this.setRanged(createKey(id, key), value, ConfigKeeper.FloatRange.class); - } - - public float getFloat(ResourceLocation id, String key, float defaultValue) { - return this.getFloat(createKey(id, key), defaultValue); - } - - public float getFloat(ResourceLocation id, String key) { - return this.getFloat(createKey(id, key)); - } - - public boolean setFloat(ResourceLocation id, String key, float value) { - return this.setFloat(createKey(id, key), value); - } - - public boolean getBoolean(ResourceLocation id, String key, boolean defaultValue) { - return this.getBoolean(createKey(id, key), defaultValue); - } - - public boolean getBoolean(ResourceLocation id, String key) { - return this.getBoolean(createKey(id, key)); - } - - public boolean setBoolean(ResourceLocation id, String key, boolean value) { - return this.setBoolean(createKey(id, key), value); - } -} diff --git a/src/main/java/org/betterx/bclib/config/MainConfig.java b/src/main/java/org/betterx/bclib/config/MainConfig.java deleted file mode 100644 index 3bb49fd5..00000000 --- a/src/main/java/org/betterx/bclib/config/MainConfig.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; - -public class MainConfig extends NamedPathConfig { - public static final ConfigToken APPLY_PATCHES = ConfigToken.Boolean( - true, - "applyPatches", - Configs.MAIN_PATCH_CATEGORY - ); - - @ConfigUI(leftPadding = 8) - public static final ConfigToken REPAIR_BIOMES = DependendConfigToken.Boolean( - false, - "repairBiomesOnLoad", - Configs.MAIN_PATCH_CATEGORY, - (config) -> config.get( - APPLY_PATCHES) - ); - - - public MainConfig() { - super(BCLib.MOD_ID, "main", true, true); - } - - public boolean applyPatches() { - return get(APPLY_PATCHES); - } - - public boolean repairBiomes() { - return get(REPAIR_BIOMES); - } -} diff --git a/src/main/java/org/betterx/bclib/config/NamedPathConfig.java b/src/main/java/org/betterx/bclib/config/NamedPathConfig.java deleted file mode 100644 index d90859fa..00000000 --- a/src/main/java/org/betterx/bclib/config/NamedPathConfig.java +++ /dev/null @@ -1,301 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; - -import net.minecraft.resources.ResourceLocation; - -import java.lang.reflect.Field; -import java.lang.reflect.Modifier; -import java.util.LinkedList; -import java.util.List; -import java.util.function.Predicate; - -public class NamedPathConfig extends PathConfig { - public static class ConfigTokenDescription { - public final ConfigToken token; - public final String internalName; - public final Boolean hidden; - public final int leftPadding; - public final int topPadding; - public final int minRange; - public final int maxRange; - - @SuppressWarnings("unchecked") - ConfigTokenDescription(Field fl) throws IllegalAccessException { - token = (ConfigToken) fl.get(null); - internalName = fl.getName(); - - ConfigUI ui = fl.getAnnotation(ConfigUI.class); - if (ui != null) { - this.hidden = ui.hide(); - leftPadding = ui.leftPadding(); - topPadding = ui.topPadding(); - minRange = ui.minValue(); - maxRange = ui.maxValue(); - } else { - this.hidden = false; - this.leftPadding = 0; - topPadding = 0; - minRange = 0; - maxRange = 0; - } - - } - - public String getPath() { - StringBuilder path = new StringBuilder(); - for (String p : token.getPath()) { - path.append(".") - .append(p); - - } - path.append(".").append(token.getEntry()); - return path.toString(); - } - } - - public static class DependendConfigToken extends ConfigToken { - protected final Predicate dependenciesTrue; - - protected DependendConfigToken( - Class type, - T defaultValue, - String entry, - ResourceLocation path, - Predicate dependenciesTrue - ) { - this(type, defaultValue, entry, new String[]{path.getNamespace(), path.getPath()}, dependenciesTrue); - } - - protected DependendConfigToken( - Class type, - T defaultValue, - String entry, - String path, - Predicate dependenciesTrue - ) { - super(type, defaultValue, entry, path); - this.dependenciesTrue = dependenciesTrue; - } - - protected DependendConfigToken( - Class type, - T defaultValue, - String entry, - String[] path, - Predicate dependenciesTrue - ) { - super(type, defaultValue, entry, path); - this.dependenciesTrue = dependenciesTrue; - } - - public boolean dependenciesTrue(NamedPathConfig config) { - return dependenciesTrue.test(config); - } - - public static DependendConfigToken Boolean( - boolean defaultValue, - String entry, - String path, - Predicate dependenciesTrue - ) { - return new DependendConfigToken( - ConfigKeeper.BooleanEntry.class, - defaultValue, - entry, - path, - dependenciesTrue - ); - } - - public static DependendConfigToken Float( - float defaultValue, - String entry, - String path, - Predicate dependenciesTrue - ) { - return new DependendConfigToken( - ConfigKeeper.FloatEntry.class, - defaultValue, - entry, - path, - dependenciesTrue - ); - } - } - - public static class ConfigToken extends ConfigKey { - public final T defaultValue; - public final Class type; - - protected ConfigToken(Class type, T defaultValue, String entry, ResourceLocation path) { - this(type, defaultValue, entry, path.getNamespace(), path.getPath()); - } - - @SuppressWarnings("unchecked") - protected ConfigToken(Class type, T defaultValue, String entry, String... path) { - super(entry, path); - this.defaultValue = defaultValue; - - this.type = type; - } - - public boolean dependenciesTrue(NamedPathConfig config) { - return true; - } - - public static ConfigToken Boolean(boolean defaultValue, String entry, String path) { - return new ConfigToken(ConfigKeeper.BooleanEntry.class, defaultValue, entry, path); - } - - public static ConfigToken Int(int defaultValue, String entry, String path) { - return new ConfigToken(ConfigKeeper.IntegerEntry.class, defaultValue, entry, path); - } - - public static ConfigToken Float(float defaultValue, String entry, String path) { - return new ConfigToken(ConfigKeeper.FloatEntry.class, defaultValue, entry, path); - } - - public static ConfigToken String(String defaultValue, String entry, String path) { - return new ConfigToken(ConfigKeeper.StringEntry.class, defaultValue, entry, path); - } - - public static ConfigToken> StringArray(List defaultValue, String entry, String path) { - return new ConfigToken>(ConfigKeeper.StringArrayEntry.class, defaultValue, entry, path); - } - } - - public NamedPathConfig(String modID, String group, boolean autoSync, boolean diffContent) { - super(modID, group, autoSync, diffContent); - onInit(); - } - - public NamedPathConfig(String modID, String group, boolean autoSync) { - super(modID, group, autoSync); - onInit(); - } - - public NamedPathConfig(String modID, String group) { - super(modID, group); - onInit(); - } - - public List> getAllOptions() { - List> res = new LinkedList<>(); - for (Field fl : this.getClass().getDeclaredFields()) { - int modifiers = fl.getModifiers(); - if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && ConfigToken.class.isAssignableFrom(fl.getType())) { - try { - res.add(new ConfigTokenDescription<>(fl)); - } catch (IllegalAccessException e) { - BCLib.LOGGER.error("Could not access " + fl); - } - } - } - return res; - } - - protected void onInit() { - getAllOptions().forEach(e -> get(e.token)); - this.saveChanges(); - } - - /** - * The value without any check of {@link DependendConfigToken} - *

- * In most cases you probably want to use {@link #get(ConfigToken)}, we use this Method if we - * present the actual value of the Settings from the Config File without any additional processing. - * - * @param what The Option you want to get - * @param The Type of the Option - * @return The Value of the Option (without checking the {@link DependendConfigToken}): - */ - public T getRaw(ConfigToken what) { - return _get(what, true); - } - - /** - * The value of an Option - * - * @param what he Option you want to get - * @param The Type of the Option - * @return The Value of the Option. If this option is a {@link DependendConfigToken}, the returned value - * may not be the value from the config File. For Example, on a {@link Boolean}-Type the result is always false - * if {@link DependendConfigToken#dependenciesTrue} returns {@code false}. - */ - public T get(ConfigToken what) { - return _get(what, false); - } - - @SuppressWarnings("unchecked") - private T _get(ConfigToken what, boolean raw) { - //TODO: Check if we can make config fully Generic to avoid runtime type checks... - if (ConfigKeeper.BooleanEntry.class.isAssignableFrom(what.type)) { - return (T) _getBoolean((ConfigToken) what, raw); - } - if (ConfigKeeper.IntegerEntry.class.isAssignableFrom(what.type)) { - return (T) _getInt((ConfigToken) what); - } - if (ConfigKeeper.FloatEntry.class.isAssignableFrom(what.type)) { - return (T) _getFloat((ConfigToken) what); - } - if (ConfigKeeper.StringEntry.class.isAssignableFrom(what.type)) { - return (T) _getString((ConfigToken) what); - } - if (ConfigKeeper.StringArrayEntry.class.isAssignableFrom(what.type)) { - return (T) _getStringArray((ConfigToken>) what); - } - return this._get(what); - } - - private T _get(ConfigToken what) { - BCLib.LOGGER.error(what + " has unsupported Type."); - return what.defaultValue; - } - - public void set(ConfigToken what, boolean value) { - this.setBoolean(what, value); - } - - private Boolean _getBoolean(ConfigToken what, boolean raw) { - if (!raw && !what.dependenciesTrue(this)) { - return false; - } - - return this.getBoolean(what, what.defaultValue); - } - - public void set(ConfigToken what, int value) { - this.setInt(what, value); - } - - private Integer _getInt(ConfigToken what) { - return this.getInt(what, what.defaultValue); - } - - public void set(ConfigToken what, float value) { - this.setFloat(what, value); - } - - private Float _getFloat(ConfigToken what) { - return this.getFloat(what, what.defaultValue); - } - - public void set(ConfigToken what, String value) { - this.setString(what, value); - } - - private String _getString(ConfigToken what) { - return this.getString(what, what.defaultValue); - } - - public void set(ConfigToken> what, List value) { - this.setStringArray(what, value); - } - - private List _getStringArray(ConfigToken> what) { - return this.getStringArray(what, what.defaultValue); - } - - -} diff --git a/src/main/java/org/betterx/bclib/config/PathConfig.java b/src/main/java/org/betterx/bclib/config/PathConfig.java deleted file mode 100644 index 2d1240f8..00000000 --- a/src/main/java/org/betterx/bclib/config/PathConfig.java +++ /dev/null @@ -1,166 +0,0 @@ -package org.betterx.bclib.config; - -import java.util.List; -import org.jetbrains.annotations.Nullable; - -public class PathConfig extends Config { - public PathConfig(String modID, String group, boolean autoSync, boolean diffContent) { - super(modID, group, autoSync, diffContent); - } - - public PathConfig(String modID, String group, boolean autoSync) { - super(modID, group, autoSync); - } - - public PathConfig(String modID, String group) { - super(modID, group); - } - - @Override - protected void registerEntries() { - } - - protected static ConfigKey createKey(String category, String key) { - return new ConfigKey(key, category.split("\\.")); - } - - protected static ConfigKey createKey(String key) { - return createKey("", key); - } - - @Nullable - public > E getEntry(String category, String key, Class type) { - return this.getEntry(createKey(category, key), type); - } - - @Nullable - public > T getDefault(String category, String key, Class type) { - return this.getDefault(createKey(category, key), type); - } - - public String getString(String category, String key, String defaultValue) { - return this.getString(createKey(category, key), defaultValue); - } - - public String getString(String category, String key) { - return this.getString(createKey(category, key)); - } - - public boolean setString(String category, String key, String value) { - return this.setString(createKey(category, key), value); - } - - public int getInt(String category, String key, int defaultValue) { - return this.getInt(createKey(category, key), defaultValue); - } - - public int getInt(String category, String key) { - return this.getInt(createKey(category, key)); - } - - public boolean setInt(String category, String key, int value) { - return this.setInt(createKey(category, key), value); - } - - public boolean setRangedInt(String category, String key, int value) { - return this.setRanged(createKey(category, key), value, ConfigKeeper.IntegerRange.class); - } - - public boolean setRangedFloat(String category, String key, float value) { - return this.setRanged(createKey(category, key), value, ConfigKeeper.FloatRange.class); - } - - public float getFloat(String category, String key, float defaultValue) { - return this.getFloat(createKey(category, key), defaultValue); - } - - public float getFloat(String category, String key) { - return this.getFloat(createKey(category, key)); - } - - public boolean setFloat(String category, String key, float value) { - return this.setFloat(createKey(category, key), value); - } - - public boolean getBoolean(String category, String key, boolean defaultValue) { - return this.getBoolean(createKey(category, key), defaultValue); - } - - public boolean getBoolean(String category, String key) { - return this.getBoolean(createKey(category, key)); - } - - public boolean setBoolean(String category, String key, boolean value) { - return this.setBoolean(createKey(category, key), value); - } - - public List getStringArray(String category, String key, List defaultValue) { - return this.getStringArray(createKey(category, key), defaultValue); - } - - public List getStringArray(String category, String key) { - return this.getStringArray(createKey(category, key)); - } - - public boolean setStringArray(String category, String key, List value) { - return this.setStringArray(createKey(category, key), value); - } - - // From Root - - public String getStringRoot(String key, String defaultValue) { - return this.getString(createKey(key), defaultValue); - } - - public String getStringRoot(String key) { - return this.getString(createKey(key)); - } - - public boolean setStringRoot(String key, String value) { - return this.setString(createKey(key), value); - } - - public int getIntRoot(String key, int defaultValue) { - return this.getInt(createKey(key), defaultValue); - } - - public int getIntRoot(String key) { - return this.getInt(createKey(key)); - } - - public boolean setIntRoot(String key, int value) { - return this.setInt(createKey(key), value); - } - - public boolean setRangedIntRoot(String key, int value) { - return this.setRanged(createKey(key), value, ConfigKeeper.IntegerRange.class); - } - - public boolean setRangedFloatRoot(String key, float value) { - return this.setRanged(createKey(key), value, ConfigKeeper.FloatRange.class); - } - - public float getFloatRoot(String key, float defaultValue) { - return this.getFloat(createKey(key), defaultValue); - } - - public float getFloatRoot(String key) { - return this.getFloat(createKey(key)); - } - - public boolean setFloatRoot(String key, float value) { - return this.setFloat(createKey(key), value); - } - - public boolean getBooleanRoot(String key, boolean defaultValue) { - return this.getBoolean(createKey(key), defaultValue); - } - - public boolean getBooleanRoot(String key) { - return this.getBoolean(createKey(key)); - } - - public boolean setBooleanRoot(String key, boolean value) { - return this.setBoolean(createKey(key), value); - } -} diff --git a/src/main/java/org/betterx/bclib/config/ServerConfig.java b/src/main/java/org/betterx/bclib/config/ServerConfig.java deleted file mode 100644 index 86ebdae8..00000000 --- a/src/main/java/org/betterx/bclib/config/ServerConfig.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.betterx.bclib.config; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.dataexchange.handler.autosync.AutoSync; - -import java.util.ArrayList; -import java.util.List; - -public class ServerConfig extends NamedPathConfig { - public static final ConfigToken ENABLED = ConfigToken.Boolean(true, "enabled", AutoSync.SYNC_CATEGORY); - public static final DependendConfigToken OFFER_CONFIGS = DependendConfigToken.Boolean( - true, - "offerConfigs", - AutoSync.SYNC_CATEGORY, - (config) -> config.get(ENABLED) - ); - public static final DependendConfigToken OFFER_FILES = DependendConfigToken.Boolean( - true, - "offerFiles", - AutoSync.SYNC_CATEGORY, - (config) -> config.get( - ENABLED) - ); - public static final DependendConfigToken OFFER_MODS = DependendConfigToken.Boolean( - true, - "offerMods", - AutoSync.SYNC_CATEGORY, - (config) -> config.get( - ENABLED) - ); - public static final DependendConfigToken OFFER_ALL_MODS = DependendConfigToken.Boolean( - false, - "offerAllMods", - AutoSync.SYNC_CATEGORY, - (config) -> config.get( - OFFER_MODS) - ); - public static final DependendConfigToken SEND_ALL_MOD_INFO = DependendConfigToken.Boolean( - false, - "sendAllModInfo", - AutoSync.SYNC_CATEGORY, - (config) -> config.get( - ENABLED) - ); - - - public static final ConfigToken> ADDITIONAL_MODS = ConfigToken.StringArray( - new ArrayList<>(0), - "additionalMods", - AutoSync.SYNC_CATEGORY - ); - public static final ConfigToken> EXCLUDED_MODS = ConfigToken.StringArray( - new ArrayList<>(0), - "excludeMods", - AutoSync.SYNC_CATEGORY - ); - public static final ConfigToken FORCE_BETTERX_PRESET = ConfigToken.Boolean( - true, - "forceBetterXPreset", - AutoSync.SYNC_CATEGORY - ); - - - public ServerConfig() { - super(BCLib.MOD_ID, "server", false); - } - - public boolean isAllowingAutoSync() { - return get(ENABLED); - } - - public boolean isOfferingConfigs() { - return get(OFFER_CONFIGS) /*&& isAllowingAutoSync()*/; - } - - public boolean isOfferingFiles() { - return get(OFFER_FILES) /*&& isAllowingAutoSync()*/; - } - - public boolean isOfferingMods() { - return get(OFFER_MODS) /*&& isAllowingAutoSync()*/; - } - - public boolean isOfferingAllMods() { - return get(OFFER_ALL_MODS) /*&& isAllowingAutoSync()*/; - } - - public boolean isOfferingInfosForMods() { - return get(SEND_ALL_MOD_INFO) /*&& isAllowingAutoSync()*/; - } - - public boolean forceBetterXPreset() { - return get(FORCE_BETTERX_PRESET); - } - -} diff --git a/src/main/java/org/betterx/bclib/entity/BCLEntityWrapper.java b/src/main/java/org/betterx/bclib/entity/BCLEntityWrapper.java deleted file mode 100644 index f8025dbb..00000000 --- a/src/main/java/org/betterx/bclib/entity/BCLEntityWrapper.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.betterx.bclib.entity; - -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; - -public record BCLEntityWrapper(EntityType type, boolean canSpawn) { -} diff --git a/src/main/java/org/betterx/bclib/entity/DespawnableAnimal.java b/src/main/java/org/betterx/bclib/entity/DespawnableAnimal.java deleted file mode 100644 index 4a39b451..00000000 --- a/src/main/java/org/betterx/bclib/entity/DespawnableAnimal.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.betterx.bclib.entity; - -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.animal.Animal; -import net.minecraft.world.level.Level; - -public abstract class DespawnableAnimal extends Animal { - protected DespawnableAnimal(EntityType entityType, Level level) { - super(entityType, level); - } - - @Override - public boolean removeWhenFarAway(double d) { - return !this.hasCustomName(); - } -} diff --git a/src/main/java/org/betterx/bclib/integration/ModIntegration.java b/src/main/java/org/betterx/bclib/integration/ModIntegration.java deleted file mode 100644 index 329f7dbb..00000000 --- a/src/main/java/org/betterx/bclib/integration/ModIntegration.java +++ /dev/null @@ -1,201 +0,0 @@ -package org.betterx.bclib.integration; - -import org.betterx.bclib.BCLib; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -import net.fabricmc.loader.api.FabricLoader; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public abstract class ModIntegration { - private final String modID; - - public void init() { - } - - public ModIntegration(String modID) { - this.modID = modID; - } - - public ResourceLocation getID(String name) { - return new ResourceLocation(modID, name); - } - - public ResourceKey getFeatureKey(String name) { - return ResourceKey.create(Registry.PLACED_FEATURE_REGISTRY, getID(name)); - } - - public Block getBlock(String name) { - return Registry.BLOCK.get(getID(name)); - } - - public Item getItem(String name) { - return Registry.ITEM.get(getID(name)); - } - - public BlockState getDefaultState(String name) { - return getBlock(name).defaultBlockState(); - } - - public ResourceKey getKey(String name) { - return ResourceKey.create(Registry.BIOME_REGISTRY, getID(name)); - } - - public boolean modIsInstalled() { - return FabricLoader.getInstance().isModLoaded(modID); - } - - - public ConfiguredFeature getConfiguredFeature(String name) { - return BuiltinRegistries.CONFIGURED_FEATURE.get(getID(name)); - } - - public Holder getBiome(String name) { - return BuiltinRegistries.BIOME.getHolder(getKey(name)).orElseThrow(); - } - - public Class getClass(String path) { - Class cl = null; - try { - cl = Class.forName(path); - } catch (ClassNotFoundException e) { - BCLib.LOGGER.error(e.getMessage()); - if (BCLib.isDevEnvironment()) { - e.printStackTrace(); - } - } - return cl; - } - - @SuppressWarnings("unchecked") - public T getStaticFieldValue(Class cl, String name) { - if (cl != null) { - try { - Field field = cl.getDeclaredField(name); - if (field != null) { - return (T) field.get(null); - } - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - } - } - return null; - } - - public Object getFieldValue(Class cl, String name, Object classInstance) { - if (cl != null) { - try { - Field field = cl.getDeclaredField(name); - if (field != null) { - return field.get(classInstance); - } - } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { - e.printStackTrace(); - } - } - return null; - } - - public Method getMethod(Class cl, String functionName, Class... args) { - if (cl != null) { - try { - return cl.getMethod(functionName, args); - } catch (NoSuchMethodException | SecurityException e) { - BCLib.LOGGER.error(e.getMessage()); - if (BCLib.isDevEnvironment()) { - e.printStackTrace(); - } - } - } - return null; - } - - public Object executeMethod(Object instance, Method method, Object... args) { - if (method != null) { - try { - return method.invoke(instance, args); - } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - BCLib.LOGGER.error(e.getMessage()); - if (BCLib.isDevEnvironment()) { - e.printStackTrace(); - } - } - } - return null; - } - - public Object getAndExecuteStatic(Class cl, String functionName, Object... args) { - if (cl != null) { - Class[] classes = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - classes[i] = args[i].getClass(); - } - Method method = getMethod(cl, functionName, classes); - return executeMethod(null, method, args); - } - return null; - } - - @SuppressWarnings("unchecked") - public T getAndExecuteRuntime( - Class cl, - Object instance, - String functionName, - Object... args - ) { - if (instance != null) { - Class[] classes = new Class[args.length]; - for (int i = 0; i < args.length; i++) { - classes[i] = args[i].getClass(); - } - Method method = getMethod(cl, functionName, classes); - return (T) executeMethod(instance, method, args); - } - return null; - } - - public Object newInstance(Class cl, Object... args) { - if (cl != null) { - for (Constructor constructor : cl.getConstructors()) { - if (constructor.getParameterCount() == args.length) { - try { - return constructor.newInstance(args); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | - InvocationTargetException e) { - BCLib.LOGGER.error(e.getMessage()); - if (BCLib.isDevEnvironment()) { - e.printStackTrace(); - } - } - } - } - } - return null; - } - - public TagKey getItemTag(String name) { - ResourceLocation id = getID(name); - return TagManager.ITEMS.makeTag(id); - } - - public TagKey getBlockTag(String name) { - ResourceLocation id = getID(name); - return TagManager.BLOCKS.makeTag(id); - } -} diff --git a/src/main/java/org/betterx/bclib/integration/emi/EMIAbstractAlloyingRecipe.java b/src/main/java/org/betterx/bclib/integration/emi/EMIAbstractAlloyingRecipe.java deleted file mode 100644 index 37cdb883..00000000 --- a/src/main/java/org/betterx/bclib/integration/emi/EMIAbstractAlloyingRecipe.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.betterx.bclib.integration.emi; - -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.Recipe; - -import dev.emi.emi.EmiPort; -import dev.emi.emi.api.recipe.EmiRecipe; -import dev.emi.emi.api.recipe.EmiRecipeCategory; -import dev.emi.emi.api.render.EmiTexture; -import dev.emi.emi.api.stack.EmiIngredient; -import dev.emi.emi.api.stack.EmiStack; -import dev.emi.emi.api.widget.WidgetHolder; - -import java.util.List; - -public abstract class EMIAbstractAlloyingRecipe> implements EmiRecipe { - private final ResourceLocation id; - private final List input; - private final List output; - protected final T recipe; - - private final int fuelMultiplier; - private final boolean infiniBurn; - - public EMIAbstractAlloyingRecipe(T recipe, ResourceLocation id, int fuelMultiplier, boolean infiniBurn) { - this.recipe = recipe; - this.id = id; - this.input = List.of( - EmiIngredient.of(recipe.getIngredients().get(0)), - recipe.getIngredients().size() > 1 - ? EmiIngredient.of(recipe.getIngredients().get(1)) - : EmiIngredient.of(Ingredient.EMPTY) - ); - - this.output = List.of(EmiStack.of(recipe.getResultItem())); - this.fuelMultiplier = fuelMultiplier; - this.infiniBurn = infiniBurn; - } - - protected abstract int getSmeltTime(); - protected abstract float getExperience(); - - - @Override - public EmiRecipeCategory getCategory() { - return EMIPlugin.END_ALLOYING_CATEGORY; - } - - @Override - public ResourceLocation getId() { - return id; - } - - @Override - public List getInputs() { - return input; - } - - @Override - public List getOutputs() { - return output; - } - - protected int getXOffset() { - return 22; - } - - @Override - public int getDisplayWidth() { - return 82 + getXOffset(); - } - - @Override - public int getDisplayHeight() { - return 38; - } - - @Override - public void addWidgets(WidgetHolder widgets) { - // Add an arrow texture to indicate processing - widgets.addFillingArrow(24 + getXOffset(), 5, 50 * getSmeltTime()).tooltip((mx, my) -> { - return List.of(ClientTooltipComponent.create(EmiPort.ordered(EmiPort.translatable( - "emi.cooking.time", - new Object[]{(float) getSmeltTime() / 20.0F} - )))); - }); - - if (this.infiniBurn) { - widgets.addTexture(EmiTexture.FULL_FLAME, 1, 24); - } else { - widgets.addTexture(EmiTexture.EMPTY_FLAME, 1, 24); - widgets.addAnimatedTexture(EmiTexture.FULL_FLAME, 1, 24, 4000 / this.fuelMultiplier, false, true, true); - } - - // Adds an input slot on the left - widgets.addSlot(input.get(0), 0, 4); - widgets.addSlot((input.size() > 1) ? input.get(1) : null, 20, 4); - widgets.addText( - EmiPort.ordered(EmiPort.translatable("emi.cooking.experience", getExperience())), - 24 + getXOffset(), 28, 0xFFFFFFFF, true - ); - - // Adds an output slot on the right - // Note that output slots need to call `recipeContext` to inform EMI about their recipe context - // This includes being able to resolve recipe trees, favorite stacks with recipe context, and more - widgets.addSlot(output.get(0), 56 + getXOffset(), 0).output(true).recipeContext(this); - } - - @Override - public boolean supportsRecipeTree() { - return true; - } -} - diff --git a/src/main/java/org/betterx/bclib/integration/emi/EMIAlloyingRecipe.java b/src/main/java/org/betterx/bclib/integration/emi/EMIAlloyingRecipe.java deleted file mode 100644 index 43a957e8..00000000 --- a/src/main/java/org/betterx/bclib/integration/emi/EMIAlloyingRecipe.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.betterx.bclib.integration.emi; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.recipes.AlloyingRecipe; - -import net.minecraft.world.Container; -import net.minecraft.world.item.crafting.RecipeManager; - -import dev.emi.emi.api.EmiRegistry; - -public class EMIAlloyingRecipe extends EMIAbstractAlloyingRecipe { - public EMIAlloyingRecipe(AlloyingRecipe recipe) { - super(recipe, recipe.getId(), 1, false); - } - - @Override - protected int getSmeltTime() { - return recipe.getSmeltTime(); - } - - @Override - protected float getExperience() { - return recipe.getExperience(); - } - - static void addAllRecipes(EmiRegistry emiRegistry, RecipeManager manager) { - EMIPlugin.addAllRecipes( - emiRegistry, manager, BCLib.LOGGER, - AlloyingRecipe.TYPE, EMIAlloyingRecipe::new - ); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/integration/emi/EMIAnvilRecipe.java b/src/main/java/org/betterx/bclib/integration/emi/EMIAnvilRecipe.java deleted file mode 100644 index c8ab419c..00000000 --- a/src/main/java/org/betterx/bclib/integration/emi/EMIAnvilRecipe.java +++ /dev/null @@ -1,110 +0,0 @@ -package org.betterx.bclib.integration.emi; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.recipes.AnvilRecipe; - -import net.minecraft.core.Holder; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeManager; - -import dev.emi.emi.api.EmiRegistry; -import dev.emi.emi.api.recipe.EmiRecipe; -import dev.emi.emi.api.recipe.EmiRecipeCategory; -import dev.emi.emi.api.render.EmiTexture; -import dev.emi.emi.api.stack.EmiIngredient; -import dev.emi.emi.api.stack.EmiStack; -import dev.emi.emi.api.widget.WidgetHolder; - -import java.util.List; -import java.util.stream.StreamSupport; -import org.jetbrains.annotations.Nullable; - -public class EMIAnvilRecipe implements EmiRecipe { - private final ResourceLocation id; - private final List input; - private final List output; - private final EmiRecipeCategory category; - - public EMIAnvilRecipe(AnvilRecipe recipe, Item hammer) { - this.id = new ResourceLocation( - "emi", - recipe.getId().getNamespace() + "/" + recipe.getId().getPath() + "/anvil/" + hammer.getDescriptionId() - ); - this.input = List.of( - EmiIngredient.of(recipe.getMainIngredient(), recipe.getInputCount()), - EmiIngredient.of(Ingredient.of(hammer)) - ); - this.output = List.of(EmiStack.of(recipe.getResultItem())); - this.category = EMIPlugin.getAnvilCategoryForLevel(recipe.getAnvilLevel()); - } - - static void addAllRecipes(EmiRegistry emiRegistry, RecipeManager manager) { - Iterable> hammers = AnvilRecipe.getAllHammers(); - EMIPlugin.addAllRecipes( - emiRegistry, manager, BCLib.LOGGER, - AnvilRecipe.TYPE, - recipe -> StreamSupport.stream(hammers.spliterator(), false) - .map(Holder::value) - .filter(recipe::canUse) - .toList(), - EMIAnvilRecipe::new - ); - } - - @Override - public EmiRecipeCategory getCategory() { - return category; - } - - @Override - public @Nullable ResourceLocation getId() { - return id; - } - - @Override - public List getInputs() { - return input; - } - - @Override - public List getOutputs() { - return output; - } - - @Override - public int getDisplayWidth() { - return 104; - } - - @Override - public int getDisplayHeight() { - return 26; - } - - @Override - public void addWidgets(WidgetHolder widgetHolder) { - // Add an arrow texture to indicate processing - widgetHolder.addTexture(EmiTexture.EMPTY_ARROW, 46, 5); - - // Adds an input slot on the left - widgetHolder.addSlot(input.get(0), 0, 4); - widgetHolder.addSlot(input.get(1), 20, 4).catalyst(true); - - // Adds an output slot on the right - // Note that output slots need to call `recipeContext` to inform EMI about their recipe context - // This includes being able to resolve recipe trees, favorite stacks with recipe context, and more - widgetHolder.addSlot(output.get(0), 78, 0).output(true).recipeContext(this); - } - - @Override - public List getCatalysts() { - return List.of(input.get(1)); - } - - @Override - public boolean supportsRecipeTree() { - return true; - } -} diff --git a/src/main/java/org/betterx/bclib/integration/emi/EMIAnvilRecipeCategory.java b/src/main/java/org/betterx/bclib/integration/emi/EMIAnvilRecipeCategory.java deleted file mode 100644 index baabdf08..00000000 --- a/src/main/java/org/betterx/bclib/integration/emi/EMIAnvilRecipeCategory.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.betterx.bclib.integration.emi; - -import org.betterx.bclib.blocks.LeveledAnvilBlock; -import org.betterx.bclib.util.RomanNumeral; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.Tesselator; -import com.mojang.math.Matrix4f; -import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.screens.inventory.tooltip.ClientTooltipComponent; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.FormattedCharSequence; - -import com.google.common.collect.Lists; -import dev.emi.emi.EmiPort; -import dev.emi.emi.EmiUtil; -import dev.emi.emi.api.recipe.EmiRecipe; -import dev.emi.emi.api.recipe.EmiRecipeCategory; -import dev.emi.emi.api.render.EmiRenderable; -import dev.emi.emi.api.render.EmiTexture; - -import java.util.Comparator; -import java.util.List; - -public class EMIAnvilRecipeCategory extends EmiRecipeCategory { - private final int anvilLevel; - private final List titleLines; - - - public EMIAnvilRecipeCategory(ResourceLocation id, EmiRenderable icon, int anvilLevel) { - super(id, icon); - this.anvilLevel = anvilLevel; - titleLines = LeveledAnvilBlock.getNamesForLevel(anvilLevel); - } - - public EMIAnvilRecipeCategory(ResourceLocation id, EmiRenderable icon, EmiRenderable simplified, int anvilLevel) { - super(id, icon, simplified); - this.anvilLevel = anvilLevel; - titleLines = LeveledAnvilBlock.getNamesForLevel(anvilLevel); - } - - public EMIAnvilRecipeCategory( - ResourceLocation id, - EmiRenderable icon, EmiTexture simplified, - Comparator sorter, - int anvilLevel - ) { - super(id, icon, simplified, sorter); - this.anvilLevel = anvilLevel; - titleLines = LeveledAnvilBlock.getNamesForLevel(anvilLevel); - - - } - - @Override - public void renderSimplified(PoseStack stack, int x, int y, float delta) { - super.renderSimplified(stack, x, y, delta); - final Font font = Minecraft.getInstance().font; - final String content = RomanNumeral.toRoman(anvilLevel); - - final MultiBufferSource.BufferSource bufferSource = MultiBufferSource - .immediate(Tesselator.getInstance().getBuilder()); - final int xx = x + 19 - 2 - font.width(content); - final int yy = y + 6 + 3; - final Matrix4f matrix = stack.last().pose(); - - font.drawInBatch(content, xx - 1, yy - 1, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - font.drawInBatch(content, xx, yy - 1, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - font.drawInBatch(content, xx + 1, yy - 1, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - font.drawInBatch(content, xx - 1, yy, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - font.drawInBatch(content, xx + 1, yy, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - font.drawInBatch(content, xx - 1, yy + 1, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - font.drawInBatch(content, xx + 1, yy + 1, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - font.drawInBatch(content, xx, yy + 1, 0xFF000000, false, matrix, bufferSource, false, 0, 0xF000F0); - - font.drawInBatch(content, xx, yy, 0xFFFFFFFF, true, matrix, bufferSource, false, 0, 0xF000F0); - bufferSource.endBatch(); - } - - public List getTooltip() { - List list = Lists.newArrayList(); - if (titleLines.isEmpty()) { - list.add(ClientTooltipComponent.create(EmiPort.ordered(EmiPort.translatable(EmiUtil.translateId( - "emi.category.", - this.getId() - ))))); - } else { - for (var line : titleLines) - list.add(ClientTooltipComponent.create(line)); - } - - - list.add(ClientTooltipComponent.create(EmiPort.ordered(EmiPort.literal( - EmiUtil.getModName(this.getId() - .getNamespace()), - new ChatFormatting[]{ChatFormatting.BLUE, ChatFormatting.ITALIC} - )))); - return list; - } -} diff --git a/src/main/java/org/betterx/bclib/integration/emi/EMIPlugin.java b/src/main/java/org/betterx/bclib/integration/emi/EMIPlugin.java deleted file mode 100644 index d276d5fe..00000000 --- a/src/main/java/org/betterx/bclib/integration/emi/EMIPlugin.java +++ /dev/null @@ -1,170 +0,0 @@ -package org.betterx.bclib.integration.emi; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.blocks.LeveledAnvilBlock; -import org.betterx.bclib.interfaces.AlloyingRecipeWorkstation; -import org.betterx.worlds.together.util.Logger; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.block.Blocks; - -import dev.emi.emi.api.EmiPlugin; -import dev.emi.emi.api.EmiRegistry; -import dev.emi.emi.api.recipe.EmiRecipe; -import dev.emi.emi.api.recipe.EmiRecipeCategory; -import dev.emi.emi.api.render.EmiTexture; -import dev.emi.emi.api.stack.EmiStack; - -import java.util.Comparator; -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Function; - -public class EMIPlugin implements EmiPlugin { - private static boolean didInit = false; - private static int maxAnvilLevel = 1; - public static final ResourceLocation BCL_SIMPLIFIED_SPRITES = BCLib.makeID( - "textures/gui/widgets.png" - ); - - public static EmiStack END_ALLOYING_WORKSTATION; - public static EmiRecipeCategory END_ALLOYING_CATEGORY; - - public static EmiRecipeCategory[] ANVIL_CATEGORIES; - public static EmiStack[] ANVIL_WORKSTATIONS; - - public static EmiTexture getSprite(int u, int v) { - return new EmiTexture(BCL_SIMPLIFIED_SPRITES, u, v, 16, 16, 16, 16, 32, 32); - } - - public void lazyInit() { - if (!didInit) { - didInit = true; - lazyInitAlloyingCategory(); - lazyInitAnvilCategories(); - } - } - - private void lazyInitAlloyingCategory() { - var workstations = AlloyingRecipeWorkstation.getWorkstationIcon(); - if (!workstations.is(Blocks.BARRIER.asItem())) { - END_ALLOYING_WORKSTATION = EmiStack.of(workstations); - - END_ALLOYING_CATEGORY = new EmiRecipeCategory( - BCLib.makeID("alloying"), - END_ALLOYING_WORKSTATION, - getSprite(16, 0) - ); - } - } - - - private void lazyInitAnvilCategories() { - if (ANVIL_CATEGORIES == null) { - maxAnvilLevel = Math.max(1, LeveledAnvilBlock - .getAnvils() - .stream() - .map(LeveledAnvilBlock::getAnvilCraftingLevel) - .reduce(0, Math::max) - ); - - ANVIL_CATEGORIES = new EmiRecipeCategory[maxAnvilLevel + 1]; - ANVIL_WORKSTATIONS = new EmiStack[maxAnvilLevel + 1]; - - for (int anvilLevel = 0; anvilLevel <= maxAnvilLevel; anvilLevel++) { - int finalAnvilLevel = anvilLevel; - ANVIL_WORKSTATIONS[anvilLevel] = EmiStack.of(LeveledAnvilBlock - .getAnvils() - .stream() - .filter(b -> LeveledAnvilBlock.canHandle(b, finalAnvilLevel)) - .sorted(Comparator.comparingInt(LeveledAnvilBlock::getAnvilCraftingLevel)) - .findFirst().orElse(Blocks.BARRIER) - ); - ANVIL_CATEGORIES[anvilLevel] = new EMIAnvilRecipeCategory( - BCLib.makeID("anvil_" + anvilLevel), - ANVIL_WORKSTATIONS[anvilLevel], - getSprite(0, 0), - anvilLevel - ); - - if (anvilLevel > 0 && ANVIL_WORKSTATIONS[anvilLevel].isEqual(ANVIL_WORKSTATIONS[anvilLevel - 1])) { - ANVIL_WORKSTATIONS[anvilLevel - 1] = ANVIL_WORKSTATIONS[anvilLevel]; - ANVIL_CATEGORIES[anvilLevel - 1] = ANVIL_CATEGORIES[anvilLevel]; - } - } - } - } - - - @Override - public void register(EmiRegistry emiRegistry) { - lazyInit(); - final RecipeManager manager = emiRegistry.getRecipeManager(); - - if (END_ALLOYING_CATEGORY != null && END_ALLOYING_WORKSTATION != null) { - emiRegistry.addCategory(END_ALLOYING_CATEGORY); - emiRegistry.addWorkstation(END_ALLOYING_CATEGORY, END_ALLOYING_WORKSTATION); - - EMIAlloyingRecipe.addAllRecipes(emiRegistry, manager); - } - - if (ANVIL_CATEGORIES != null && ANVIL_WORKSTATIONS != null && ANVIL_CATEGORIES.length > 0) { - for (int i = 0; i <= maxAnvilLevel; i++) { - emiRegistry.addCategory(ANVIL_CATEGORIES[i]); - emiRegistry.addWorkstation(ANVIL_CATEGORIES[i], ANVIL_WORKSTATIONS[i]); - } - EMIAnvilRecipe.addAllRecipes(emiRegistry, manager); - } - } - - public static , E extends EmiRecipe> void addAllRecipes( - EmiRegistry emiRegistry, - RecipeManager manager, - Logger logger, - RecipeType recipeType, - Function createRecipe - ) { - addAllRecipes( - emiRegistry, - manager, - logger, - recipeType, - (_ignored) -> null, - (recipe, _ignored) -> createRecipe.apply(recipe) - ); - } - - public static , E extends EmiRecipe, V> void addAllRecipes( - EmiRegistry emiRegistry, - RecipeManager manager, - Logger logger, - RecipeType recipeType, - Function> variantSupplier, - BiFunction createRecipe - ) { - for (T recipe : manager.getAllRecipesFor(recipeType)) { - List variants = variantSupplier.apply(recipe); - if (variants == null) { - emiRegistry.addRecipe(createRecipe.apply(recipe, null)); - } else { - for (V variantData : variants) { - try { - emiRegistry.addRecipe(createRecipe.apply(recipe, variantData)); - } catch (Exception e) { - logger.error("Exception when parsing vanilla recipe " + recipe.getId(), e); - } - } - } - } - } - - - static EmiRecipeCategory getAnvilCategoryForLevel(int anvilLevel) { - anvilLevel = Math.max(0, Math.min(ANVIL_CATEGORIES.length - 1, anvilLevel)); - return ANVIL_CATEGORIES[anvilLevel]; - } -} diff --git a/src/main/java/org/betterx/bclib/integration/modmenu/ModMenu.java b/src/main/java/org/betterx/bclib/integration/modmenu/ModMenu.java deleted file mode 100644 index 414862ad..00000000 --- a/src/main/java/org/betterx/bclib/integration/modmenu/ModMenu.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.betterx.bclib.integration.modmenu; - -import net.minecraft.client.gui.screens.Screen; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - -/** - * Integration, to provide a custom Screen for ModMenu. - *

- * This integration allows you to use ModMenu without adding a dependency to your project. If the - * Mod is installed on the Client. - *

- * You can add a screen for your mod by calling {@link #addModMenuScreen(String, Function)} - */ -public class ModMenu { - static final Map> screen = new HashMap<>(); - - /** - * registers a ModMenu entrypoint for another Mod. For Example {@code addModMenuScreen("myMod", (parent)->new Screen(parent));} - * - * @param modID The ID of your Mod - * @param scr a function that takes a parent {@link Screen} and provides the main Screen you want - * to show with ModMenu for your Mod. - */ - public static void addModMenuScreen(String modID, Function scr) { - screen.put(modID, scr); - } -} diff --git a/src/main/java/org/betterx/bclib/integration/modmenu/ModMenuEntryPoint.java b/src/main/java/org/betterx/bclib/integration/modmenu/ModMenuEntryPoint.java deleted file mode 100644 index 9ea1f0e3..00000000 --- a/src/main/java/org/betterx/bclib/integration/modmenu/ModMenuEntryPoint.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.betterx.bclib.integration.modmenu; - -import org.betterx.bclib.client.gui.modmenu.MainScreen; - -import com.terraformersmc.modmenu.api.ConfigScreenFactory; -import com.terraformersmc.modmenu.api.ModMenuApi; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Function; - - -/** - * Internal class to hook into ModMenu, you should not need to use this class. If you want to register a - * ModMenu Screen for a Mod using BCLib, use {@link ModMenu#addModMenuScreen(String, Function)} - */ -public class ModMenuEntryPoint implements ModMenuApi { - @Override - public Map> getProvidedConfigScreenFactories() { - Map> copy = new HashMap<>(); - for (var entry : ModMenu.screen.entrySet()) { - copy.put(entry.getKey(), (parent) -> entry.getValue().apply(parent)); - } - return copy; - } - - @Override - public ConfigScreenFactory getModConfigScreenFactory() { - //return (parent) -> new TestScreen(parent, Component.literal("Hello Test")); - return (parent) -> new MainScreen(parent); - } - - -} diff --git a/src/main/java/org/betterx/bclib/integration/modmenu/ModMenuIntegration.java b/src/main/java/org/betterx/bclib/integration/modmenu/ModMenuIntegration.java deleted file mode 100644 index 4687d418..00000000 --- a/src/main/java/org/betterx/bclib/integration/modmenu/ModMenuIntegration.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.betterx.bclib.integration.modmenu; - -import org.betterx.bclib.integration.modmenu.ModMenuIntegration.ModMenuScreenFactory; - -import net.minecraft.client.gui.screens.Screen; - -import com.google.common.collect.ImmutableMap; -import com.terraformersmc.modmenu.api.ConfigScreenFactory; -import com.terraformersmc.modmenu.api.ModMenuApi; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Map; - -@Deprecated -class ModMenuScreenFactoryImpl { - record ScreenFactoryInvocationHandler(ModMenuScreenFactory act) implements InvocationHandler { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return switch (method.getName()) { - case "toString" -> ""; - case "equals" -> false; - case "hashCode" -> 0; - default -> act.create((Screen) args[0]); - }; - } - } - - public static ModMenuScreenFactory create(ModMenuScreenFactory act) { - Class iConfigScreenFactory = null; - try { - iConfigScreenFactory = Class.forName("com.terraformersmc.modmenu.api.ConfigScreenFactory"); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - - Object o = Proxy.newProxyInstance( - ModMenuIntegration.class.getClassLoader(), - new Class[]{iConfigScreenFactory, ModMenuScreenFactory.class}, - new ScreenFactoryInvocationHandler(act) - ); - - return (ModMenuScreenFactory) o; - } -} - -@Deprecated -/** - * Integration, to provide a custom Screen for ModMenu. - *

- * This integration allows you to use ModMenu without adding a dependency to your project. If the - * Mod is installed on the Client, and the correct ModMenu-EntryPoint is registered in your fabric.mod.json - * the screen will show up. - *

- * You only need to subclass this class, and initialize a static Field of Type {@link ModMenuApi} using - * the {@link #createEntrypoint(ModMenuIntegration)}-Method. - *

- * Example: - *

{@code public class ModMenu extends ModMenuIntegration {
- *	 public static final ModMenuApiMarker entrypointObject = createEntrypoint(new EntryPoint());
- *
- * 		public EntryPoint() {
- * 			super(GridScreen::new);
- *      }
- * }}
- * You'd also need to add the ModMenu-Entrypoint to your fabric.mod.json: - *
"entrypoints": {
- * 		...
- *	 "modmenu": [ "your.mod.ModMenu::entrypointObject" ]
- * }
- */ -public abstract class ModMenuIntegration { - /** - * Creates a new EntryPoint Object that is accepted by ModMenu - * - * @param target The delegate Object that will receive calls from ModMenu - * @return A Proxy that conforms to the ModMenu spec - */ - public static ModMenuApi createEntrypoint(ModMenuIntegration target) { - Class iModMenuAPI; - //Class iModMenuAPIMarker = null; - try { - iModMenuAPI = Class.forName("com.terraformersmc.modmenu.api.ModMenuApi"); - //iModMenuAPIMarker = Class.forName("com.terraformersmc.modmenu.util.ModMenuApiMarker"); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - return null; - } - - Object o = Proxy.newProxyInstance( - ModMenuIntegration.class.getClassLoader(), - new Class[]{iModMenuAPI}, - new BCLibModMenuInvocationHandler(target) - ); - - return (ModMenuApi) o; - } - - /** - * The factory passed to {@link #ModMenuIntegration(ModMenuScreenFactory)} - */ - protected final ModMenuScreenFactory screenFactory; - - /** - * Create a new ModMenu delegate - * - * @param screenFactory A Factory. The Factory receives the currently visible {@code parent}-Screen - * and must return a new Screen Object. - */ - public ModMenuIntegration(ModMenuScreenFactory screenFactory) { - this.screenFactory = screenFactory; - } - - /** - * A Helper class to make a BCLib-Factory conform to the ModMenu-Factory Interface. - * - * @param factory A BCLib-Type Factory, ie. {@code GridScreen::new } - * @return A ModMenu Factory for a Screen - */ - final protected ModMenuScreenFactory createFactory(ModMenuScreenFactory factory) { - return ModMenuScreenFactoryImpl.create(factory); - } - - /** - * Used to construct a new config screen instance when your mod's - * configuration button is selected on the mod menu screen. The - * screen instance parameter is the active mod menu screen. - * (Text copied from ModMenu) - * - * @return A factory for constructing config screen instances. - */ - public ModMenuScreenFactory getModConfigScreenFactory() { - return createFactory(screenFactory); - } - - /** - * Used to provide config screen factories for other mods. This takes second - * priority to a mod's own config screen factory provider. For example, if - * mod `xyz` supplies a config screen factory, mod `abc` providing a config - * screen to `xyz` will be pointless, as the one provided by `xyz` will be - * used. - *

- * This method is NOT meant to be used to add a config screen factory to - * your own mod. - * (Text copied from ModMenu) - * - * @return a map of mod ids to screen factories. - */ - public Map getProvidedConfigScreenFactories() { - return ImmutableMap.of(); - } - - @Override - public String toString() { - return super.toString(); - } - - /** - * A Factory Interface for ModMenu-Screens - *

- * The Interface matches {@code com.terraformersmc.modmenu.api.ConfigScreenFactory} - */ - @FunctionalInterface - public interface ModMenuScreenFactory extends ConfigScreenFactory { - } - - record BCLibModMenuInvocationHandler(ModMenuIntegration target) implements InvocationHandler { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - return switch (method.getName()) { - case "getModConfigScreenFactory" -> target.getModConfigScreenFactory(); - case "getProvidedConfigScreenFactories" -> target.getProvidedConfigScreenFactories(); - case "toString" -> target.toString(); - case "equals" -> target.equals(args[0]); - case "hashCode" -> target.hashCode(); - default -> null; - }; - } - } - -} diff --git a/src/main/java/org/betterx/bclib/interfaces/AlloyingRecipeWorkstation.java b/src/main/java/org/betterx/bclib/interfaces/AlloyingRecipeWorkstation.java deleted file mode 100644 index 44766e63..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/AlloyingRecipeWorkstation.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.core.Registry; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; - -import java.util.List; - -public interface AlloyingRecipeWorkstation { - static List getWorkstations() { - return Registry.BLOCK - .stream() - .filter(b -> b instanceof AlloyingRecipeWorkstation) - .toList(); - } - - static ItemStack getWorkstationIcon() { - var workstations = AlloyingRecipeWorkstation.getWorkstations(); - if (workstations.isEmpty()) return new ItemStack(Blocks.BARRIER); - return new ItemStack(workstations.get(0)); - } -} diff --git a/src/main/java/org/betterx/bclib/interfaces/AnvilScreenHandlerExtended.java b/src/main/java/org/betterx/bclib/interfaces/AnvilScreenHandlerExtended.java deleted file mode 100644 index b17116f2..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/AnvilScreenHandlerExtended.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.betterx.bclib.interfaces; - - -import org.betterx.bclib.recipes.AnvilRecipe; - -import java.util.List; - -public interface AnvilScreenHandlerExtended { - void be_updateCurrentRecipe(AnvilRecipe recipe); - - AnvilRecipe be_getCurrentRecipe(); - - List be_getRecipes(); - - default void be_nextRecipe() { - List recipes = be_getRecipes(); - if (recipes.size() < 2) return; - AnvilRecipe current = be_getCurrentRecipe(); - int i = recipes.indexOf(current) + 1; - if (i >= recipes.size()) { - i = 0; - } - be_updateCurrentRecipe(recipes.get(i)); - } - - default void be_previousRecipe() { - List recipes = be_getRecipes(); - if (recipes.size() < 2) return; - AnvilRecipe current = be_getCurrentRecipe(); - int i = recipes.indexOf(current) - 1; - if (i <= 0) { - i = recipes.size() - 1; - } - be_updateCurrentRecipe(recipes.get(i)); - } -} diff --git a/src/main/java/org/betterx/bclib/interfaces/BCLPlacementContext.java b/src/main/java/org/betterx/bclib/interfaces/BCLPlacementContext.java deleted file mode 100644 index 3656f479..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/BCLPlacementContext.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; - -public interface BCLPlacementContext { - Rotation bcl_getRotation(); - void bcl_setRotation(Rotation bcl_rotation); - Mirror bcl_getMirror(); - void bcl_setMirror(Mirror bcl_mirror); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/BiomeChunk.java b/src/main/java/org/betterx/bclib/interfaces/BiomeChunk.java deleted file mode 100644 index 66752937..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/BiomeChunk.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.api.v2.generator.BiomePicker; - -public interface BiomeChunk { - void setBiome(int x, int z, BiomePicker.ActualBiome biome); - BiomePicker.ActualBiome getBiome(int x, int z); - int getSide(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/BiomeMap.java b/src/main/java/org/betterx/bclib/interfaces/BiomeMap.java deleted file mode 100644 index 2dd82747..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/BiomeMap.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.api.v2.generator.BiomePicker; - -public interface BiomeMap { - void setChunkProcessor(TriConsumer processor); - BiomeChunk getChunk(int cx, int cz, boolean update); - BiomePicker.ActualBiome getBiome(double x, double y, double z); - void clearCache(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/BiomeSetter.java b/src/main/java/org/betterx/bclib/interfaces/BiomeSetter.java deleted file mode 100644 index eee82afa..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/BiomeSetter.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.biome.Biome; - -public interface BiomeSetter { - void bclib_setBiome(Biome biome, BlockPos pos); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/BiomeSourceAccessor.java b/src/main/java/org/betterx/bclib/interfaces/BiomeSourceAccessor.java deleted file mode 100644 index 837af156..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/BiomeSourceAccessor.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.betterx.bclib.interfaces; - -public interface BiomeSourceAccessor { - void bclRebuildFeatures(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/BlockModelProvider.java b/src/main/java/org/betterx/bclib/interfaces/BlockModelProvider.java deleted file mode 100644 index dd7a76cd..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/BlockModelProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.state.BlockState; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Map; -import java.util.Optional; -import org.jetbrains.annotations.Nullable; - -public interface BlockModelProvider extends ItemModelProvider { - @Environment(EnvType.CLIENT) - default @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { - Optional pattern = PatternsHelper.createBlockSimple(resourceLocation); - return ModelsHelper.fromPattern(pattern); - } - - @Environment(EnvType.CLIENT) - default UnbakedModel getModelVariant( - ResourceLocation stateId, - BlockState blockState, - Map modelCache - ) { - ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), "block/" + stateId.getPath()); - registerBlockModel(stateId, modelId, blockState, modelCache); - return ModelsHelper.createBlockSimple(modelId); - } - - @Environment(EnvType.CLIENT) - default void registerBlockModel( - ResourceLocation stateId, - ResourceLocation modelId, - BlockState blockState, - Map modelCache - ) { - if (!modelCache.containsKey(modelId)) { - BlockModel model = getBlockModel(stateId, blockState); - if (model != null) { - model.name = modelId.toString(); - modelCache.put(modelId, model); - } else { - BCLib.LOGGER.warning("Error loading model: {}", modelId); - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/interfaces/ChunkGeneratorAccessor.java b/src/main/java/org/betterx/bclib/interfaces/ChunkGeneratorAccessor.java deleted file mode 100644 index 07aea210..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/ChunkGeneratorAccessor.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.core.Registry; -import net.minecraft.world.level.levelgen.structure.StructureSet; - -public interface ChunkGeneratorAccessor { - Registry bclib_getStructureSetsRegistry(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/CustomColorProvider.java b/src/main/java/org/betterx/bclib/interfaces/CustomColorProvider.java deleted file mode 100644 index 5fff479f..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/CustomColorProvider.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.client.color.block.BlockColor; -import net.minecraft.client.color.item.ItemColor; - -public interface CustomColorProvider { - BlockColor getProvider(); - - ItemColor getItemProvider(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/CustomItemProvider.java b/src/main/java/org/betterx/bclib/interfaces/CustomItemProvider.java deleted file mode 100644 index 0c2e261f..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/CustomItemProvider.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; - -public interface CustomItemProvider { - /** - * Used to replace default Block Item when block is registered. - * - * @return {@link BlockItem} - */ - BlockItem getCustomItem(ResourceLocation blockID, Item.Properties settings); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/Fuel.java b/src/main/java/org/betterx/bclib/interfaces/Fuel.java deleted file mode 100644 index 0809f99b..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/Fuel.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.betterx.bclib.interfaces; - -public interface Fuel { - int getFuelTime(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/ItemModelProvider.java b/src/main/java/org/betterx/bclib/interfaces/ItemModelProvider.java deleted file mode 100644 index a1dc638a..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/ItemModelProvider.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.client.models.ModelsHelper; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public interface ItemModelProvider { - @Environment(EnvType.CLIENT) - default BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createItemModel(resourceLocation); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/interfaces/LootPoolAccessor.java b/src/main/java/org/betterx/bclib/interfaces/LootPoolAccessor.java deleted file mode 100644 index 01e2838d..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/LootPoolAccessor.java +++ /dev/null @@ -1,10 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.world.level.storage.loot.LootPool; -import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; - -import java.util.List; - -public interface LootPoolAccessor { - LootPool bcl_mergeEntries(List newEntries); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/NoiseGeneratorSettingsProvider.java b/src/main/java/org/betterx/bclib/interfaces/NoiseGeneratorSettingsProvider.java deleted file mode 100644 index 24dbb70f..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/NoiseGeneratorSettingsProvider.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; -import net.minecraft.world.level.levelgen.synth.NormalNoise; - -public interface NoiseGeneratorSettingsProvider { - NoiseGeneratorSettings bclib_getNoiseGeneratorSettings(); - Holder bclib_getNoiseGeneratorSettingHolders(); - - Registry bclib_getNoises(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/NumericProvider.java b/src/main/java/org/betterx/bclib/interfaces/NumericProvider.java deleted file mode 100644 index fb141b51..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/NumericProvider.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.mixin.common.SurfaceRulesContextAccessor; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.Lifecycle; -import net.minecraft.core.MappedRegistry; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceKey; - -import java.util.function.Function; - -public interface NumericProvider { - ResourceKey>> NUMERIC_PROVIDER_REGISTRY = ResourceKey.createRegistryKey( - BCLib.makeID("worldgen/numeric_provider")); - Registry> NUMERIC_PROVIDER = new MappedRegistry<>( - NUMERIC_PROVIDER_REGISTRY, - Lifecycle.experimental(), - null - ); - Codec CODEC = NUMERIC_PROVIDER.byNameCodec() - .dispatch(NumericProvider::pcodec, Function.identity()); - int getNumber(SurfaceRulesContextAccessor context); - - Codec pcodec(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/PatchBiFunction.java b/src/main/java/org/betterx/bclib/interfaces/PatchBiFunction.java deleted file mode 100644 index b9b654c1..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/PatchBiFunction.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.api.v2.datafixer.MigrationProfile; -import org.betterx.bclib.api.v2.datafixer.PatchDidiFailException; - -@FunctionalInterface -public interface PatchBiFunction { - R apply(U t, V v, MigrationProfile profile) throws PatchDidiFailException; -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/interfaces/PatchFunction.java b/src/main/java/org/betterx/bclib/interfaces/PatchFunction.java deleted file mode 100644 index c6e292f0..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/PatchFunction.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.api.v2.datafixer.MigrationProfile; -import org.betterx.bclib.api.v2.datafixer.PatchDidiFailException; - -@FunctionalInterface -public interface PatchFunction { - R apply(T t, MigrationProfile profile) throws PatchDidiFailException; -} diff --git a/src/main/java/org/betterx/bclib/interfaces/PostInitable.java b/src/main/java/org/betterx/bclib/interfaces/PostInitable.java deleted file mode 100644 index 751fe877..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/PostInitable.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.betterx.bclib.interfaces; - -public interface PostInitable { - void postInit(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/RenderLayerProvider.java b/src/main/java/org/betterx/bclib/interfaces/RenderLayerProvider.java deleted file mode 100644 index 5fc1f2d7..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/RenderLayerProvider.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.client.render.BCLRenderLayer; - -public interface RenderLayerProvider { - BCLRenderLayer getRenderLayer(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/SettingsExtender.java b/src/main/java/org/betterx/bclib/interfaces/SettingsExtender.java deleted file mode 100644 index 357d106a..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/SettingsExtender.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.world.level.block.state.BlockBehaviour; - -@FunctionalInterface -public interface SettingsExtender { - BlockBehaviour.Properties amend(BlockBehaviour.Properties props); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/SpawnRule.java b/src/main/java/org/betterx/bclib/interfaces/SpawnRule.java deleted file mode 100644 index 1cfcdf78..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/SpawnRule.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.core.BlockPos; -import net.minecraft.util.RandomSource; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.level.LevelAccessor; - -@FunctionalInterface -public interface SpawnRule { - boolean canSpawn( - EntityType type, - LevelAccessor world, - MobSpawnType spawnReason, - BlockPos pos, - RandomSource random - ); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/SurfaceMaterialProvider.java b/src/main/java/org/betterx/bclib/interfaces/SurfaceMaterialProvider.java deleted file mode 100644 index aee8f19e..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/SurfaceMaterialProvider.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.betterx.bclib.interfaces; - -import org.betterx.bclib.api.v2.levelgen.surface.SurfaceRuleBuilder; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.world.level.block.state.BlockState; - -public interface SurfaceMaterialProvider { - public static final Codec CODEC = RecordCodecBuilder.create(instance -> instance - .group( - BlockState.CODEC.fieldOf("top").forGetter(o -> o.getTopMaterial()), - BlockState.CODEC.fieldOf("under").forGetter(o -> o.getUnderMaterial()), - BlockState.CODEC.fieldOf("alt").forGetter(o -> o.getAltTopMaterial()), - Codec.BOOL.fieldOf("floor_rule").forGetter(o -> o.generateFloorRule()) - ).apply(instance, SurfaceMaterialProvider::create)); - - public static SurfaceMaterialProvider create( - BlockState top, - BlockState under, - BlockState alt, - boolean genFloorRule - ) { - return new SurfaceMaterialProvider() { - @Override - public BlockState getTopMaterial() { - return top; - } - - @Override - public BlockState getUnderMaterial() { - return under; - } - - @Override - public BlockState getAltTopMaterial() { - return alt; - } - - @Override - public boolean generateFloorRule() { - return genFloorRule; - } - - @Override - public SurfaceRuleBuilder surface() { - return null; - } - }; - } - - BlockState getTopMaterial(); - BlockState getUnderMaterial(); - BlockState getAltTopMaterial(); - - boolean generateFloorRule(); - SurfaceRuleBuilder surface(); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/SurfaceProvider.java b/src/main/java/org/betterx/bclib/interfaces/SurfaceProvider.java deleted file mode 100644 index 60283118..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/SurfaceProvider.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Holder; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.block.state.BlockState; - -public interface SurfaceProvider { - BlockState bclib_getSurface(BlockPos pos, Holder biome, ServerLevel level); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/SurvivesOnBlocks.java b/src/main/java/org/betterx/bclib/interfaces/SurvivesOnBlocks.java deleted file mode 100644 index f11fbb60..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/SurvivesOnBlocks.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - -public interface SurvivesOnBlocks extends SurvivesOnSpecialGround { - List getSurvivableBlocks(); - - @Override - default String getSurvivableBlocksString() { - return getSurvivableBlocks() - .stream() - .filter(block -> block != Blocks.AIR && block != null) - .map(block -> { - ItemStack stack = new ItemStack(block); - if (stack.hasCustomHoverName()) return stack.getHoverName().getString(); - else return block.getName().getString(); - }) - .sorted(Comparator.naturalOrder()) - .collect(Collectors.joining(", ")); - } - - @Override - default boolean isSurvivable(BlockState state) { - return getSurvivableBlocks().contains(state.getBlock()); - } -} diff --git a/src/main/java/org/betterx/bclib/interfaces/SurvivesOnSpecialGround.java b/src/main/java/org/betterx/bclib/interfaces/SurvivesOnSpecialGround.java deleted file mode 100644 index 04ec5562..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/SurvivesOnSpecialGround.java +++ /dev/null @@ -1,66 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.ChatFormatting; -import net.minecraft.core.BlockPos; -import net.minecraft.network.chat.Component; -import net.minecraft.world.level.LevelReader; -import net.minecraft.world.level.block.state.BlockState; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Lists; - -import java.util.List; - -public interface SurvivesOnSpecialGround { - String getSurvivableBlocksString(); - - @Environment(EnvType.CLIENT) - static List splitLines(String input) { - final int MAX_LEN = 45; - List lines = Lists.newArrayList(); - - while (input.length() > MAX_LEN) { - int idx = input.lastIndexOf(",", MAX_LEN); - if (idx >= 0) { - lines.add(input.substring(0, idx + 1).trim()); - input = input.substring(idx + 1).trim(); - } else { - break; - } - } - lines.add(input.trim()); - - return lines; - } - - @Environment(EnvType.CLIENT) - static void appendHoverText(List list, String description) { - final int MAX_LINES = 7; - List lines = splitLines(description); - if (lines.size() == 1) { - list.add(Component.translatable("tooltip.bclib.place_on", lines.get(0)).withStyle(ChatFormatting.GREEN)); - } else if (lines.size() > 1) { - list.add(Component.translatable("tooltip.bclib.place_on", "").withStyle(ChatFormatting.GREEN)); - for (int i = 0; i < Math.min(lines.size(), MAX_LINES); i++) { - String line = lines.get(i); - if (i == MAX_LINES - 1 && i < lines.size() - 1) line += " ..."; - list.add(Component.literal(" " + line).withStyle(ChatFormatting.GREEN)); - } - } - } - - boolean isSurvivable(BlockState state); - - default boolean canSurviveOnTop(LevelReader world, BlockPos pos) { - return isSurvivable(world.getBlockState(pos.below())); - } - - default boolean canSurviveOnBottom(LevelReader world, BlockPos pos) { - return isSurvivable(world.getBlockState(pos.above())); - } - default boolean isTerrain(BlockState state) { - return isSurvivable(state); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/interfaces/SurvivesOnTags.java b/src/main/java/org/betterx/bclib/interfaces/SurvivesOnTags.java deleted file mode 100644 index 11820474..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/SurvivesOnTags.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.core.Registry; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.Comparator; -import java.util.List; -import java.util.stream.Collectors; - -public interface SurvivesOnTags extends SurvivesOnSpecialGround { - List> getSurvivableTags(); - - @Override - default String getSurvivableBlocksString() { - return getSurvivableTags() - .stream() - .map(tag -> Registry.BLOCK.getTag(tag)) - .filter(named -> named.isPresent()) - .map(named -> named.get()) - .flatMap(named -> named.stream()) - .filter(block -> block != Blocks.AIR && block != null) - .map(block -> { - ItemStack stack = new ItemStack(block.value()); - if (stack.hasCustomHoverName()) return stack.getHoverName().getString(); - else return block.value().getName().getString(); - }) - .sorted(Comparator.naturalOrder()) - .collect(Collectors.joining(", ")); - } - - @Override - default boolean isSurvivable(BlockState state) { - return getSurvivableTags().stream().anyMatch(tag -> state.is(tag)); - } -} diff --git a/src/main/java/org/betterx/bclib/interfaces/TagProvider.java b/src/main/java/org/betterx/bclib/interfaces/TagProvider.java deleted file mode 100644 index ee754cbd..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/TagProvider.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; - -import java.util.List; - -public interface TagProvider { - void addTags(List> blockTags, List> itemTags); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/TheEndBiomesAccessor.java b/src/main/java/org/betterx/bclib/interfaces/TheEndBiomesAccessor.java deleted file mode 100644 index aa39ebb6..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/TheEndBiomesAccessor.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.betterx.bclib.interfaces; - -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; - -public interface TheEndBiomesAccessor { - boolean bcl_canGenerateAsEndBiome(ResourceKey key); - - boolean bcl_canGenerateAsEndMidlandBiome(ResourceKey key); - - boolean bcl_canGenerateAsEndBarrensBiome(ResourceKey key); - - default boolean bcl_isNonVanillaAndCanGenerateInEnd(ResourceKey key) { - return !"minecraft".equals(key.location().getNamespace()) && - bcl_canGenerateInEnd(key); - } - default boolean bcl_canGenerateInEnd(ResourceKey key) { - return bcl_canGenerateAsEndBarrensBiome(key) || - bcl_canGenerateAsEndMidlandBiome(key) || - bcl_canGenerateAsEndBiome(key) - ; - } -} diff --git a/src/main/java/org/betterx/bclib/interfaces/TileEntityRenderProvider.java b/src/main/java/org/betterx/bclib/interfaces/TileEntityRenderProvider.java deleted file mode 100644 index 732d8f4b..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/TileEntityRenderProvider.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.betterx.bclib.interfaces; - -public interface TileEntityRenderProvider { - -} diff --git a/src/main/java/org/betterx/bclib/interfaces/TriConsumer.java b/src/main/java/org/betterx/bclib/interfaces/TriConsumer.java deleted file mode 100644 index a06dcdcd..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/TriConsumer.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.betterx.bclib.interfaces; - -@FunctionalInterface -public interface TriConsumer { - void accept(A a, B b, C c); -} diff --git a/src/main/java/org/betterx/bclib/interfaces/UnknownReceipBookCategory.java b/src/main/java/org/betterx/bclib/interfaces/UnknownReceipBookCategory.java deleted file mode 100644 index 46052df4..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/UnknownReceipBookCategory.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces; - -public interface UnknownReceipBookCategory { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableAxe.java b/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableAxe.java deleted file mode 100644 index 7a110d3d..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableAxe.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface AddMineableAxe { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableHammer.java b/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableHammer.java deleted file mode 100644 index 6826e308..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableHammer.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface AddMineableHammer { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableHoe.java b/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableHoe.java deleted file mode 100644 index 6db28739..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableHoe.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface AddMineableHoe { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineablePickaxe.java b/src/main/java/org/betterx/bclib/interfaces/tools/AddMineablePickaxe.java deleted file mode 100644 index 9a9017a9..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineablePickaxe.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface AddMineablePickaxe { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableShears.java b/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableShears.java deleted file mode 100644 index d26fba7b..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableShears.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface AddMineableShears { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableShovel.java b/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableShovel.java deleted file mode 100644 index d9ae344d..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableShovel.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface AddMineableShovel { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableSword.java b/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableSword.java deleted file mode 100644 index c38f3767..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/AddMineableSword.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface AddMineableSword { -} diff --git a/src/main/java/org/betterx/bclib/interfaces/tools/PreventMineableAdd.java b/src/main/java/org/betterx/bclib/interfaces/tools/PreventMineableAdd.java deleted file mode 100644 index 5c75262f..00000000 --- a/src/main/java/org/betterx/bclib/interfaces/tools/PreventMineableAdd.java +++ /dev/null @@ -1,4 +0,0 @@ -package org.betterx.bclib.interfaces.tools; - -public interface PreventMineableAdd { -} diff --git a/src/main/java/org/betterx/bclib/items/BaseAnvilItem.java b/src/main/java/org/betterx/bclib/items/BaseAnvilItem.java deleted file mode 100644 index 03b7401f..00000000 --- a/src/main/java/org/betterx/bclib/items/BaseAnvilItem.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.betterx.bclib.items; - -import org.betterx.bclib.blocks.BaseAnvilBlock; -import org.betterx.bclib.interfaces.BlockModelProvider; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.core.Registry; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.item.context.BlockPlaceContext; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.IntegerProperty; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.List; -import java.util.Locale; -import org.jetbrains.annotations.Nullable; - -public class BaseAnvilItem extends BlockItem implements ItemModelProvider { - public final static String DESTRUCTION = "destruction"; - - public BaseAnvilItem(Block block, Properties properties) { - super(block, properties); - } - - @Override - protected BlockState getPlacementState(BlockPlaceContext blockPlaceContext) { - BlockState blockState = super.getPlacementState(blockPlaceContext); - ItemStack stack = blockPlaceContext.getItemInHand(); - int destruction = stack.getOrCreateTag().getInt(DESTRUCTION); - if (blockState != null) { - BaseAnvilBlock block = (BaseAnvilBlock) blockState.getBlock(); - IntegerProperty durabilityProp = block.getDurabilityProp(); - if (destruction == 0) { - blockState = blockState.setValue(durabilityProp, 0).setValue(BaseAnvilBlock.DESTRUCTION, 0); - } else { - int destructionValue = destruction / block.getMaxDurability(); - int durabilityValue = destruction - destructionValue * block.getMaxDurability(); - blockState = blockState.setValue(durabilityProp, durabilityValue) - .setValue(BaseAnvilBlock.DESTRUCTION, destructionValue); - } - } - return blockState; - } - - @Override - @Environment(EnvType.CLIENT) - public void appendHoverText( - ItemStack itemStack, - @Nullable Level level, - List list, - TooltipFlag tooltipFlag - ) { - int destruction = itemStack.getOrCreateTag().getInt(DESTRUCTION); - if (destruction > 0) { - BaseAnvilBlock block = (BaseAnvilBlock) ((BaseAnvilItem) itemStack.getItem()).getBlock(); - int maxValue = block.getMaxDurability() * 3; - float damage = maxValue - destruction; - String percents = String.format(Locale.ROOT, "%.0f%%", damage); - list.add(Component.translatable("message.bclib.anvil_damage").append(": " + percents)); - } - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - Block anvilBlock = getBlock(); - ResourceLocation blockId = Registry.BLOCK.getKey(anvilBlock); - return ((BlockModelProvider) anvilBlock).getBlockModel(blockId, anvilBlock.defaultBlockState()); - } -} diff --git a/src/main/java/org/betterx/bclib/items/BaseArmorItem.java b/src/main/java/org/betterx/bclib/items/BaseArmorItem.java deleted file mode 100644 index 625904c7..00000000 --- a/src/main/java/org/betterx/bclib/items/BaseArmorItem.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.items; - -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.ai.attributes.Attribute; -import net.minecraft.world.entity.ai.attributes.AttributeModifier; -import net.minecraft.world.entity.ai.attributes.Attributes; -import net.minecraft.world.item.ArmorItem; -import net.minecraft.world.item.ArmorMaterial; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Multimap; - -import java.util.UUID; - -public class BaseArmorItem extends ArmorItem implements ItemModelProvider { - - protected static final UUID[] ARMOR_MODIFIER_UUID_PER_SLOT = new UUID[]{ - UUID.fromString("845DB27C-C624-495F-8C9F-6020A9A58B6B"), - UUID.fromString("D8499B04-0E66-4726-AB29-64469D734E0D"), - UUID.fromString("9F3D476D-C118-4544-8365-64846904B48E"), - UUID.fromString("2AD3F246-FEE1-4E67-B886-69FD380BB150") - }; - - protected final Multimap defaultModifiers; - - public BaseArmorItem(ArmorMaterial material, EquipmentSlot equipmentSlot, Properties settings) { - super(material, equipmentSlot, settings); - this.defaultModifiers = HashMultimap.create(); - UUID uuid = ARMOR_MODIFIER_UUID_PER_SLOT[equipmentSlot.getIndex()]; - addAttributeModifier( - Attributes.ARMOR, - new AttributeModifier(uuid, "Armor modifier", getDefense(), AttributeModifier.Operation.ADDITION) - ); - addAttributeModifier( - Attributes.ARMOR_TOUGHNESS, - new AttributeModifier(uuid, "Armor toughness", getToughness(), AttributeModifier.Operation.ADDITION) - ); - if (knockbackResistance > 0.0F) { - addAttributeModifier( - Attributes.KNOCKBACK_RESISTANCE, - new AttributeModifier( - uuid, - "Armor knockback resistance", - knockbackResistance, - AttributeModifier.Operation.ADDITION - ) - ); - } - } - - @Override - public Multimap getDefaultAttributeModifiers(EquipmentSlot equipmentSlot) { - return equipmentSlot == slot ? defaultModifiers : super.getDefaultAttributeModifiers(equipmentSlot); - } - - protected void addAttributeModifier(Attribute attribute, AttributeModifier modifier) { - if (defaultModifiers.containsKey(attribute)) { - defaultModifiers.removeAll(attribute); - } - defaultModifiers.put(attribute, modifier); - } -} diff --git a/src/main/java/org/betterx/bclib/items/BaseAttribute.java b/src/main/java/org/betterx/bclib/items/BaseAttribute.java deleted file mode 100644 index 2ff7cd72..00000000 --- a/src/main/java/org/betterx/bclib/items/BaseAttribute.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.items; - -import net.minecraft.world.entity.ai.attributes.Attribute; - -public class BaseAttribute extends Attribute { - public BaseAttribute(String description, double value) { - super(description, value); - } -} diff --git a/src/main/java/org/betterx/bclib/items/BaseBucketItem.java b/src/main/java/org/betterx/bclib/items/BaseBucketItem.java deleted file mode 100644 index 283273c9..00000000 --- a/src/main/java/org/betterx/bclib/items/BaseBucketItem.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.betterx.bclib.items; - -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.sounds.SoundEvents; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.MobBucketItem; -import net.minecraft.world.level.material.Fluids; - -public class BaseBucketItem extends MobBucketItem implements ItemModelProvider { - public BaseBucketItem(EntityType type, Item.Properties settings) { - super(type, Fluids.WATER, SoundEvents.BUCKET_EMPTY_FISH, settings.stacksTo(1)); - } -} diff --git a/src/main/java/org/betterx/bclib/items/BaseDiscItem.java b/src/main/java/org/betterx/bclib/items/BaseDiscItem.java deleted file mode 100644 index 18227f20..00000000 --- a/src/main/java/org/betterx/bclib/items/BaseDiscItem.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.betterx.bclib.items; - -import org.betterx.bclib.BCLib; - -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.RecordItem; - -import java.lang.reflect.Constructor; - -public class BaseDiscItem { - public static RecordItem create( - int comparatorOutput, - SoundEvent sound, - Item.Properties settings, - int lengthInSeconds - ) { - for (Constructor c : RecordItem.class.getDeclaredConstructors()) { - if (c.getParameterCount() == 4) { - var types = c.getParameterTypes(); - if (types.length == 4) { //1.19.1 Constructor - if ( - types[0].isAssignableFrom(int.class) - && types[1].isAssignableFrom(SoundEvent.class) - && types[2].isAssignableFrom(Item.Properties.class) - && types[3].isAssignableFrom(int.class) - ) { - c.setAccessible(true); - try { - return (RecordItem) c.newInstance(comparatorOutput, sound, settings, lengthInSeconds); - } catch (Exception e) { - BCLib.LOGGER.error("Failed to instantiate RecordItem", e); - } - } - } - } else if (c.getParameterCount() == 3) { - var types = c.getParameterTypes(); - if (types.length == 3) { //1.19 constructor - if ( - types[0].isAssignableFrom(int.class) - && types[1].isAssignableFrom(SoundEvent.class) - && types[2].isAssignableFrom(Item.Properties.class) - ) { - c.setAccessible(true); - try { - return (RecordItem) c.newInstance(comparatorOutput, sound, settings); - } catch (Exception e) { - BCLib.LOGGER.error("Failed to instantiate RecordItem", e); - } - } - } - } - } - BCLib.LOGGER.error("No Constructor for RecordItems found:"); - for (Constructor c : RecordItem.class.getDeclaredConstructors()) { - BCLib.LOGGER.error(" - " + c); - } - return null; - } -} diff --git a/src/main/java/org/betterx/bclib/items/BaseDrinkItem.java b/src/main/java/org/betterx/bclib/items/BaseDrinkItem.java deleted file mode 100644 index 85b3ebeb..00000000 --- a/src/main/java/org/betterx/bclib/items/BaseDrinkItem.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.betterx.bclib.items; - -import net.minecraft.advancements.CriteriaTriggers; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.stats.Stats; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResultHolder; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.ItemUtils; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.UseAnim; -import net.minecraft.world.level.Level; - -public class BaseDrinkItem extends ModelProviderItem { - public BaseDrinkItem(Properties settings) { - super(settings); - } - - @Override - public int getUseDuration(ItemStack stack) { - return 32; - } - - @Override - public UseAnim getUseAnimation(ItemStack stack) { - return UseAnim.DRINK; - } - - @Override - public InteractionResultHolder use(Level world, Player user, InteractionHand hand) { - return ItemUtils.startUsingInstantly(world, user, hand); - } - - @Override - public ItemStack finishUsingItem(ItemStack stack, Level level, LivingEntity user) { - if (this.isEdible()) { - int count = stack.getCount(); - user.eat(level, stack); - stack.setCount(count); - } - - if (user instanceof ServerPlayer serverPlayerEntity) { - CriteriaTriggers.CONSUME_ITEM.trigger(serverPlayerEntity, stack); - serverPlayerEntity.awardStat(Stats.ITEM_USED.get(this)); - } - - if (user instanceof Player && !((Player) user).getAbilities().instabuild) { - stack.shrink(1); - } - - if (!level.isClientSide) { - user.removeAllEffects(); - } - - return stack.isEmpty() ? new ItemStack(Items.GLASS_BOTTLE) : stack; - } -} diff --git a/src/main/java/org/betterx/bclib/items/BaseSpawnEggItem.java b/src/main/java/org/betterx/bclib/items/BaseSpawnEggItem.java deleted file mode 100644 index 493785d2..00000000 --- a/src/main/java/org/betterx/bclib/items/BaseSpawnEggItem.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.betterx.bclib.items; - -import org.betterx.bclib.client.models.BasePatterns; -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.client.models.PatternsHelper; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.item.SpawnEggItem; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.Optional; - -public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider { - public BaseSpawnEggItem(EntityType type, int primaryColor, int secondaryColor, Properties settings) { - super(type, primaryColor, secondaryColor, settings); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_SPAWN_EGG, resourceLocation); - return ModelsHelper.fromPattern(pattern); - } -} diff --git a/src/main/java/org/betterx/bclib/items/ModelProviderItem.java b/src/main/java/org/betterx/bclib/items/ModelProviderItem.java deleted file mode 100644 index bb207265..00000000 --- a/src/main/java/org/betterx/bclib/items/ModelProviderItem.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.betterx.bclib.items; - -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public class ModelProviderItem extends Item implements ItemModelProvider { - public ModelProviderItem(Properties settings) { - super(settings); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createItemModel(resourceLocation); - } -} diff --git a/src/main/java/org/betterx/bclib/items/boat/BaseBoatItem.java b/src/main/java/org/betterx/bclib/items/boat/BaseBoatItem.java deleted file mode 100644 index 32ac4066..00000000 --- a/src/main/java/org/betterx/bclib/items/boat/BaseBoatItem.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.betterx.bclib.items.boat; - -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.world.entity.vehicle.Boat; -import net.minecraft.world.item.BoatItem; - -public class BaseBoatItem extends BoatItem implements CustomBoatTypeOverride, ItemModelProvider { - BoatTypeOverride customType; - - public BaseBoatItem(boolean bl, BoatTypeOverride type, Properties properties) { - super(bl, Boat.Type.OAK, properties); - setCustomType(type); - } - - @Override - public void setCustomType(BoatTypeOverride type) { - customType = type; - } - - @Override - public BoatTypeOverride bcl_getCustomType() { - return customType; - } -} diff --git a/src/main/java/org/betterx/bclib/items/boat/BoatTypeOverride.java b/src/main/java/org/betterx/bclib/items/boat/BoatTypeOverride.java deleted file mode 100644 index de59ed99..00000000 --- a/src/main/java/org/betterx/bclib/items/boat/BoatTypeOverride.java +++ /dev/null @@ -1,174 +0,0 @@ -package org.betterx.bclib.items.boat; - -import org.betterx.bclib.BCLib; - -import net.minecraft.client.model.BoatModel; -import net.minecraft.client.model.geom.ModelLayerLocation; -import net.minecraft.client.renderer.entity.EntityRendererProvider; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BoatItem; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.stream.Stream; - -public final class BoatTypeOverride { - private static final String DEFAULT_LAYER = "main"; - - private static final List values = new ArrayList<>(8); - private final String name; - private final Block planks; - private final int ordinal; - public final ResourceLocation id; - public final ResourceLocation boatTexture; - public final ResourceLocation chestBoatTexture; - public final ModelLayerLocation boatModelName; - public final ModelLayerLocation chestBoatModelName; - private BoatModel boatModel, chestBoatModel; - private BoatItem boat, chestBoat; - - BoatTypeOverride(String modID, String name, Block planks) { - this.id = new ResourceLocation(modID, name); - this.name = name; - this.planks = planks; - int nr = Objects.hash(name); - if (nr >= 0 && nr <= 1000) nr += 1000; - while (byId(nr) != null) { - BCLib.LOGGER.warning("Boat Type Ordinal " + nr + " is already used, searching for another one"); - nr++; - if (nr >= 0 && nr <= 1000) nr += 1000; - } - this.ordinal = nr; - if (BCLib.isClient()) { - this.boatModelName = createBoatModelName(id.getNamespace(), id.getPath()); - this.chestBoatModelName = createChestBoatModelName(id.getNamespace(), id.getPath()); - this.boatTexture = getTextureLocation(modID, name, false); - this.chestBoatTexture = getTextureLocation(modID, name, true); - } else { - this.boatModelName = null; - this.chestBoatModelName = null; - this.boatTexture = null; - this.chestBoatTexture = null; - } - - values.add(this); - } - - public BoatModel getBoatModel(boolean chest) { - return chest ? chestBoatModel : boatModel; - } - - public void createBoatModels(EntityRendererProvider.Context context) { - if (boatModel == null) { - boatModel = new BoatModel(context.bakeLayer(boatModelName), false); - chestBoatModel = new BoatModel(context.bakeLayer(chestBoatModelName), true); - } - } - - public Block getPlanks() { - return planks; - } - - public void setBoatItem(BoatItem item) { - this.boat = item; - } - - public BoatItem getBoatItem() { - return boat; - } - - public void setChestBoatItem(BoatItem item) { - this.chestBoat = item; - } - - public BoatItem getChestBoatItem() { - return chestBoat; - } - - public static Stream values() { - return values.stream(); - } - - private static ModelLayerLocation createBoatModelName(String modID, String name) { - return new ModelLayerLocation(new ResourceLocation(modID, "boat/" + name), DEFAULT_LAYER); - } - - private static ModelLayerLocation createChestBoatModelName(String modID, String name) { - return new ModelLayerLocation(new ResourceLocation(modID, "chest_boat/" + name), DEFAULT_LAYER); - } - - private static ResourceLocation getTextureLocation(String modID, String name, boolean chest) { - if (chest) { - return new ResourceLocation(modID, "textures/entity/chest_boat/" + name + ".png"); - } - return new ResourceLocation(modID, "textures/entity/boat/" + name + ".png"); - } - - public static BoatTypeOverride create(String modID, String name, Block planks) { - BoatTypeOverride t = new BoatTypeOverride(modID, name, planks); - - return t; - } - - public BoatItem createItem(boolean hasChest) { - return createItem(hasChest, new Item.Properties().stacksTo(1).tab(CreativeModeTab.TAB_TRANSPORTATION)); - } - - public BoatItem createItem(boolean hasChest, Item.Properties itemSettings) { - BoatItem item = new BaseBoatItem(hasChest, this, itemSettings); - - if (hasChest) this.setChestBoatItem(item); - else this.setBoatItem(item); - - return item; - } - - public static BoatTypeOverride byId(int i) { - for (BoatTypeOverride t : values) { - if (t.ordinal == i) return t; - } - return null; - } - - public static BoatTypeOverride byName(String string) { - for (BoatTypeOverride t : values) { - if (!t.name().equals(string)) continue; - return t; - } - return null; - } - - public String name() { - return name; - } - - public int ordinal() { - return ordinal; - } - - @Override - public boolean equals(Object obj) { - if (obj == this) return true; - if (obj == null || obj.getClass() != this.getClass()) return false; - var that = (BoatTypeOverride) obj; - return Objects.equals(this.name, that.name) && - this.ordinal == that.ordinal; - } - - @Override - public int hashCode() { - return Objects.hash(name, ordinal); - } - - @Override - public String toString() { - return "BoatTypeOverride[" + - "name=" + name + ", " + - "ordinal=" + ordinal + ']'; - } - -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/items/boat/CustomBoatTypeOverride.java b/src/main/java/org/betterx/bclib/items/boat/CustomBoatTypeOverride.java deleted file mode 100644 index 4d1ddd99..00000000 --- a/src/main/java/org/betterx/bclib/items/boat/CustomBoatTypeOverride.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.betterx.bclib.items.boat; - -public interface CustomBoatTypeOverride { - void setCustomType(BoatTypeOverride type); - BoatTypeOverride bcl_getCustomType(); -} diff --git a/src/main/java/org/betterx/bclib/items/complex/EquipmentDescription.java b/src/main/java/org/betterx/bclib/items/complex/EquipmentDescription.java deleted file mode 100644 index a03e699c..00000000 --- a/src/main/java/org/betterx/bclib/items/complex/EquipmentDescription.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.betterx.bclib.items.complex; - -import org.betterx.bclib.items.BaseArmorItem; -import org.betterx.bclib.recipes.BCLRecipeBuilder; -import org.betterx.bclib.recipes.GridRecipe; -import org.betterx.bclib.registry.ItemRegistry; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.item.*; -import net.minecraft.world.level.ItemLike; - -import java.util.function.Function; - -public class EquipmentDescription { - private final Function creator; - private I item; - - public EquipmentDescription(Function creator) { - this.creator = creator; - } - - public void init(ResourceLocation id, ItemRegistry itemsRegistry, Tier material, ItemLike stick) { - item = creator.apply(material); - itemsRegistry.registerTool(id, item); - - addRecipe(id, item, material, stick); - } - - public void addRecipe(ResourceLocation id, Item tool, Tier material, ItemLike stick) { - if (material == null) return; - var repair = material.getRepairIngredient(); - if (repair == null) return; - var repairItems = repair.getItems(); - if (repairItems == null || repairItems.length == 0) return; - final ItemLike ingot = repairItems[0].getItem(); - - var builder = BCLRecipeBuilder.crafting(id, tool) - .addMaterial('#', ingot); - - if (buildRecipe(tool, stick, builder)) return; - builder - .setGroup(id.getPath()) - .build(); - - } - - protected boolean buildRecipe(Item tool, ItemLike stick, GridRecipe builder) { - if (tool instanceof ShearsItem) { - builder.setShape(" #", "# "); - } else if (tool instanceof BaseArmorItem bai) { - if (bai.getSlot() == EquipmentSlot.FEET) { - builder.setShape("# #", "# #"); - } else if (bai.getSlot() == EquipmentSlot.HEAD) { - builder.setShape("###", "# #"); - } else if (bai.getSlot() == EquipmentSlot.CHEST) { - builder.setShape("# #", "###", "###"); - } else if (bai.getSlot() == EquipmentSlot.LEGS) { - builder.setShape("###", "# #", "# #"); - } else return true; - } else { - builder.addMaterial('I', stick); - if (tool instanceof PickaxeItem) { - builder.setShape("###", " I ", " I "); - } else if (tool instanceof AxeItem) { - builder.setShape("##", "#I", " I"); - } else if (tool instanceof HoeItem) { - builder.setShape("##", " I", " I"); - } else if (tool instanceof ShovelItem) { - builder.setShape("#", "I", "I"); - } else if (tool instanceof SwordItem) { - builder.setShape("#", "#", "I"); - } else return true; - } - return false; - } - - public I getItem() { - return item; - } -} diff --git a/src/main/java/org/betterx/bclib/items/complex/EquipmentSet.java b/src/main/java/org/betterx/bclib/items/complex/EquipmentSet.java deleted file mode 100644 index a0872575..00000000 --- a/src/main/java/org/betterx/bclib/items/complex/EquipmentSet.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.betterx.bclib.items.complex; - -import org.betterx.bclib.registry.ItemRegistry; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Tier; -import net.minecraft.world.level.ItemLike; - -import java.util.HashMap; -import java.util.Map; -import org.jetbrains.annotations.NotNull; - -public abstract class EquipmentSet { - public final Tier material; - public final String baseName; - public final String modID; - public final ItemLike stick; - - public static final String PICKAXE_SLOT = "pickaxe"; - public static final String AXE_SLOT = "axe"; - public static final String SHOVEL_SLOT = "shovel"; - public static final String SWORD_SLOT = "sword"; - public static final String HOE_SLOT = "hoe"; - public static final String SHEARS_SLOT = "shears"; - public static final String HELMET_SLOT = "helmet"; - public static final String CHESTPLATE_SLOT = "chestplate"; - public static final String LEGGINGS_SLOT = "leggings"; - public static final String BOOTS_SLOT = "boots"; - - private final Map> descriptions = new HashMap<>(); - - public EquipmentSet(Tier material, String modID, String baseName, ItemLike stick) { - this.material = material; - this.baseName = baseName; - this.modID = modID; - this.stick = stick; - } - - protected void add(String slot, EquipmentDescription desc) { - descriptions.put(slot, desc); - } - - public EquipmentSet init(ItemRegistry itemsRegistry) { - for (var desc : descriptions.entrySet()) { - desc.getValue() - .init(buildID(desc), itemsRegistry, material, stick); - } - return this; - } - - @NotNull - protected ResourceLocation buildID(Map.Entry> desc) { - return new ResourceLocation(modID, baseName + "_" + desc.getKey()); - } - - public I getSlot(String slot) { - return (I) descriptions.get(slot).getItem(); - } -} diff --git a/src/main/java/org/betterx/bclib/items/elytra/BCLElytraItem.java b/src/main/java/org/betterx/bclib/items/elytra/BCLElytraItem.java deleted file mode 100644 index 2671ff5f..00000000 --- a/src/main/java/org/betterx/bclib/items/elytra/BCLElytraItem.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.betterx.bclib.items.elytra; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.gameevent.GameEvent; - -import net.fabricmc.fabric.api.entity.event.v1.FabricElytraItem; - -public interface BCLElytraItem extends FabricElytraItem { - ResourceLocation getModelTexture(); - - double getMovementFactor(); - - - default void doVanillaElytraTick(LivingEntity entity, ItemStack chestStack) { - vanillaElytraTick(entity, chestStack); - } - - static void vanillaElytraTick(LivingEntity entity, ItemStack chestStack) { - int nextRoll = entity.getFallFlyingTicks() + 1; - - if (!entity.level.isClientSide && nextRoll % 10 == 0) { - if ((nextRoll / 10) % 2 == 0) { - chestStack.hurtAndBreak(1, entity, (e) -> BCLElytraUtils.onBreak.accept(e, chestStack)); - } - - entity.gameEvent(GameEvent.ELYTRA_GLIDE); - } - } -} diff --git a/src/main/java/org/betterx/bclib/items/elytra/BCLElytraUtils.java b/src/main/java/org/betterx/bclib/items/elytra/BCLElytraUtils.java deleted file mode 100644 index ee20dfed..00000000 --- a/src/main/java/org/betterx/bclib/items/elytra/BCLElytraUtils.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.items.elytra; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; - -import java.util.function.BiConsumer; -import java.util.function.Function; - -public class BCLElytraUtils { - @FunctionalInterface - public interface SlotProvider { - ItemStack getElytra(LivingEntity entity, Function slotGetter); - } - - public static SlotProvider slotProvider = null; - public static BiConsumer onBreak = - (entity, chestStack) -> entity.broadcastBreakEvent(EquipmentSlot.CHEST); -} diff --git a/src/main/java/org/betterx/bclib/items/tool/BaseAxeItem.java b/src/main/java/org/betterx/bclib/items/tool/BaseAxeItem.java deleted file mode 100644 index 90807831..00000000 --- a/src/main/java/org/betterx/bclib/items/tool/BaseAxeItem.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.items.tool; - -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.AxeItem; -import net.minecraft.world.item.Tier; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public class BaseAxeItem extends AxeItem implements ItemModelProvider { - public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { - super(material, attackDamage, attackSpeed, settings); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createHandheldItem(resourceLocation); - } -} diff --git a/src/main/java/org/betterx/bclib/items/tool/BaseHoeItem.java b/src/main/java/org/betterx/bclib/items/tool/BaseHoeItem.java deleted file mode 100644 index f316166a..00000000 --- a/src/main/java/org/betterx/bclib/items/tool/BaseHoeItem.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.items.tool; - -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.HoeItem; -import net.minecraft.world.item.Tier; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public class BaseHoeItem extends HoeItem implements ItemModelProvider { - public BaseHoeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { - super(material, attackDamage, attackSpeed, settings); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createHandheldItem(resourceLocation); - } -} diff --git a/src/main/java/org/betterx/bclib/items/tool/BasePickaxeItem.java b/src/main/java/org/betterx/bclib/items/tool/BasePickaxeItem.java deleted file mode 100644 index 1ed0e38d..00000000 --- a/src/main/java/org/betterx/bclib/items/tool/BasePickaxeItem.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.items.tool; - -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.PickaxeItem; -import net.minecraft.world.item.Tier; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public class BasePickaxeItem extends PickaxeItem implements ItemModelProvider { - public BasePickaxeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { - super(material, attackDamage, attackSpeed, settings); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createHandheldItem(resourceLocation); - } -} diff --git a/src/main/java/org/betterx/bclib/items/tool/BaseShearsItem.java b/src/main/java/org/betterx/bclib/items/tool/BaseShearsItem.java deleted file mode 100644 index 84c4a602..00000000 --- a/src/main/java/org/betterx/bclib/items/tool/BaseShearsItem.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.items.tool; - - -import org.betterx.worlds.together.tag.v3.CommonItemTags; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.ShearsItem; - -import net.fabricmc.fabric.api.mininglevel.v1.FabricMineableTags; - -public class BaseShearsItem extends ShearsItem { - public BaseShearsItem(Properties properties) { - super(properties); - } - - public static boolean isShear(ItemStack tool) { - return tool.is(Items.SHEARS) | tool.is(CommonItemTags.SHEARS) || TagManager.isToolWithMineableTag( - tool, - FabricMineableTags.SHEARS_MINEABLE - ); - } - - public static boolean isShear(ItemStack itemStack, Item item) { - if (item == Items.SHEARS) { - return itemStack.is(item) | itemStack.is(CommonItemTags.SHEARS); - } else { - return itemStack.is(item); - } - } -} diff --git a/src/main/java/org/betterx/bclib/items/tool/BaseShovelItem.java b/src/main/java/org/betterx/bclib/items/tool/BaseShovelItem.java deleted file mode 100644 index 4dd0e746..00000000 --- a/src/main/java/org/betterx/bclib/items/tool/BaseShovelItem.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.items.tool; - -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ShovelItem; -import net.minecraft.world.item.Tier; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public class BaseShovelItem extends ShovelItem implements ItemModelProvider { - public BaseShovelItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { - super(material, attackDamage, attackSpeed, settings); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createHandheldItem(resourceLocation); - } -} diff --git a/src/main/java/org/betterx/bclib/items/tool/BaseSwordItem.java b/src/main/java/org/betterx/bclib/items/tool/BaseSwordItem.java deleted file mode 100644 index 960c9389..00000000 --- a/src/main/java/org/betterx/bclib/items/tool/BaseSwordItem.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.items.tool; - -import org.betterx.bclib.client.models.ModelsHelper; -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.client.renderer.block.model.BlockModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.SwordItem; -import net.minecraft.world.item.Tier; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -public class BaseSwordItem extends SwordItem implements ItemModelProvider { - public BaseSwordItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { - super(material, attackDamage, attackSpeed, settings); - } - - @Override - @Environment(EnvType.CLIENT) - public BlockModel getItemModel(ResourceLocation resourceLocation) { - return ModelsHelper.createHandheldItem(resourceLocation); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/AnvilScreenMixin.java b/src/main/java/org/betterx/bclib/mixin/client/AnvilScreenMixin.java deleted file mode 100644 index dd7faa9c..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/AnvilScreenMixin.java +++ /dev/null @@ -1,99 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.interfaces.AnvilScreenHandlerExtended; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.components.AbstractWidget; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.EditBox; -import net.minecraft.client.gui.components.events.ContainerEventHandler; -import net.minecraft.client.gui.screens.inventory.AnvilScreen; -import net.minecraft.client.gui.screens.inventory.ItemCombinerScreen; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.inventory.AbstractContainerMenu; -import net.minecraft.world.inventory.AnvilMenu; -import net.minecraft.world.item.ItemStack; - -import com.google.common.collect.Lists; -import org.spongepowered.asm.mixin.*; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; - -@Mixin(AnvilScreen.class) -@Implements(@Interface(iface = ContainerEventHandler.class, prefix = "bcl$")) -public class AnvilScreenMixin extends ItemCombinerScreen { - - @Shadow - private EditBox name; - - private final List be_buttons = Lists.newArrayList(); - - public AnvilScreenMixin(AnvilMenu handler, Inventory playerInventory, Component title, ResourceLocation texture) { - super(handler, playerInventory, title, texture); - } - - @Inject(method = "subInit", at = @At("TAIL")) - protected void be_subInit(CallbackInfo info) { - int x = (width - imageWidth) / 2; - int y = (height - imageHeight) / 2; - be_buttons.clear(); - be_buttons.add(new Button(x + 8, y + 45, 15, 20, Component.literal("<"), b -> be_previousRecipe())); - be_buttons.add(new Button(x + 154, y + 45, 15, 20, Component.literal(">"), b -> be_nextRecipe())); - - be_buttons.forEach(button -> addWidget(button)); - } - - @Inject(method = "renderFg", at = @At("TAIL")) - protected void be_renderForeground(PoseStack matrices, int mouseX, int mouseY, float delta, CallbackInfo info) { - be_buttons.forEach(button -> { - button.render(matrices, mouseX, mouseY, delta); - }); - } - - @Inject(method = "slotChanged", at = @At("HEAD"), cancellable = true) - public void be_onSlotUpdate(AbstractContainerMenu handler, int slotId, ItemStack stack, CallbackInfo info) { - AnvilScreenHandlerExtended anvilHandler = (AnvilScreenHandlerExtended) handler; - if (anvilHandler.be_getCurrentRecipe() != null) { - if (anvilHandler.be_getRecipes().size() > 1) { - be_buttons.forEach(button -> button.visible = true); - } else { - be_buttons.forEach(button -> button.visible = false); - } - name.setValue(""); - info.cancel(); - } else { - be_buttons.forEach(button -> button.visible = false); - } - } - - private void be_nextRecipe() { - ((AnvilScreenHandlerExtended) menu).be_nextRecipe(); - } - - private void be_previousRecipe() { - ((AnvilScreenHandlerExtended) menu).be_previousRecipe(); - } - - - @Intrinsic(displace = true) - //@Override - public boolean bcl$mouseClicked(double mouseX, double mouseY, int button) { - if (minecraft != null) { - for (AbstractWidget elem : be_buttons) { - if (elem.visible && elem.mouseClicked(mouseX, mouseY, button)) { - if (minecraft.gameMode != null) { - int i = be_buttons.indexOf(elem); - minecraft.gameMode.handleInventoryButtonClick(menu.containerId, i); - return true; - } - } - } - } - return super.mouseClicked(mouseX, mouseY, button); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/BlockMixin.java b/src/main/java/org/betterx/bclib/mixin/client/BlockMixin.java deleted file mode 100644 index 5d85f93b..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/BlockMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.interfaces.SurvivesOnSpecialGround; - -import net.minecraft.network.chat.Component; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TooltipFlag; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.Block; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; -import org.jetbrains.annotations.Nullable; - -@Mixin(Block.class) -public class BlockMixin { - @Inject(method = "appendHoverText", at = @At("HEAD")) - void bclib_appendSurvivalBlock( - ItemStack itemStack, - @Nullable BlockGetter blockGetter, - List list, - TooltipFlag tooltipFlag, - CallbackInfo ci - ) { - if (this instanceof SurvivesOnSpecialGround surv) { - SurvivesOnSpecialGround.appendHoverText(list, surv.getSurvivableBlocksString()); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/ClientRecipeBookMixin.java b/src/main/java/org/betterx/bclib/mixin/client/ClientRecipeBookMixin.java deleted file mode 100644 index ea8c32d6..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/ClientRecipeBookMixin.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.interfaces.UnknownReceipBookCategory; - -import net.minecraft.client.ClientRecipeBook; -import net.minecraft.client.RecipeBookCategories; -import net.minecraft.world.item.crafting.Recipe; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(ClientRecipeBook.class) -public abstract class ClientRecipeBookMixin { - @Inject(method = "getCategory", at = @At("HEAD"), cancellable = true) - private static void be_getGroupForRecipe(Recipe recipe, CallbackInfoReturnable info) { - if (recipe instanceof UnknownReceipBookCategory) { - info.setReturnValue(RecipeBookCategories.UNKNOWN); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/FogRendererMixin.java b/src/main/java/org/betterx/bclib/mixin/client/FogRendererMixin.java deleted file mode 100644 index cd4e63ee..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/FogRendererMixin.java +++ /dev/null @@ -1,73 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.client.render.CustomFogRenderer; -import org.betterx.bclib.util.BackgroundInfo; - -import net.minecraft.client.Camera; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.FogRenderer; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.effect.MobEffects; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.material.FogType; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(FogRenderer.class) -public class FogRendererMixin { - @Shadow - private static float fogRed; - @Shadow - private static float fogGreen; - @Shadow - private static float fogBlue; - - @Inject(method = "setupColor", at = @At("RETURN")) - private static void bclib_onRender( - Camera camera, - float tickDelta, - ClientLevel world, - int i, - float f, - CallbackInfo info - ) { - FogType fogType = camera.getFluidInCamera(); - if (fogType != FogType.WATER && world.dimension().equals(Level.END)) { - Entity entity = camera.getEntity(); - boolean skip = false; - if (entity instanceof LivingEntity) { - MobEffectInstance effect = ((LivingEntity) entity).getEffect(MobEffects.NIGHT_VISION); - skip = effect != null && effect.getDuration() > 0; - } - if (!skip) { - fogRed *= 4; - fogGreen *= 4; - fogBlue *= 4; - } - } - - BackgroundInfo.fogColorRed = fogRed; - BackgroundInfo.fogColorGreen = fogGreen; - BackgroundInfo.fogColorBlue = fogBlue; - } - - @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) - private static void bclib_fogDensity( - Camera camera, - FogRenderer.FogMode fogMode, - float viewDistance, - boolean thickFog, - float g, - CallbackInfo ci - ) { - if (CustomFogRenderer.applyFogDensity(camera, viewDistance, thickFog)) { - ci.cancel(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/GameMixin.java b/src/main/java/org/betterx/bclib/mixin/client/GameMixin.java deleted file mode 100644 index bf4ba667..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/GameMixin.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; - -import net.minecraft.client.Game; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(Game.class) -public class GameMixin { - - @Inject(method = "onStartGameSession", at = @At("TAIL")) - public void bclib_onStart(CallbackInfo ci) { - DataExchangeAPI.sendOnEnter(); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/MinecraftMixin.java b/src/main/java/org/betterx/bclib/mixin/client/MinecraftMixin.java deleted file mode 100644 index d306bfa9..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/MinecraftMixin.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.interfaces.CustomColorProvider; -import org.betterx.bclib.networking.VersionCheckerClient; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.color.item.ItemColors; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.main.GameConfig; -import net.minecraft.core.Registry; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import org.jetbrains.annotations.Nullable; - -@Mixin(Minecraft.class) -public abstract class MinecraftMixin { - @Final - @Shadow - private BlockColors blockColors; - - @Final - @Shadow - private ItemColors itemColors; - - - @Shadow - @Nullable - public Screen screen; - - @Inject(method = "*", at = @At("TAIL")) - private void bclib_onMCInit(GameConfig args, CallbackInfo info) { - Registry.BLOCK.forEach(block -> { - if (block instanceof CustomColorProvider provider) { - blockColors.register(provider.getProvider(), block); - itemColors.register(provider.getItemProvider(), block.asItem()); - } - }); - - VersionCheckerClient.presentUpdateScreen(screen); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/org/betterx/bclib/mixin/client/ModelBakeryMixin.java deleted file mode 100644 index 4d0ae211..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/ModelBakeryMixin.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.api.v2.ModIntegrationAPI; -import org.betterx.bclib.client.models.CustomModelBakery; - -import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.resources.model.ModelBakery; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.profiling.ProfilerFiller; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.Map; - -@Mixin(ModelBakery.class) -public abstract class ModelBakeryMixin { - @Final - @Shadow - private Map unbakedCache; - - @Inject(method = "*", at = @At("TAIL")) - private void bclib_findEmissiveModels( - ResourceManager resourceManager, - BlockColors blockColors, - ProfilerFiller profiler, - int mipmap, - CallbackInfo info - ) { - //CustomModelBakery.setModelsLoaded(false); - if (ModIntegrationAPI.hasCanvas()) { - CustomModelBakery.loadEmissiveModels(unbakedCache); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/ModelManagerMixin.java b/src/main/java/org/betterx/bclib/mixin/client/ModelManagerMixin.java deleted file mode 100644 index 89b0feb7..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/ModelManagerMixin.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.client.BCLibClient; - -import net.minecraft.client.resources.model.ModelBakery; -import net.minecraft.client.resources.model.ModelManager; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.profiling.ProfilerFiller; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(ModelManager.class) -public class ModelManagerMixin { - @Inject(method = "prepare", at = @At("HEAD")) - private void bclib_loadCustomModels( - ResourceManager resourceManager, - ProfilerFiller profilerFiller, - CallbackInfoReturnable info - ) { - BCLibClient.modelBakery.loadCustomModels(resourceManager); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/MultiPackResourceManagerMixin.java b/src/main/java/org/betterx/bclib/mixin/client/MultiPackResourceManagerMixin.java deleted file mode 100644 index 728a02e7..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/MultiPackResourceManagerMixin.java +++ /dev/null @@ -1,58 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.ModIntegrationAPI; -import org.betterx.bclib.client.render.EmissiveTextureInfo; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.FallbackResourceManager; -import net.minecraft.server.packs.resources.MultiPackResourceManager; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.io.IOException; -import java.util.Map; - -@Mixin(MultiPackResourceManager.class) -public class MultiPackResourceManagerMixin { - @Final - @Shadow - private Map namespacedManagers; - - private final ResourceLocation bclib_alphaEmissionMaterial = BCLib.makeID("materialmaps/block/alpha_emission.json"); - - @Inject(method = "getResource", at = @At("HEAD"), cancellable = true) - private void bclib_getResource( - ResourceLocation resourceLocation, - CallbackInfoReturnable info - ) throws IOException { - if (!ModIntegrationAPI.hasCanvas()) { - return; - } - if (!resourceLocation.getPath().startsWith("materialmaps")) { - return; - } - if (!resourceLocation.getPath().contains("/block/")) { - return; - } - - String name = resourceLocation.getPath().replace("materialmaps/block/", "").replace(".json", ""); - ResourceLocation blockID = new ResourceLocation(resourceLocation.getNamespace(), name); - - if (!EmissiveTextureInfo.isEmissiveBlock(blockID)) { - return; - } - - ResourceManager resourceManager = this.namespacedManagers.get(resourceLocation.getNamespace()); - if (resourceManager != null && resourceManager.getResource(resourceLocation).isEmpty()) { - info.setReturnValue(resourceManager.getResource(bclib_alphaEmissionMaterial).get()); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/PresetEditorMixin.java b/src/main/java/org/betterx/bclib/mixin/client/PresetEditorMixin.java deleted file mode 100644 index 694741e8..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/PresetEditorMixin.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import net.minecraft.client.gui.screens.worldselection.PresetEditor; - -import com.google.common.collect.Maps; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -import java.util.Map; - - -@Mixin(PresetEditor.class) -interface PresetEditorMixin { - //Make Sure the PresetEditor.EDITORS Field is a mutable List. Allows us to add new Custom WorldPreset UIs in - //WorldPresetsUI - @Redirect(method = "", at = @At(value = "INVOKE", target = "Ljava/util/Map;of(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)Ljava/util/Map;")) - private static Map bcl_foo(K k1, V v1, K k2, V v2) { - Map a = Maps.newHashMap(); - a.put(k1, v1); - a.put(k2, v2); - return a; - } - -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/mixin/client/SignEditScreenMixin.java b/src/main/java/org/betterx/bclib/mixin/client/SignEditScreenMixin.java deleted file mode 100644 index 2a8e10a1..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/SignEditScreenMixin.java +++ /dev/null @@ -1,80 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.blocks.BaseSignBlock; -import org.betterx.bclib.client.render.BaseSignBlockEntityRenderer; - -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.VertexConsumer; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.inventory.SignEditScreen; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.blockentity.SignRenderer; -import net.minecraft.network.chat.Component; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.SignBlockEntity; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.At.Shift; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.LocalCapture; - -@Mixin(SignEditScreen.class) -public abstract class SignEditScreenMixin extends Screen { - @Shadow - @Final - private SignBlockEntity sign; - @Shadow - private SignRenderer.SignModel signModel; - @Unique - private boolean bclib_renderStick; - @Unique - private boolean bclib_isSign; - - protected SignEditScreenMixin(Component component) { - super(component); - } - - @Inject(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;IIF)V", locals = LocalCapture.CAPTURE_FAILSOFT, at = @At(ordinal = 1, - value = "INVOKE", - target = "Lcom/mojang/blaze3d/vertex/PoseStack;pushPose()V", - shift = Shift.BEFORE - )) - private void bclib_checkOffset( - PoseStack poseStack, - int i, - int j, - float f, - CallbackInfo ci, - float g, - BlockState blockState, - boolean bl, - boolean bl2, - float h - ) { - bclib_isSign = blockState.getBlock() instanceof BaseSignBlock; - if (bclib_isSign) { - bclib_renderStick = blockState.getValue(BaseSignBlock.FLOOR); - if (bclib_renderStick) { - poseStack.translate(0.0, 0.3125, 0.0); - } - } - } - - @ModifyArg(method = "render(Lcom/mojang/blaze3d/vertex/PoseStack;IIF)V", at = @At(value = "INVOKE", target = "Lnet/minecraft/client/model/geom/ModelPart;render(Lcom/mojang/blaze3d/vertex/PoseStack;Lcom/mojang/blaze3d/vertex/VertexConsumer;II)V"), index = 1) - private VertexConsumer bclib_signRender(VertexConsumer consumer) { - if (bclib_isSign) { - signModel.stick.visible = bclib_renderStick; - Block block = sign.getBlockState().getBlock(); - MultiBufferSource.BufferSource bufferSource = this.minecraft.renderBuffers().bufferSource(); - return BaseSignBlockEntityRenderer.getConsumer(bufferSource, block); - } - return consumer; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/TextureAtlasMixin.java b/src/main/java/org/betterx/bclib/mixin/client/TextureAtlasMixin.java deleted file mode 100644 index 3ef912b8..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/TextureAtlasMixin.java +++ /dev/null @@ -1,114 +0,0 @@ -package org.betterx.bclib.mixin.client; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.client.render.EmissiveTextureInfo; - -import com.mojang.blaze3d.platform.NativeImage; -import net.minecraft.client.renderer.texture.TextureAtlas; -import net.minecraft.client.renderer.texture.TextureAtlasSprite; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; - -import net.fabricmc.fabric.impl.client.texture.FabricSprite; -import net.fabricmc.loader.api.FabricLoader; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.io.IOException; -import java.util.Optional; - -@Mixin(TextureAtlas.class) -public class TextureAtlasMixin { - private static final int EMISSIVE_ALPHA = 254 << 24; - private boolean bclib_modifyAtlas; - - @Inject(method = "*", at = @At("TAIL")) - private void bclib_onAtlasInit(ResourceLocation resourceLocation, CallbackInfo info) { - boolean hasOptifine = FabricLoader.getInstance().isModLoaded("optifabric"); - bclib_modifyAtlas = !hasOptifine && resourceLocation.toString().equals("minecraft:textures/atlas/blocks.png"); - if (bclib_modifyAtlas) { - EmissiveTextureInfo.clear(); - } - } - - @Inject(method = "load(Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/client/renderer/texture/TextureAtlasSprite$Info;IIIII)Lnet/minecraft/client/renderer/texture/TextureAtlasSprite;", at = @At("HEAD"), cancellable = true) - private void bclib_loadSprite( - ResourceManager resourceManager, - TextureAtlasSprite.Info spriteInfo, - int atlasWidth, - int atlasHeight, - int maxLevel, - int posX, - int posY, - CallbackInfoReturnable info - ) { - if (!bclib_modifyAtlas) { - return; - } - - ResourceLocation location = spriteInfo.name(); - if (!location.getPath().startsWith("block")) { - return; - } - - ResourceLocation emissiveLocation = new ResourceLocation( - location.getNamespace(), - "textures/" + location.getPath() + "_e.png" - ); - Optional emissiveRes = resourceManager.getResource(emissiveLocation); - if (emissiveRes.isPresent()) { - NativeImage sprite = null; - NativeImage emission = null; - try { - ResourceLocation spriteLocation = new ResourceLocation( - location.getNamespace(), - "textures/" + location.getPath() + ".png" - ); - Resource resource = resourceManager.getResource(spriteLocation).orElse(null); - sprite = NativeImage.read(resource.open()); - - resource = emissiveRes.get(); - emission = NativeImage.read(resource.open()); - } catch (IOException e) { - BCLib.LOGGER.warning(e.getMessage()); - } - if (sprite != null && emission != null) { - int width = Math.min(sprite.getWidth(), emission.getWidth()); - int height = Math.min(sprite.getHeight(), emission.getHeight()); - for (int x = 0; x < width; x++) { - for (int y = 0; y < height; y++) { - int argb = emission.getPixelRGBA(x, y); - int alpha = (argb >> 24) & 255; - if (alpha > 127) { - int r = (argb >> 16) & 255; - int g = (argb >> 8) & 255; - int b = argb & 255; - if (r > 0 || g > 0 || b > 0) { - argb = (argb & 0x00FFFFFF) | EMISSIVE_ALPHA; - sprite.setPixelRGBA(x, y, argb); - } - } - } - } - TextureAtlas self = (TextureAtlas) (Object) this; - FabricSprite result = new FabricSprite( - self, - spriteInfo, - maxLevel, - atlasWidth, - atlasHeight, - posX, - posY, - sprite - ); - EmissiveTextureInfo.addTexture(location); - info.setReturnValue(result); - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/client/boat/BoatRendererMixin.java b/src/main/java/org/betterx/bclib/mixin/client/boat/BoatRendererMixin.java deleted file mode 100644 index 62da3630..00000000 --- a/src/main/java/org/betterx/bclib/mixin/client/boat/BoatRendererMixin.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.betterx.bclib.mixin.client.boat; - - -import org.betterx.bclib.items.boat.BoatTypeOverride; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.renderer.MultiBufferSource; -import net.minecraft.client.renderer.entity.BoatRenderer; -import net.minecraft.client.renderer.entity.EntityRenderer; -import net.minecraft.client.renderer.entity.EntityRendererProvider; -import net.minecraft.world.entity.vehicle.Boat; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(BoatRenderer.class) -public abstract class BoatRendererMixin extends EntityRenderer { - protected BoatRendererMixin(EntityRendererProvider.Context context) { - super(context); - } - - @Inject(method = "", at = @At("TAIL")) - private void bcl_init(EntityRendererProvider.Context context, boolean bl, CallbackInfo ci) { - BoatTypeOverride.values().forEach(type -> type.createBoatModels(context)); - } - - @Inject(method = "render(Lnet/minecraft/world/entity/vehicle/Boat;FFLcom/mojang/blaze3d/vertex/PoseStack;Lnet/minecraft/client/renderer/MultiBufferSource;I)V", at = @At("HEAD"), cancellable = true) - void bcl_render( - Boat boat, - float f, float g, - PoseStack poseStack, MultiBufferSource multiBufferSource, - int i, - CallbackInfo ci - ) { - if (org.betterx.bclib.client.render.BoatRenderer.render(boat, f, g, poseStack, multiBufferSource, i)) { - super.render(boat, f, g, poseStack, multiBufferSource, i); - ci.cancel(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/AnvilBlockMixin.java b/src/main/java/org/betterx/bclib/mixin/common/AnvilBlockMixin.java deleted file mode 100644 index 7a85d149..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/AnvilBlockMixin.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.blocks.BaseAnvilBlock; - -import net.minecraft.world.level.block.AnvilBlock; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(AnvilBlock.class) -public class AnvilBlockMixin { - @Inject(method = "damage", at = @At("HEAD"), cancellable = true) - private static void bclib_anvilDamage(BlockState state, CallbackInfoReturnable info) { - if (state.getBlock() instanceof BaseAnvilBlock) { - BaseAnvilBlock anvil = (BaseAnvilBlock) state.getBlock(); - info.setReturnValue(anvil.damageAnvilFall(state)); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/org/betterx/bclib/mixin/common/AnvilMenuMixin.java deleted file mode 100644 index 8004c532..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/AnvilMenuMixin.java +++ /dev/null @@ -1,186 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.blocks.BaseAnvilBlock; -import org.betterx.bclib.blocks.LeveledAnvilBlock; -import org.betterx.bclib.interfaces.AnvilScreenHandlerExtended; -import org.betterx.bclib.recipes.AnvilRecipe; - -import net.minecraft.core.BlockPos; -import net.minecraft.tags.BlockTags; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.*; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.LevelEvent; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; -import org.jetbrains.annotations.Nullable; - -@Mixin(AnvilMenu.class) -public abstract class AnvilMenuMixin extends ItemCombinerMenu implements AnvilScreenHandlerExtended { - private List be_recipes = Collections.emptyList(); - private AnvilRecipe be_currentRecipe; - private DataSlot anvilLevel; - - @Shadow - private int repairItemCountCost; - - @Final - @Shadow - private DataSlot cost; - - public AnvilMenuMixin( - @Nullable MenuType menuType, - int i, - Inventory inventory, - ContainerLevelAccess containerLevelAccess - ) { - super(menuType, i, inventory, containerLevelAccess); - } - - @Inject(method = "(ILnet/minecraft/world/entity/player/Inventory;Lnet/minecraft/world/inventory/ContainerLevelAccess;)V", at = @At("TAIL")) - public void be_initAnvilLevel(int syncId, Inventory inventory, ContainerLevelAccess context, CallbackInfo info) { - this.anvilLevel = addDataSlot(DataSlot.standalone()); - if (context != ContainerLevelAccess.NULL) { - int level = context.evaluate((world, blockPos) -> { - Block anvilBlock = world.getBlockState(blockPos).getBlock(); - return LeveledAnvilBlock.getAnvilCraftingLevel(anvilBlock); - }, 0); - anvilLevel.set(level); - } else { - anvilLevel.set(0); - } - } - - @Shadow - public abstract void createResult(); - - @Inject(method = "mayPickup", at = @At("HEAD"), cancellable = true) - protected void be_canTakeOutput(Player player, boolean present, CallbackInfoReturnable info) { - if (be_currentRecipe != null) { - info.setReturnValue(be_currentRecipe.checkHammerDurability(inputSlots, player)); - } - } - - @Inject(method = "method_24922", at = @At(value = "HEAD"), cancellable = true) - private static void bclib_onDamageAnvil(Player player, Level level, BlockPos blockPos, CallbackInfo ci) { - BlockState blockState = level.getBlockState(blockPos); - if (blockState.getBlock() instanceof BaseAnvilBlock anvil) { - BlockState damaged = anvil.damageAnvilUse(blockState, player.getRandom()); - bcl_destroyWhenNull(level, blockPos, damaged); - ci.cancel(); - } - } - - private static void bcl_destroyWhenNull(Level level, BlockPos blockPos, BlockState damaged) { - if (damaged == null) { - level.removeBlock(blockPos, false); - level.levelEvent(LevelEvent.SOUND_ANVIL_BROKEN, blockPos, 0); - } else { - level.setBlock(blockPos, damaged, 2); - level.levelEvent(LevelEvent.SOUND_ANVIL_USED, blockPos, 0); - } - } - - @Inject(method = "onTake", at = @At("HEAD"), cancellable = true) - protected void bclib_onTakeAnvilOutput(Player player, ItemStack stack, CallbackInfo info) { - if (be_currentRecipe != null) { - final int ingredientSlot = AnvilRecipe.getIngredientSlot(inputSlots); - - inputSlots.getItem(ingredientSlot).shrink(be_currentRecipe.getInputCount()); - stack = be_currentRecipe.craft(inputSlots, player); - slotsChanged(inputSlots); - access.execute((level, blockPos) -> { - final BlockState anvilState = level.getBlockState(blockPos); - final Block anvilBlock = anvilState.getBlock(); - if (anvilBlock instanceof BaseAnvilBlock) { - final BaseAnvilBlock anvil = (BaseAnvilBlock) anvilBlock; - if (!player.getAbilities().instabuild && anvilState.is(BlockTags.ANVIL) && player.getRandom() - .nextDouble() < 0.1) { - BlockState damagedState = anvil.damageAnvilUse(anvilState, player.getRandom()); - bcl_destroyWhenNull(level, blockPos, damagedState); - } else { - level.levelEvent(LevelEvent.SOUND_ANVIL_USED, blockPos, 0); - } - } - }); - info.cancel(); - } - } - - @Inject(method = "createResult", at = @At("HEAD"), cancellable = true) - public void be_updateOutput(CallbackInfo info) { - RecipeManager recipeManager = this.player.level.getRecipeManager(); - be_recipes = recipeManager.getRecipesFor(AnvilRecipe.TYPE, inputSlots, player.level); - if (be_recipes.size() > 0) { - int anvilLevel = this.anvilLevel.get(); - be_recipes = be_recipes.stream() - .filter(recipe -> anvilLevel >= recipe.getAnvilLevel()) - .collect(Collectors.toList()); - if (be_recipes.size() > 0) { - if (be_currentRecipe == null || !be_recipes.contains(be_currentRecipe)) { - be_currentRecipe = be_recipes.get(0); - } - be_updateResult(); - info.cancel(); - } else { - be_currentRecipe = null; - } - } - } - - @Inject(method = "setItemName", at = @At("HEAD"), cancellable = true) - public void be_setNewItemName(String string, CallbackInfo info) { - if (be_currentRecipe != null) { - info.cancel(); - } - } - - @Override - public boolean clickMenuButton(Player player, int id) { - if (id == 0) { - be_previousRecipe(); - return true; - } else if (id == 1) { - be_nextRecipe(); - return true; - } - return super.clickMenuButton(player, id); - } - - private void be_updateResult() { - if (be_currentRecipe == null) return; - resultSlots.setItem(0, be_currentRecipe.assemble(inputSlots)); - broadcastChanges(); - } - - @Override - public void be_updateCurrentRecipe(AnvilRecipe recipe) { - this.be_currentRecipe = recipe; - be_updateResult(); - } - - @Override - public AnvilRecipe be_getCurrentRecipe() { - return be_currentRecipe; - } - - @Override - public List be_getRecipes() { - return be_recipes; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/BiomeGenerationSettingsAccessor.java b/src/main/java/org/betterx/bclib/mixin/common/BiomeGenerationSettingsAccessor.java deleted file mode 100644 index 15c80ed4..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/BiomeGenerationSettingsAccessor.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.core.HolderSet; -import net.minecraft.world.level.biome.BiomeGenerationSettings; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; -import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; -import net.minecraft.world.level.levelgen.placement.PlacedFeature; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; - -@Mixin(BiomeGenerationSettings.class) -public interface BiomeGenerationSettingsAccessor { - @Accessor("features") - List> bclib_getFeatures(); - - @Accessor("features") - @Mutable - void bclib_setFeatures(List> value); - - @Accessor("featureSet") - void bclib_setFeatureSet(Supplier> featureSet); - - @Accessor("flowerFeatures") - void bclib_setFlowerFeatures(Supplier>> flowerFeatures); - - @Accessor("carvers") - Map>> bclib_getCarvers(); - - @Accessor("carvers") - void bclib_setCarvers(Map>> features); -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/BiomeMixin.java b/src/main/java/org/betterx/bclib/mixin/common/BiomeMixin.java deleted file mode 100644 index bcade6fd..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/BiomeMixin.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.world.level.biome.Biome; - -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(Biome.class) -public class BiomeMixin { -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/BiomeSourceMixin.java b/src/main/java/org/betterx/bclib/mixin/common/BiomeSourceMixin.java deleted file mode 100644 index f1580e32..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/BiomeSourceMixin.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.interfaces.BiomeSourceAccessor; - -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.BiomeSource; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; -import java.util.Set; - -@Mixin(BiomeSource.class) -public abstract class BiomeSourceMixin implements BiomeSourceAccessor { - - @Shadow - public abstract Set possibleBiomes(); - - public void bclRebuildFeatures() { - //Feature sorting is now a task in ChunkGenerator - BCLib.LOGGER.info("Rebuilding features in BiomeSource " + this); - //featuresPerStep = Suppliers.memoize(() -> FeatureSorter.buildFeaturesPerStep(this.possibleBiomes().stream().toList(), true)); - } - - @Inject(method = "(Ljava/util/List;)V", at = @At("TAIL")) - public void bcl_init(List list, CallbackInfo ci) { -// System.out.println("new BiomeSource (" + Integer.toHexString(hashCode()) + ", biomes=" + possibleBiomes().size() + ")"); -// if (possibleBiomes().size() == 27) { -// System.out.println("Nether????"); -// } else if (possibleBiomes().size() == 2) { -// System.out.println("Datapack Nether???"); -// } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/BoneMealItemMixin.java b/src/main/java/org/betterx/bclib/mixin/common/BoneMealItemMixin.java deleted file mode 100644 index 9ed3f337..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/BoneMealItemMixin.java +++ /dev/null @@ -1,169 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.BonemealAPI; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.bclib.util.BlocksHelper; -import org.betterx.bclib.util.MHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.core.Vec3i; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.item.BoneMealItem; -import net.minecraft.world.item.context.UseOnContext; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.Property; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Unique; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.function.BiConsumer; - -@Mixin(BoneMealItem.class) -public class BoneMealItemMixin { - @Unique - private static final MutableBlockPos BCLIB_BLOCK_POS = new MutableBlockPos(); - - @Inject(method = "useOn", at = @At("HEAD"), cancellable = true) - private void bclib_onUse(UseOnContext context, CallbackInfoReturnable info) { - Level world = context.getLevel(); - BlockPos blockPos = context.getClickedPos(); - if (!world.isClientSide()) { - if (BonemealAPI.isTerrain(world.getBlockState(blockPos).getBlock())) { - boolean consume = false; - if (BonemealAPI.isSpreadableTerrain(world.getBlockState(blockPos).getBlock())) { - BlockState terrain = bclib_getSpreadable(world, blockPos); - if (terrain != null) { - BlocksHelper.setWithoutUpdate(world, blockPos, terrain); - consume = true; - } - } else { - BlockState stateAbove = world.getBlockState(blockPos.above()); - if (!stateAbove.getFluidState().isEmpty()) { - if (stateAbove.is(Blocks.WATER)) { - consume = bclib_growWaterGrass(world, blockPos); - } - } else if (stateAbove.isAir()) { - consume = bclib_growLandGrass(world, blockPos); - } - } - if (consume) { - if (!context.getPlayer().isCreative()) { - context.getItemInHand().shrink(1); - } - world.levelEvent(2005, blockPos, 0); - info.setReturnValue(InteractionResult.SUCCESS); - info.cancel(); - } - } - } - } - - @Unique - private boolean bclib_growLandGrass(Level level, BlockPos pos) { - int y1 = pos.getY() + 3; - int y2 = pos.getY() - 3; - boolean result = false; - for (byte i = 0; i < 64; i++) { - int x = (int) (pos.getX() + level.random.nextGaussian() * 2); - int z = (int) (pos.getZ() + level.random.nextGaussian() * 2); - BCLIB_BLOCK_POS.setX(x); - BCLIB_BLOCK_POS.setZ(z); - for (int y = y1; y >= y2; y--) { - BCLIB_BLOCK_POS.setY(y); - BlockPos down = BCLIB_BLOCK_POS.below(); - if (level.isEmptyBlock(BCLIB_BLOCK_POS) && !level.isEmptyBlock(down)) { - BiConsumer grass = bclib_getLandGrassState(level, down); - if (grass != null) { - grass.accept(level, BCLIB_BLOCK_POS); - result = true; - } - break; - } - } - } - return result; - } - - @Unique - private boolean bclib_growWaterGrass(Level level, BlockPos pos) { - int y1 = pos.getY() + 3; - int y2 = pos.getY() - 3; - boolean result = false; - for (byte i = 0; i < 64; i++) { - int x = (int) (pos.getX() + level.random.nextGaussian() * 2); - int z = (int) (pos.getZ() + level.random.nextGaussian() * 2); - BCLIB_BLOCK_POS.setX(x); - BCLIB_BLOCK_POS.setZ(z); - for (int y = y1; y >= y2; y--) { - BCLIB_BLOCK_POS.setY(y); - BlockPos down = BCLIB_BLOCK_POS.below(); - if (BlocksHelper.isFluid(level.getBlockState(BCLIB_BLOCK_POS)) && !BlocksHelper.isFluid(level.getBlockState( - down))) { - BiConsumer grass = bclib_getWaterGrassState(level, down); - if (grass != null) { - grass.accept(level, BCLIB_BLOCK_POS); - result = true; - } - break; - } - } - } - return result; - } - - @Unique - private BiConsumer bclib_getLandGrassState(Level level, BlockPos pos) { - BlockState state = level.getBlockState(pos); - return BonemealAPI.getLandGrass(BiomeAPI.getBiomeID(level.getBiome(pos)), state.getBlock(), level.getRandom()); - } - - @Unique - private BiConsumer bclib_getWaterGrassState(Level level, BlockPos pos) { - BlockState state = level.getBlockState(pos); - return BonemealAPI.getWaterGrass(BiomeAPI.getBiomeID(level.getBiome(pos)), state.getBlock(), level.getRandom()); - } - - @Unique - private BlockState bclib_getSpreadable(Level level, BlockPos pos) { - Vec3i[] offsets = MHelper.getOffsets(level.getRandom()); - BlockState center = level.getBlockState(pos); - for (Vec3i dir : offsets) { - BlockPos p = pos.offset(dir); - BlockState state = level.getBlockState(p); - Block terrain = BonemealAPI.getSpreadable(state.getBlock()); - if (center.is(terrain)) { - if (bclib_haveSameProperties(state, center)) { - for (Property property : center.getProperties()) { - state = state.setValue(property, center.getValue(property)); - } - } - return state; - } - } - return null; - } - - @Unique - private boolean bclib_haveSameProperties(BlockState state1, BlockState state2) { - Property[] properties1 = state1.getProperties().toArray(new Property[0]); - Property[] properties2 = state2.getProperties().toArray(new Property[0]); - if (properties1.length != properties2.length) { - return false; - } - for (int i = 0; i < properties1.length; i++) { - String name1 = properties1[i].getName(); - String name2 = properties2[i].getName(); - if (!name1.equals(name2)) { - return false; - } - } - return true; - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/mixin/common/BuiltinRegistriesMixin.java b/src/main/java/org/betterx/bclib/mixin/common/BuiltinRegistriesMixin.java deleted file mode 100644 index b5733252..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/BuiltinRegistriesMixin.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; - -import com.mojang.serialization.Lifecycle; -import net.minecraft.core.MappedRegistry; -import net.minecraft.core.Registry; -import net.minecraft.core.WritableRegistry; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceKey; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(BuiltinRegistries.class) -public abstract class BuiltinRegistriesMixin { - @Shadow - protected static > R internalRegister( - ResourceKey> resourceKey, - R writableRegistry, - BuiltinRegistries.RegistryBootstrap registryBootstrap, - Lifecycle lifecycle - ) { - throw new RuntimeException("Shadowed Call"); - } - - //this needs to be added BEFORE the WORLD_PRESET-Registry. Otherwise decoding will fail! - @Inject(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/data/BuiltinRegistries;registerSimple(Lnet/minecraft/resources/ResourceKey;Lnet/minecraft/data/BuiltinRegistries$RegistryBootstrap;)Lnet/minecraft/core/Registry;", ordinal = 0)) - private static void bcl_registerBuiltin(CallbackInfo ci) { - BCLBiomeRegistry.BUILTIN_BCL_BIOMES = internalRegister( - BCLBiomeRegistry.BCL_BIOMES_REGISTRY, - (MappedRegistry) BCLBiomeRegistry.BUILTIN_BCL_BIOMES, - BCLBiomeRegistry::bootstrap, - Lifecycle.stable() - ); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorAccessor.java b/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorAccessor.java deleted file mode 100644 index 39a8e25e..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorAccessor.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.FeatureSorter; -import net.minecraft.world.level.chunk.ChunkGenerator; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.List; -import java.util.function.Supplier; - -@Mixin(ChunkGenerator.class) -public interface ChunkGeneratorAccessor { - @Accessor("biomeSource") - @Mutable - void bcl_setBiomeSource(BiomeSource biomeSource); - - @Accessor("featuresPerStep") - @Mutable - void bcl_setFeaturesPerStep(Supplier> supplier); -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorMixin.java b/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorMixin.java deleted file mode 100644 index cd726c4b..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorMixin.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.interfaces.ChunkGeneratorAccessor; - -import net.minecraft.core.Registry; -import net.minecraft.world.level.StructureManager; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.structure.StructureSet; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(ChunkGenerator.class) -public class ChunkGeneratorMixin implements ChunkGeneratorAccessor { - @Shadow - @Final - protected Registry structureSets; - private int bclib_featureIteratorSeed; - - - @ModifyArg(method = "applyBiomeDecoration", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/WorldgenRandom;setFeatureSeed(JII)V")) - private long bclib_updateFeatureSeed(long seed) { - return Long.rotateRight(seed, bclib_featureIteratorSeed++); - } - - @Inject(method = "applyBiomeDecoration", at = @At("HEAD")) - private void bclib_obBiomeGenerate( - WorldGenLevel worldGenLevel, - ChunkAccess chunkAccess, - StructureManager structureFeatureManager, - CallbackInfo ci - ) { - bclib_featureIteratorSeed = 0; - } - - public Registry bclib_getStructureSetsRegistry() { - return structureSets; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorsMixin.java b/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorsMixin.java deleted file mode 100644 index f7602586..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/ChunkGeneratorsMixin.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.generator.BCLChunkGenerator; - -import com.mojang.serialization.Codec; -import net.minecraft.core.Registry; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.chunk.ChunkGenerators; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(ChunkGenerators.class) -public class ChunkGeneratorsMixin { - @Inject(method = "bootstrap", at = @At(value = "HEAD")) - private static void bcl_bootstrap( - Registry> registry, - CallbackInfoReturnable> cir - ) { - Registry.register(registry, BCLib.makeID("betterx"), BCLChunkGenerator.CODEC); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/CraftingMenuMixin.java b/src/main/java/org/betterx/bclib/mixin/common/CraftingMenuMixin.java deleted file mode 100644 index 6854d7b0..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/CraftingMenuMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.ContainerLevelAccess; -import net.minecraft.world.inventory.CraftingMenu; -import net.minecraft.world.level.block.CraftingTableBlock; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(CraftingMenu.class) -public abstract class CraftingMenuMixin { - @Final - @Shadow - private ContainerLevelAccess access; - - @Inject(method = "stillValid", at = @At("HEAD"), cancellable = true) - private void bclib_stillValid(Player player, CallbackInfoReturnable info) { - if (access.evaluate((world, pos) -> { - BlockState state = world.getBlockState(pos); - return state.getBlock() instanceof CraftingTableBlock || state.is(CommonBlockTags.WORKBENCHES); - }, true)) { - info.setReturnValue(true); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/DiggerItemMixin.java b/src/main/java/org/betterx/bclib/mixin/common/DiggerItemMixin.java deleted file mode 100644 index 1fa10a78..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/DiggerItemMixin.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.DiggerItemSpeed; - -import net.minecraft.world.item.DiggerItem; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Optional; - -@Mixin(DiggerItem.class) -public class DiggerItemMixin { - @Inject(method = "getDestroySpeed", at = @At(value = "RETURN"), cancellable = true) - void bn_getDestroySpeed(ItemStack stack, BlockState state, CallbackInfoReturnable cir) { - final Optional newSpeed = DiggerItemSpeed.getModifiedSpeed(stack, state, cir.getReturnValue()); - if (newSpeed.isPresent()) { - cir.setReturnValue(newSpeed.get()); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/DimensionTypeMixin.java b/src/main/java/org/betterx/bclib/mixin/common/DimensionTypeMixin.java deleted file mode 100644 index 34ce1afb..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/DimensionTypeMixin.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.core.WritableRegistry; -import net.minecraft.world.level.dimension.DimensionType; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(DimensionType.class) -public class DimensionTypeMixin { - // @Inject( -// method = "defaultDimensions(Lnet/minecraft/core/RegistryAccess;JZ)Lnet/minecraft/core/Registry;", -// locals = LocalCapture.CAPTURE_FAILHARD, -// at = @At("TAIL") -// ) - private static void bclib_updateDimensions( - RegistryAccess registryAccess, - long seed, - boolean bl, - CallbackInfoReturnable info, - WritableRegistry writableRegistry, - Registry registry, - Registry biomeRegistry, - Registry structureRegistry, - Registry noiseSettingsRegistry, - Registry noiseParamRegistry - ) { - //This probably moved to WorldPresets.bootstrap(); -// int id = writableRegistry.getId(writableRegistry.get(LevelStem.NETHER)); -// writableRegistry.registerOrOverride( -// OptionalInt.of(id), -// LevelStem.NETHER, -// new LevelStem( -// registry.getOrCreateHolder(BuiltinDimensionTypes.NETHER), -// new NoiseBasedChunkGenerator( -// structureRegistry, -// noiseParamRegistry, -// new BCLibNetherBiomeSource(biomeRegistry, seed), -// seed, -// noiseSettingsRegistry.getOrCreateHolder(NoiseGeneratorSettings.NETHER)) -// ), -// Lifecycle.stable() -// ); -// -// -// id = writableRegistry.getId(writableRegistry.get(LevelStem.END)); -// writableRegistry.registerOrOverride( -// OptionalInt.of(id), -// LevelStem.END, -// new LevelStem( -// registry.getOrCreateHolder(BuiltinDimensionTypes.END), -// new NoiseBasedChunkGenerator( -// structureRegistry, -// noiseParamRegistry, -// new BCLibEndBiomeSource(biomeRegistry, seed), -// seed, -// noiseSettingsRegistry.getOrCreateHolder(NoiseGeneratorSettings.END)) -// ), -// Lifecycle.stable() -// ); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/EnchantingTableBlockMixin.java b/src/main/java/org/betterx/bclib/mixin/common/EnchantingTableBlockMixin.java deleted file mode 100644 index cc72f506..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/EnchantingTableBlockMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.EnchantmentTableBlock; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(EnchantmentTableBlock.class) -public abstract class EnchantingTableBlockMixin extends Block { - public EnchantingTableBlockMixin(Properties settings) { - super(settings); - } - - @Inject(method = "isValidBookShelf(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/core/BlockPos;)Z", at = @At("HEAD"), cancellable = true) - private static void bclib_isBookshelf( - Level level, - BlockPos tablePos, - BlockPos delta, - CallbackInfoReturnable info - ) { - if (level.getBlockState(tablePos.offset(delta)).is(CommonBlockTags.BOOKSHELVES) - && level.isEmptyBlock(tablePos.offset(delta.getX() / 2, delta.getY(), delta.getZ() / 2))) { - info.setReturnValue(true); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/ItemStackMixin.java b/src/main/java/org/betterx/bclib/mixin/common/ItemStackMixin.java deleted file mode 100644 index 19f1b440..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/ItemStackMixin.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.util.MethodReplace; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.function.Function; - -@Mixin(ItemStack.class) -public class ItemStackMixin { - @Inject(method = "is(Lnet/minecraft/world/item/Item;)Z", at = @At("HEAD"), cancellable = true) - private void bclib_replaceFunction(Item item, CallbackInfoReturnable info) { - Function replacement = MethodReplace.getItemReplace(item); - if (replacement != null) { - info.setReturnValue(replacement.apply(ItemStack.class.cast(this))); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/LayerLightSectionStorageMixin.java b/src/main/java/org/betterx/bclib/mixin/common/LayerLightSectionStorageMixin.java deleted file mode 100644 index e2948d5b..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/LayerLightSectionStorageMixin.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.SectionPos; -import net.minecraft.world.level.chunk.DataLayer; -import net.minecraft.world.level.lighting.LayerLightSectionStorage; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(LayerLightSectionStorage.class) -public class LayerLightSectionStorageMixin { - @Shadow - protected DataLayer getDataLayer(long sectionPos, boolean cached) { - return null; - } - - @Inject(method = "getStoredLevel", at = @At(value = "HEAD"), cancellable = true) - private void bclib_lightFix(long blockPos, CallbackInfoReturnable info) { - try { - long pos = SectionPos.blockToSection(blockPos); - DataLayer dataLayer = this.getDataLayer(pos, true); - info.setReturnValue(dataLayer.get( - SectionPos.sectionRelative(BlockPos.getX(blockPos)), - SectionPos.sectionRelative(BlockPos.getY(blockPos)), - SectionPos.sectionRelative(BlockPos.getZ(blockPos)) - )); - } catch (Exception e) { - info.setReturnValue(0); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/LootPoolMixin.java b/src/main/java/org/betterx/bclib/mixin/common/LootPoolMixin.java deleted file mode 100644 index a0cbd667..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/LootPoolMixin.java +++ /dev/null @@ -1,59 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.interfaces.LootPoolAccessor; - -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.LootPool; -import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; -import net.minecraft.world.level.storage.loot.functions.LootItemFunction; -import net.minecraft.world.level.storage.loot.predicates.LootItemCondition; -import net.minecraft.world.level.storage.loot.providers.number.NumberProvider; - -import com.google.common.collect.Lists; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Predicate; - -@Mixin(LootPool.class) -public class LootPoolMixin implements LootPoolAccessor { - @Shadow - @Final - public LootPoolEntryContainer[] entries; - @Shadow - @Final - public LootItemCondition[] conditions; - @Shadow - @Final - private Predicate compositeCondition; - @Shadow - @Final - public LootItemFunction[] functions; - @Shadow - @Final - private BiFunction compositeFunction; - @Shadow - @Final - public NumberProvider rolls; - @Shadow - @Final - public NumberProvider bonusRolls; - - @Override - public LootPool bcl_mergeEntries(List newEntries) { - final List merged = Lists.newArrayList(entries); - merged.addAll(newEntries); - - return new LootPool( - merged.toArray(new LootPoolEntryContainer[0]), - this.conditions, - this.functions, - this.rolls, - this.bonusRolls - ); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/org/betterx/bclib/mixin/common/MinecraftServerMixin.java deleted file mode 100644 index 429e315c..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/MinecraftServerMixin.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.recipes.BCLRecipeManager; - -import net.minecraft.server.MinecraftServer; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Collection; -import java.util.concurrent.CompletableFuture; - -@Mixin(value = MinecraftServer.class) -public class MinecraftServerMixin { - @Shadow - private MinecraftServer.ReloadableResources resources; - - - @Inject(method = "reloadResources", at = @At(value = "RETURN"), cancellable = true) - private void bclib_reloadResources( - Collection collection, - CallbackInfoReturnable> info - ) { - bclib_injectRecipes(); - } - - @Inject(method = "loadLevel", at = @At(value = "RETURN"), cancellable = true) - private void bclib_loadLevel(CallbackInfo info) { - bclib_injectRecipes(); - } - - private void bclib_injectRecipes() { - RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.managers().getRecipeManager(); - accessor.bclib_setRecipesByName(BCLRecipeManager.getMapByName(accessor.bclib_getRecipesByName())); - accessor.bclib_setRecipes(BCLRecipeManager.getMap(accessor.bclib_getRecipes())); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/MobSpawnSettingsAccessor.java b/src/main/java/org/betterx/bclib/mixin/common/MobSpawnSettingsAccessor.java deleted file mode 100644 index 7207fcff..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/MobSpawnSettingsAccessor.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.util.random.WeightedRandomList; -import net.minecraft.world.entity.MobCategory; -import net.minecraft.world.level.biome.MobSpawnSettings; -import net.minecraft.world.level.biome.MobSpawnSettings.SpawnerData; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Mutable; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Map; - -@Mixin(MobSpawnSettings.class) -public interface MobSpawnSettingsAccessor { - @Accessor("spawners") - Map> bcl_getSpawners(); - - @Accessor("spawners") - @Mutable - void bcl_setSpawners(Map> spawners); -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/MultiPackResourceManagerMixin.java b/src/main/java/org/betterx/bclib/mixin/common/MultiPackResourceManagerMixin.java deleted file mode 100644 index f6ed11c6..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/MultiPackResourceManagerMixin.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.MultiPackResourceManager; -import net.minecraft.server.packs.resources.Resource; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Optional; - -@Mixin(MultiPackResourceManager.class) -public class MultiPackResourceManagerMixin { - private static final String[] BCLIB_MISSING_RESOURCES = new String[]{ - "dimension/the_end.json", - "dimension/the_nether.json", - "dimension_type/the_end.json", - "dimension_type/the_nether.json" - }; - - @Inject(method = "getResource", at = @At("HEAD"), cancellable = true) - private void bclib_hasResource(ResourceLocation resourceLocation, CallbackInfoReturnable> info) { - if (resourceLocation.getNamespace().equals("minecraft")) { - for (String key : BCLIB_MISSING_RESOURCES) { - if (resourceLocation.getPath().equals(key)) { -// info.setReturnValue(Optional.empty()); -// info.cancel(); - return; - } - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/NoiseBasedChunkGeneratorMixin.java b/src/main/java/org/betterx/bclib/mixin/common/NoiseBasedChunkGeneratorMixin.java deleted file mode 100644 index eeb56c85..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/NoiseBasedChunkGeneratorMixin.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.interfaces.NoiseGeneratorSettingsProvider; -import org.betterx.bclib.interfaces.SurfaceProvider; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; -import net.minecraft.world.level.levelgen.synth.NormalNoise; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; - -@Mixin(NoiseBasedChunkGenerator.class) -public abstract class NoiseBasedChunkGeneratorMixin implements SurfaceProvider, NoiseGeneratorSettingsProvider { - @Final - @Shadow - protected Holder settings; - - @Shadow - @Final - private Registry noises; - - @Override - public NoiseGeneratorSettings bclib_getNoiseGeneratorSettings() { - return settings.value(); - } - - @Override - public Holder bclib_getNoiseGeneratorSettingHolders() { - return settings; - } - - @Override - public Registry bclib_getNoises() { - return noises; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/PistonBaseBlockMixin.java b/src/main/java/org/betterx/bclib/mixin/common/PistonBaseBlockMixin.java deleted file mode 100644 index 1401045b..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/PistonBaseBlockMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.piston.PistonBaseBlock; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(PistonBaseBlock.class) -public class PistonBaseBlockMixin { - @Inject(method = "isPushable", at = @At("HEAD"), cancellable = true) - private static void bclib_isPushable( - BlockState blockState, - Level level, - BlockPos blockPos, - Direction direction, - boolean bl, - Direction direction2, - CallbackInfoReturnable cir - ) { - if (blockState.is(CommonBlockTags.IMMOBILE)) { - cir.setReturnValue(false); - cir.cancel(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/PlacementContextMixin.java b/src/main/java/org/betterx/bclib/mixin/common/PlacementContextMixin.java deleted file mode 100644 index d6bc7828..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/PlacementContextMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.levelgen.placement.PlacementContext; - -import org.spongepowered.asm.mixin.Mixin; - -@Mixin(PlacementContext.class) -public class PlacementContextMixin implements org.betterx.bclib.interfaces.BCLPlacementContext { - private Rotation bcl_rotation = Rotation.NONE; - private Mirror bcl_mirror = Mirror.NONE; - - - @Override - public Rotation bcl_getRotation() { - return bcl_rotation; - } - - @Override - public void bcl_setRotation(Rotation bcl_rotation) { - this.bcl_rotation = bcl_rotation; - } - - @Override - public Mirror bcl_getMirror() { - return bcl_mirror; - } - - @Override - public void bcl_setMirror(Mirror bcl_mirror) { - this.bcl_mirror = bcl_mirror; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/PoiTypeMixin.java b/src/main/java/org/betterx/bclib/mixin/common/PoiTypeMixin.java deleted file mode 100644 index 6a081e01..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/PoiTypeMixin.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.poi.PoiTypeExtension; - -import net.minecraft.tags.TagKey; -import net.minecraft.world.entity.ai.village.poi.PoiType; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(PoiType.class) -public class PoiTypeMixin implements PoiTypeExtension { - private TagKey bcl_tag = null; - - - @Inject(method = "is", cancellable = true, at = @At("HEAD")) - void bcl_is(BlockState blockState, CallbackInfoReturnable cir) { - if (bcl_tag != null && blockState.is(bcl_tag)) { - cir.setReturnValue(true); - } - } - - public void bcl_setTag(TagKey tag) { - bcl_tag = tag; - } - - public TagKey bcl_getTag() { - return bcl_tag; - } - -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/PortalShapeMixin.java b/src/main/java/org/betterx/bclib/mixin/common/PortalShapeMixin.java deleted file mode 100644 index 6d3957f7..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/PortalShapeMixin.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.block.state.BlockBehaviour.StatePredicate; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.portal.PortalShape; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; - -@Mixin(PortalShape.class) -public class PortalShapeMixin { - @Redirect(method = "getDistanceUntilEdgeAboveFrame", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockBehaviour$StatePredicate;test(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z")) - private boolean be_getDistanceUntilEdgeAboveFrame( - StatePredicate statePredicate, - BlockState blockState, - BlockGetter blockGetter, - BlockPos blockPos - ) { - return be_FRAME(statePredicate, blockState, blockGetter, blockPos); - } - - @Redirect(method = "hasTopFrame", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockBehaviour$StatePredicate;test(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z")) - private boolean be_hasTopFrame( - StatePredicate statePredicate, - BlockState blockState, - BlockGetter blockGetter, - BlockPos blockPos - ) { - return be_FRAME(statePredicate, blockState, blockGetter, blockPos); - } - - @Redirect(method = "getDistanceUntilTop", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/block/state/BlockBehaviour$StatePredicate;test(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/BlockGetter;Lnet/minecraft/core/BlockPos;)Z")) - private boolean be_getDistanceUntilTop( - StatePredicate statePredicate, - BlockState blockState, - BlockGetter blockGetter, - BlockPos blockPos - ) { - return be_FRAME(statePredicate, blockState, blockGetter, blockPos); - } - - private static boolean be_FRAME(StatePredicate FRAME, BlockState state, BlockGetter getter, BlockPos pos) { - return state.is(CommonBlockTags.NETHER_PORTAL_FRAME) || FRAME.test(state, getter, pos); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/RecipeManagerAccessor.java b/src/main/java/org/betterx/bclib/mixin/common/RecipeManagerAccessor.java deleted file mode 100644 index 197a9d46..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/RecipeManagerAccessor.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraft.world.item.crafting.RecipeType; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Map; - -@Mixin(RecipeManager.class) -public interface RecipeManagerAccessor { - @Accessor("recipes") - > Map, Map> bclib_getRecipes(); - - @Accessor("recipes") - > void bclib_setRecipes(Map, Map> recipes); - - @Accessor("byName") - > Map bclib_getRecipesByName(); - - @Accessor("byName") - > void bclib_setRecipesByName(Map recipes); -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/mixin/common/RecipeManagerMixin.java b/src/main/java/org/betterx/bclib/mixin/common/RecipeManagerMixin.java deleted file mode 100644 index 5e5af94c..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/RecipeManagerMixin.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.recipes.BCLRecipeManager; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.Level; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Map; -import java.util.Optional; - -@Mixin(RecipeManager.class) -public abstract class RecipeManagerMixin { - @Shadow - protected abstract > Map byType(RecipeType recipeType); - - @Inject(method = "getRecipeFor", at = @At(value = "HEAD"), cancellable = true) - private > void bclib_getRecipeFor( - RecipeType type, - C inventory, - Level level, - CallbackInfoReturnable> info - ) { - info.setReturnValue(BCLRecipeManager.getSortedRecipe(type, inventory, level, this::byType)); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/mixin/common/RecipeMixin.java b/src/main/java/org/betterx/bclib/mixin/common/RecipeMixin.java deleted file mode 100644 index 1df41cdd..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/RecipeMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.core.NonNullList; -import net.minecraft.world.Container; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.PotionItem; -import net.minecraft.world.item.alchemy.PotionUtils; -import net.minecraft.world.item.alchemy.Potions; -import net.minecraft.world.item.crafting.Recipe; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(Recipe.class) -public interface RecipeMixin { - //Water Bottles are potions and they do not return an empty bottle in crafting Recipes - //This mixin will fix that behaviour - - @Inject(method = "getRemainingItems", at = @At("RETURN")) - default void bcl_getRemainingItems(C container, CallbackInfoReturnable> cir) { - NonNullList remaining = cir.getReturnValue(); - - for (int i = 0; i < remaining.size(); ++i) { - ItemStack stack = container.getItem(i); - if (stack.getItem() instanceof PotionItem pi) { - if (PotionUtils.getPotion(stack) == Potions.WATER) - remaining.set(i, new ItemStack(Items.GLASS_BOTTLE)); - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/RegistryAccessMixin.java b/src/main/java/org/betterx/bclib/mixin/common/RegistryAccessMixin.java deleted file mode 100644 index 79b6478e..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/RegistryAccessMixin.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiomeRegistry; -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeData; - -import com.mojang.serialization.Codec; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.resources.ResourceKey; - -import com.google.common.collect.ImmutableMap; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; - -import java.util.Map; -import java.util.function.Supplier; - -@Mixin(RegistryAccess.class) -public interface RegistryAccessMixin { - - @ModifyArg(method = "", at = @At(value = "INVOKE", target = "Lnet/minecraft/Util;make(Ljava/util/function/Supplier;)Ljava/lang/Object;")) - private static Supplier>, RegistryAccess.RegistryData>> together_addRegistry( - Supplier>, RegistryAccess.RegistryData>> supplier - ) { - return () -> { - ImmutableMap.Builder>, RegistryAccess.RegistryData> builder = ImmutableMap.builder(); - //Make sure this gets added before WORLD_PRESETS - put(builder, BCLBiomeRegistry.BCL_BIOMES_REGISTRY, BiomeData.CODEC); - - Map>, RegistryAccess.RegistryData> res = supplier.get(); - builder.putAll(res); - - return builder.build(); - }; - } - - @Shadow - static void put( - ImmutableMap.Builder>, RegistryAccess.RegistryData> builder, - ResourceKey> resourceKey, - Codec codec - ) { - throw new RuntimeException("Shadowed Call"); - } - -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/ServerAdvancementManagerMixin.java b/src/main/java/org/betterx/bclib/mixin/common/ServerAdvancementManagerMixin.java deleted file mode 100644 index 5dad6785..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/ServerAdvancementManagerMixin.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.advancement.AdvancementManager; - -import net.minecraft.advancements.Advancement; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.ServerAdvancementManager; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; - -import java.util.Map; - -@Mixin(ServerAdvancementManager.class) -public class ServerAdvancementManagerMixin { - @ModifyArg(method = "apply(Ljava/util/Map;Lnet/minecraft/server/packs/resources/ResourceManager;Lnet/minecraft/util/profiling/ProfilerFiller;)V", - at = @At(value = "INVOKE", target = "Lnet/minecraft/advancements/AdvancementList;add(Ljava/util/Map;)V")) - public Map bcl_interceptApply(Map map) { - AdvancementManager.addAdvancements(map); - return map; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/org/betterx/bclib/mixin/common/ServerLevelMixin.java deleted file mode 100644 index b85859e9..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/ServerLevelMixin.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.LifeCycleAPI; -import org.betterx.worlds.together.world.BiomeSourceWithNoiseRelatedSettings; -import org.betterx.worlds.together.world.BiomeSourceWithSeed; - -import net.minecraft.core.Holder; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.progress.ChunkProgressListener; -import net.minecraft.util.profiling.ProfilerFiller; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; -import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; -import net.minecraft.world.level.storage.ServerLevelData; -import net.minecraft.world.level.storage.WritableLevelData; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -import java.util.List; -import java.util.concurrent.Executor; -import java.util.function.Supplier; - -@Mixin(ServerLevel.class) -public abstract class ServerLevelMixin extends Level { - private static String bclib_lastWorld = null; - - protected ServerLevelMixin( - WritableLevelData writableLevelData, - ResourceKey resourceKey, - Holder holder, - Supplier supplier, - boolean bl, - boolean bl2, - long l, - int i - ) { - super(writableLevelData, resourceKey, holder, supplier, bl, bl2, l, i); - } - - - @Inject(method = "*", at = @At("TAIL")) - private void bclib_onServerWorldInit( - MinecraftServer server, - Executor executor, - LevelStorageAccess levelStorageAccess, - ServerLevelData serverLevelData, - ResourceKey resourceKey, - LevelStem levelStem, - ChunkProgressListener chunkProgressListener, - boolean bl, - long l, - List list, - boolean bl2, - CallbackInfo ci - ) { - ServerLevel level = ServerLevel.class.cast(this); - LifeCycleAPI._runLevelLoad( - level, - server, - executor, - levelStorageAccess, - serverLevelData, - resourceKey, - chunkProgressListener, - bl, - l, - list, - bl2 - ); - - if (levelStem.generator().getBiomeSource() instanceof BiomeSourceWithSeed source) { - source.setSeed(level.getSeed()); - } - - if (levelStem.generator().getBiomeSource() instanceof BiomeSourceWithNoiseRelatedSettings bcl - && levelStem.generator() instanceof NoiseBasedChunkGenerator noiseGenerator) { - bcl.onLoadGeneratorSettings(noiseGenerator.generatorSettings().value()); - } - - if (bclib_lastWorld != null && bclib_lastWorld.equals(levelStorageAccess.getLevelId())) { - return; - } - - bclib_lastWorld = levelStorageAccess.getLevelId(); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/ShovelItemAccessor.java b/src/main/java/org/betterx/bclib/mixin/common/ShovelItemAccessor.java deleted file mode 100644 index 6f9bd859..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/ShovelItemAccessor.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.world.item.ShovelItem; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.Map; - -@Mixin(ShovelItem.class) -public interface ShovelItemAccessor { - @Accessor("FLATTENABLES") - static Map bclib_getFlattenables() { - throw new AssertionError("@Accessor dummy body called"); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/StructuresAccessor.java b/src/main/java/org/betterx/bclib/mixin/common/StructuresAccessor.java deleted file mode 100644 index 463ebc03..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/StructuresAccessor.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.core.Holder; -import net.minecraft.data.worldgen.Structures; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.levelgen.structure.Structure; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; - -@Mixin(Structures.class) -public interface StructuresAccessor { - @Invoker - static Holder callRegister(ResourceKey resourceKey, Structure structure) { - throw new RuntimeException("Unexpected call"); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/SurfaceRulesContextAccessor.java b/src/main/java/org/betterx/bclib/mixin/common/SurfaceRulesContextAccessor.java deleted file mode 100644 index 0b7ffcfd..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/SurfaceRulesContextAccessor.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.core.Holder; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.chunk.ChunkAccess; -import net.minecraft.world.level.levelgen.NoiseChunk; -import net.minecraft.world.level.levelgen.RandomState; -import net.minecraft.world.level.levelgen.SurfaceRules; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Accessor; - -import java.util.function.Supplier; - -@Mixin(SurfaceRules.Context.class) -public interface SurfaceRulesContextAccessor { - @Accessor("blockX") - int getBlockX(); - - @Accessor("blockY") - int getBlockY(); - - @Accessor("blockZ") - int getBlockZ(); - - @Accessor("surfaceDepth") - int getSurfaceDepth(); - - @Accessor("biome") - Supplier> getBiome(); - - @Accessor("chunk") - ChunkAccess getChunk(); - - @Accessor("noiseChunk") - NoiseChunk getNoiseChunk(); - - @Accessor("stoneDepthAbove") - int getStoneDepthAbove(); - - @Accessor("stoneDepthBelow") - int getStoneDepthBelow(); - - @Accessor("lastUpdateY") - long getLastUpdateY(); - - @Accessor("lastUpdateXZ") - long getLastUpdateXZ(); - - @Accessor("randomState") - RandomState getRandomState(); -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/TheEndBiomesMixin.java b/src/main/java/org/betterx/bclib/mixin/common/TheEndBiomesMixin.java deleted file mode 100644 index 7a3aa38b..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/TheEndBiomesMixin.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import org.betterx.bclib.api.v2.generator.TheEndBiomesHelper; -import org.betterx.bclib.api.v2.levelgen.biomes.BCLBiome; -import org.betterx.bclib.api.v2.levelgen.biomes.InternalBiomeAPI; - -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; - -import net.fabricmc.fabric.api.biome.v1.TheEndBiomes; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(value = TheEndBiomes.class, remap = false) -public class TheEndBiomesMixin { - @Inject(method = "addBarrensBiome", at = @At("HEAD")) - private static void bcl_registerBarrens( - ResourceKey highlands, - ResourceKey barrens, - double weight, - CallbackInfo ci - ) { - TheEndBiomesHelper.add(InternalBiomeAPI.OTHER_END_BARRENS, barrens); - } - - @Inject(method = "addMidlandsBiome", at = @At("HEAD")) - private static void bcl_registerMidlands( - ResourceKey highlands, - ResourceKey midlands, - double weight, - CallbackInfo ci - ) { - BCLBiome highland = InternalBiomeAPI.wrapNativeBiome(highlands, InternalBiomeAPI.OTHER_END_LAND); - BCLBiome midland = InternalBiomeAPI.wrapNativeBiome(midlands, InternalBiomeAPI.OTHER_END_LAND); - if (highland != null) { - highland.addEdge(midland); - } - TheEndBiomesHelper.add(InternalBiomeAPI.OTHER_END_LAND, midlands); - } - - @Inject(method = "addSmallIslandsBiome", at = @At("HEAD")) - private static void bcl_registerSmallIslands( - ResourceKey biome, double weight, CallbackInfo ci - ) { - TheEndBiomesHelper.add(InternalBiomeAPI.OTHER_END_VOID, biome); - } - - @Inject(method = "addHighlandsBiome", at = @At("HEAD")) - private static void bcl_registerHighlands( - ResourceKey biome, double weight, CallbackInfo ci - ) { - TheEndBiomesHelper.add(InternalBiomeAPI.OTHER_END_LAND, biome); - } - - @Inject(method = "addMainIslandBiome", at = @At("HEAD")) - private static void bcl_registerMainIsnalnd( - ResourceKey biome, double weight, CallbackInfo ci - ) { - TheEndBiomesHelper.add(InternalBiomeAPI.OTHER_END_CENTER, biome); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/WorldGenRegionMixin.java b/src/main/java/org/betterx/bclib/mixin/common/WorldGenRegionMixin.java deleted file mode 100644 index 3715b3fb..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/WorldGenRegionMixin.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.betterx.bclib.mixin.common; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.WorldGenRegion; -import net.minecraft.world.level.chunk.ChunkAccess; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(WorldGenRegion.class) -public class WorldGenRegionMixin { - @Final - @Shadow - private ChunkAccess center; - - //TODO: 1.19 Is it ok to remove this? - @Inject(method = "ensureCanWrite", at = @At("HEAD"), cancellable = true) - private void be_alterBlockCheck(BlockPos blockPos, CallbackInfoReturnable info) { - int x = blockPos.getX() >> 4; - int z = blockPos.getZ() >> 4; - WorldGenRegion region = (WorldGenRegion) (Object) this; - info.setReturnValue(Math.abs(x - center.getPos().x) < 2 && Math.abs(z - center.getPos().z) < 2); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/boat/BoatItemMixin.java b/src/main/java/org/betterx/bclib/mixin/common/boat/BoatItemMixin.java deleted file mode 100644 index e349d1b4..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/boat/BoatItemMixin.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.betterx.bclib.mixin.common.boat; - -import org.betterx.bclib.items.boat.CustomBoatTypeOverride; - -import net.minecraft.world.entity.Entity; -import net.minecraft.world.item.BoatItem; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; - -@Mixin(BoatItem.class) -public class BoatItemMixin { - @ModifyArg(method = "use", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;noCollision(Lnet/minecraft/world/entity/Entity;Lnet/minecraft/world/phys/AABB;)Z")) - Entity bcl_suse(Entity boat) { - if (this instanceof CustomBoatTypeOverride self) { - if (boat instanceof CustomBoatTypeOverride newBoat) { - newBoat.setCustomType(self.bcl_getCustomType()); - } - } - return boat; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/boat/BoatMixin.java b/src/main/java/org/betterx/bclib/mixin/common/boat/BoatMixin.java deleted file mode 100644 index 689f9cfd..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/boat/BoatMixin.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.betterx.bclib.mixin.common.boat; - -import org.betterx.bclib.items.boat.BoatTypeOverride; -import org.betterx.bclib.items.boat.CustomBoatTypeOverride; - -import net.minecraft.core.BlockPos; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.network.syncher.EntityDataAccessor; -import net.minecraft.world.entity.Entity; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.vehicle.Boat; -import net.minecraft.world.item.BoatItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.GameRules; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(Boat.class) -public abstract class BoatMixin extends Entity implements CustomBoatTypeOverride { - private BoatTypeOverride bcl_type = null; - @Shadow - @Final - private static EntityDataAccessor DATA_ID_TYPE; - - public BoatMixin(EntityType entityType, Level level) { - super(entityType, level); - } - - public void setCustomType(BoatTypeOverride type) { - bcl_type = type; - if (type == null) - this.entityData.set(DATA_ID_TYPE, Boat.Type.OAK.ordinal()); - else - this.entityData.set(DATA_ID_TYPE, bcl_type.ordinal()); - } - - public BoatTypeOverride bcl_getCustomType() { - bcl_type = BoatTypeOverride.byId(this.entityData.get(DATA_ID_TYPE)); - return bcl_type; - } - - @Inject(method = "setType", at = @At("HEAD"), cancellable = true) - void bcl_setType(Boat.Type type, CallbackInfo ci) { - if (bcl_type != null) { - this.entityData.set(DATA_ID_TYPE, bcl_type.ordinal()); - ci.cancel(); - } - } - - @Inject(method = "getBoatType", at = @At("HEAD"), cancellable = true) - void bcl_getBoatType(CallbackInfoReturnable cir) { - BoatTypeOverride type = BoatTypeOverride.byId(this.entityData.get(DATA_ID_TYPE)); - if (type != null) { - bcl_type = type; - cir.setReturnValue(Boat.Type.OAK); - } - } - - - @Inject(method = "addAdditionalSaveData", at = @At("HEAD")) - void bcl_addAdditionalSaveData(CompoundTag compoundTag, CallbackInfo ci) { - BoatTypeOverride type = this.bcl_getCustomType(); - if (type != null) { - compoundTag.putString("cType", type.name()); - } - } - - @Inject(method = "readAdditionalSaveData", at = @At("HEAD")) - void bcl_readAdditionalSaveData(CompoundTag compoundTag, CallbackInfo ci) { - if (compoundTag.contains("cType")) { - this.setCustomType(BoatTypeOverride.byName(compoundTag.getString("cType"))); - } else { - this.setCustomType(null); - } - } - - @Inject(method = "getDropItem", at = @At("HEAD"), cancellable = true) - void bcl_getDropItem(CallbackInfoReturnable cir) { - BoatTypeOverride type = this.bcl_getCustomType(); - if (type != null) { - BoatItem boat = type.getBoatItem(); - if (boat != null) { - cir.setReturnValue(boat); - } - } - } - - @Inject(method = "checkFallDamage", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/vehicle/Boat;kill()V", shift = At.Shift.AFTER), cancellable = true) - void bcl_checkFallDamage(double d, boolean bl, BlockState blockState, BlockPos blockPos, CallbackInfo ci) { - BoatTypeOverride type = this.bcl_getCustomType(); - if (type != null) { - if (this.level.getGameRules().getBoolean(GameRules.RULE_DOENTITYDROPS)) { - for (int i = 0; i < 3; ++i) { - this.spawnAtLocation(type.getPlanks()); - } - for (int i = 0; i < 2; ++i) { - this.spawnAtLocation(Items.STICK); - } - - this.resetFallDistance(); - ci.cancel(); - } - - - } - } - -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/boat/ChestBoatMixin.java b/src/main/java/org/betterx/bclib/mixin/common/boat/ChestBoatMixin.java deleted file mode 100644 index bdb8c552..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/boat/ChestBoatMixin.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.betterx.bclib.mixin.common.boat; - -import org.betterx.bclib.items.boat.BoatTypeOverride; -import org.betterx.bclib.items.boat.CustomBoatTypeOverride; - -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.entity.vehicle.ChestBoat; -import net.minecraft.world.item.BoatItem; -import net.minecraft.world.item.Item; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(ChestBoat.class) -public abstract class ChestBoatMixin { - @Shadow - public abstract InteractionResult interact(Player player, InteractionHand interactionHand); - - @Inject(method = "getDropItem", at = @At("HEAD"), cancellable = true) - void bcl_getDropItem(CallbackInfoReturnable cir) { - if (this instanceof CustomBoatTypeOverride cbto) { - BoatTypeOverride type = cbto.bcl_getCustomType(); - if (type != null) { - BoatItem boat = type.getChestBoatItem(); - if (boat != null) { - cir.setReturnValue(boat); - } - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/elytra/LivingEntityMixin.java b/src/main/java/org/betterx/bclib/mixin/common/elytra/LivingEntityMixin.java deleted file mode 100644 index 5a2e5825..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/elytra/LivingEntityMixin.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.betterx.bclib.mixin.common.elytra; - -import org.betterx.bclib.items.elytra.BCLElytraItem; -import org.betterx.bclib.items.elytra.BCLElytraUtils; - -import net.minecraft.world.entity.EquipmentSlot; -import net.minecraft.world.entity.LivingEntity; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.phys.Vec3; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import org.spongepowered.asm.mixin.injection.Slice; - -@Mixin(value = LivingEntity.class, priority = 199) -public abstract class LivingEntityMixin { - @Shadow - public abstract ItemStack getItemBySlot(EquipmentSlot equipmentSlot); - - @ModifyArg( - method = "travel", - slice = @Slice( - from = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;isFallFlying()Z"), - to = @At(value = "INVOKE:LAST", target = "Lnet/minecraft/world/entity/LivingEntity;setSharedFlag(IZ)V") - ), - at = @At(value = "INVOKE", target = "Lnet/minecraft/world/entity/LivingEntity;setDeltaMovement(Lnet/minecraft/world/phys/Vec3;)V") - ) - public Vec3 be_travel(Vec3 moveDelta) { - ItemStack itemStack; - if (BCLElytraUtils.slotProvider == null) itemStack = getItemBySlot(EquipmentSlot.CHEST); - else itemStack = BCLElytraUtils.slotProvider.getElytra((LivingEntity) (Object) this, this::getItemBySlot); - if (itemStack != null && itemStack.getItem() instanceof BCLElytraItem elytra) { - double movementFactor = elytra.getMovementFactor(); - moveDelta = moveDelta.multiply(movementFactor, 1.0D, movementFactor); - } - return moveDelta; - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/BeehiveBlockMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/BeehiveBlockMixin.java deleted file mode 100644 index 2e06db29..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/BeehiveBlockMixin.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.MethodReplace; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.BeehiveBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(BeehiveBlock.class) -public class BeehiveBlockMixin { - @Inject(method = "use(Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;Lnet/minecraft/world/phys/BlockHitResult;)Lnet/minecraft/world/InteractionResult;", at = @At("HEAD")) - private void bclib_isShears( - BlockState blockState, - Level level, - BlockPos blockPos, - Player player, - InteractionHand interactionHand, - BlockHitResult blockHitResult, - CallbackInfoReturnable info - ) { - MethodReplace.addItemReplace(Items.SHEARS, BaseShearsItem::isShear); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/DiggingEnchantmentMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/DiggingEnchantmentMixin.java deleted file mode 100644 index 779f8dfb..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/DiggingEnchantmentMixin.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.bclib.items.tool.BaseShearsItem; - -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.enchantment.DiggingEnchantment; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(DiggingEnchantment.class) -public class DiggingEnchantmentMixin { - @Inject(method = "canEnchant(Lnet/minecraft/world/item/ItemStack;)Z", at = @At("HEAD"), cancellable = true) - private void bclib_isShears(ItemStack itemStack, CallbackInfoReturnable info) { - if (BaseShearsItem.isShear(itemStack)) info.setReturnValue(true); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/ItemPredicateBuilderMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/ItemPredicateBuilderMixin.java deleted file mode 100644 index c9eff80e..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/ItemPredicateBuilderMixin.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.worlds.together.tag.v3.CommonItemTags; - -import net.minecraft.advancements.critereon.ItemPredicate; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; - -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -import java.util.Set; -import org.jetbrains.annotations.Nullable; - -@Mixin(ItemPredicate.class) -public abstract class ItemPredicateBuilderMixin { - @Shadow - @Final - private @Nullable Set items; - - @Inject(method = "matches", at = @At("HEAD"), cancellable = true) - void bclib_isShears(ItemStack itemStack, CallbackInfoReturnable info) { - if (this.items != null && this.items.size() == 1 && this.items.contains(Items.SHEARS)) { - if (itemStack.is(CommonItemTags.SHEARS)) { - info.setReturnValue(true); - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/MushroomCowMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/MushroomCowMixin.java deleted file mode 100644 index 0bd0580d..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/MushroomCowMixin.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.MethodReplace; - -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.animal.MushroomCow; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Items; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(MushroomCow.class) -public class MushroomCowMixin { - @Inject(method = "mobInteract(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;)Lnet/minecraft/world/InteractionResult;", at = @At("HEAD")) - private void bclib_isShears( - Player player, - InteractionHand interactionHand, - CallbackInfoReturnable info - ) { - MethodReplace.addItemReplace(Items.SHEARS, BaseShearsItem::isShear); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/PumpkinBlockMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/PumpkinBlockMixin.java deleted file mode 100644 index 41c1c43f..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/PumpkinBlockMixin.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.MethodReplace; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.PumpkinBlock; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.BlockHitResult; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(PumpkinBlock.class) -public abstract class PumpkinBlockMixin { - @Inject(method = "use", at = @At("HEAD")) - private void bclib_isShears( - BlockState blockState, - Level level, - BlockPos blockPos, - Player player, - InteractionHand interactionHand, - BlockHitResult blockHitResult, - CallbackInfoReturnable info - ) { - MethodReplace.addItemReplace(Items.SHEARS, BaseShearsItem::isShear); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/SheepMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/SheepMixin.java deleted file mode 100644 index 7727382e..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/SheepMixin.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.MethodReplace; - -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.animal.Sheep; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Items; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(Sheep.class) -public class SheepMixin { - @Inject(method = "mobInteract(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;)Lnet/minecraft/world/InteractionResult;", at = @At("HEAD")) - private void bclib_isShears( - Player player, - InteractionHand interactionHand, - CallbackInfoReturnable info - ) { - MethodReplace.addItemReplace(Items.SHEARS, BaseShearsItem::isShear); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/SnowGolemMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/SnowGolemMixin.java deleted file mode 100644 index afdd2c75..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/SnowGolemMixin.java +++ /dev/null @@ -1,27 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.MethodReplace; - -import net.minecraft.world.InteractionHand; -import net.minecraft.world.InteractionResult; -import net.minecraft.world.entity.animal.SnowGolem; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Items; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; - -@Mixin(SnowGolem.class) -public class SnowGolemMixin { - @Inject(method = "mobInteract(Lnet/minecraft/world/entity/player/Player;Lnet/minecraft/world/InteractionHand;)Lnet/minecraft/world/InteractionResult;", at = @At("HEAD")) - private void bclib_isShears( - Player player, - InteractionHand interactionHand, - CallbackInfoReturnable info - ) { - MethodReplace.addItemReplace(Items.SHEARS, BaseShearsItem::isShear); - } -} diff --git a/src/main/java/org/betterx/bclib/mixin/common/shears/TripWireBlockMixin.java b/src/main/java/org/betterx/bclib/mixin/common/shears/TripWireBlockMixin.java deleted file mode 100644 index 1ada450b..00000000 --- a/src/main/java/org/betterx/bclib/mixin/common/shears/TripWireBlockMixin.java +++ /dev/null @@ -1,30 +0,0 @@ -package org.betterx.bclib.mixin.common.shears; - -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.util.MethodReplace; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.TripWireBlock; -import net.minecraft.world.level.block.state.BlockState; - -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(TripWireBlock.class) -public class TripWireBlockMixin { - @Inject(method = "playerWillDestroy(Lnet/minecraft/world/level/Level;Lnet/minecraft/core/BlockPos;Lnet/minecraft/world/level/block/state/BlockState;Lnet/minecraft/world/entity/player/Player;)V", at = @At("HEAD")) - private void bclib_isShears( - Level level, - BlockPos blockPos, - BlockState blockState, - Player player, - CallbackInfo info - ) { - MethodReplace.addItemReplace(Items.SHEARS, BaseShearsItem::isShear); - } -} diff --git a/src/main/java/org/betterx/bclib/models/RecordItemModelProvider.java b/src/main/java/org/betterx/bclib/models/RecordItemModelProvider.java deleted file mode 100644 index 34d33e53..00000000 --- a/src/main/java/org/betterx/bclib/models/RecordItemModelProvider.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.betterx.bclib.models; - -import org.betterx.bclib.interfaces.ItemModelProvider; - -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.RecordItem; - -import java.util.HashMap; -import java.util.Map; -import org.jetbrains.annotations.ApiStatus; - -/** - * This was just added because the constructor of a RecordItem from 1.19 to 1.19.1 changed - * and we only need to add the {@link ItemModelProvider} interface. - *

- * In order to keep cross version compat for bclib we choose to use reflection to instanciate - * RecordItem, but we need an additional registry that will provide the {@link ItemModelProvider} - * for RecordItems. - *

- * This class (and and all according changes in - * {@link org.betterx.bclib.client.models.CustomModelBakery#loadCustomModels(ResourceManager)} can - * be abandoned when we drop support for 1.19. - */ -@ApiStatus.Internal -public class RecordItemModelProvider { - @ApiStatus.Internal - public static final ItemModelProvider DEFAULT_PROVIDER = new ItemModelProvider() { - }; - private static final Map PROIVDER_MAPPPING = new HashMap<>(); - - @ApiStatus.Internal - public static void add(RecordItem record) { - if (record != null) { - PROIVDER_MAPPPING.put(record, DEFAULT_PROVIDER); - } - } - - @ApiStatus.Internal - public static boolean has(Item i) { - return PROIVDER_MAPPPING.containsKey(i); - } - - @ApiStatus.Internal - public static ItemModelProvider get(Item i) { - return PROIVDER_MAPPPING.get(i); - } -} diff --git a/src/main/java/org/betterx/bclib/networking/VersionChecker.java b/src/main/java/org/betterx/bclib/networking/VersionChecker.java deleted file mode 100644 index e0c882b4..00000000 --- a/src/main/java/org/betterx/bclib/networking/VersionChecker.java +++ /dev/null @@ -1,157 +0,0 @@ -package org.betterx.bclib.networking; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.Configs; -import org.betterx.worlds.together.util.ModUtil; - -import net.fabricmc.loader.api.FabricLoader; - -import com.google.gson.Gson; - -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.LinkedList; -import java.util.List; - -public class VersionChecker implements Runnable { - @FunctionalInterface - public interface UpdateInfoProvider { - void send(String modID, String currentVersion, String newVersion); - } - - private static final List KNOWN_MODS = new LinkedList<>(); - private static final List NEW_VERSIONS = new LinkedList<>(); - - public static class ModVersion { - String n; - String v; - - @Override - public String toString() { - return n + ":" + v; - } - } - - public static class Versions { - String mc; - String loader; - List mods; - - @Override - public String toString() { - return "Versions{" + - "mc='" + mc + '\'' + - ", loader='" + loader + '\'' + - ", mods=" + mods + - '}'; - } - } - - public static final int WAIT_FOR_DAYS = 5; - private static final String BASE_URL = "https://wunderreich.ambertation.de/api/v1/versions/"; - private static Thread versionChecker; - - public static void startCheck(boolean isClient) { - if (versionChecker == null && isClient) { - if (Configs.CLIENT_CONFIG.checkVersions() && Configs.CLIENT_CONFIG.didShowWelcomeScreen()) { - versionChecker = new Thread(isClient ? new VersionCheckerClient() : new VersionChecker()); - versionChecker.start(); - } - } - } - - public static void registerMod(String modID) { - KNOWN_MODS.add(modID); - } - - boolean needRecheck() { - Instant lastCheck = Configs.CACHED_CONFIG.lastCheckDate().plus(WAIT_FOR_DAYS, ChronoUnit.DAYS); - Instant now = Instant.now(); - - return now.isAfter(lastCheck); - } - - @Override - public void run() { - Gson gson = new Gson(); - if (needRecheck()) { - String minecraftVersion = ModUtil.getModVersion("minecraft").replace(".", "_"); - BCLib.LOGGER.info("Check Versions for minecraft=" + minecraftVersion); - - try { - String fileName = "mc_fabric_" + URLEncoder.encode( - minecraftVersion, - StandardCharsets.ISO_8859_1.toString() - ) + ".json"; - - URL url = new URL(BASE_URL + fileName); - try (InputStreamReader reader = new InputStreamReader(url.openStream())) { - Versions json = gson.fromJson(reader, Versions.class); - String str = gson.getAdapter(Versions.class).toJson(json); - Configs.CACHED_CONFIG.setLastVersionJson(str); - Configs.CACHED_CONFIG.setLastCheckDate(); - Configs.CACHED_CONFIG.saveChanges(); - - processVersions(json); - } - } catch (UnsupportedEncodingException e) { - BCLib.LOGGER.error("Failed to encode URL during VersionCheck", e); - return; - } catch (MalformedURLException e) { - BCLib.LOGGER.error("Invalid URL during VersionCheck", e); - return; - } catch (IOException e) { - BCLib.LOGGER.error("I/O Error during VersionCheck", e); - return; - } - } else { - String str = Configs.CACHED_CONFIG.lastVersionJson(); - if (str != null && str.trim().length() > 0) { - Versions json = gson.fromJson(str, Versions.class); - processVersions(json); - } - } - } - - private void processVersions(Versions json) { - if (json != null) { - BCLib.LOGGER.info("Received Version Info for minecraft=" + json.mc + ", loader=" + json.loader); - if (json.mods != null) { - for (ModVersion mod : json.mods) { - if (!KNOWN_MODS.contains(mod.n)) { - if (FabricLoader.getInstance().getModContainer(mod.n).isPresent()) - registerMod(mod.n); - } - if (mod.n != null && mod.v != null && KNOWN_MODS.contains(mod.n)) { - String installedVersion = ModUtil.getModVersion(mod.n); - boolean isNew = ModUtil.isLargerVersion(mod.v, installedVersion) && !installedVersion.equals( - "0.0.0"); - BCLib.LOGGER.info(" - " + mod.n + ":" + mod.v + (isNew ? " (update available)" : "")); - if (isNew) - NEW_VERSIONS.add(mod); - } - } - } - } else { - BCLib.LOGGER.warning("No valid Version Info"); - } - } - - public static boolean isEmpty() { - return NEW_VERSIONS.isEmpty(); - } - - public static void forEachUpdate(UpdateInfoProvider consumer) { - for (ModVersion v : NEW_VERSIONS) { - String currrent = ModUtil.getModVersion(v.n); - consumer.send(v.n, currrent, v.v); - } - } -} diff --git a/src/main/java/org/betterx/bclib/networking/VersionCheckerClient.java b/src/main/java/org/betterx/bclib/networking/VersionCheckerClient.java deleted file mode 100644 index f6baae73..00000000 --- a/src/main/java/org/betterx/bclib/networking/VersionCheckerClient.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.networking; - -import org.betterx.bclib.client.gui.screens.UpdatesScreen; -import org.betterx.bclib.client.gui.screens.WelcomeScreen; -import org.betterx.bclib.config.Configs; - -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.screens.Screen; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class VersionCheckerClient extends VersionChecker { - - public static void presentUpdateScreen(Screen parent) { - if (!Configs.CLIENT_CONFIG.didShowWelcomeScreen()) { - Minecraft.getInstance().setScreen(new WelcomeScreen(parent)); - - } else if (Configs.CLIENT_CONFIG.showUpdateInfo() && !VersionChecker.isEmpty()) { - Minecraft.getInstance().setScreen(new UpdatesScreen(parent)); - } - } -} diff --git a/src/main/java/org/betterx/bclib/noise/Noises.java b/src/main/java/org/betterx/bclib/noise/Noises.java deleted file mode 100644 index 9022cbf7..00000000 --- a/src/main/java/org/betterx/bclib/noise/Noises.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.betterx.bclib.noise; - -import org.betterx.bclib.BCLib; - -import net.minecraft.core.Holder; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.resources.ResourceKey; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.synth.NormalNoise; - -import java.util.HashMap; -import java.util.Map; - -public class Noises { - private static final Map, NormalNoise> noiseIntances = new HashMap<>(); - public static final ResourceKey ROUGHNESS_NOISE = createKey(BCLib.makeID( - "roughness_noise")); - - public static ResourceKey createKey(ResourceLocation loc) { - return ResourceKey.create(Registry.NOISE_REGISTRY, loc); - } - - public static NormalNoise createNoise( - Registry registry, - RandomSource randomSource, - ResourceKey resourceKey - ) { - Holder holder = registry.getHolderOrThrow(resourceKey); - return NormalNoise.create(randomSource, holder.value()); - } - - public static NormalNoise getOrCreateNoise( - RegistryAccess registryAccess, - RandomSource randomSource, - ResourceKey noise - ) { - final Registry registry = registryAccess.registryOrThrow(Registry.NOISE_REGISTRY); - return noiseIntances.computeIfAbsent(noise, (key) -> createNoise(registry, randomSource, noise)); - } -} diff --git a/src/main/java/org/betterx/bclib/noise/OpenSimplexNoise.java b/src/main/java/org/betterx/bclib/noise/OpenSimplexNoise.java deleted file mode 100644 index 5c2f9956..00000000 --- a/src/main/java/org/betterx/bclib/noise/OpenSimplexNoise.java +++ /dev/null @@ -1,2528 +0,0 @@ -package org.betterx.bclib.noise; - -/* - * OpenSimplex Noise in Java. - * by Kurt Spencer - * - * v1.1 (October 5, 2014) - * - Added 2D and 4D implementations. - * - Proper gradient sets for all dimensions, from a - * dimensionally-generalizable scheme with an actual - * rhyme and reason behind it. - * - Removed default permutation array in favor of - * default seed. - * - Changed seed-based constructor to be independent - * of any particular randomization library, so results - * will be the same when ported to other languages. - */ - -public class OpenSimplexNoise { - private static final double STRETCH_CONSTANT_2D = -0.211324865405187; // (1/Math.sqrt(2+1)-1)/2; - private static final double SQUISH_CONSTANT_2D = 0.366025403784439; // (Math.sqrt(2+1)-1)/2; - private static final double STRETCH_CONSTANT_3D = -1.0 / 6; // (1/Math.sqrt(3+1)-1)/3; - private static final double SQUISH_CONSTANT_3D = 1.0 / 3; // (Math.sqrt(3+1)-1)/3; - private static final double STRETCH_CONSTANT_4D = -0.138196601125011; // (1/Math.sqrt(4+1)-1)/4; - private static final double SQUISH_CONSTANT_4D = 0.309016994374947; // (Math.sqrt(4+1)-1)/4; - - private static final double NORM_CONSTANT_2D = 47; - private static final double NORM_CONSTANT_3D = 103; - private static final double NORM_CONSTANT_4D = 30; - - private static final long DEFAULT_SEED = 0; - - private final short[] perm; - private final short[] permGradIndex3D; - - public OpenSimplexNoise() { - this(DEFAULT_SEED); - } - - public OpenSimplexNoise(short[] perm) { - this.perm = perm; - permGradIndex3D = new short[256]; - - for (int i = 0; i < 256; i++) { - // Since 3D has 24 gradients, simple bitmask won't work, so - // precompute modulo array. - permGradIndex3D[i] = (short) ((perm[i] % (gradients3D.length / 3)) * 3); - } - } - - // Initializes the class using a permutation array generated from a 64-bit - // seed. - // Generates a proper permutation (i.e. doesn't merely perform N successive - // pair swaps on a base array) - // Uses a simple 64-bit LCG. - public OpenSimplexNoise(long seed) { - perm = new short[256]; - permGradIndex3D = new short[256]; - short[] source = new short[256]; - for (short i = 0; i < 256; i++) { - source[i] = i; - } - seed = seed * 6364136223846793005l + 1442695040888963407l; - seed = seed * 6364136223846793005l + 1442695040888963407l; - seed = seed * 6364136223846793005l + 1442695040888963407l; - for (int i = 255; i >= 0; i--) { - seed = seed * 6364136223846793005l + 1442695040888963407l; - int r = (int) ((seed + 31) % (i + 1)); - if (r < 0) r += (i + 1); - perm[i] = source[r]; - permGradIndex3D[i] = (short) ((perm[i] % (gradients3D.length / 3)) * 3); - source[r] = source[i]; - } - } - - // 2D OpenSimplex Noise. - public double eval(double x, double y) { - - // Place input coordinates onto grid. - double stretchOffset = (x + y) * STRETCH_CONSTANT_2D; - double xs = x + stretchOffset; - double ys = y + stretchOffset; - - // Floor to get grid coordinates of rhombus (stretched square) - // super-cell origin. - int xsb = fastFloor(xs); - int ysb = fastFloor(ys); - - // Skew out to get actual coordinates of rhombus origin. We'll need - // these later. - double squishOffset = (xsb + ysb) * SQUISH_CONSTANT_2D; - double xb = xsb + squishOffset; - double yb = ysb + squishOffset; - - // Compute grid coordinates relative to rhombus origin. - double xins = xs - xsb; - double yins = ys - ysb; - - // Sum those together to get a value that determines which region we're - // in. - double inSum = xins + yins; - - // Positions relative to origin point. - double dx0 = x - xb; - double dy0 = y - yb; - - // We'll be defining these inside the next block and using them - // afterwards. - double dx_ext, dy_ext; - int xsv_ext, ysv_ext; - - double value = 0; - - // Contribution (1,0) - double dx1 = dx0 - 1 - SQUISH_CONSTANT_2D; - double dy1 = dy0 - 0 - SQUISH_CONSTANT_2D; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, dx1, dy1); - } - - // Contribution (0,1) - double dx2 = dx0 - 0 - SQUISH_CONSTANT_2D; - double dy2 = dy0 - 1 - SQUISH_CONSTANT_2D; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, dx2, dy2); - } - - if (inSum <= 1) { // We're inside the triangle (2-Simplex) at (0,0) - double zins = 1 - inSum; - if (zins > xins || zins > yins) { // (0,0) is one of the closest two - // triangular vertices - if (xins > yins) { - xsv_ext = xsb + 1; - ysv_ext = ysb - 1; - dx_ext = dx0 - 1; - dy_ext = dy0 + 1; - } else { - xsv_ext = xsb - 1; - ysv_ext = ysb + 1; - dx_ext = dx0 + 1; - dy_ext = dy0 - 1; - } - } else { // (1,0) and (0,1) are the closest two vertices. - xsv_ext = xsb + 1; - ysv_ext = ysb + 1; - dx_ext = dx0 - 1 - 2 * SQUISH_CONSTANT_2D; - dy_ext = dy0 - 1 - 2 * SQUISH_CONSTANT_2D; - } - } else { // We're inside the triangle (2-Simplex) at (1,1) - double zins = 2 - inSum; - if (zins < xins || zins < yins) { // (0,0) is one of the closest two - // triangular vertices - if (xins > yins) { - xsv_ext = xsb + 2; - ysv_ext = ysb + 0; - dx_ext = dx0 - 2 - 2 * SQUISH_CONSTANT_2D; - dy_ext = dy0 + 0 - 2 * SQUISH_CONSTANT_2D; - } else { - xsv_ext = xsb + 0; - ysv_ext = ysb + 2; - dx_ext = dx0 + 0 - 2 * SQUISH_CONSTANT_2D; - dy_ext = dy0 - 2 - 2 * SQUISH_CONSTANT_2D; - } - } else { // (1,0) and (0,1) are the closest two vertices. - dx_ext = dx0; - dy_ext = dy0; - xsv_ext = xsb; - ysv_ext = ysb; - } - xsb += 1; - ysb += 1; - dx0 = dx0 - 1 - 2 * SQUISH_CONSTANT_2D; - dy0 = dy0 - 1 - 2 * SQUISH_CONSTANT_2D; - } - - // Contribution (0,0) or (1,1) - double attn0 = 2 - dx0 * dx0 - dy0 * dy0; - if (attn0 > 0) { - attn0 *= attn0; - value += attn0 * attn0 * extrapolate(xsb, ysb, dx0, dy0); - } - - // Extra Vertex - double attn_ext = 2 - dx_ext * dx_ext - dy_ext * dy_ext; - if (attn_ext > 0) { - attn_ext *= attn_ext; - value += attn_ext * attn_ext * extrapolate(xsv_ext, ysv_ext, dx_ext, dy_ext); - } - - return value / NORM_CONSTANT_2D; - } - - // 3D OpenSimplex Noise. - public double eval(double x, double y, double z) { - - // Place input coordinates on simplectic honeycomb. - double stretchOffset = (x + y + z) * STRETCH_CONSTANT_3D; - double xs = x + stretchOffset; - double ys = y + stretchOffset; - double zs = z + stretchOffset; - - // Floor to get simplectic honeycomb coordinates of rhombohedron - // (stretched cube) super-cell origin. - int xsb = fastFloor(xs); - int ysb = fastFloor(ys); - int zsb = fastFloor(zs); - - // Skew out to get actual coordinates of rhombohedron origin. We'll need - // these later. - double squishOffset = (xsb + ysb + zsb) * SQUISH_CONSTANT_3D; - double xb = xsb + squishOffset; - double yb = ysb + squishOffset; - double zb = zsb + squishOffset; - - // Compute simplectic honeycomb coordinates relative to rhombohedral - // origin. - double xins = xs - xsb; - double yins = ys - ysb; - double zins = zs - zsb; - - // Sum those together to get a value that determines which region we're - // in. - double inSum = xins + yins + zins; - - // Positions relative to origin point. - double dx0 = x - xb; - double dy0 = y - yb; - double dz0 = z - zb; - - // We'll be defining these inside the next block and using them - // afterwards. - double dx_ext0, dy_ext0, dz_ext0; - double dx_ext1, dy_ext1, dz_ext1; - int xsv_ext0, ysv_ext0, zsv_ext0; - int xsv_ext1, ysv_ext1, zsv_ext1; - - double value = 0; - if (inSum <= 1) { // We're inside the tetrahedron (3-Simplex) at (0,0,0) - - // Determine which two of (0,0,1), (0,1,0), (1,0,0) are closest. - byte aPoint = 0x01; - double aScore = xins; - byte bPoint = 0x02; - double bScore = yins; - if (aScore >= bScore && zins > bScore) { - bScore = zins; - bPoint = 0x04; - } else if (aScore < bScore && zins > aScore) { - aScore = zins; - aPoint = 0x04; - } - - // Now we determine the two lattice points not part of the - // tetrahedron that may contribute. - // This depends on the closest two tetrahedral vertices, including - // (0,0,0) - double wins = 1 - inSum; - if (wins > aScore || wins > bScore) { // (0,0,0) is one of the - // closest two tetrahedral - // vertices. - byte c = (bScore > aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - - if ((c & 0x01) == 0) { - xsv_ext0 = xsb - 1; - xsv_ext1 = xsb; - dx_ext0 = dx0 + 1; - dx_ext1 = dx0; - } else { - xsv_ext0 = xsv_ext1 = xsb + 1; - dx_ext0 = dx_ext1 = dx0 - 1; - } - - if ((c & 0x02) == 0) { - ysv_ext0 = ysv_ext1 = ysb; - dy_ext0 = dy_ext1 = dy0; - if ((c & 0x01) == 0) { - ysv_ext1 -= 1; - dy_ext1 += 1; - } else { - ysv_ext0 -= 1; - dy_ext0 += 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy_ext1 = dy0 - 1; - } - - if ((c & 0x04) == 0) { - zsv_ext0 = zsb; - zsv_ext1 = zsb - 1; - dz_ext0 = dz0; - dz_ext1 = dz0 + 1; - } else { - zsv_ext0 = zsv_ext1 = zsb + 1; - dz_ext0 = dz_ext1 = dz0 - 1; - } - } else { // (0,0,0) is not one of the closest two tetrahedral - // vertices. - byte c = (byte) (aPoint | bPoint); // Our two extra vertices are - // determined by the closest - // two. - - if ((c & 0x01) == 0) { - xsv_ext0 = xsb; - xsv_ext1 = xsb - 1; - dx_ext0 = dx0 - 2 * SQUISH_CONSTANT_3D; - dx_ext1 = dx0 + 1 - SQUISH_CONSTANT_3D; - } else { - xsv_ext0 = xsv_ext1 = xsb + 1; - dx_ext0 = dx0 - 1 - 2 * SQUISH_CONSTANT_3D; - dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_3D; - } - - if ((c & 0x02) == 0) { - ysv_ext0 = ysb; - ysv_ext1 = ysb - 1; - dy_ext0 = dy0 - 2 * SQUISH_CONSTANT_3D; - dy_ext1 = dy0 + 1 - SQUISH_CONSTANT_3D; - } else { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy0 - 1 - 2 * SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_3D; - } - - if ((c & 0x04) == 0) { - zsv_ext0 = zsb; - zsv_ext1 = zsb - 1; - dz_ext0 = dz0 - 2 * SQUISH_CONSTANT_3D; - dz_ext1 = dz0 + 1 - SQUISH_CONSTANT_3D; - } else { - zsv_ext0 = zsv_ext1 = zsb + 1; - dz_ext0 = dz0 - 1 - 2 * SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_3D; - } - } - - // Contribution (0,0,0) - double attn0 = 2 - dx0 * dx0 - dy0 * dy0 - dz0 * dz0; - if (attn0 > 0) { - attn0 *= attn0; - value += attn0 * attn0 * extrapolate(xsb + 0, ysb + 0, zsb + 0, dx0, dy0, dz0); - } - - // Contribution (1,0,0) - double dx1 = dx0 - 1 - SQUISH_CONSTANT_3D; - double dy1 = dy0 - 0 - SQUISH_CONSTANT_3D; - double dz1 = dz0 - 0 - SQUISH_CONSTANT_3D; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1 - dz1 * dz1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, dx1, dy1, dz1); - } - - // Contribution (0,1,0) - double dx2 = dx0 - 0 - SQUISH_CONSTANT_3D; - double dy2 = dy0 - 1 - SQUISH_CONSTANT_3D; - double dz2 = dz1; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2 - dz2 * dz2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, dx2, dy2, dz2); - } - - // Contribution (0,0,1) - double dx3 = dx2; - double dy3 = dy1; - double dz3 = dz0 - 1 - SQUISH_CONSTANT_3D; - double attn3 = 2 - dx3 * dx3 - dy3 * dy3 - dz3 * dz3; - if (attn3 > 0) { - attn3 *= attn3; - value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, dx3, dy3, dz3); - } - } else if (inSum >= 2) { // We're inside the tetrahedron (3-Simplex) at - // (1,1,1) - - // Determine which two tetrahedral vertices are the closest, out of - // (1,1,0), (1,0,1), (0,1,1) but not (1,1,1). - byte aPoint = 0x06; - double aScore = xins; - byte bPoint = 0x05; - double bScore = yins; - if (aScore <= bScore && zins < bScore) { - bScore = zins; - bPoint = 0x03; - } else if (aScore > bScore && zins < aScore) { - aScore = zins; - aPoint = 0x03; - } - - // Now we determine the two lattice points not part of the - // tetrahedron that may contribute. - // This depends on the closest two tetrahedral vertices, including - // (1,1,1) - double wins = 3 - inSum; - if (wins < aScore || wins < bScore) { // (1,1,1) is one of the - // closest two tetrahedral - // vertices. - byte c = (bScore < aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - - if ((c & 0x01) != 0) { - xsv_ext0 = xsb + 2; - xsv_ext1 = xsb + 1; - dx_ext0 = dx0 - 2 - 3 * SQUISH_CONSTANT_3D; - dx_ext1 = dx0 - 1 - 3 * SQUISH_CONSTANT_3D; - } else { - xsv_ext0 = xsv_ext1 = xsb; - dx_ext0 = dx_ext1 = dx0 - 3 * SQUISH_CONSTANT_3D; - } - - if ((c & 0x02) != 0) { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy_ext1 = dy0 - 1 - 3 * SQUISH_CONSTANT_3D; - if ((c & 0x01) != 0) { - ysv_ext1 += 1; - dy_ext1 -= 1; - } else { - ysv_ext0 += 1; - dy_ext0 -= 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysb; - dy_ext0 = dy_ext1 = dy0 - 3 * SQUISH_CONSTANT_3D; - } - - if ((c & 0x04) != 0) { - zsv_ext0 = zsb + 1; - zsv_ext1 = zsb + 2; - dz_ext0 = dz0 - 1 - 3 * SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 2 - 3 * SQUISH_CONSTANT_3D; - } else { - zsv_ext0 = zsv_ext1 = zsb; - dz_ext0 = dz_ext1 = dz0 - 3 * SQUISH_CONSTANT_3D; - } - } else { // (1,1,1) is not one of the closest two tetrahedral - // vertices. - byte c = (byte) (aPoint & bPoint); // Our two extra vertices are - // determined by the closest - // two. - - if ((c & 0x01) != 0) { - xsv_ext0 = xsb + 1; - xsv_ext1 = xsb + 2; - dx_ext0 = dx0 - 1 - SQUISH_CONSTANT_3D; - dx_ext1 = dx0 - 2 - 2 * SQUISH_CONSTANT_3D; - } else { - xsv_ext0 = xsv_ext1 = xsb; - dx_ext0 = dx0 - SQUISH_CONSTANT_3D; - dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; - } - - if ((c & 0x02) != 0) { - ysv_ext0 = ysb + 1; - ysv_ext1 = ysb + 2; - dy_ext0 = dy0 - 1 - SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 2 - 2 * SQUISH_CONSTANT_3D; - } else { - ysv_ext0 = ysv_ext1 = ysb; - dy_ext0 = dy0 - SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; - } - - if ((c & 0x04) != 0) { - zsv_ext0 = zsb + 1; - zsv_ext1 = zsb + 2; - dz_ext0 = dz0 - 1 - SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 2 - 2 * SQUISH_CONSTANT_3D; - } else { - zsv_ext0 = zsv_ext1 = zsb; - dz_ext0 = dz0 - SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 2 * SQUISH_CONSTANT_3D; - } - } - - // Contribution (1,1,0) - double dx3 = dx0 - 1 - 2 * SQUISH_CONSTANT_3D; - double dy3 = dy0 - 1 - 2 * SQUISH_CONSTANT_3D; - double dz3 = dz0 - 0 - 2 * SQUISH_CONSTANT_3D; - double attn3 = 2 - dx3 * dx3 - dy3 * dy3 - dz3 * dz3; - if (attn3 > 0) { - attn3 *= attn3; - value += attn3 * attn3 * extrapolate(xsb + 1, ysb + 1, zsb + 0, dx3, dy3, dz3); - } - - // Contribution (1,0,1) - double dx2 = dx3; - double dy2 = dy0 - 0 - 2 * SQUISH_CONSTANT_3D; - double dz2 = dz0 - 1 - 2 * SQUISH_CONSTANT_3D; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2 - dz2 * dz2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 1, ysb + 0, zsb + 1, dx2, dy2, dz2); - } - - // Contribution (0,1,1) - double dx1 = dx0 - 0 - 2 * SQUISH_CONSTANT_3D; - double dy1 = dy3; - double dz1 = dz2; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1 - dz1 * dz1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 0, ysb + 1, zsb + 1, dx1, dy1, dz1); - } - - // Contribution (1,1,1) - dx0 = dx0 - 1 - 3 * SQUISH_CONSTANT_3D; - dy0 = dy0 - 1 - 3 * SQUISH_CONSTANT_3D; - dz0 = dz0 - 1 - 3 * SQUISH_CONSTANT_3D; - double attn0 = 2 - dx0 * dx0 - dy0 * dy0 - dz0 * dz0; - if (attn0 > 0) { - attn0 *= attn0; - value += attn0 * attn0 * extrapolate(xsb + 1, ysb + 1, zsb + 1, dx0, dy0, dz0); - } - } else { // We're inside the octahedron (Rectified 3-Simplex) in - // between. - double aScore; - byte aPoint; - boolean aIsFurtherSide; - double bScore; - byte bPoint; - boolean bIsFurtherSide; - - // Decide between point (0,0,1) and (1,1,0) as closest - double p1 = xins + yins; - if (p1 > 1) { - aScore = p1 - 1; - aPoint = 0x03; - aIsFurtherSide = true; - } else { - aScore = 1 - p1; - aPoint = 0x04; - aIsFurtherSide = false; - } - - // Decide between point (0,1,0) and (1,0,1) as closest - double p2 = xins + zins; - if (p2 > 1) { - bScore = p2 - 1; - bPoint = 0x05; - bIsFurtherSide = true; - } else { - bScore = 1 - p2; - bPoint = 0x02; - bIsFurtherSide = false; - } - - // The closest out of the two (1,0,0) and (0,1,1) will replace the - // furthest out of the two decided above, if closer. - double p3 = yins + zins; - if (p3 > 1) { - double score = p3 - 1; - if (aScore <= bScore && aScore < score) { - aScore = score; - aPoint = 0x06; - aIsFurtherSide = true; - } else if (aScore > bScore && bScore < score) { - bScore = score; - bPoint = 0x06; - bIsFurtherSide = true; - } - } else { - double score = 1 - p3; - if (aScore <= bScore && aScore < score) { - aScore = score; - aPoint = 0x01; - aIsFurtherSide = false; - } else if (aScore > bScore && bScore < score) { - bScore = score; - bPoint = 0x01; - bIsFurtherSide = false; - } - } - - // Where each of the two closest points are determines how the extra - // two vertices are calculated. - if (aIsFurtherSide == bIsFurtherSide) { - if (aIsFurtherSide) { // Both closest points on (1,1,1) side - - // One of the two extra points is (1,1,1) - dx_ext0 = dx0 - 1 - 3 * SQUISH_CONSTANT_3D; - dy_ext0 = dy0 - 1 - 3 * SQUISH_CONSTANT_3D; - dz_ext0 = dz0 - 1 - 3 * SQUISH_CONSTANT_3D; - xsv_ext0 = xsb + 1; - ysv_ext0 = ysb + 1; - zsv_ext0 = zsb + 1; - - // Other extra point is based on the shared axis. - byte c = (byte) (aPoint & bPoint); - if ((c & 0x01) != 0) { - dx_ext1 = dx0 - 2 - 2 * SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 2 * SQUISH_CONSTANT_3D; - xsv_ext1 = xsb + 2; - ysv_ext1 = ysb; - zsv_ext1 = zsb; - } else if ((c & 0x02) != 0) { - dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 2 - 2 * SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 2 * SQUISH_CONSTANT_3D; - xsv_ext1 = xsb; - ysv_ext1 = ysb + 2; - zsv_ext1 = zsb; - } else { - dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 2 - 2 * SQUISH_CONSTANT_3D; - xsv_ext1 = xsb; - ysv_ext1 = ysb; - zsv_ext1 = zsb + 2; - } - } else {// Both closest points on (0,0,0) side - - // One of the two extra points is (0,0,0) - dx_ext0 = dx0; - dy_ext0 = dy0; - dz_ext0 = dz0; - xsv_ext0 = xsb; - ysv_ext0 = ysb; - zsv_ext0 = zsb; - - // Other extra point is based on the omitted axis. - byte c = (byte) (aPoint | bPoint); - if ((c & 0x01) == 0) { - dx_ext1 = dx0 + 1 - SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_3D; - xsv_ext1 = xsb - 1; - ysv_ext1 = ysb + 1; - zsv_ext1 = zsb + 1; - } else if ((c & 0x02) == 0) { - dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_3D; - dy_ext1 = dy0 + 1 - SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_3D; - xsv_ext1 = xsb + 1; - ysv_ext1 = ysb - 1; - zsv_ext1 = zsb + 1; - } else { - dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_3D; - dz_ext1 = dz0 + 1 - SQUISH_CONSTANT_3D; - xsv_ext1 = xsb + 1; - ysv_ext1 = ysb + 1; - zsv_ext1 = zsb - 1; - } - } - } else { // One point on (0,0,0) side, one point on (1,1,1) side - byte c1, c2; - if (aIsFurtherSide) { - c1 = aPoint; - c2 = bPoint; - } else { - c1 = bPoint; - c2 = aPoint; - } - - // One contribution is a permutation of (1,1,-1) - if ((c1 & 0x01) == 0) { - dx_ext0 = dx0 + 1 - SQUISH_CONSTANT_3D; - dy_ext0 = dy0 - 1 - SQUISH_CONSTANT_3D; - dz_ext0 = dz0 - 1 - SQUISH_CONSTANT_3D; - xsv_ext0 = xsb - 1; - ysv_ext0 = ysb + 1; - zsv_ext0 = zsb + 1; - } else if ((c1 & 0x02) == 0) { - dx_ext0 = dx0 - 1 - SQUISH_CONSTANT_3D; - dy_ext0 = dy0 + 1 - SQUISH_CONSTANT_3D; - dz_ext0 = dz0 - 1 - SQUISH_CONSTANT_3D; - xsv_ext0 = xsb + 1; - ysv_ext0 = ysb - 1; - zsv_ext0 = zsb + 1; - } else { - dx_ext0 = dx0 - 1 - SQUISH_CONSTANT_3D; - dy_ext0 = dy0 - 1 - SQUISH_CONSTANT_3D; - dz_ext0 = dz0 + 1 - SQUISH_CONSTANT_3D; - xsv_ext0 = xsb + 1; - ysv_ext0 = ysb + 1; - zsv_ext0 = zsb - 1; - } - - // One contribution is a permutation of (0,0,2) - dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; - dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; - dz_ext1 = dz0 - 2 * SQUISH_CONSTANT_3D; - xsv_ext1 = xsb; - ysv_ext1 = ysb; - zsv_ext1 = zsb; - if ((c2 & 0x01) != 0) { - dx_ext1 -= 2; - xsv_ext1 += 2; - } else if ((c2 & 0x02) != 0) { - dy_ext1 -= 2; - ysv_ext1 += 2; - } else { - dz_ext1 -= 2; - zsv_ext1 += 2; - } - } - - // Contribution (1,0,0) - double dx1 = dx0 - 1 - SQUISH_CONSTANT_3D; - double dy1 = dy0 - 0 - SQUISH_CONSTANT_3D; - double dz1 = dz0 - 0 - SQUISH_CONSTANT_3D; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1 - dz1 * dz1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, dx1, dy1, dz1); - } - - // Contribution (0,1,0) - double dx2 = dx0 - 0 - SQUISH_CONSTANT_3D; - double dy2 = dy0 - 1 - SQUISH_CONSTANT_3D; - double dz2 = dz1; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2 - dz2 * dz2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, dx2, dy2, dz2); - } - - // Contribution (0,0,1) - double dx3 = dx2; - double dy3 = dy1; - double dz3 = dz0 - 1 - SQUISH_CONSTANT_3D; - double attn3 = 2 - dx3 * dx3 - dy3 * dy3 - dz3 * dz3; - if (attn3 > 0) { - attn3 *= attn3; - value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, dx3, dy3, dz3); - } - - // Contribution (1,1,0) - double dx4 = dx0 - 1 - 2 * SQUISH_CONSTANT_3D; - double dy4 = dy0 - 1 - 2 * SQUISH_CONSTANT_3D; - double dz4 = dz0 - 0 - 2 * SQUISH_CONSTANT_3D; - double attn4 = 2 - dx4 * dx4 - dy4 * dy4 - dz4 * dz4; - if (attn4 > 0) { - attn4 *= attn4; - value += attn4 * attn4 * extrapolate(xsb + 1, ysb + 1, zsb + 0, dx4, dy4, dz4); - } - - // Contribution (1,0,1) - double dx5 = dx4; - double dy5 = dy0 - 0 - 2 * SQUISH_CONSTANT_3D; - double dz5 = dz0 - 1 - 2 * SQUISH_CONSTANT_3D; - double attn5 = 2 - dx5 * dx5 - dy5 * dy5 - dz5 * dz5; - if (attn5 > 0) { - attn5 *= attn5; - value += attn5 * attn5 * extrapolate(xsb + 1, ysb + 0, zsb + 1, dx5, dy5, dz5); - } - - // Contribution (0,1,1) - double dx6 = dx0 - 0 - 2 * SQUISH_CONSTANT_3D; - double dy6 = dy4; - double dz6 = dz5; - double attn6 = 2 - dx6 * dx6 - dy6 * dy6 - dz6 * dz6; - if (attn6 > 0) { - attn6 *= attn6; - value += attn6 * attn6 * extrapolate(xsb + 0, ysb + 1, zsb + 1, dx6, dy6, dz6); - } - } - - // First extra vertex - double attn_ext0 = 2 - dx_ext0 * dx_ext0 - dy_ext0 * dy_ext0 - dz_ext0 * dz_ext0; - if (attn_ext0 > 0) { - attn_ext0 *= attn_ext0; - value += attn_ext0 * attn_ext0 * extrapolate(xsv_ext0, ysv_ext0, zsv_ext0, dx_ext0, dy_ext0, dz_ext0); - } - - // Second extra vertex - double attn_ext1 = 2 - dx_ext1 * dx_ext1 - dy_ext1 * dy_ext1 - dz_ext1 * dz_ext1; - if (attn_ext1 > 0) { - attn_ext1 *= attn_ext1; - value += attn_ext1 * attn_ext1 * extrapolate(xsv_ext1, ysv_ext1, zsv_ext1, dx_ext1, dy_ext1, dz_ext1); - } - - return value / NORM_CONSTANT_3D; - } - - // 4D OpenSimplex Noise. - public double eval(double x, double y, double z, double w) { - - // Place input coordinates on simplectic honeycomb. - double stretchOffset = (x + y + z + w) * STRETCH_CONSTANT_4D; - double xs = x + stretchOffset; - double ys = y + stretchOffset; - double zs = z + stretchOffset; - double ws = w + stretchOffset; - - // Floor to get simplectic honeycomb coordinates of rhombo-hypercube - // super-cell origin. - int xsb = fastFloor(xs); - int ysb = fastFloor(ys); - int zsb = fastFloor(zs); - int wsb = fastFloor(ws); - - // Skew out to get actual coordinates of stretched rhombo-hypercube - // origin. We'll need these later. - double squishOffset = (xsb + ysb + zsb + wsb) * SQUISH_CONSTANT_4D; - double xb = xsb + squishOffset; - double yb = ysb + squishOffset; - double zb = zsb + squishOffset; - double wb = wsb + squishOffset; - - // Compute simplectic honeycomb coordinates relative to rhombo-hypercube - // origin. - double xins = xs - xsb; - double yins = ys - ysb; - double zins = zs - zsb; - double wins = ws - wsb; - - // Sum those together to get a value that determines which region we're - // in. - double inSum = xins + yins + zins + wins; - - // Positions relative to origin point. - double dx0 = x - xb; - double dy0 = y - yb; - double dz0 = z - zb; - double dw0 = w - wb; - - // We'll be defining these inside the next block and using them - // afterwards. - double dx_ext0, dy_ext0, dz_ext0, dw_ext0; - double dx_ext1, dy_ext1, dz_ext1, dw_ext1; - double dx_ext2, dy_ext2, dz_ext2, dw_ext2; - int xsv_ext0, ysv_ext0, zsv_ext0, wsv_ext0; - int xsv_ext1, ysv_ext1, zsv_ext1, wsv_ext1; - int xsv_ext2, ysv_ext2, zsv_ext2, wsv_ext2; - - double value = 0; - if (inSum <= 1) { // We're inside the pentachoron (4-Simplex) at - // (0,0,0,0) - - // Determine which two of (0,0,0,1), (0,0,1,0), (0,1,0,0), (1,0,0,0) - // are closest. - byte aPoint = 0x01; - double aScore = xins; - byte bPoint = 0x02; - double bScore = yins; - if (aScore >= bScore && zins > bScore) { - bScore = zins; - bPoint = 0x04; - } else if (aScore < bScore && zins > aScore) { - aScore = zins; - aPoint = 0x04; - } - if (aScore >= bScore && wins > bScore) { - bScore = wins; - bPoint = 0x08; - } else if (aScore < bScore && wins > aScore) { - aScore = wins; - aPoint = 0x08; - } - - // Now we determine the three lattice points not part of the - // pentachoron that may contribute. - // This depends on the closest two pentachoron vertices, including - // (0,0,0,0) - double uins = 1 - inSum; - if (uins > aScore || uins > bScore) { // (0,0,0,0) is one of the - // closest two pentachoron - // vertices. - byte c = (bScore > aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - if ((c & 0x01) == 0) { - xsv_ext0 = xsb - 1; - xsv_ext1 = xsv_ext2 = xsb; - dx_ext0 = dx0 + 1; - dx_ext1 = dx_ext2 = dx0; - } else { - xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb + 1; - dx_ext0 = dx_ext1 = dx_ext2 = dx0 - 1; - } - - if ((c & 0x02) == 0) { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; - dy_ext0 = dy_ext1 = dy_ext2 = dy0; - if ((c & 0x01) == 0x01) { - ysv_ext0 -= 1; - dy_ext0 += 1; - } else { - ysv_ext1 -= 1; - dy_ext1 += 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; - dy_ext0 = dy_ext1 = dy_ext2 = dy0 - 1; - } - - if ((c & 0x04) == 0) { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; - dz_ext0 = dz_ext1 = dz_ext2 = dz0; - if ((c & 0x03) != 0) { - if ((c & 0x03) == 0x03) { - zsv_ext0 -= 1; - dz_ext0 += 1; - } else { - zsv_ext1 -= 1; - dz_ext1 += 1; - } - } else { - zsv_ext2 -= 1; - dz_ext2 += 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; - dz_ext0 = dz_ext1 = dz_ext2 = dz0 - 1; - } - - if ((c & 0x08) == 0) { - wsv_ext0 = wsv_ext1 = wsb; - wsv_ext2 = wsb - 1; - dw_ext0 = dw_ext1 = dw0; - dw_ext2 = dw0 + 1; - } else { - wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb + 1; - dw_ext0 = dw_ext1 = dw_ext2 = dw0 - 1; - } - } else { // (0,0,0,0) is not one of the closest two pentachoron - // vertices. - byte c = (byte) (aPoint | bPoint); // Our three extra vertices - // are determined by the - // closest two. - - if ((c & 0x01) == 0) { - xsv_ext0 = xsv_ext2 = xsb; - xsv_ext1 = xsb - 1; - dx_ext0 = dx0 - 2 * SQUISH_CONSTANT_4D; - dx_ext1 = dx0 + 1 - SQUISH_CONSTANT_4D; - dx_ext2 = dx0 - SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb + 1; - dx_ext0 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - dx_ext1 = dx_ext2 = dx0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c & 0x02) == 0) { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; - dy_ext0 = dy0 - 2 * SQUISH_CONSTANT_4D; - dy_ext1 = dy_ext2 = dy0 - SQUISH_CONSTANT_4D; - if ((c & 0x01) == 0x01) { - ysv_ext1 -= 1; - dy_ext1 += 1; - } else { - ysv_ext2 -= 1; - dy_ext2 += 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; - dy_ext0 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - dy_ext1 = dy_ext2 = dy0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c & 0x04) == 0) { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; - dz_ext0 = dz0 - 2 * SQUISH_CONSTANT_4D; - dz_ext1 = dz_ext2 = dz0 - SQUISH_CONSTANT_4D; - if ((c & 0x03) == 0x03) { - zsv_ext1 -= 1; - dz_ext1 += 1; - } else { - zsv_ext2 -= 1; - dz_ext2 += 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; - dz_ext0 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - dz_ext1 = dz_ext2 = dz0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c & 0x08) == 0) { - wsv_ext0 = wsv_ext1 = wsb; - wsv_ext2 = wsb - 1; - dw_ext0 = dw0 - 2 * SQUISH_CONSTANT_4D; - dw_ext1 = dw0 - SQUISH_CONSTANT_4D; - dw_ext2 = dw0 + 1 - SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb + 1; - dw_ext0 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - dw_ext1 = dw_ext2 = dw0 - 1 - SQUISH_CONSTANT_4D; - } - } - - // Contribution (0,0,0,0) - double attn0 = 2 - dx0 * dx0 - dy0 * dy0 - dz0 * dz0 - dw0 * dw0; - if (attn0 > 0) { - attn0 *= attn0; - value += attn0 * attn0 * extrapolate(xsb + 0, ysb + 0, zsb + 0, wsb + 0, dx0, dy0, dz0, dw0); - } - - // Contribution (1,0,0,0) - double dx1 = dx0 - 1 - SQUISH_CONSTANT_4D; - double dy1 = dy0 - 0 - SQUISH_CONSTANT_4D; - double dz1 = dz0 - 0 - SQUISH_CONSTANT_4D; - double dw1 = dw0 - 0 - SQUISH_CONSTANT_4D; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1 - dz1 * dz1 - dw1 * dw1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 0, dx1, dy1, dz1, dw1); - } - - // Contribution (0,1,0,0) - double dx2 = dx0 - 0 - SQUISH_CONSTANT_4D; - double dy2 = dy0 - 1 - SQUISH_CONSTANT_4D; - double dz2 = dz1; - double dw2 = dw1; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2 - dz2 * dz2 - dw2 * dw2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 0, dx2, dy2, dz2, dw2); - } - - // Contribution (0,0,1,0) - double dx3 = dx2; - double dy3 = dy1; - double dz3 = dz0 - 1 - SQUISH_CONSTANT_4D; - double dw3 = dw1; - double attn3 = 2 - dx3 * dx3 - dy3 * dy3 - dz3 * dz3 - dw3 * dw3; - if (attn3 > 0) { - attn3 *= attn3; - value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 0, dx3, dy3, dz3, dw3); - } - - // Contribution (0,0,0,1) - double dx4 = dx2; - double dy4 = dy1; - double dz4 = dz1; - double dw4 = dw0 - 1 - SQUISH_CONSTANT_4D; - double attn4 = 2 - dx4 * dx4 - dy4 * dy4 - dz4 * dz4 - dw4 * dw4; - if (attn4 > 0) { - attn4 *= attn4; - value += attn4 * attn4 * extrapolate(xsb + 0, ysb + 0, zsb + 0, wsb + 1, dx4, dy4, dz4, dw4); - } - } else if (inSum >= 3) { // We're inside the pentachoron (4-Simplex) at - // (1,1,1,1) - // Determine which two of (1,1,1,0), - // (1,1,0,1), (1,0,1,1), (0,1,1,1) - // are closest. - byte aPoint = 0x0E; - double aScore = xins; - byte bPoint = 0x0D; - double bScore = yins; - if (aScore <= bScore && zins < bScore) { - bScore = zins; - bPoint = 0x0B; - } else if (aScore > bScore && zins < aScore) { - aScore = zins; - aPoint = 0x0B; - } - if (aScore <= bScore && wins < bScore) { - bScore = wins; - bPoint = 0x07; - } else if (aScore > bScore && wins < aScore) { - aScore = wins; - aPoint = 0x07; - } - - // Now we determine the three lattice points not part of the - // pentachoron that may contribute. - // This depends on the closest two pentachoron vertices, including - // (0,0,0,0) - double uins = 4 - inSum; - if (uins < aScore || uins < bScore) { // (1,1,1,1) is one of the - // closest two pentachoron - // vertices. - byte c = (bScore < aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - - if ((c & 0x01) != 0) { - xsv_ext0 = xsb + 2; - xsv_ext1 = xsv_ext2 = xsb + 1; - dx_ext0 = dx0 - 2 - 4 * SQUISH_CONSTANT_4D; - dx_ext1 = dx_ext2 = dx0 - 1 - 4 * SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb; - dx_ext0 = dx_ext1 = dx_ext2 = dx0 - 4 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x02) != 0) { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; - dy_ext0 = dy_ext1 = dy_ext2 = dy0 - 1 - 4 * SQUISH_CONSTANT_4D; - if ((c & 0x01) != 0) { - ysv_ext1 += 1; - dy_ext1 -= 1; - } else { - ysv_ext0 += 1; - dy_ext0 -= 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; - dy_ext0 = dy_ext1 = dy_ext2 = dy0 - 4 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x04) != 0) { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; - dz_ext0 = dz_ext1 = dz_ext2 = dz0 - 1 - 4 * SQUISH_CONSTANT_4D; - if ((c & 0x03) != 0x03) { - if ((c & 0x03) == 0) { - zsv_ext0 += 1; - dz_ext0 -= 1; - } else { - zsv_ext1 += 1; - dz_ext1 -= 1; - } - } else { - zsv_ext2 += 1; - dz_ext2 -= 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; - dz_ext0 = dz_ext1 = dz_ext2 = dz0 - 4 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x08) != 0) { - wsv_ext0 = wsv_ext1 = wsb + 1; - wsv_ext2 = wsb + 2; - dw_ext0 = dw_ext1 = dw0 - 1 - 4 * SQUISH_CONSTANT_4D; - dw_ext2 = dw0 - 2 - 4 * SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb; - dw_ext0 = dw_ext1 = dw_ext2 = dw0 - 4 * SQUISH_CONSTANT_4D; - } - } else { // (1,1,1,1) is not one of the closest two pentachoron - // vertices. - byte c = (byte) (aPoint & bPoint); // Our three extra vertices - // are determined by the - // closest two. - - if ((c & 0x01) != 0) { - xsv_ext0 = xsv_ext2 = xsb + 1; - xsv_ext1 = xsb + 2; - dx_ext0 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - dx_ext1 = dx0 - 2 - 3 * SQUISH_CONSTANT_4D; - dx_ext2 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsv_ext2 = xsb; - dx_ext0 = dx0 - 2 * SQUISH_CONSTANT_4D; - dx_ext1 = dx_ext2 = dx0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x02) != 0) { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb + 1; - dy_ext0 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - dy_ext1 = dy_ext2 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; - if ((c & 0x01) != 0) { - ysv_ext2 += 1; - dy_ext2 -= 1; - } else { - ysv_ext1 += 1; - dy_ext1 -= 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysv_ext2 = ysb; - dy_ext0 = dy0 - 2 * SQUISH_CONSTANT_4D; - dy_ext1 = dy_ext2 = dy0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x04) != 0) { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb + 1; - dz_ext0 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - dz_ext1 = dz_ext2 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; - if ((c & 0x03) != 0) { - zsv_ext2 += 1; - dz_ext2 -= 1; - } else { - zsv_ext1 += 1; - dz_ext1 -= 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsv_ext2 = zsb; - dz_ext0 = dz0 - 2 * SQUISH_CONSTANT_4D; - dz_ext1 = dz_ext2 = dz0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x08) != 0) { - wsv_ext0 = wsv_ext1 = wsb + 1; - wsv_ext2 = wsb + 2; - dw_ext0 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - dw_ext1 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; - dw_ext2 = dw0 - 2 - 3 * SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsv_ext2 = wsb; - dw_ext0 = dw0 - 2 * SQUISH_CONSTANT_4D; - dw_ext1 = dw_ext2 = dw0 - 3 * SQUISH_CONSTANT_4D; - } - } - - // Contribution (1,1,1,0) - double dx4 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - double dy4 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; - double dz4 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; - double dw4 = dw0 - 3 * SQUISH_CONSTANT_4D; - double attn4 = 2 - dx4 * dx4 - dy4 * dy4 - dz4 * dz4 - dw4 * dw4; - if (attn4 > 0) { - attn4 *= attn4; - value += attn4 * attn4 * extrapolate(xsb + 1, ysb + 1, zsb + 1, wsb + 0, dx4, dy4, dz4, dw4); - } - - // Contribution (1,1,0,1) - double dx3 = dx4; - double dy3 = dy4; - double dz3 = dz0 - 3 * SQUISH_CONSTANT_4D; - double dw3 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; - double attn3 = 2 - dx3 * dx3 - dy3 * dy3 - dz3 * dz3 - dw3 * dw3; - if (attn3 > 0) { - attn3 *= attn3; - value += attn3 * attn3 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 1, dx3, dy3, dz3, dw3); - } - - // Contribution (1,0,1,1) - double dx2 = dx4; - double dy2 = dy0 - 3 * SQUISH_CONSTANT_4D; - double dz2 = dz4; - double dw2 = dw3; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2 - dz2 * dz2 - dw2 * dw2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 1, dx2, dy2, dz2, dw2); - } - - // Contribution (0,1,1,1) - double dx1 = dx0 - 3 * SQUISH_CONSTANT_4D; - double dz1 = dz4; - double dy1 = dy4; - double dw1 = dw3; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1 - dz1 * dz1 - dw1 * dw1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 1, dx1, dy1, dz1, dw1); - } - - // Contribution (1,1,1,1) - dx0 = dx0 - 1 - 4 * SQUISH_CONSTANT_4D; - dy0 = dy0 - 1 - 4 * SQUISH_CONSTANT_4D; - dz0 = dz0 - 1 - 4 * SQUISH_CONSTANT_4D; - dw0 = dw0 - 1 - 4 * SQUISH_CONSTANT_4D; - double attn0 = 2 - dx0 * dx0 - dy0 * dy0 - dz0 * dz0 - dw0 * dw0; - if (attn0 > 0) { - attn0 *= attn0; - value += attn0 * attn0 * extrapolate(xsb + 1, ysb + 1, zsb + 1, wsb + 1, dx0, dy0, dz0, dw0); - } - } else if (inSum <= 2) { // We're inside the first dispentachoron - // (Rectified 4-Simplex) - double aScore; - byte aPoint; - boolean aIsBiggerSide = true; - double bScore; - byte bPoint; - boolean bIsBiggerSide = true; - - // Decide between (1,1,0,0) and (0,0,1,1) - if (xins + yins > zins + wins) { - aScore = xins + yins; - aPoint = 0x03; - } else { - aScore = zins + wins; - aPoint = 0x0C; - } - - // Decide between (1,0,1,0) and (0,1,0,1) - if (xins + zins > yins + wins) { - bScore = xins + zins; - bPoint = 0x05; - } else { - bScore = yins + wins; - bPoint = 0x0A; - } - - // Closer between (1,0,0,1) and (0,1,1,0) will replace the further - // of a and b, if closer. - if (xins + wins > yins + zins) { - double score = xins + wins; - if (aScore >= bScore && score > bScore) { - bScore = score; - bPoint = 0x09; - } else if (aScore < bScore && score > aScore) { - aScore = score; - aPoint = 0x09; - } - } else { - double score = yins + zins; - if (aScore >= bScore && score > bScore) { - bScore = score; - bPoint = 0x06; - } else if (aScore < bScore && score > aScore) { - aScore = score; - aPoint = 0x06; - } - } - - // Decide if (1,0,0,0) is closer. - double p1 = 2 - inSum + xins; - if (aScore >= bScore && p1 > bScore) { - bScore = p1; - bPoint = 0x01; - bIsBiggerSide = false; - } else if (aScore < bScore && p1 > aScore) { - aScore = p1; - aPoint = 0x01; - aIsBiggerSide = false; - } - - // Decide if (0,1,0,0) is closer. - double p2 = 2 - inSum + yins; - if (aScore >= bScore && p2 > bScore) { - bScore = p2; - bPoint = 0x02; - bIsBiggerSide = false; - } else if (aScore < bScore && p2 > aScore) { - aScore = p2; - aPoint = 0x02; - aIsBiggerSide = false; - } - - // Decide if (0,0,1,0) is closer. - double p3 = 2 - inSum + zins; - if (aScore >= bScore && p3 > bScore) { - bScore = p3; - bPoint = 0x04; - bIsBiggerSide = false; - } else if (aScore < bScore && p3 > aScore) { - aScore = p3; - aPoint = 0x04; - aIsBiggerSide = false; - } - - // Decide if (0,0,0,1) is closer. - double p4 = 2 - inSum + wins; - if (aScore >= bScore && p4 > bScore) { - bScore = p4; - bPoint = 0x08; - bIsBiggerSide = false; - } else if (aScore < bScore && p4 > aScore) { - aScore = p4; - aPoint = 0x08; - aIsBiggerSide = false; - } - - // Where each of the two closest points are determines how the extra - // three vertices are calculated. - if (aIsBiggerSide == bIsBiggerSide) { - if (aIsBiggerSide) { // Both closest points on the bigger side - byte c1 = (byte) (aPoint | bPoint); - byte c2 = (byte) (aPoint & bPoint); - if ((c1 & 0x01) == 0) { - xsv_ext0 = xsb; - xsv_ext1 = xsb - 1; - dx_ext0 = dx0 - 3 * SQUISH_CONSTANT_4D; - dx_ext1 = dx0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsb + 1; - dx_ext0 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - dx_ext1 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x02) == 0) { - ysv_ext0 = ysb; - ysv_ext1 = ysb - 1; - dy_ext0 = dy0 - 3 * SQUISH_CONSTANT_4D; - dy_ext1 = dy0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; - dy_ext1 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x04) == 0) { - zsv_ext0 = zsb; - zsv_ext1 = zsb - 1; - dz_ext0 = dz0 - 3 * SQUISH_CONSTANT_4D; - dz_ext1 = dz0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { - zsv_ext0 = zsv_ext1 = zsb + 1; - dz_ext0 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; - dz_ext1 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x08) == 0) { - wsv_ext0 = wsb; - wsv_ext1 = wsb - 1; - dw_ext0 = dw0 - 3 * SQUISH_CONSTANT_4D; - dw_ext1 = dw0 + 1 - 2 * SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsb + 1; - dw_ext0 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; - dw_ext1 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - } - - // One combination is a permutation of (0,0,0,2) based on c2 - xsv_ext2 = xsb; - ysv_ext2 = ysb; - zsv_ext2 = zsb; - wsv_ext2 = wsb; - dx_ext2 = dx0 - 2 * SQUISH_CONSTANT_4D; - dy_ext2 = dy0 - 2 * SQUISH_CONSTANT_4D; - dz_ext2 = dz0 - 2 * SQUISH_CONSTANT_4D; - dw_ext2 = dw0 - 2 * SQUISH_CONSTANT_4D; - if ((c2 & 0x01) != 0) { - xsv_ext2 += 2; - dx_ext2 -= 2; - } else if ((c2 & 0x02) != 0) { - ysv_ext2 += 2; - dy_ext2 -= 2; - } else if ((c2 & 0x04) != 0) { - zsv_ext2 += 2; - dz_ext2 -= 2; - } else { - wsv_ext2 += 2; - dw_ext2 -= 2; - } - - } else { // Both closest points on the smaller side - // One of the two extra points is (0,0,0,0) - xsv_ext2 = xsb; - ysv_ext2 = ysb; - zsv_ext2 = zsb; - wsv_ext2 = wsb; - dx_ext2 = dx0; - dy_ext2 = dy0; - dz_ext2 = dz0; - dw_ext2 = dw0; - - // Other two points are based on the omitted axes. - byte c = (byte) (aPoint | bPoint); - - if ((c & 0x01) == 0) { - xsv_ext0 = xsb - 1; - xsv_ext1 = xsb; - dx_ext0 = dx0 + 1 - SQUISH_CONSTANT_4D; - dx_ext1 = dx0 - SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsb + 1; - dx_ext0 = dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c & 0x02) == 0) { - ysv_ext0 = ysv_ext1 = ysb; - dy_ext0 = dy_ext1 = dy0 - SQUISH_CONSTANT_4D; - if ((c & 0x01) == 0x01) { - ysv_ext0 -= 1; - dy_ext0 += 1; - } else { - ysv_ext1 -= 1; - dy_ext1 += 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c & 0x04) == 0) { - zsv_ext0 = zsv_ext1 = zsb; - dz_ext0 = dz_ext1 = dz0 - SQUISH_CONSTANT_4D; - if ((c & 0x03) == 0x03) { - zsv_ext0 -= 1; - dz_ext0 += 1; - } else { - zsv_ext1 -= 1; - dz_ext1 += 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsb + 1; - dz_ext0 = dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c & 0x08) == 0) { - wsv_ext0 = wsb; - wsv_ext1 = wsb - 1; - dw_ext0 = dw0 - SQUISH_CONSTANT_4D; - dw_ext1 = dw0 + 1 - SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsb + 1; - dw_ext0 = dw_ext1 = dw0 - 1 - SQUISH_CONSTANT_4D; - } - - } - } else { // One point on each "side" - byte c1, c2; - if (aIsBiggerSide) { - c1 = aPoint; - c2 = bPoint; - } else { - c1 = bPoint; - c2 = aPoint; - } - - // Two contributions are the bigger-sided point with each 0 - // replaced with -1. - if ((c1 & 0x01) == 0) { - xsv_ext0 = xsb - 1; - xsv_ext1 = xsb; - dx_ext0 = dx0 + 1 - SQUISH_CONSTANT_4D; - dx_ext1 = dx0 - SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsb + 1; - dx_ext0 = dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x02) == 0) { - ysv_ext0 = ysv_ext1 = ysb; - dy_ext0 = dy_ext1 = dy0 - SQUISH_CONSTANT_4D; - if ((c1 & 0x01) == 0x01) { - ysv_ext0 -= 1; - dy_ext0 += 1; - } else { - ysv_ext1 -= 1; - dy_ext1 += 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x04) == 0) { - zsv_ext0 = zsv_ext1 = zsb; - dz_ext0 = dz_ext1 = dz0 - SQUISH_CONSTANT_4D; - if ((c1 & 0x03) == 0x03) { - zsv_ext0 -= 1; - dz_ext0 += 1; - } else { - zsv_ext1 -= 1; - dz_ext1 += 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsb + 1; - dz_ext0 = dz_ext1 = dz0 - 1 - SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x08) == 0) { - wsv_ext0 = wsb; - wsv_ext1 = wsb - 1; - dw_ext0 = dw0 - SQUISH_CONSTANT_4D; - dw_ext1 = dw0 + 1 - SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsb + 1; - dw_ext0 = dw_ext1 = dw0 - 1 - SQUISH_CONSTANT_4D; - } - - // One contribution is a permutation of (0,0,0,2) based on the - // smaller-sided point - xsv_ext2 = xsb; - ysv_ext2 = ysb; - zsv_ext2 = zsb; - wsv_ext2 = wsb; - dx_ext2 = dx0 - 2 * SQUISH_CONSTANT_4D; - dy_ext2 = dy0 - 2 * SQUISH_CONSTANT_4D; - dz_ext2 = dz0 - 2 * SQUISH_CONSTANT_4D; - dw_ext2 = dw0 - 2 * SQUISH_CONSTANT_4D; - if ((c2 & 0x01) != 0) { - xsv_ext2 += 2; - dx_ext2 -= 2; - } else if ((c2 & 0x02) != 0) { - ysv_ext2 += 2; - dy_ext2 -= 2; - } else if ((c2 & 0x04) != 0) { - zsv_ext2 += 2; - dz_ext2 -= 2; - } else { - wsv_ext2 += 2; - dw_ext2 -= 2; - } - } - - // Contribution (1,0,0,0) - double dx1 = dx0 - 1 - SQUISH_CONSTANT_4D; - double dy1 = dy0 - 0 - SQUISH_CONSTANT_4D; - double dz1 = dz0 - 0 - SQUISH_CONSTANT_4D; - double dw1 = dw0 - 0 - SQUISH_CONSTANT_4D; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1 - dz1 * dz1 - dw1 * dw1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 0, dx1, dy1, dz1, dw1); - } - - // Contribution (0,1,0,0) - double dx2 = dx0 - 0 - SQUISH_CONSTANT_4D; - double dy2 = dy0 - 1 - SQUISH_CONSTANT_4D; - double dz2 = dz1; - double dw2 = dw1; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2 - dz2 * dz2 - dw2 * dw2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 0, dx2, dy2, dz2, dw2); - } - - // Contribution (0,0,1,0) - double dx3 = dx2; - double dy3 = dy1; - double dz3 = dz0 - 1 - SQUISH_CONSTANT_4D; - double dw3 = dw1; - double attn3 = 2 - dx3 * dx3 - dy3 * dy3 - dz3 * dz3 - dw3 * dw3; - if (attn3 > 0) { - attn3 *= attn3; - value += attn3 * attn3 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 0, dx3, dy3, dz3, dw3); - } - - // Contribution (0,0,0,1) - double dx4 = dx2; - double dy4 = dy1; - double dz4 = dz1; - double dw4 = dw0 - 1 - SQUISH_CONSTANT_4D; - double attn4 = 2 - dx4 * dx4 - dy4 * dy4 - dz4 * dz4 - dw4 * dw4; - if (attn4 > 0) { - attn4 *= attn4; - value += attn4 * attn4 * extrapolate(xsb + 0, ysb + 0, zsb + 0, wsb + 1, dx4, dy4, dz4, dw4); - } - - // Contribution (1,1,0,0) - double dx5 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dy5 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dz5 = dz0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dw5 = dw0 - 0 - 2 * SQUISH_CONSTANT_4D; - double attn5 = 2 - dx5 * dx5 - dy5 * dy5 - dz5 * dz5 - dw5 * dw5; - if (attn5 > 0) { - attn5 *= attn5; - value += attn5 * attn5 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 0, dx5, dy5, dz5, dw5); - } - - // Contribution (1,0,1,0) - double dx6 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dy6 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dz6 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dw6 = dw0 - 0 - 2 * SQUISH_CONSTANT_4D; - double attn6 = 2 - dx6 * dx6 - dy6 * dy6 - dz6 * dz6 - dw6 * dw6; - if (attn6 > 0) { - attn6 *= attn6; - value += attn6 * attn6 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 0, dx6, dy6, dz6, dw6); - } - - // Contribution (1,0,0,1) - double dx7 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dy7 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dz7 = dz0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dw7 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - double attn7 = 2 - dx7 * dx7 - dy7 * dy7 - dz7 * dz7 - dw7 * dw7; - if (attn7 > 0) { - attn7 *= attn7; - value += attn7 * attn7 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 1, dx7, dy7, dz7, dw7); - } - - // Contribution (0,1,1,0) - double dx8 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dy8 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dz8 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dw8 = dw0 - 0 - 2 * SQUISH_CONSTANT_4D; - double attn8 = 2 - dx8 * dx8 - dy8 * dy8 - dz8 * dz8 - dw8 * dw8; - if (attn8 > 0) { - attn8 *= attn8; - value += attn8 * attn8 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 0, dx8, dy8, dz8, dw8); - } - - // Contribution (0,1,0,1) - double dx9 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dy9 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dz9 = dz0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dw9 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - double attn9 = 2 - dx9 * dx9 - dy9 * dy9 - dz9 * dz9 - dw9 * dw9; - if (attn9 > 0) { - attn9 *= attn9; - value += attn9 * attn9 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 1, dx9, dy9, dz9, dw9); - } - - // Contribution (0,0,1,1) - double dx10 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dy10 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dz10 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dw10 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - double attn10 = 2 - dx10 * dx10 - dy10 * dy10 - dz10 * dz10 - dw10 * dw10; - if (attn10 > 0) { - attn10 *= attn10; - value += attn10 * attn10 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 1, dx10, dy10, dz10, dw10); - } - } else { // We're inside the second dispentachoron (Rectified 4-Simplex) - double aScore; - byte aPoint; - boolean aIsBiggerSide = true; - double bScore; - byte bPoint; - boolean bIsBiggerSide = true; - - // Decide between (0,0,1,1) and (1,1,0,0) - if (xins + yins < zins + wins) { - aScore = xins + yins; - aPoint = 0x0C; - } else { - aScore = zins + wins; - aPoint = 0x03; - } - - // Decide between (0,1,0,1) and (1,0,1,0) - if (xins + zins < yins + wins) { - bScore = xins + zins; - bPoint = 0x0A; - } else { - bScore = yins + wins; - bPoint = 0x05; - } - - // Closer between (0,1,1,0) and (1,0,0,1) will replace the further - // of a and b, if closer. - if (xins + wins < yins + zins) { - double score = xins + wins; - if (aScore <= bScore && score < bScore) { - bScore = score; - bPoint = 0x06; - } else if (aScore > bScore && score < aScore) { - aScore = score; - aPoint = 0x06; - } - } else { - double score = yins + zins; - if (aScore <= bScore && score < bScore) { - bScore = score; - bPoint = 0x09; - } else if (aScore > bScore && score < aScore) { - aScore = score; - aPoint = 0x09; - } - } - - // Decide if (0,1,1,1) is closer. - double p1 = 3 - inSum + xins; - if (aScore <= bScore && p1 < bScore) { - bScore = p1; - bPoint = 0x0E; - bIsBiggerSide = false; - } else if (aScore > bScore && p1 < aScore) { - aScore = p1; - aPoint = 0x0E; - aIsBiggerSide = false; - } - - // Decide if (1,0,1,1) is closer. - double p2 = 3 - inSum + yins; - if (aScore <= bScore && p2 < bScore) { - bScore = p2; - bPoint = 0x0D; - bIsBiggerSide = false; - } else if (aScore > bScore && p2 < aScore) { - aScore = p2; - aPoint = 0x0D; - aIsBiggerSide = false; - } - - // Decide if (1,1,0,1) is closer. - double p3 = 3 - inSum + zins; - if (aScore <= bScore && p3 < bScore) { - bScore = p3; - bPoint = 0x0B; - bIsBiggerSide = false; - } else if (aScore > bScore && p3 < aScore) { - aScore = p3; - aPoint = 0x0B; - aIsBiggerSide = false; - } - - // Decide if (1,1,1,0) is closer. - double p4 = 3 - inSum + wins; - if (aScore <= bScore && p4 < bScore) { - bScore = p4; - bPoint = 0x07; - bIsBiggerSide = false; - } else if (aScore > bScore && p4 < aScore) { - aScore = p4; - aPoint = 0x07; - aIsBiggerSide = false; - } - - // Where each of the two closest points are determines how the extra - // three vertices are calculated. - if (aIsBiggerSide == bIsBiggerSide) { - if (aIsBiggerSide) { // Both closest points on the bigger side - byte c1 = (byte) (aPoint & bPoint); - byte c2 = (byte) (aPoint | bPoint); - - // Two contributions are permutations of (0,0,0,1) and - // (0,0,0,2) based on c1 - xsv_ext0 = xsv_ext1 = xsb; - ysv_ext0 = ysv_ext1 = ysb; - zsv_ext0 = zsv_ext1 = zsb; - wsv_ext0 = wsv_ext1 = wsb; - dx_ext0 = dx0 - SQUISH_CONSTANT_4D; - dy_ext0 = dy0 - SQUISH_CONSTANT_4D; - dz_ext0 = dz0 - SQUISH_CONSTANT_4D; - dw_ext0 = dw0 - SQUISH_CONSTANT_4D; - dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_4D; - dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_4D; - dz_ext1 = dz0 - 2 * SQUISH_CONSTANT_4D; - dw_ext1 = dw0 - 2 * SQUISH_CONSTANT_4D; - if ((c1 & 0x01) != 0) { - xsv_ext0 += 1; - dx_ext0 -= 1; - xsv_ext1 += 2; - dx_ext1 -= 2; - } else if ((c1 & 0x02) != 0) { - ysv_ext0 += 1; - dy_ext0 -= 1; - ysv_ext1 += 2; - dy_ext1 -= 2; - } else if ((c1 & 0x04) != 0) { - zsv_ext0 += 1; - dz_ext0 -= 1; - zsv_ext1 += 2; - dz_ext1 -= 2; - } else { - wsv_ext0 += 1; - dw_ext0 -= 1; - wsv_ext1 += 2; - dw_ext1 -= 2; - } - - // One contribution is a permutation of (1,1,1,-1) based on - // c2 - xsv_ext2 = xsb + 1; - ysv_ext2 = ysb + 1; - zsv_ext2 = zsb + 1; - wsv_ext2 = wsb + 1; - dx_ext2 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - dy_ext2 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - dz_ext2 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - dw_ext2 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - if ((c2 & 0x01) == 0) { - xsv_ext2 -= 2; - dx_ext2 += 2; - } else if ((c2 & 0x02) == 0) { - ysv_ext2 -= 2; - dy_ext2 += 2; - } else if ((c2 & 0x04) == 0) { - zsv_ext2 -= 2; - dz_ext2 += 2; - } else { - wsv_ext2 -= 2; - dw_ext2 += 2; - } - } else { // Both closest points on the smaller side - // One of the two extra points is (1,1,1,1) - xsv_ext2 = xsb + 1; - ysv_ext2 = ysb + 1; - zsv_ext2 = zsb + 1; - wsv_ext2 = wsb + 1; - dx_ext2 = dx0 - 1 - 4 * SQUISH_CONSTANT_4D; - dy_ext2 = dy0 - 1 - 4 * SQUISH_CONSTANT_4D; - dz_ext2 = dz0 - 1 - 4 * SQUISH_CONSTANT_4D; - dw_ext2 = dw0 - 1 - 4 * SQUISH_CONSTANT_4D; - - // Other two points are based on the shared axes. - byte c = (byte) (aPoint & bPoint); - - if ((c & 0x01) != 0) { - xsv_ext0 = xsb + 2; - xsv_ext1 = xsb + 1; - dx_ext0 = dx0 - 2 - 3 * SQUISH_CONSTANT_4D; - dx_ext1 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsb; - dx_ext0 = dx_ext1 = dx0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x02) != 0) { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy_ext1 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; - if ((c & 0x01) == 0) { - ysv_ext0 += 1; - dy_ext0 -= 1; - } else { - ysv_ext1 += 1; - dy_ext1 -= 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysb; - dy_ext0 = dy_ext1 = dy0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x04) != 0) { - zsv_ext0 = zsv_ext1 = zsb + 1; - dz_ext0 = dz_ext1 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; - if ((c & 0x03) == 0) { - zsv_ext0 += 1; - dz_ext0 -= 1; - } else { - zsv_ext1 += 1; - dz_ext1 -= 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsb; - dz_ext0 = dz_ext1 = dz0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c & 0x08) != 0) { - wsv_ext0 = wsb + 1; - wsv_ext1 = wsb + 2; - dw_ext0 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; - dw_ext1 = dw0 - 2 - 3 * SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsb; - dw_ext0 = dw_ext1 = dw0 - 3 * SQUISH_CONSTANT_4D; - } - } - } else { // One point on each "side" - byte c1, c2; - if (aIsBiggerSide) { - c1 = aPoint; - c2 = bPoint; - } else { - c1 = bPoint; - c2 = aPoint; - } - - // Two contributions are the bigger-sided point with each 1 - // replaced with 2. - if ((c1 & 0x01) != 0) { - xsv_ext0 = xsb + 2; - xsv_ext1 = xsb + 1; - dx_ext0 = dx0 - 2 - 3 * SQUISH_CONSTANT_4D; - dx_ext1 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - } else { - xsv_ext0 = xsv_ext1 = xsb; - dx_ext0 = dx_ext1 = dx0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x02) != 0) { - ysv_ext0 = ysv_ext1 = ysb + 1; - dy_ext0 = dy_ext1 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; - if ((c1 & 0x01) == 0) { - ysv_ext0 += 1; - dy_ext0 -= 1; - } else { - ysv_ext1 += 1; - dy_ext1 -= 1; - } - } else { - ysv_ext0 = ysv_ext1 = ysb; - dy_ext0 = dy_ext1 = dy0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x04) != 0) { - zsv_ext0 = zsv_ext1 = zsb + 1; - dz_ext0 = dz_ext1 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; - if ((c1 & 0x03) == 0) { - zsv_ext0 += 1; - dz_ext0 -= 1; - } else { - zsv_ext1 += 1; - dz_ext1 -= 1; - } - } else { - zsv_ext0 = zsv_ext1 = zsb; - dz_ext0 = dz_ext1 = dz0 - 3 * SQUISH_CONSTANT_4D; - } - - if ((c1 & 0x08) != 0) { - wsv_ext0 = wsb + 1; - wsv_ext1 = wsb + 2; - dw_ext0 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; - dw_ext1 = dw0 - 2 - 3 * SQUISH_CONSTANT_4D; - } else { - wsv_ext0 = wsv_ext1 = wsb; - dw_ext0 = dw_ext1 = dw0 - 3 * SQUISH_CONSTANT_4D; - } - - // One contribution is a permutation of (1,1,1,-1) based on the - // smaller-sided point - xsv_ext2 = xsb + 1; - ysv_ext2 = ysb + 1; - zsv_ext2 = zsb + 1; - wsv_ext2 = wsb + 1; - dx_ext2 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - dy_ext2 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - dz_ext2 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - dw_ext2 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - if ((c2 & 0x01) == 0) { - xsv_ext2 -= 2; - dx_ext2 += 2; - } else if ((c2 & 0x02) == 0) { - ysv_ext2 -= 2; - dy_ext2 += 2; - } else if ((c2 & 0x04) == 0) { - zsv_ext2 -= 2; - dz_ext2 += 2; - } else { - wsv_ext2 -= 2; - dw_ext2 += 2; - } - } - - // Contribution (1,1,1,0) - double dx4 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - double dy4 = dy0 - 1 - 3 * SQUISH_CONSTANT_4D; - double dz4 = dz0 - 1 - 3 * SQUISH_CONSTANT_4D; - double dw4 = dw0 - 3 * SQUISH_CONSTANT_4D; - double attn4 = 2 - dx4 * dx4 - dy4 * dy4 - dz4 * dz4 - dw4 * dw4; - if (attn4 > 0) { - attn4 *= attn4; - value += attn4 * attn4 * extrapolate(xsb + 1, ysb + 1, zsb + 1, wsb + 0, dx4, dy4, dz4, dw4); - } - - // Contribution (1,1,0,1) - double dx3 = dx4; - double dy3 = dy4; - double dz3 = dz0 - 3 * SQUISH_CONSTANT_4D; - double dw3 = dw0 - 1 - 3 * SQUISH_CONSTANT_4D; - double attn3 = 2 - dx3 * dx3 - dy3 * dy3 - dz3 * dz3 - dw3 * dw3; - if (attn3 > 0) { - attn3 *= attn3; - value += attn3 * attn3 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 1, dx3, dy3, dz3, dw3); - } - - // Contribution (1,0,1,1) - double dx2 = dx4; - double dy2 = dy0 - 3 * SQUISH_CONSTANT_4D; - double dz2 = dz4; - double dw2 = dw3; - double attn2 = 2 - dx2 * dx2 - dy2 * dy2 - dz2 * dz2 - dw2 * dw2; - if (attn2 > 0) { - attn2 *= attn2; - value += attn2 * attn2 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 1, dx2, dy2, dz2, dw2); - } - - // Contribution (0,1,1,1) - double dx1 = dx0 - 3 * SQUISH_CONSTANT_4D; - double dz1 = dz4; - double dy1 = dy4; - double dw1 = dw3; - double attn1 = 2 - dx1 * dx1 - dy1 * dy1 - dz1 * dz1 - dw1 * dw1; - if (attn1 > 0) { - attn1 *= attn1; - value += attn1 * attn1 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 1, dx1, dy1, dz1, dw1); - } - - // Contribution (1,1,0,0) - double dx5 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dy5 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dz5 = dz0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dw5 = dw0 - 0 - 2 * SQUISH_CONSTANT_4D; - double attn5 = 2 - dx5 * dx5 - dy5 * dy5 - dz5 * dz5 - dw5 * dw5; - if (attn5 > 0) { - attn5 *= attn5; - value += attn5 * attn5 * extrapolate(xsb + 1, ysb + 1, zsb + 0, wsb + 0, dx5, dy5, dz5, dw5); - } - - // Contribution (1,0,1,0) - double dx6 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dy6 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dz6 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dw6 = dw0 - 0 - 2 * SQUISH_CONSTANT_4D; - double attn6 = 2 - dx6 * dx6 - dy6 * dy6 - dz6 * dz6 - dw6 * dw6; - if (attn6 > 0) { - attn6 *= attn6; - value += attn6 * attn6 * extrapolate(xsb + 1, ysb + 0, zsb + 1, wsb + 0, dx6, dy6, dz6, dw6); - } - - // Contribution (1,0,0,1) - double dx7 = dx0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dy7 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dz7 = dz0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dw7 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - double attn7 = 2 - dx7 * dx7 - dy7 * dy7 - dz7 * dz7 - dw7 * dw7; - if (attn7 > 0) { - attn7 *= attn7; - value += attn7 * attn7 * extrapolate(xsb + 1, ysb + 0, zsb + 0, wsb + 1, dx7, dy7, dz7, dw7); - } - - // Contribution (0,1,1,0) - double dx8 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dy8 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dz8 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dw8 = dw0 - 0 - 2 * SQUISH_CONSTANT_4D; - double attn8 = 2 - dx8 * dx8 - dy8 * dy8 - dz8 * dz8 - dw8 * dw8; - if (attn8 > 0) { - attn8 *= attn8; - value += attn8 * attn8 * extrapolate(xsb + 0, ysb + 1, zsb + 1, wsb + 0, dx8, dy8, dz8, dw8); - } - - // Contribution (0,1,0,1) - double dx9 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dy9 = dy0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dz9 = dz0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dw9 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - double attn9 = 2 - dx9 * dx9 - dy9 * dy9 - dz9 * dz9 - dw9 * dw9; - if (attn9 > 0) { - attn9 *= attn9; - value += attn9 * attn9 * extrapolate(xsb + 0, ysb + 1, zsb + 0, wsb + 1, dx9, dy9, dz9, dw9); - } - - // Contribution (0,0,1,1) - double dx10 = dx0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dy10 = dy0 - 0 - 2 * SQUISH_CONSTANT_4D; - double dz10 = dz0 - 1 - 2 * SQUISH_CONSTANT_4D; - double dw10 = dw0 - 1 - 2 * SQUISH_CONSTANT_4D; - double attn10 = 2 - dx10 * dx10 - dy10 * dy10 - dz10 * dz10 - dw10 * dw10; - if (attn10 > 0) { - attn10 *= attn10; - value += attn10 * attn10 * extrapolate(xsb + 0, ysb + 0, zsb + 1, wsb + 1, dx10, dy10, dz10, dw10); - } - } - - // First extra vertex - double attn_ext0 = 2 - dx_ext0 * dx_ext0 - dy_ext0 * dy_ext0 - dz_ext0 * dz_ext0 - dw_ext0 * dw_ext0; - if (attn_ext0 > 0) { - attn_ext0 *= attn_ext0; - value += attn_ext0 * attn_ext0 * extrapolate( - xsv_ext0, - ysv_ext0, - zsv_ext0, - wsv_ext0, - dx_ext0, - dy_ext0, - dz_ext0, - dw_ext0 - ); - } - - // Second extra vertex - double attn_ext1 = 2 - dx_ext1 * dx_ext1 - dy_ext1 * dy_ext1 - dz_ext1 * dz_ext1 - dw_ext1 * dw_ext1; - if (attn_ext1 > 0) { - attn_ext1 *= attn_ext1; - value += attn_ext1 * attn_ext1 * extrapolate( - xsv_ext1, - ysv_ext1, - zsv_ext1, - wsv_ext1, - dx_ext1, - dy_ext1, - dz_ext1, - dw_ext1 - ); - } - - // Third extra vertex - double attn_ext2 = 2 - dx_ext2 * dx_ext2 - dy_ext2 * dy_ext2 - dz_ext2 * dz_ext2 - dw_ext2 * dw_ext2; - if (attn_ext2 > 0) { - attn_ext2 *= attn_ext2; - value += attn_ext2 * attn_ext2 * extrapolate( - xsv_ext2, - ysv_ext2, - zsv_ext2, - wsv_ext2, - dx_ext2, - dy_ext2, - dz_ext2, - dw_ext2 - ); - } - - return value / NORM_CONSTANT_4D; - } - - private double extrapolate(int xsb, int ysb, double dx, double dy) { - int index = perm[(perm[xsb & 0xFF] + ysb) & 0xFF] & 0x0E; - return gradients2D[index] * dx + gradients2D[index + 1] * dy; - } - - private double extrapolate(int xsb, int ysb, int zsb, double dx, double dy, double dz) { - int index = permGradIndex3D[(perm[(perm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF]; - return gradients3D[index] * dx + gradients3D[index + 1] * dy + gradients3D[index + 2] * dz; - } - - private double extrapolate(int xsb, int ysb, int zsb, int wsb, double dx, double dy, double dz, double dw) { - int index = perm[(perm[(perm[(perm[xsb & 0xFF] + ysb) & 0xFF] + zsb) & 0xFF] + wsb) & 0xFF] & 0xFC; - return gradients4D[index] * dx + gradients4D[index + 1] * dy + gradients4D[index + 2] * dz + gradients4D[index + 3] * dw; - } - - private static int fastFloor(double x) { - int xi = (int) x; - return x < xi ? xi - 1 : xi; - } - - // Gradients for 2D. They approximate the directions to the - // vertices of an octagon from the center. - private static final byte[] gradients2D = new byte[]{5, 2, 2, 5, -5, 2, -2, 5, 5, -2, 2, -5, -5, -2, -2, -5,}; - - // Gradients for 3D. They approximate the directions to the - // vertices of a rhombicuboctahedron from the center, skewed so - // that the triangular and square facets can be inscribed inside - // circles of the same radius. - private static final byte[] gradients3D = new byte[]{ - -11, - 4, - 4, - -4, - 11, - 4, - -4, - 4, - 11, - 11, - 4, - 4, - 4, - 11, - 4, - 4, - 4, - 11, - -11, - -4, - 4, - -4, - -11, - 4, - -4, - -4, - 11, - 11, - -4, - 4, - 4, - -11, - 4, - 4, - -4, - 11, - -11, - 4, - -4, - -4, - 11, - -4, - -4, - 4, - -11, - 11, - 4, - -4, - 4, - 11, - -4, - 4, - 4, - -11, - -11, - -4, - -4, - -4, - -11, - -4, - -4, - -4, - -11, - 11, - -4, - -4, - 4, - -11, - -4, - 4, - -4, - -11, - }; - - // Gradients for 4D. They approximate the directions to the - // vertices of a disprismatotesseractihexadecachoron from the center, - // skewed so that the tetrahedral and cubic facets can be inscribed inside - // spheres of the same radius. - private static final byte[] gradients4D = new byte[]{ - 3, - 1, - 1, - 1, - 1, - 3, - 1, - 1, - 1, - 1, - 3, - 1, - 1, - 1, - 1, - 3, - -3, - 1, - 1, - 1, - -1, - 3, - 1, - 1, - -1, - 1, - 3, - 1, - -1, - 1, - 1, - 3, - 3, - -1, - 1, - 1, - 1, - -3, - 1, - 1, - 1, - -1, - 3, - 1, - 1, - -1, - 1, - 3, - -3, - -1, - 1, - 1, - -1, - -3, - 1, - 1, - -1, - -1, - 3, - 1, - -1, - -1, - 1, - 3, - 3, - 1, - -1, - 1, - 1, - 3, - -1, - 1, - 1, - 1, - -3, - 1, - 1, - 1, - -1, - 3, - -3, - 1, - -1, - 1, - -1, - 3, - -1, - 1, - -1, - 1, - -3, - 1, - -1, - 1, - -1, - 3, - 3, - -1, - -1, - 1, - 1, - -3, - -1, - 1, - 1, - -1, - -3, - 1, - 1, - -1, - -1, - 3, - -3, - -1, - -1, - 1, - -1, - -3, - -1, - 1, - -1, - -1, - -3, - 1, - -1, - -1, - -1, - 3, - 3, - 1, - 1, - -1, - 1, - 3, - 1, - -1, - 1, - 1, - 3, - -1, - 1, - 1, - 1, - -3, - -3, - 1, - 1, - -1, - -1, - 3, - 1, - -1, - -1, - 1, - 3, - -1, - -1, - 1, - 1, - -3, - 3, - -1, - 1, - -1, - 1, - -3, - 1, - -1, - 1, - -1, - 3, - -1, - 1, - -1, - 1, - -3, - -3, - -1, - 1, - -1, - -1, - -3, - 1, - -1, - -1, - -1, - 3, - -1, - -1, - -1, - 1, - -3, - 3, - 1, - -1, - -1, - 1, - 3, - -1, - -1, - 1, - 1, - -3, - -1, - 1, - 1, - -1, - -3, - -3, - 1, - -1, - -1, - -1, - 3, - -1, - -1, - -1, - 1, - -3, - -1, - -1, - 1, - -1, - -3, - 3, - -1, - -1, - -1, - 1, - -3, - -1, - -1, - 1, - -1, - -3, - -1, - 1, - -1, - -1, - -3, - -3, - -1, - -1, - -1, - -1, - -3, - -1, - -1, - -1, - -1, - -3, - -1, - -1, - -1, - -1, - -3, - }; -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/noise/VoronoiNoise.java b/src/main/java/org/betterx/bclib/noise/VoronoiNoise.java deleted file mode 100644 index 49bf43c1..00000000 --- a/src/main/java/org/betterx/bclib/noise/VoronoiNoise.java +++ /dev/null @@ -1,149 +0,0 @@ -package org.betterx.bclib.noise; - -import org.betterx.bclib.util.MHelper; - -import net.minecraft.core.BlockPos; - -import java.util.Random; - -public class VoronoiNoise { - private static final Random RANDOM = new Random(); - final int seed; - - public VoronoiNoise() { - this(0); - } - - public VoronoiNoise(int seed) { - this.seed = seed; - } - - private int getSeed(int x, int y, int z) { - int h = seed + x * 374761393 + y * 668265263 + z; - h = (h ^ (h >> 13)) * 1274126177; - return h ^ (h >> 16); - } - - public double sample(double x, double y, double z) { - int ix = MHelper.floor(x); - int iy = MHelper.floor(y); - int iz = MHelper.floor(z); - - float px = (float) (x - ix); - float py = (float) (y - iy); - float pz = (float) (z - iz); - - float d = 10; - - for (int pox = -1; pox < 2; pox++) { - for (int poy = -1; poy < 2; poy++) { - for (int poz = -1; poz < 2; poz++) { - RANDOM.setSeed(getSeed(pox + ix, poy + iy, poz + iz)); - float pointX = pox + RANDOM.nextFloat(); - float pointY = poy + RANDOM.nextFloat(); - float pointZ = poz + RANDOM.nextFloat(); - float d2 = MHelper.lengthSqr(pointX - px, pointY - py, pointZ - pz); - if (d2 < d) { - d = d2; - } - } - } - } - - return Math.sqrt(d); - } - - public Random getRandom(double x, double y, double z) { - int ix = MHelper.floor(x); - int iy = MHelper.floor(y); - int iz = MHelper.floor(z); - - float px = (float) (x - ix); - float py = (float) (y - iy); - float pz = (float) (z - iz); - - float d = 10; - - int posX = 0; - int posY = 0; - int posZ = 0; - - for (int pox = -1; pox < 2; pox++) { - for (int poy = -1; poy < 2; poy++) { - for (int poz = -1; poz < 2; poz++) { - RANDOM.setSeed(getSeed(pox + ix, poy + iy, poz + iz)); - float pointX = pox + RANDOM.nextFloat(); - float pointY = poy + RANDOM.nextFloat(); - float pointZ = poz + RANDOM.nextFloat(); - float d2 = MHelper.lengthSqr(pointX - px, pointY - py, pointZ - pz); - if (d2 < d) { - d = d2; - posX = pox; - posY = poy; - posZ = poz; - } - } - } - } - - posX += ix; - posY += iy; - posZ += iz; - - int seed = MHelper.getSeed(posY, posX, posZ); - RANDOM.setSeed(seed); - - return RANDOM; - } - - public BlockPos[] getPos(double x, double y, double z, double scale) { - int ix = MHelper.floor(x); - int iy = MHelper.floor(y); - int iz = MHelper.floor(z); - - float px = (float) (x - ix); - float py = (float) (y - iy); - float pz = (float) (z - iz); - - float d = 10; - float selX = 0; - float selY = 0; - float selZ = 0; - float selXPre = 0; - float selYPre = 0; - float selZPre = 0; - - for (int pox = -1; pox < 2; pox++) { - for (int poy = -1; poy < 2; poy++) { - for (int poz = -1; poz < 2; poz++) { - RANDOM.setSeed(getSeed(pox + ix, poy + iy, poz + iz)); - float pointX = pox + RANDOM.nextFloat(); - float pointY = poy + RANDOM.nextFloat(); - float pointZ = poz + RANDOM.nextFloat(); - float d2 = MHelper.lengthSqr(pointX - px, pointY - py, pointZ - pz); - if (d2 < d) { - d = d2; - selXPre = selX; - selYPre = selY; - selZPre = selZ; - selX = pointX; - selY = pointY; - selZ = pointZ; - } - } - } - } - - BlockPos p1 = new BlockPos( - (ix + (double) selX) * scale, - (iy + (double) selY) * scale, - (iz + (double) selZ) * scale - ); - BlockPos p2 = new BlockPos( - (ix + (double) selXPre) * scale, - (iy + (double) selYPre) * scale, - (iz + (double) selZPre) * scale - ); - return new BlockPos[]{p1, p2}; - } -} diff --git a/src/main/java/org/betterx/bclib/particles/BCLParticleType.java b/src/main/java/org/betterx/bclib/particles/BCLParticleType.java deleted file mode 100644 index 4c0c8eff..00000000 --- a/src/main/java/org/betterx/bclib/particles/BCLParticleType.java +++ /dev/null @@ -1,84 +0,0 @@ -package org.betterx.bclib.particles; - -import com.mojang.serialization.Codec; -import net.minecraft.core.Registry; -import net.minecraft.core.particles.ParticleOptions; -import net.minecraft.core.particles.ParticleType; -import net.minecraft.core.particles.SimpleParticleType; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.fabric.api.client.particle.v1.ParticleFactoryRegistry; - -public class BCLParticleType { - - public static ParticleType deserializer( - ParticleOptions.Deserializer factory, - Codec codec - ) { - return deserializer(false, factory, codec); - } - - public static ParticleType deserializer( - boolean overrideLimiter, - ParticleOptions.Deserializer factory, - Codec codec - ) { - return new ParticleType(overrideLimiter, factory) { - @Override - public Codec codec() { - return codec; - } - }; - } - - public static ParticleType register( - ResourceLocation location, - ParticleOptions.Deserializer factory, - Codec codec - ) { - return register(location, false, factory, codec); - } - - public static ParticleType register( - ResourceLocation location, - boolean overrideLimiter, - ParticleOptions.Deserializer factory, - Codec codec - ) { - return Registry.register(Registry.PARTICLE_TYPE, location, deserializer(overrideLimiter, factory, codec)); - } - - public static SimpleParticleType simple(boolean overrideLimiter) { - return new SimpleParticleType(overrideLimiter) { - }; - } - - public static SimpleParticleType simple() { - return simple(false); - } - - public static SimpleParticleType register(ResourceLocation location) { - return register(location, false); - } - - public static SimpleParticleType register(ResourceLocation location, boolean overrideLimiter) { - return Registry.register(Registry.PARTICLE_TYPE, location, simple(overrideLimiter)); - } - - public static SimpleParticleType register( - ResourceLocation location, - ParticleFactoryRegistry.PendingParticleFactory provider - ) { - return register(location, false, provider); - } - - public static SimpleParticleType register( - ResourceLocation location, - boolean overrideLimiter, - ParticleFactoryRegistry.PendingParticleFactory provider - ) { - SimpleParticleType type = Registry.register(Registry.PARTICLE_TYPE, location, simple(overrideLimiter)); - ParticleFactoryRegistry.getInstance().register(type, provider); - return type; - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/AbstractAdvancementRecipe.java b/src/main/java/org/betterx/bclib/recipes/AbstractAdvancementRecipe.java deleted file mode 100644 index 2f8cf591..00000000 --- a/src/main/java/org/betterx/bclib/recipes/AbstractAdvancementRecipe.java +++ /dev/null @@ -1,220 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.api.v2.advancement.AdvancementManager; - -import net.minecraft.advancements.RequirementsStrategy; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.ArmorItem; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TieredItem; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; - -import java.util.Arrays; -import java.util.stream.Collectors; - -/** - * Simple extension class that allows Recipe-builders to automatically generated Recipe-Avancements. - *

- * Implementing classes need to call {@link #createAdvancement(ResourceLocation, boolean)} or - * {@link #createAdvancement(ResourceLocation, ItemLike)} to enable an advncement and - * {@link #registerAdvancement(Recipe)} to finalize and register the new Advancement. - *

- * After that the unlockedBy-Methods can bes used to add Items that will unlock the Recipe (and prompt the unlock) - */ -public class AbstractAdvancementRecipe { - protected AdvancementManager.Builder advancement; - boolean hasUnlockTrigger = false; - boolean generateAdvancement = false; - - /** - * Your implementing class should call this method to prepare a new {@link AdvancementManager.Builder} - *

- * For Example {@link FurnaceRecipe} will call this in the - * {@link FurnaceRecipe#make(ResourceLocation, ItemLike)}-Method - * - * @param id {@link ResourceLocation} for this advancement - * @param isTool true, if this is registered for a tool - */ - protected void createAdvancement(ResourceLocation id, boolean isTool) { - hasUnlockTrigger = false; - generateAdvancement = true; - advancement = AdvancementManager.Builder.create( - id, - isTool - ? AdvancementManager.AdvancementType.RECIPE_TOOL - : AdvancementManager.AdvancementType.RECIPE_DECORATIONS - ); - } - - - /** - * Your implementing class should call this method to prepare a new {@link AdvancementManager.Builder} - *

- * For Example {@link GridRecipe} will call this in the {@link GridRecipe#make(ResourceLocation, ItemLike)}-Method. - *

- * This method will call {@link #createAdvancement(ResourceLocation, boolean)}. The output object is used to - * determine wether or not this is a tool recipe. - * - * @param id {@link ResourceLocation} for this advancement - * @param output Used to determine wether or not this is a tool recipe. - */ - protected void createAdvancement(ResourceLocation id, ItemLike output) { - createAdvancement(id, (output.asItem() instanceof TieredItem || output.asItem() instanceof ArmorItem)); - } - - private int nameCounter = 0; - - /** - * The Recipe will be unlocked by one of the passed Items. As sonn als players have one in their Inventory - * the recipe will unlock. Those Items are mostly the input Items for the recipe. - *

- * If you need to use other unlock-Criteria, you can get the {@link AdvancementManager.Builder}-Instance - * using {@link #getAdvancementBuilder()} - *

- * This method will automatically get the Items from the stacl and call {@link #unlockedBy(ItemLike...)} - * - * @param stacks {@link ItemStack}s that will unlock the recipe. The count is ignored. - */ - public void unlockedBy(ItemStack... stacks) { - ItemLike[] items = Arrays.stream(stacks) - .filter(stack -> stack.getCount() > 0) - .map(stack -> (ItemLike) stack.getItem()) - .toArray(ItemLike[]::new); - - unlockedBy(items); - } - - /** - * The Recipe will be unlocked by one of the passed Items. As sonn als players have one in their Inventory - * the recipe will unlock. Those Items are mostly the input Items for the recipe. - *

- * If you need to use other unlock-Criteria, you can get the {@link AdvancementManager.Builder}-Instance - * using {@link #getAdvancementBuilder()} - *

- * This method will automatically derive a unique name for the criterion and call - * {@link #unlockedBy(String, ItemLike...)} - * - * @param items {@link Item}s or {@link Block}s that will unlock the recipe. - */ - public void unlockedBy(ItemLike... items) { - String name = "has_" + (nameCounter++) + "_" + - Arrays.stream(items) - .map(block -> (block instanceof Block) - ? Registry.BLOCK.getKey((Block) block) - : Registry.ITEM.getKey((Item) block)) - .filter(id -> id != null) - .map(id -> id.getPath()) - .collect(Collectors.joining("_")); - if (name.length() > 45) name = name.substring(0, 42); - unlockedBy(name, items); - } - - /** - * The Recipe will be unlocked by one of the passed Items. As sonn als players have one in their Inventory - * the recipe will unlock. Those Items are mostly the input Items for the recipe. - *

- * If you need to use other unlock-Criteria, you can get the {@link AdvancementManager.Builder}-Instance - * using {@link #getAdvancementBuilder()} - *

- * This method will automatically derive a unique name for the criterion and call - * {@link #unlockedBy(String, TagKey)} - * - * @param tag All items from this Tag will unlock the recipe - */ - public void unlockedBy(TagKey tag) { - ResourceLocation id = tag.location(); - if (id != null) { - unlockedBy("has_tag_" + id.getPath(), tag); - } - } - - - /** - * The Recipe will be unlocked by one of the passed Items. As sonn als players have one in their Inventory - * the recipe will unlock. Those Items are mostly the input Items for the recipe. - *

- * If you need to use other unlock-Criteria, you can get the {@link AdvancementManager.Builder}-Instance - * using {@link #getAdvancementBuilder()} - * - * @param name The name for this unlock-Criteria - * @param items {@link Item}s or {@link Block}s that will unlock the recipe. - */ - public void unlockedBy(String name, ItemLike... items) { - if (advancement != null) { - hasUnlockTrigger = true; - advancement.addInventoryChangedCriterion(name, items); - } - } - - /** - * The Recipe will be unlocked by one of the passed Items. As sonn als players have one in their Inventory - * the recipe will unlock. Those Items are mostly the input Items for the recipe. - *

- * If you need to use other unlock-Criteria, you can get the {@link AdvancementManager.Builder}-Instance - * using {@link #getAdvancementBuilder()} - * - * @param name The name for this unlock-Criteria - * @param tag All items from this Tag will unlock the recipe - */ - public void unlockedBy(String name, TagKey tag) { - if (advancement != null) { - hasUnlockTrigger = true; - advancement.addInventoryChangedCriterion(name, tag); - } - } - - /** - * Disables the generation of an advancement - */ - public void noAdvancement() { - generateAdvancement = false; - } - - /** - * Resets the advancement. This is usefully when you need more controll but the Recipe Builder - * (like {@link GridRecipe} is automatically adding Items to the criterion list. - */ - public void resetAdvancement() { - if (advancement != null) - advancement = AdvancementManager.Builder.createEmptyCopy(advancement); - } - - /** - * Returns the underlying Builder Instance - * - * @return null or The underlying builder Instance - */ - public AdvancementManager.Builder getAdvancementBuilder() { - return advancement; - } - - - /** - * Your implementing class should calls this method to finalize the advancement and register it. - *

- * For Example {@link GridRecipe} will call this in the {@link GridRecipe#build()}-Method - * - * @param recipe The generated recipe that need to be linked to the Advancement - */ - protected void registerAdvancement(Recipe recipe) { - if (hasUnlockTrigger && generateAdvancement && advancement != null) { - advancement - .startDisplay(recipe.getResultItem().getItem()) - .hideFromChat() - .hideToast() - .endDisplay() - .addRecipeUnlockCriterion("has_the_recipe", recipe) - .startReward() - .addRecipe(recipe.getId()) - .endReward() - .requirements(RequirementsStrategy.OR); - - advancement.buildAndRegister(); - } - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/AbstractSimpleRecipe.java b/src/main/java/org/betterx/bclib/recipes/AbstractSimpleRecipe.java deleted file mode 100644 index 09158850..00000000 --- a/src/main/java/org/betterx/bclib/recipes/AbstractSimpleRecipe.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.PathConfig; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.Container; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.ItemLike; - -public abstract class AbstractSimpleRecipe> extends AbstractAdvancementRecipe { - public final ResourceLocation id; - protected String group; - protected Ingredient input; - protected ItemLike output; - protected final String category; - protected final RecipeType type; - protected int count; - protected boolean exist; - - - protected AbstractSimpleRecipe(ResourceLocation id, RecipeType type, ItemLike output) { - this(id, type, type.toString(), output); - } - - protected AbstractSimpleRecipe(ResourceLocation id, RecipeType type, String category, ItemLike output) { - this.id = id; - this.group = ""; - this.exist = true; - this.count = 1; - this.output = output; - - this.category = category; - this.type = type; - } - - - protected T setInput(ItemLike in) { - this.exist &= BCLRecipeManager.exists(in); - this.input = Ingredient.of(in); - unlockedBy(in); - return (T) this; - } - - protected T setInput(TagKey in) { - this.input = Ingredient.of(in); - unlockedBy(in); - return (T) this; - } - - public T setGroup(String group) { - this.group = group; - return (T) this; - } - - public T setOutputCount(int count) { - this.count = count; - return (T) this; - } - - public T checkConfig(PathConfig config) { - exist &= config.getBoolean(category, id.getPath(), true); - return (T) this; - } - - protected abstract R buildRecipe(); - - protected boolean hasErrors() { - return false; - } - - public final void build() { - if (!exist) { - BCLib.LOGGER.warning("Unable to build Recipe " + id); - return; - } - - if (input == null || input.isEmpty()) { - BCLib.LOGGER.warning("Unable to build Recipe " + id + ": No Input Material"); - return; - } - - if (output == null) { - BCLib.LOGGER.warning("Result recipe can't be 'null', recipe {} will be ignored!", id); - return; - } - if (BCLRecipeManager.getRecipe(type, id) != null) { - BCLib.LOGGER.warning("Can't add Smithing recipe! Id {} already exists!", id); - return; - } - - if (hasErrors()) return; - - R recipe = buildRecipe(); - BCLRecipeManager.addRecipe(type, recipe); - registerAdvancement(recipe); - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/AlloyingRecipe.java b/src/main/java/org/betterx/bclib/recipes/AlloyingRecipe.java deleted file mode 100644 index a6fb2be9..00000000 --- a/src/main/java/org/betterx/bclib/recipes/AlloyingRecipe.java +++ /dev/null @@ -1,311 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.PathConfig; -import org.betterx.bclib.interfaces.AlloyingRecipeWorkstation; -import org.betterx.bclib.interfaces.UnknownReceipBookCategory; -import org.betterx.bclib.util.ItemUtil; -import org.betterx.bclib.util.RecipeHelper; - -import net.minecraft.core.NonNullList; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.util.GsonHelper; -import net.minecraft.world.Container; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.Level; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; - -public class AlloyingRecipe implements Recipe, UnknownReceipBookCategory { - public final static String GROUP = "alloying"; - public final static RecipeType TYPE = BCLRecipeManager.registerType(BCLib.MOD_ID, GROUP); - public final static Serializer SERIALIZER = BCLRecipeManager.registerSerializer( - BCLib.MOD_ID, - GROUP, - new Serializer() - ); - - protected final RecipeType type; - protected final ResourceLocation id; - protected final Ingredient primaryInput; - protected final Ingredient secondaryInput; - protected final ItemStack output; - protected final String group; - protected final float experience; - protected final int smeltTime; - - public AlloyingRecipe( - ResourceLocation id, - String group, - Ingredient primaryInput, - Ingredient secondaryInput, - ItemStack output, - float experience, - int smeltTime - ) { - this.group = group; - this.id = id; - this.primaryInput = primaryInput; - this.secondaryInput = secondaryInput; - this.output = output; - this.experience = experience; - this.smeltTime = smeltTime; - this.type = TYPE; - } - - public float getExperience() { - return this.experience; - } - - public int getSmeltTime() { - return this.smeltTime; - } - - @Override - public NonNullList getIngredients() { - NonNullList defaultedList = NonNullList.create(); - defaultedList.add(primaryInput); - defaultedList.add(secondaryInput); - - return defaultedList; - } - - @Override - public boolean matches(Container inv, Level world) { - return this.primaryInput.test(inv.getItem(0)) && this.secondaryInput.test(inv.getItem(1)) || this.primaryInput.test( - inv.getItem(1)) && this.secondaryInput.test(inv.getItem(0)); - } - - @Override - public ItemStack assemble(Container inv) { - return this.output.copy(); - } - - @Override - public boolean canCraftInDimensions(int width, int height) { - return true; - } - - @Override - public ItemStack getResultItem() { - return this.output; - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeSerializer getSerializer() { - return SERIALIZER; - } - - @Override - public RecipeType getType() { - return this.type; - } - - @Override - @Environment(EnvType.CLIENT) - public String getGroup() { - return this.group; - } - - @Environment(EnvType.CLIENT) - public ItemStack getToastSymbol() { - return AlloyingRecipeWorkstation.getWorkstationIcon(); - } - - public static class Builder { - private final static Builder INSTANCE = new Builder(); - private static boolean exist; - - static Builder create(ResourceLocation id, ItemLike output) { - INSTANCE.id = id; - INSTANCE.group = String.format("%s_%s", GROUP, id); - INSTANCE.primaryInput = null; - INSTANCE.secondaryInput = null; - INSTANCE.output = output; - INSTANCE.experience = 0.0F; - INSTANCE.smeltTime = 350; - INSTANCE.count = 1; - INSTANCE.alright = RecipeHelper.exists(output); - exist = true; - - return INSTANCE; - } - - private int count = 1; - private ResourceLocation id; - private Ingredient primaryInput; - private Ingredient secondaryInput; - private ItemLike output; - private String group; - private float experience; - private int smeltTime; - private boolean alright = true; - - protected Builder() { - } - - public Builder checkConfig(PathConfig config) { - exist &= config.getBoolean("alloying", id.getPath(), true); - return this; - } - - public Builder setGroup(String group) { - this.group = group; - return this; - } - - public Builder setOutputCount(int count) { - this.count = count; - return this; - } - - public Builder setPrimaryInput(ItemLike... inputs) { - for (ItemLike item : inputs) { - this.alright &= RecipeHelper.exists(item); - } - this.primaryInput = Ingredient.of(inputs); - return this; - } - - public Builder setSecondaryInput(ItemLike... inputs) { - for (ItemLike item : inputs) { - this.alright &= RecipeHelper.exists(item); - } - this.secondaryInput = Ingredient.of(inputs); - return this; - } - - public Builder setPrimaryInput(TagKey input) { - this.primaryInput = Ingredient.of(input); - return this; - } - - public Builder setSecondaryInput(TagKey input) { - this.secondaryInput = Ingredient.of(input); - return this; - } - - public Builder setInput(ItemLike primaryInput, ItemLike secondaryInput) { - this.setPrimaryInput(primaryInput); - this.setSecondaryInput(secondaryInput); - return this; - } - - public Builder setInput(TagKey primaryInput, TagKey secondaryInput) { - this.setPrimaryInput(primaryInput); - this.setSecondaryInput(secondaryInput); - return this; - } - - public Builder setExperience(float amount) { - this.experience = amount; - return this; - } - - public Builder setSmeltTime(int time) { - this.smeltTime = time; - return this; - } - - public void build() { - if (exist) { - if (primaryInput == null) { - BCLib.LOGGER.warning( - "Primary input for Alloying recipe can't be 'null', recipe {} will be ignored!", - id - ); - return; - } - if (secondaryInput == null) { - BCLib.LOGGER.warning( - "Secondary input for Alloying can't be 'null', recipe {} will be ignored!", - id - ); - return; - } - if (output == null) { - BCLib.LOGGER.warning("Output for Alloying can't be 'null', recipe {} will be ignored!", id); - return; - } - if (BCLRecipeManager.getRecipe(TYPE, id) != null) { - BCLib.LOGGER.warning("Can't add Alloying recipe! Id {} already exists!", id); - return; - } - if (!alright) { - BCLib.LOGGER.debug("Can't add Alloying recipe {}! Ingeredient or output not exists.", id); - return; - } - BCLRecipeManager.addRecipe( - TYPE, - new AlloyingRecipe( - id, - group, - primaryInput, - secondaryInput, - new ItemStack(output, count), - experience, - smeltTime - ) - ); - } - } - } - - public static class Serializer implements RecipeSerializer { - @Override - public AlloyingRecipe fromJson(ResourceLocation id, JsonObject json) { - JsonArray ingredients = GsonHelper.getAsJsonArray(json, "ingredients"); - Ingredient primaryInput = Ingredient.fromJson(ingredients.get(0)); - Ingredient secondaryInput = Ingredient.fromJson(ingredients.get(1)); - String group = GsonHelper.getAsString(json, "group", ""); - JsonObject result = GsonHelper.getAsJsonObject(json, "result"); - ItemStack output = ItemUtil.fromJsonRecipe(result); - if (output == null) { - throw new IllegalStateException("Output item does not exists!"); - } - float experience = GsonHelper.getAsFloat(json, "experience", 0.0F); - int smeltTime = GsonHelper.getAsInt(json, "smelttime", 350); - - return new AlloyingRecipe(id, group, primaryInput, secondaryInput, output, experience, smeltTime); - } - - @Override - public AlloyingRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf packetBuffer) { - String group = packetBuffer.readUtf(32767); - Ingredient primary = Ingredient.fromNetwork(packetBuffer); - Ingredient secondary = Ingredient.fromNetwork(packetBuffer); - ItemStack output = packetBuffer.readItem(); - float experience = packetBuffer.readFloat(); - int smeltTime = packetBuffer.readVarInt(); - - return new AlloyingRecipe(id, group, primary, secondary, output, experience, smeltTime); - } - - @Override - public void toNetwork(FriendlyByteBuf packetBuffer, AlloyingRecipe recipe) { - packetBuffer.writeUtf(recipe.group); - recipe.primaryInput.toNetwork(packetBuffer); - recipe.secondaryInput.toNetwork(packetBuffer); - packetBuffer.writeItem(recipe.output); - packetBuffer.writeFloat(recipe.experience); - packetBuffer.writeVarInt(recipe.smeltTime); - } - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/AnvilRecipe.java b/src/main/java/org/betterx/bclib/recipes/AnvilRecipe.java deleted file mode 100644 index 55890896..00000000 --- a/src/main/java/org/betterx/bclib/recipes/AnvilRecipe.java +++ /dev/null @@ -1,408 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.PathConfig; -import org.betterx.bclib.interfaces.UnknownReceipBookCategory; -import org.betterx.bclib.util.ItemUtil; -import org.betterx.bclib.util.RecipeHelper; -import org.betterx.worlds.together.tag.v3.CommonItemTags; -import org.betterx.worlds.together.world.event.WorldBootstrap; - -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.minecraft.core.Holder; -import net.minecraft.core.NonNullList; -import net.minecraft.core.Registry; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.TagParser; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.util.GsonHelper; -import net.minecraft.world.Container; -import net.minecraft.world.InteractionHand; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.TieredItem; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.Level; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.gson.JsonObject; - -import java.util.Objects; -import org.jetbrains.annotations.NotNull; - -public class AnvilRecipe implements Recipe, UnknownReceipBookCategory { - public final static String GROUP = "smithing"; - public final static RecipeType TYPE = BCLRecipeManager.registerType(BCLib.MOD_ID, GROUP); - public final static Serializer SERIALIZER = BCLRecipeManager.registerSerializer( - BCLib.MOD_ID, - GROUP, - new Serializer() - ); - public final static ResourceLocation ID = BCLib.makeID(GROUP); - - public static void register() { - - } - - private final ResourceLocation id; - private final Ingredient input; - private final ItemStack output; - private final int damage; - private final int toolLevel; - private final int anvilLevel; - private final int inputCount; - - public AnvilRecipe( - ResourceLocation identifier, - Ingredient input, - ItemStack output, - int inputCount, - int toolLevel, - int anvilLevel, - int damage - ) { - this.id = identifier; - this.input = input; - this.output = output; - this.toolLevel = toolLevel; - this.anvilLevel = anvilLevel; - this.inputCount = inputCount; - this.damage = damage; - } - - static Builder create(ResourceLocation id, ItemLike output) { - Builder.INSTANCE.id = id; - Builder.INSTANCE.input = null; - Builder.INSTANCE.output = output; - Builder.INSTANCE.inputCount = 1; - Builder.INSTANCE.toolLevel = 1; - Builder.INSTANCE.anvilLevel = 1; - Builder.INSTANCE.damage = 1; - Builder.INSTANCE.alright = true; - Builder.INSTANCE.exist &= RecipeHelper.exists(output); - - return Builder.INSTANCE; - } - - @Override - public RecipeSerializer getSerializer() { - return SERIALIZER; - } - - @Override - public ItemStack getResultItem() { - return this.output; - } - - @Override - public boolean matches(@NotNull Container craftingInventory, @NotNull Level world) { - return this.matches(craftingInventory); - } - - @Override - public ItemStack assemble(@NotNull Container craftingInventory) { - return this.output.copy(); - } - - public static Iterable> getAllHammers() { - Registry registry = WorldBootstrap.getLastRegistryAccessOrElseBuiltin() - .registryOrThrow(CommonItemTags.HAMMERS.registry()); - return registry.getTagOrEmpty(CommonItemTags.HAMMERS); - } - - public static int getHammerSlot(Container c) { - ItemStack h = c.getItem(0); - if (!h.isEmpty() && h.is(CommonItemTags.HAMMERS)) return 0; - - //this is the default slot - return 1; - } - - public static int getIngredientSlot(Container c) { - return Math.abs(getHammerSlot(c) - 1); - } - - public ItemStack getHammer(Container c) { - ItemStack h = c.getItem(1); - if (!h.isEmpty() && h.is(CommonItemTags.HAMMERS)) return h; - h = c.getItem(0); - if (!h.isEmpty() && h.is(CommonItemTags.HAMMERS)) return h; - return null; - } - - public ItemStack getIngredient(Container c) { - ItemStack i = c.getItem(0); - if (i.is(CommonItemTags.HAMMERS)) i = c.getItem(1); - return i; - } - - public ItemStack craft(Container craftingInventory, Player player) { - if (!player.isCreative()) { - if (!checkHammerDurability(craftingInventory, player)) return ItemStack.EMPTY; - ItemStack hammer = getHammer(craftingInventory); - if (hammer != null) { - hammer.hurtAndBreak(this.damage, player, entity -> entity.broadcastBreakEvent((InteractionHand) null)); - return ItemStack.EMPTY; - } - } - return this.assemble(craftingInventory); - } - - public boolean checkHammerDurability(Container craftingInventory, Player player) { - if (player.isCreative()) return true; - ItemStack hammer = getHammer(craftingInventory); - if (hammer != null) { - int damage = hammer.getDamageValue() + this.damage; - return damage < hammer.getMaxDamage(); - } - return true; - } - - public boolean matches(Container craftingInventory) { - ItemStack hammer = getHammer(craftingInventory); - if (hammer == null) { - return false; - } - ItemStack material = getIngredient(craftingInventory); - int materialCount = material.getCount(); - int level = ((TieredItem) hammer.getItem()).getTier().getLevel(); - return this.input.test(getIngredient(craftingInventory)) && materialCount >= this.inputCount && level >= this.toolLevel; - } - - public int getDamage() { - return this.damage; - } - - public int getInputCount() { - return this.inputCount; - } - - public Ingredient getMainIngredient() { - return this.input; - } - - public int getAnvilLevel() { - return this.anvilLevel; - } - - public boolean canUse(Item tool) { - if (tool instanceof TieredItem ti) { - return ti.getTier().getLevel() >= toolLevel; - } - return false; - } - - public static boolean isHammer(Item tool) { - if (tool == null) return false; - return tool.getDefaultInstance().is(CommonItemTags.HAMMERS); - } - - @Override - public NonNullList getIngredients() { - NonNullList defaultedList = NonNullList.create(); - defaultedList.add(Ingredient.of(Registry.ITEM.stream() - .filter(AnvilRecipe::isHammer) - .filter(this::canUse) - .map(ItemStack::new)) - ); - defaultedList.add(input); - return defaultedList; - } - - @Override - @Environment(EnvType.CLIENT) - public boolean canCraftInDimensions(int width, int height) { - return true; - } - - @Override - public ResourceLocation getId() { - return this.id; - } - - @Override - public RecipeType getType() { - return TYPE; - } - - @Override - public boolean isSpecial() { - return true; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - AnvilRecipe that = (AnvilRecipe) o; - return damage == that.damage && toolLevel == that.toolLevel && id.equals(that.id) && input.equals(that.input) && output.equals( - that.output); - } - - @Override - public int hashCode() { - return Objects.hash(id, input, output, damage, toolLevel); - } - - @Override - public String toString() { - return "AnvilRecipe [" + id + "]"; - } - - public static class Builder { - private final static Builder INSTANCE = new Builder(); - - private ResourceLocation id; - private Ingredient input; - private ItemLike output; - private int inputCount = 1; - private int outputCount = 1; - private int toolLevel = 1; - private int anvilLevel = 1; - private int damage = 1; - private boolean alright; - private boolean exist; - - private Builder() { - } - - public Builder setInput(ItemLike... inputItems) { - this.alright &= RecipeHelper.exists(inputItems); - this.setInput(Ingredient.of(inputItems)); - return this; - } - - public Builder setInput(TagKey inputTag) { - this.setInput(Ingredient.of(inputTag)); - return this; - } - - public Builder setInput(Ingredient ingredient) { - this.input = ingredient; - return this; - } - - public Builder setInputCount(int count) { - this.inputCount = count; - return this; - } - - public Builder setOutputCount(int count) { - this.outputCount = count; - return this; - } - - public Builder setToolLevel(int level) { - this.toolLevel = level; - return this; - } - - public Builder setAnvilLevel(int level) { - this.anvilLevel = level; - return this; - } - - public Builder setDamage(int damage) { - this.damage = damage; - return this; - } - - public Builder checkConfig(PathConfig config) { - exist &= config.getBoolean("anvil", id.getPath(), true); - return this; - } - - public void build() { - if (!exist) { - return; - } - - if (input == null) { - BCLib.LOGGER.warning("Input for Anvil recipe can't be 'null', recipe {} will be ignored!", id); - return; - } - if (output == null) { - BCLib.LOGGER.warning("Output for Anvil recipe can't be 'null', recipe {} will be ignored!", id); - return; - } - if (BCLRecipeManager.getRecipe(TYPE, id) != null) { - BCLib.LOGGER.warning("Can't add Anvil recipe! Id {} already exists!", id); - return; - } - if (!alright) { - BCLib.LOGGER.debug("Can't add Anvil recipe {}! Ingeredient or output not exists.", id); - return; - } - BCLRecipeManager.addRecipe( - TYPE, - new AnvilRecipe( - id, - input, - new ItemStack(output, outputCount), - inputCount, - toolLevel, - anvilLevel, - damage - ) - ); - } - } - - public static class Serializer implements RecipeSerializer { - @Override - public AnvilRecipe fromJson(ResourceLocation id, JsonObject json) { - Ingredient input = Ingredient.fromJson(json.get("input")); - JsonObject result = GsonHelper.getAsJsonObject(json, "result"); - ItemStack output = ItemUtil.fromJsonRecipe(result); - if (output == null) { - throw new IllegalStateException("Output item does not exists!"); - } - if (result.has("nbt")) { - try { - String nbtData = GsonHelper.getAsString(result, "nbt"); - CompoundTag nbt = TagParser.parseTag(nbtData); - output.setTag(nbt); - } catch (CommandSyntaxException ex) { - BCLib.LOGGER.warning("Error parse nbt data for output.", ex); - } - } - int inputCount = GsonHelper.getAsInt(json, "inputCount", 1); - int toolLevel = GsonHelper.getAsInt(json, "toolLevel", 1); - int anvilLevel = GsonHelper.getAsInt(json, "anvilLevel", 1); - int damage = GsonHelper.getAsInt(json, "damage", 1); - - return new AnvilRecipe(id, input, output, inputCount, toolLevel, anvilLevel, damage); - } - - @Override - public AnvilRecipe fromNetwork(ResourceLocation id, FriendlyByteBuf packetBuffer) { - Ingredient input = Ingredient.fromNetwork(packetBuffer); - ItemStack output = packetBuffer.readItem(); - int inputCount = packetBuffer.readVarInt(); - int toolLevel = packetBuffer.readVarInt(); - int anvilLevel = packetBuffer.readVarInt(); - int damage = packetBuffer.readVarInt(); - - return new AnvilRecipe(id, input, output, inputCount, toolLevel, anvilLevel, damage); - } - - @Override - public void toNetwork(FriendlyByteBuf packetBuffer, AnvilRecipe recipe) { - recipe.input.toNetwork(packetBuffer); - packetBuffer.writeItem(recipe.output); - packetBuffer.writeVarInt(recipe.inputCount); - packetBuffer.writeVarInt(recipe.toolLevel); - packetBuffer.writeVarInt(recipe.anvilLevel); - packetBuffer.writeVarInt(recipe.damage); - } - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/BCLRecipeBuilder.java b/src/main/java/org/betterx/bclib/recipes/BCLRecipeBuilder.java deleted file mode 100644 index 17529b73..00000000 --- a/src/main/java/org/betterx/bclib/recipes/BCLRecipeBuilder.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.betterx.bclib.recipes; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.ItemLike; - -public class BCLRecipeBuilder { - public static AlloyingRecipe.Builder alloying(ResourceLocation id, ItemLike output) { - return AlloyingRecipe.Builder.create(id, output); - } - - public static AnvilRecipe.Builder anvil(ResourceLocation id, ItemLike output) { - return AnvilRecipe.create(id, output); - } - - public static BlastFurnaceRecipe blasting(ResourceLocation id, ItemLike output) { - return BlastFurnaceRecipe.make(id, output); - } - - public static GridRecipe crafting(ResourceLocation id, ItemLike output) { - return GridRecipe.make(id, output); - } - - public static FurnaceRecipe smelting(ResourceLocation id, ItemLike output) { - return FurnaceRecipe.make(id, output); - } - - public static SmithingTableRecipe smithing(ResourceLocation id, ItemLike output) { - return SmithingTableRecipe.make(id, output); - } - - public static StoneCutterRecipe stonecutting(ResourceLocation id, ItemLike output) { - return StoneCutterRecipe.make(id, output); - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/BCLRecipeManager.java b/src/main/java/org/betterx/bclib/recipes/BCLRecipeManager.java deleted file mode 100644 index bccb8937..00000000 --- a/src/main/java/org/betterx/bclib/recipes/BCLRecipeManager.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.util.CollectionsUtil; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeSerializer; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.block.Block; - -import com.google.common.collect.Maps; - -import java.util.*; -import java.util.Map.Entry; -import java.util.function.Function; - -public class BCLRecipeManager { - private static final Map> _RECIPES = Maps.newHashMap(); - private static final Map> _SORTED = Maps.newHashMap(); - private static final String MINECRAFT = "minecraft"; - - @SuppressWarnings("unchecked") - private static > Map, Map> RECIPES() { - return (Map, Map>) _RECIPES; - } - - @SuppressWarnings("unchecked") - private static > Map, List> SORTED() { - return (Map, List>) _SORTED; - } - - public static > Optional getSortedRecipe( - RecipeType type, - C inventory, - Level level, - Function, Map> getter - ) { - List recipes = BCLRecipeManager.SORTED().computeIfAbsent(type, t -> { - Collection values = getter.apply(type).values(); - List list = new ArrayList<>(values); - list.sort((v1, v2) -> { - boolean b1 = v1.getId().getNamespace().equals(MINECRAFT); - boolean b2 = v2.getId().getNamespace().equals(MINECRAFT); - return b1 ^ b2 ? (b1 ? 1 : -1) : v1.getId().compareTo(v2.getId()); - }); - return list; - }); - return recipes.stream().filter(recipe -> recipe.matches(inventory, level)).findFirst(); - } - - public static > void addRecipe(RecipeType type, T recipe) { - Map list = BCLRecipeManager.RECIPES().computeIfAbsent(type, i -> Maps.newHashMap()); - list.put(recipe.getId(), recipe); - } - - public static > T getRecipe(RecipeType type, ResourceLocation id) { - Map map = BCLRecipeManager.RECIPES().get(type); - return map != null ? map.get(id) : null; - } - - public static > Map, Map> getMap( - Map, Map> recipes - ) { - Map, Map> result = Maps.newHashMap(); - - for (RecipeType type : recipes.keySet()) { - Map typeList = Maps.newHashMap(); - typeList.putAll(recipes.get(type)); - result.put(type, typeList); - } - - SORTED().clear(); - BCLRecipeManager.RECIPES().forEach((type, list) -> { - if (list != null) { - Map typeList = result.computeIfAbsent(type, i -> Maps.newHashMap()); - for (Entry entry : list.entrySet()) { - ResourceLocation id = entry.getKey(); - typeList.computeIfAbsent(id, i -> entry.getValue()); - } - } - }); - - return result; - } - - public static > Map getMapByName(Map recipes) { - Map result = CollectionsUtil.getMutable(recipes); - BCLRecipeManager.RECIPES().values() - .forEach(map -> map.forEach((location, recipe) -> result.computeIfAbsent( - location, - i -> recipe - ))); - return result; - } - - public static , T extends Recipe> S registerSerializer( - String modID, - String id, - S serializer - ) { - return Registry.register(Registry.RECIPE_SERIALIZER, modID + ":" + id, serializer); - } - - public static > RecipeType registerType(String modID, String type) { - ResourceLocation recipeTypeId = new ResourceLocation(modID, type); - return Registry.register(Registry.RECIPE_TYPE, recipeTypeId, new RecipeType() { - public String toString() { - return type; - } - }); - } - - public static boolean exists(ItemLike item) { - if (item instanceof Block) { - return Registry.BLOCK.getKey((Block) item) != Registry.BLOCK.getDefaultKey(); - } else { - return item != Items.AIR && Registry.ITEM.getKey(item.asItem()) != Registry.ITEM.getDefaultKey(); - } - } - - public static boolean exists(ItemLike... items) { - for (ItemLike item : items) { - if (!exists(item)) { - return false; - } - } - return true; - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/bclib/recipes/BlastFurnaceRecipe.java b/src/main/java/org/betterx/bclib/recipes/BlastFurnaceRecipe.java deleted file mode 100644 index 373f015c..00000000 --- a/src/main/java/org/betterx/bclib/recipes/BlastFurnaceRecipe.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.betterx.bclib.recipes; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.Container; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.BlastingRecipe; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.ItemLike; - -public class BlastFurnaceRecipe extends CookingRecipe { - BlastFurnaceRecipe(ResourceLocation id, ItemLike output) { - super(id, RecipeType.BLASTING, output); - } - - static BlastFurnaceRecipe make(String modID, String name, ItemLike output) { - return make(new ResourceLocation(modID, name), output); - } - - static BlastFurnaceRecipe make(ResourceLocation id, ItemLike output) { - BlastFurnaceRecipe res = new BlastFurnaceRecipe(id, output); - res.createAdvancement(id, false); - return res; - } - - @Override - protected BlastingRecipe buildRecipe() { - return new BlastingRecipe(id, group, input, new ItemStack(output, count), experience, cookingTime); - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/CookingRecipe.java b/src/main/java/org/betterx/bclib/recipes/CookingRecipe.java deleted file mode 100644 index 7799715c..00000000 --- a/src/main/java/org/betterx/bclib/recipes/CookingRecipe.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.betterx.bclib.recipes; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.Container; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.crafting.Recipe; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.level.ItemLike; - -public abstract class CookingRecipe> extends AbstractSimpleRecipe { - protected float experience; - protected int cookingTime; - - CookingRecipe(ResourceLocation id, RecipeType type, ItemLike output) { - this(id, type, type.toString(), output); - } - - CookingRecipe(ResourceLocation id, RecipeType type, String category, ItemLike output) { - super(id, type, category, output); - cookingTime = 1000; - experience = 0; - } - - public T setInput(ItemLike in) { - return super.setInput(in); - } - - public T setInput(TagKey in) { - return super.setInput(in); - } - - public T setExperience(float xp) { - experience = xp; - return (T) this; - } - - public T setCookingTime(int time) { - cookingTime = time; - return (T) this; - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/CraftingRecipes.java b/src/main/java/org/betterx/bclib/recipes/CraftingRecipes.java deleted file mode 100644 index 10bf0bb2..00000000 --- a/src/main/java/org/betterx/bclib/recipes/CraftingRecipes.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.Configs; -import org.betterx.worlds.together.tag.v3.CommonItemTags; - -import net.minecraft.tags.ItemTags; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Blocks; - -public class CraftingRecipes { - public static void init() { - BCLRecipeBuilder.crafting(BCLib.makeID("tag_smith_table"), Blocks.SMITHING_TABLE) - .setShape("II", "##", "##") - .addMaterial('#', ItemTags.PLANKS) - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_cauldron"), Blocks.CAULDRON) - .setShape("I I", "I I", "III") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_hopper"), Blocks.HOPPER) - .setShape("I I", "ICI", " I ") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .addMaterial('C', CommonItemTags.CHEST) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_piston"), Blocks.PISTON) - .setShape("WWW", "CIC", "CDC") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .addMaterial('D', Items.REDSTONE) - .addMaterial('C', Items.COBBLESTONE) - .addMaterial('W', ItemTags.PLANKS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_rail"), Blocks.RAIL) - .setOutputCount(16) - .setShape("I I", "ISI", "I I") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .addMaterial('S', Items.STICK) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_stonecutter"), Blocks.STONECUTTER) - .setShape(" I ", "SSS") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .addMaterial('S', Items.STONE) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_compass"), Items.COMPASS) - .setShape(" I ", "IDI", " I ") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .addMaterial('D', Items.REDSTONE) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_bucket"), Items.BUCKET) - .setShape("I I", " I ") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_minecart"), Items.MINECART) - .setShape("I I", "III") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - BCLRecipeBuilder.crafting(BCLib.makeID("tag_shield"), Items.SHIELD) - .setShape("WIW", "WWW", " W ") - .addMaterial('I', CommonItemTags.IRON_INGOTS) - .addMaterial('W', ItemTags.PLANKS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - - BCLRecipeBuilder.crafting(BCLib.makeID("tag_shulker_box"), Blocks.SHULKER_BOX) - .setShape("S", "C", "S") - .addMaterial('S', Items.SHULKER_SHELL) - .addMaterial('C', CommonItemTags.CHEST) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/FurnaceRecipe.java b/src/main/java/org/betterx/bclib/recipes/FurnaceRecipe.java deleted file mode 100644 index 39f57971..00000000 --- a/src/main/java/org/betterx/bclib/recipes/FurnaceRecipe.java +++ /dev/null @@ -1,146 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.config.PathConfig; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.*; -import net.minecraft.world.level.ItemLike; - -public class FurnaceRecipe extends AbstractAdvancementRecipe { - private static final FurnaceRecipe INSTANCE = new FurnaceRecipe(); - - private ResourceLocation id; - private Ingredient input; - private ItemLike output; - private boolean exist; - private String group; - private int count; - private int time; - private float xp; - - private FurnaceRecipe() { - } - - static FurnaceRecipe make(ResourceLocation id, ItemLike output) { - INSTANCE.id = id; - INSTANCE.group = ""; - INSTANCE.input = null; - INSTANCE.output = output; - INSTANCE.count = 1; - INSTANCE.time = 200; - INSTANCE.xp = 0; - INSTANCE.exist = BCLRecipeManager.exists(output); - INSTANCE.createAdvancement(INSTANCE.id, false); - - return INSTANCE; - } - - public FurnaceRecipe setInput(ItemLike input) { - exist &= BCLRecipeManager.exists(input); - this.input = Ingredient.of(input); - unlockedBy(input); - return this; - } - - public FurnaceRecipe setInput(TagKey tag) { - this.input = Ingredient.of(tag); - unlockedBy(tag); - return this; - } - - public FurnaceRecipe checkConfig(PathConfig config) { - exist &= config.getBoolean("furnace", id.getPath(), true); - return this; - } - - public FurnaceRecipe setGroup(String group) { - this.group = group; - return this; - } - - public FurnaceRecipe setOutputCount(int count) { - this.count = count; - return this; - } - - public FurnaceRecipe setExperience(float xp) { - this.xp = xp; - return this; - } - - public FurnaceRecipe setCookingTime(int time) { - this.time = time; - return this; - } - - public void build() { - build(false, false, false); - } - - public void buildWithBlasting() { - build(true, false, false); - } - - public void buildFoodlike() { - build(false, true, true); - } - - public void build(boolean blasting, boolean campfire, boolean smoker) { - if (!exist) { - return; - } - - SmeltingRecipe recipe = new SmeltingRecipe( - new ResourceLocation(id + "_smelting"), - group, - input, - new ItemStack(output, count), - xp, - time - ); - BCLRecipeManager.addRecipe(RecipeType.SMELTING, recipe); - registerAdvancement(recipe); - - if (blasting) { - BlastingRecipe recipe2 = new BlastingRecipe( - new ResourceLocation(id + "_blasting"), - group, - input, - new ItemStack(output, count), - xp, - time / 2 - ); - - BCLRecipeManager.addRecipe(RecipeType.BLASTING, recipe2); - } - - if (campfire) { - CampfireCookingRecipe recipe2 = new CampfireCookingRecipe( - new ResourceLocation(id + "_campfire"), - group, - input, - new ItemStack(output, count), - xp, - time * 3 - ); - - BCLRecipeManager.addRecipe(RecipeType.CAMPFIRE_COOKING, recipe2); - } - - if (smoker) { - SmokingRecipe recipe2 = new SmokingRecipe( - new ResourceLocation(id + "_smoker"), - group, - input, - new ItemStack(output, count), - xp, - time / 2 - ); - - BCLRecipeManager.addRecipe(RecipeType.SMOKING, recipe2); - } - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/GridRecipe.java b/src/main/java/org/betterx/bclib/recipes/GridRecipe.java deleted file mode 100644 index 9d82a4a3..00000000 --- a/src/main/java/org/betterx/bclib/recipes/GridRecipe.java +++ /dev/null @@ -1,157 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.config.PathConfig; - -import net.minecraft.core.NonNullList; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.crafting.*; -import net.minecraft.world.level.ItemLike; - -import com.google.common.collect.Maps; - -import java.util.Arrays; -import java.util.Map; - -public class GridRecipe extends AbstractAdvancementRecipe { - private static final GridRecipe INSTANCE = new GridRecipe(); - - private ResourceLocation id; - private ItemLike output; - - private String group; - private RecipeType type; - private boolean shaped; - private String[] shape; - private final Map materialKeys = Maps.newHashMap(); - private int count; - private boolean exist; - - private GridRecipe() { - } - - /** - * Please use {@link BCLRecipeBuilder#crafting(ResourceLocation, ItemLike)} instead - * - * @param id - * @param output - * @return - */ - static GridRecipe make(ResourceLocation id, ItemLike output) { - INSTANCE.id = id; - INSTANCE.output = output; - - INSTANCE.group = ""; - INSTANCE.type = RecipeType.CRAFTING; - INSTANCE.shaped = true; - INSTANCE.shape = new String[]{"#"}; - INSTANCE.materialKeys.clear(); - INSTANCE.count = 1; - - INSTANCE.exist = output != null && BCLRecipeManager.exists(output); - INSTANCE.createAdvancement(id, output); - return INSTANCE; - } - - public GridRecipe checkConfig(PathConfig config) { - exist &= config.getBoolean("grid", id.getPath(), true); - return this; - } - - public GridRecipe setGroup(String group) { - this.group = group; - return this; - } - - public GridRecipe setShape(String... shape) { - this.shape = shape; - return this; - } - - public GridRecipe setList(String shape) { - this.shape = new String[]{shape}; - this.shaped = false; - return this; - } - - public GridRecipe addMaterial(char key, TagKey value) { - unlockedBy(value); - return addMaterial(key, Ingredient.of(value)); - } - - public GridRecipe addMaterial(char key, ItemStack... values) { - unlockedBy(values); - return addMaterial(key, Ingredient.of(Arrays.stream(values))); - } - - public GridRecipe addMaterial(char key, ItemLike... values) { - for (ItemLike item : values) { - exist &= BCLRecipeManager.exists(item); - } - unlockedBy(values); - return addMaterial(key, Ingredient.of(values)); - } - - private GridRecipe addMaterial(char key, Ingredient value) { - materialKeys.put(key, value); - return this; - } - - public GridRecipe setOutputCount(int count) { - this.count = count; - return this; - } - - private NonNullList getMaterials(int width, int height) { - NonNullList materials = NonNullList.withSize(width * height, Ingredient.EMPTY); - int pos = 0; - boolean hasNonEmpty = false; - for (String line : shape) { - for (int i = 0; i < width; i++) { - char c = line.charAt(i); - Ingredient material = materialKeys.get(c); - if (material != null && !material.isEmpty()) hasNonEmpty = true; - materials.set(pos++, material == null ? Ingredient.EMPTY : material); - } - } - if (!hasNonEmpty) return null; - return materials; - } - - - public void build() { - if (!exist) { - BCLib.LOGGER.warning("Unable to build Recipe " + id); - return; - } - - int height = shape.length; - int width = shape[0].length(); - ItemStack result = new ItemStack(output, count); - if (result.is(Items.AIR)) { - BCLib.LOGGER.warning("Unable to build Recipe " + id + ": Result is AIR"); - return; - } - NonNullList materials = this.getMaterials(width, height); - if (materials == null || materials.isEmpty()) { - BCLib.LOGGER.warning("Unable to build Recipe " + id + ": Empty Material List"); - return; - } - - CraftingRecipe recipe = shaped ? new ShapedRecipe( - id, - group, - width, - height, - materials, - result - ) : new ShapelessRecipe(id, group, result, materials); - - BCLRecipeManager.addRecipe(type, recipe); - registerAdvancement(recipe); - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/SmithingTableRecipe.java b/src/main/java/org/betterx/bclib/recipes/SmithingTableRecipe.java deleted file mode 100644 index 22afa290..00000000 --- a/src/main/java/org/betterx/bclib/recipes/SmithingTableRecipe.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.betterx.bclib.recipes; - -import org.betterx.bclib.BCLib; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.Container; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.Ingredient; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.item.crafting.UpgradeRecipe; -import net.minecraft.world.level.ItemLike; - -public class SmithingTableRecipe extends AbstractSimpleRecipe { - protected Ingredient addon; - - protected SmithingTableRecipe(ResourceLocation id, ItemLike output) { - super(id, RecipeType.SMITHING, output); - } - - - static SmithingTableRecipe make(ResourceLocation id, ItemLike output) { - SmithingTableRecipe res = new SmithingTableRecipe(id, output); - res.createAdvancement(id, false); - return res; - } - - public SmithingTableRecipe setBase(ItemLike in) { - return super.setInput(in); - } - - public SmithingTableRecipe setBase(TagKey in) { - return super.setInput(in); - } - - public SmithingTableRecipe setAddition(ItemLike in) { - this.exist &= BCLRecipeManager.exists(in); - this.addon = Ingredient.of(in); - unlockedBy(in); - return this; - } - - public SmithingTableRecipe setAddition(TagKey in) { - this.addon = Ingredient.of(in); - unlockedBy(in); - return this; - } - - @Override - protected boolean hasErrors() { - if (addon == null || addon.isEmpty()) { - BCLib.LOGGER.warning("Unable to build Recipe " + id + ": No Addon Ingredient"); - return true; - } - return super.hasErrors(); - } - - @Override - protected UpgradeRecipe buildRecipe() { - return new UpgradeRecipe(id, input, addon, new ItemStack(output, count)); - } -} diff --git a/src/main/java/org/betterx/bclib/recipes/StoneCutterRecipe.java b/src/main/java/org/betterx/bclib/recipes/StoneCutterRecipe.java deleted file mode 100644 index de64ab9e..00000000 --- a/src/main/java/org/betterx/bclib/recipes/StoneCutterRecipe.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.recipes; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.Container; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeType; -import net.minecraft.world.item.crafting.StonecutterRecipe; -import net.minecraft.world.level.ItemLike; - -public class StoneCutterRecipe extends AbstractSimpleRecipe { - StoneCutterRecipe(ResourceLocation id, ItemLike output) { - super(id, RecipeType.STONECUTTING, "stonecutting", output); - } - - static StoneCutterRecipe make(ResourceLocation id, ItemLike output) { - StoneCutterRecipe res = new StoneCutterRecipe(id, output); - res.createAdvancement(id, false); - return res; - } - - public StoneCutterRecipe setInput(ItemLike in) { - return super.setInput(in); - } - - public StoneCutterRecipe setInput(TagKey in) { - return super.setInput(in); - } - - @Override - protected StonecutterRecipe buildRecipe() { - return new StonecutterRecipe(id, group, input, new ItemStack(output, count)); - } -} diff --git a/src/main/java/org/betterx/bclib/registry/BaseBlockEntities.java b/src/main/java/org/betterx/bclib/registry/BaseBlockEntities.java deleted file mode 100644 index 8988b4d6..00000000 --- a/src/main/java/org/betterx/bclib/registry/BaseBlockEntities.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.betterx.bclib.registry; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.blockentities.*; -import org.betterx.bclib.blockentities.DynamicBlockEntityType.BlockEntitySupplier; -import org.betterx.bclib.blocks.BaseBarrelBlock; -import org.betterx.bclib.blocks.BaseChestBlock; -import org.betterx.bclib.blocks.BaseFurnaceBlock; -import org.betterx.bclib.blocks.BaseSignBlock; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.entity.BlockEntity; - -public class BaseBlockEntities { - public static final DynamicBlockEntityType CHEST = registerBlockEntityType(BCLib.makeID( - "chest"), BaseChestBlockEntity::new); - public static final DynamicBlockEntityType BARREL = registerBlockEntityType(BCLib.makeID( - "barrel"), BaseBarrelBlockEntity::new); - public static final DynamicBlockEntityType SIGN = registerBlockEntityType( - BCLib.makeID("sign"), - BaseSignBlockEntity::new - ); - public static final DynamicBlockEntityType FURNACE = registerBlockEntityType(BCLib.makeID( - "furnace"), BaseFurnaceBlockEntity::new); - - public static DynamicBlockEntityType registerBlockEntityType( - ResourceLocation typeId, - BlockEntitySupplier supplier - ) { - return Registry.register(Registry.BLOCK_ENTITY_TYPE, typeId, new DynamicBlockEntityType<>(supplier)); - } - - public static void register() { - } - - public static Block[] getChests() { - return Registry.BLOCK - .stream() - .filter(block -> block instanceof BaseChestBlock) - .toArray(Block[]::new); - } - - public static Block[] getBarrels() { - return Registry.BLOCK - .stream() - .filter(block -> block instanceof BaseBarrelBlock) - .toArray(Block[]::new); - } - - public static Block[] getSigns() { - return Registry.BLOCK - .stream() - .filter(block -> block instanceof BaseSignBlock) - .toArray(Block[]::new); - } - - public static Block[] getFurnaces() { - return Registry.BLOCK - .stream() - .filter(block -> block instanceof BaseFurnaceBlock) - .toArray(Block[]::new); - } -} diff --git a/src/main/java/org/betterx/bclib/registry/BaseBlockEntityRenders.java b/src/main/java/org/betterx/bclib/registry/BaseBlockEntityRenders.java deleted file mode 100644 index 89faed81..00000000 --- a/src/main/java/org/betterx/bclib/registry/BaseBlockEntityRenders.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.betterx.bclib.registry; - -import org.betterx.bclib.client.render.BaseChestBlockEntityRenderer; -import org.betterx.bclib.client.render.BaseSignBlockEntityRenderer; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.client.rendering.v1.BlockEntityRendererRegistry; - -@Environment(EnvType.CLIENT) -public class BaseBlockEntityRenders { - public static void register() { - BlockEntityRendererRegistry.register(BaseBlockEntities.CHEST, BaseChestBlockEntityRenderer::new); - BlockEntityRendererRegistry.register(BaseBlockEntities.SIGN, BaseSignBlockEntityRenderer::new); - } -} diff --git a/src/main/java/org/betterx/bclib/registry/BaseRegistry.java b/src/main/java/org/betterx/bclib/registry/BaseRegistry.java deleted file mode 100644 index eb8961a4..00000000 --- a/src/main/java/org/betterx/bclib/registry/BaseRegistry.java +++ /dev/null @@ -1,81 +0,0 @@ -package org.betterx.bclib.registry; - -import org.betterx.bclib.config.PathConfig; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import java.util.List; -import java.util.Map; - -public abstract class BaseRegistry { - private static final List> REGISTRIES = Lists.newArrayList(); - private static final Map> MOD_BLOCK_ITEMS = Maps.newHashMap(); - private static final Map> MOD_BLOCKS = Maps.newHashMap(); - private static final Map> MOD_ITEMS = Maps.newHashMap(); - - protected final CreativeModeTab creativeTab; - protected final PathConfig config; - - protected BaseRegistry(CreativeModeTab creativeTab, PathConfig config) { - this.creativeTab = creativeTab; - this.config = config; - REGISTRIES.add(this); - } - - public abstract T register(ResourceLocation objId, T obj); - - public abstract void registerItem(ResourceLocation id, Item item); - - public Item.Properties makeItemSettings() { - Item.Properties properties = new Item.Properties(); - return properties.tab(creativeTab); - } - - private void registerInternal() { - } - - public static Map> getRegisteredBlocks() { - return MOD_BLOCK_ITEMS; - } - - public static Map> getRegisteredItems() { - return MOD_ITEMS; - } - - public static List getModBlockItems(String modId) { - if (MOD_BLOCK_ITEMS.containsKey(modId)) { - return MOD_BLOCK_ITEMS.get(modId); - } - List modBlocks = Lists.newArrayList(); - MOD_BLOCK_ITEMS.put(modId, modBlocks); - return modBlocks; - } - - public static List getModItems(String modId) { - if (MOD_ITEMS.containsKey(modId)) { - return MOD_ITEMS.get(modId); - } - List modBlocks = Lists.newArrayList(); - MOD_ITEMS.put(modId, modBlocks); - return modBlocks; - } - - public static List getModBlocks(String modId) { - if (MOD_BLOCKS.containsKey(modId)) { - return MOD_BLOCKS.get(modId); - } - List modBlocks = Lists.newArrayList(); - MOD_BLOCKS.put(modId, modBlocks); - return modBlocks; - } - - public static void register() { - REGISTRIES.forEach(BaseRegistry::registerInternal); - } -} diff --git a/src/main/java/org/betterx/bclib/registry/BlockRegistry.java b/src/main/java/org/betterx/bclib/registry/BlockRegistry.java deleted file mode 100644 index 69d881fb..00000000 --- a/src/main/java/org/betterx/bclib/registry/BlockRegistry.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.betterx.bclib.registry; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.blocks.BaseLeavesBlock; -import org.betterx.bclib.blocks.BaseOreBlock; -import org.betterx.bclib.blocks.FeatureSaplingBlock; -import org.betterx.bclib.config.PathConfig; -import org.betterx.bclib.interfaces.CustomItemProvider; -import org.betterx.worlds.together.tag.v3.CommonBlockTags; -import org.betterx.worlds.together.tag.v3.CommonItemTags; -import org.betterx.worlds.together.tag.v3.MineableTags; -import org.betterx.worlds.together.tag.v3.TagManager; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.Items; -import net.minecraft.world.level.block.Block; - -import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; - -public class BlockRegistry extends BaseRegistry { - public BlockRegistry(CreativeModeTab creativeTab, PathConfig config) { - super(creativeTab, config); - } - - @Override - public Block register(ResourceLocation id, Block block) { - if (!config.getBooleanRoot(id.getNamespace(), true)) { - BCLib.LOGGER.warning("Block " + id + " disabled"); - return block; - } - BlockItem item = null; - if (block instanceof CustomItemProvider) { - item = ((CustomItemProvider) block).getCustomItem(id, makeItemSettings()); - } else { - item = new BlockItem(block, makeItemSettings()); - - } - registerBlockItem(id, item); - if (block.defaultBlockState().getMaterial().isFlammable() - && FlammableBlockRegistry.getDefaultInstance() - .get(block) - .getBurnChance() == 0) { - FlammableBlockRegistry.getDefaultInstance().add(block, 5, 5); - } - - block = Registry.register(Registry.BLOCK, id, block); - getModBlocks(id.getNamespace()).add(block); - - if (block instanceof BaseLeavesBlock) { - TagManager.BLOCKS.add( - block, - BlockTags.LEAVES, - CommonBlockTags.LEAVES, - MineableTags.HOE, - MineableTags.SHEARS - ); - if (item != null) { - TagManager.ITEMS.add(item, CommonItemTags.LEAVES, ItemTags.LEAVES); - } - } else if (block instanceof BaseOreBlock) { - TagManager.BLOCKS.add(block, MineableTags.PICKAXE); - } else if (block instanceof FeatureSaplingBlock) { - TagManager.BLOCKS.add(block, CommonBlockTags.SAPLINGS, BlockTags.SAPLINGS); - if (item != null) { - TagManager.ITEMS.add(item, CommonItemTags.SAPLINGS, ItemTags.SAPLINGS); - } - } - - return block; - } - - public Block registerBlockOnly(ResourceLocation id, Block block) { - if (!config.getBooleanRoot(id.getNamespace(), true)) { - return block; - } - getModBlocks(id.getNamespace()).add(block); - return Registry.register(Registry.BLOCK, id, block); - } - - private Item registerBlockItem(ResourceLocation id, BlockItem item) { - registerItem(id, item); - return item; - } - - @Override - public void registerItem(ResourceLocation id, Item item) { - if (item != null && item != Items.AIR) { - Registry.register(Registry.ITEM, id, item); - getModBlockItems(id.getNamespace()).add(item); - } - } -} diff --git a/src/main/java/org/betterx/bclib/registry/ItemRegistry.java b/src/main/java/org/betterx/bclib/registry/ItemRegistry.java deleted file mode 100644 index ea86bfeb..00000000 --- a/src/main/java/org/betterx/bclib/registry/ItemRegistry.java +++ /dev/null @@ -1,152 +0,0 @@ -package org.betterx.bclib.registry; - -import org.betterx.bclib.config.PathConfig; -import org.betterx.bclib.items.BaseDiscItem; -import org.betterx.bclib.items.BaseDrinkItem; -import org.betterx.bclib.items.BaseSpawnEggItem; -import org.betterx.bclib.items.ModelProviderItem; -import org.betterx.bclib.items.tool.BaseAxeItem; -import org.betterx.bclib.items.tool.BaseHoeItem; -import org.betterx.bclib.items.tool.BasePickaxeItem; -import org.betterx.bclib.items.tool.BaseShearsItem; -import org.betterx.bclib.models.RecordItemModelProvider; -import org.betterx.worlds.together.tag.v3.CommonItemTags; -import org.betterx.worlds.together.tag.v3.TagManager; -import org.betterx.worlds.together.tag.v3.ToolTags; - -import net.minecraft.core.BlockSource; -import net.minecraft.core.Direction; -import net.minecraft.core.Registry; -import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; -import net.minecraft.core.dispenser.ShearsDispenseItemBehavior; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.sounds.SoundEvent; -import net.minecraft.world.effect.MobEffectInstance; -import net.minecraft.world.entity.EntityType; -import net.minecraft.world.entity.Mob; -import net.minecraft.world.entity.MobSpawnType; -import net.minecraft.world.food.FoodProperties; -import net.minecraft.world.item.*; -import net.minecraft.world.level.block.DispenserBlock; - -public class ItemRegistry extends BaseRegistry { - public ItemRegistry(CreativeModeTab creativeTab, PathConfig config) { - super(creativeTab, config); - } - - public Item registerDisc(ResourceLocation itemId, int power, SoundEvent sound, int lengthInSeconds) { - RecordItem item = BaseDiscItem.create(power, sound, makeItemSettings().stacksTo(1), lengthInSeconds); - if (item != null) { - RecordItemModelProvider.add(item); - if (!config.getBoolean("musicDiscs", itemId.getPath(), true)) { - return item; - } - register(itemId, item); - } - return item; - } - - public Item register(ResourceLocation itemId) { - return register(itemId, new ModelProviderItem(makeItemSettings())); - } - - @Override - public Item register(ResourceLocation itemId, Item item) { - if (!config.getBoolean("items", itemId.getPath(), true)) { - return item; - } - - registerItem(itemId, item); - - return item; - } - - public Item registerTool(ResourceLocation itemId, Item item) { - if (!config.getBoolean("tools", itemId.getPath(), true)) { - return item; - } - - registerItem(itemId, item); - - if (item instanceof ShovelItem) { - TagManager.ITEMS.add(ToolTags.FABRIC_SHOVELS, item); - } else if (item instanceof SwordItem) { - TagManager.ITEMS.add(ToolTags.FABRIC_SWORDS, item); - } else if (item instanceof BasePickaxeItem) { - TagManager.ITEMS.add(ToolTags.FABRIC_PICKAXES, item); - } else if (item instanceof BaseAxeItem) { - TagManager.ITEMS.add(ToolTags.FABRIC_AXES, item); - } else if (item instanceof BaseHoeItem) { - TagManager.ITEMS.add(ToolTags.FABRIC_HOES, item); - } else if (item instanceof BaseShearsItem) { - TagManager.ITEMS.add(item, ToolTags.FABRIC_SHEARS, CommonItemTags.SHEARS); - DispenserBlock.registerBehavior(item.asItem(), new ShearsDispenseItemBehavior()); - } - - return item; - } - - public Item registerEgg(ResourceLocation itemId, EntityType type, int background, int dots) { - SpawnEggItem item = new BaseSpawnEggItem(type, background, dots, makeItemSettings()); - - if (!config.getBoolean("spawnEggs", itemId.getPath(), true)) { - return item; - } - - DefaultDispenseItemBehavior behavior = new DefaultDispenseItemBehavior() { - public ItemStack execute(BlockSource pointer, ItemStack stack) { - Direction direction = pointer.getBlockState().getValue(DispenserBlock.FACING); - EntityType entityType = ((SpawnEggItem) stack.getItem()).getType(stack.getTag()); - entityType.spawn( - pointer.getLevel(), - stack, - null, - pointer.getPos().relative(direction), - MobSpawnType.DISPENSER, - direction != Direction.UP, - false - ); - stack.shrink(1); - return stack; - } - }; - DispenserBlock.registerBehavior(item, behavior); - return register(itemId, item); - } - - public Item registerFood(ResourceLocation itemId, int hunger, float saturation, MobEffectInstance... effects) { - FoodProperties.Builder builder = new FoodProperties.Builder().nutrition(hunger).saturationMod(saturation); - for (MobEffectInstance effect : effects) { - builder.effect(effect, 1F); - } - return registerFood(itemId, builder.build()); - } - - public Item registerFood(ResourceLocation itemId, FoodProperties foodComponent) { - return register(itemId, new ModelProviderItem(makeItemSettings().food(foodComponent))); - } - - public Item registerDrink(ResourceLocation itemId, FoodProperties foodComponent) { - return register(itemId, new BaseDrinkItem(makeItemSettings().stacksTo(1).food(foodComponent))); - } - - public Item registerDrink(ResourceLocation itemId, int hunger, float saturation) { - FoodProperties.Builder builder = new FoodProperties.Builder().nutrition(hunger).saturationMod(saturation); - return registerDrink(itemId, builder.build()); - } - - @Override - public void registerItem(ResourceLocation id, Item item) { - if (item != null && item != Items.AIR) { - Registry.register(Registry.ITEM, id, item); - getModItems(id.getNamespace()).add(item); - } - } - - public Item register(ResourceLocation itemId, Item item, String category) { - if (config.getBoolean(category, itemId.getPath(), true)) { - registerItem(itemId, item); - } - return item; - } -} diff --git a/src/main/java/org/betterx/bclib/registry/PresetsRegistry.java b/src/main/java/org/betterx/bclib/registry/PresetsRegistry.java deleted file mode 100644 index 3cd61b77..00000000 --- a/src/main/java/org/betterx/bclib/registry/PresetsRegistry.java +++ /dev/null @@ -1,86 +0,0 @@ -package org.betterx.bclib.registry; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.api.v2.generator.config.BCLEndBiomeSourceConfig; -import org.betterx.bclib.api.v2.generator.config.BCLNetherBiomeSourceConfig; -import org.betterx.bclib.api.v2.levelgen.LevelGenUtil; -import org.betterx.bclib.config.Configs; -import org.betterx.worlds.together.entrypoints.WorldPresetBootstrap; -import org.betterx.worlds.together.levelgen.WorldGenUtil; -import org.betterx.worlds.together.worldPreset.TogetherWorldPreset; -import org.betterx.worlds.together.worldPreset.WorldPresets; - -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.dimension.LevelStem; -import net.minecraft.world.level.levelgen.presets.WorldPreset; - -import java.util.Map; - -public class PresetsRegistry implements WorldPresetBootstrap { - public static ResourceKey BCL_WORLD; - public static ResourceKey BCL_WORLD_17; - - public void bootstrapWorldPresets() { - BCL_WORLD = - WorldPresets.register( - BCLib.makeID("normal"), - (overworldStem, netherContext, endContext) -> - buildPreset( - overworldStem, - netherContext, - BCLNetherBiomeSourceConfig.DEFAULT, endContext, - BCLEndBiomeSourceConfig.DEFAULT - ), - true - ); - - BCL_WORLD_17 = WorldPresets.register( - BCLib.makeID("legacy_17"), - (overworldStem, netherContext, endContext) -> - buildPreset( - overworldStem, - netherContext, - BCLNetherBiomeSourceConfig.MINECRAFT_17, endContext, - BCLEndBiomeSourceConfig.MINECRAFT_17 - ), - false - ); - - if (Configs.CLIENT_CONFIG.forceBetterXPreset()) - WorldPresets.setDEFAULT(BCL_WORLD); - else - WorldPresets.setDEFAULT(net.minecraft.world.level.levelgen.presets.WorldPresets.NORMAL); - } - - public static TogetherWorldPreset buildPreset( - LevelStem overworldStem, - WorldGenUtil.Context netherContext, - BCLNetherBiomeSourceConfig netherConfig, - WorldGenUtil.Context endContext, - BCLEndBiomeSourceConfig endConfig - ) { - return new TogetherWorldPreset(buildDimensionMap( - overworldStem, - netherContext, - netherConfig, endContext, - endConfig - ), 1000); - } - - public static Map, LevelStem> buildDimensionMap( - LevelStem overworldStem, - WorldGenUtil.Context netherContext, - BCLNetherBiomeSourceConfig netherConfig, - WorldGenUtil.Context endContext, - BCLEndBiomeSourceConfig endConfig - ) { - return Map.of( - LevelStem.OVERWORLD, - overworldStem, - LevelStem.NETHER, - LevelGenUtil.getBCLNetherLevelStem(netherContext, netherConfig), - LevelStem.END, - LevelGenUtil.getBCLEndLevelStem(endContext, endConfig) - ); - } -} diff --git a/src/main/java/org/betterx/bclib/registry/PresetsRegistryClient.java b/src/main/java/org/betterx/bclib/registry/PresetsRegistryClient.java deleted file mode 100644 index be28feb3..00000000 --- a/src/main/java/org/betterx/bclib/registry/PresetsRegistryClient.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.betterx.bclib.registry; - -import org.betterx.bclib.client.gui.screens.WorldSetupScreen; -import org.betterx.worlds.together.worldPreset.client.WorldPresetsClient; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class PresetsRegistryClient { - public static void onLoad() { - WorldPresetsClient.registerCustomizeUI(PresetsRegistry.BCL_WORLD, (createWorldScreen, worldCreationContext) -> { - return new WorldSetupScreen(createWorldScreen, worldCreationContext); - }); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/PosInfo.java b/src/main/java/org/betterx/bclib/sdf/PosInfo.java deleted file mode 100644 index 97b5eb1a..00000000 --- a/src/main/java/org/betterx/bclib/sdf/PosInfo.java +++ /dev/null @@ -1,104 +0,0 @@ -package org.betterx.bclib.sdf; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.Map; - -public class PosInfo implements Comparable { - private static final BlockState AIR = Blocks.AIR.defaultBlockState(); - private final Map blocks; - private final Map add; - private final BlockPos pos; - private BlockState state; - - public static PosInfo create(Map blocks, Map add, BlockPos pos) { - return new PosInfo(blocks, add, pos); - } - - private PosInfo(Map blocks, Map add, BlockPos pos) { - this.blocks = blocks; - this.add = add; - this.pos = pos; - blocks.put(pos, this); - } - - public BlockState getState() { - return state; - } - - public BlockState getState(BlockPos pos) { - PosInfo info = blocks.get(pos); - if (info == null) { - info = add.get(pos); - return info == null ? AIR : info.getState(); - } - return info.getState(); - } - - public void setState(BlockState state) { - this.state = state; - } - - public void setState(BlockPos pos, BlockState state) { - PosInfo info = blocks.get(pos); - if (info != null) { - info.setState(state); - } - } - - public BlockState getState(Direction dir) { - PosInfo info = blocks.get(pos.relative(dir)); - if (info == null) { - info = add.get(pos.relative(dir)); - return info == null ? AIR : info.getState(); - } - return info.getState(); - } - - public BlockState getState(Direction dir, int distance) { - PosInfo info = blocks.get(pos.relative(dir, distance)); - if (info == null) { - return AIR; - } - return info.getState(); - } - - public BlockState getStateUp() { - return getState(Direction.UP); - } - - public BlockState getStateDown() { - return getState(Direction.DOWN); - } - - @Override - public int hashCode() { - return pos.hashCode(); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof PosInfo)) { - return false; - } - return pos.equals(((PosInfo) obj).pos); - } - - @Override - public int compareTo(PosInfo info) { - return this.pos.getY() - info.pos.getY(); - } - - public BlockPos getPos() { - return pos; - } - - public void setBlockPos(BlockPos pos, BlockState state) { - PosInfo info = new PosInfo(blocks, add, pos); - info.state = state; - add.put(pos, info); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/SDF.java b/src/main/java/org/betterx/bclib/sdf/SDF.java deleted file mode 100644 index 31adeabe..00000000 --- a/src/main/java/org/betterx/bclib/sdf/SDF.java +++ /dev/null @@ -1,307 +0,0 @@ -package org.betterx.bclib.sdf; - -import org.betterx.bclib.api.v2.levelgen.structures.StructureWorld; -import org.betterx.bclib.util.BlocksHelper; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.core.Direction; -import net.minecraft.world.level.ServerLevelAccessor; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.phys.AABB; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -import java.util.*; -import java.util.function.Function; - -public abstract class SDF { - private final List> postProcesses = Lists.newArrayList(); - private Function canReplace = (state) -> { - return state.getMaterial().isReplaceable(); - }; - - public abstract float getDistance(float x, float y, float z); - - public abstract BlockState getBlockState(BlockPos pos); - - public SDF addPostProcess(Function postProcess) { - this.postProcesses.add(postProcess); - return this; - } - - public SDF setReplaceFunction(Function canReplace) { - this.canReplace = canReplace; - return this; - } - - public void fillRecursive(ServerLevelAccessor world, BlockPos start) { - Map mapWorld = Maps.newHashMap(); - Map addInfo = Maps.newHashMap(); - Set blocks = Sets.newHashSet(); - Set ends = Sets.newHashSet(); - Set add = Sets.newHashSet(); - ends.add(new BlockPos(0, 0, 0)); - boolean run = true; - - MutableBlockPos bPos = new MutableBlockPos(); - - while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { - bPos.set(center).move(dir); - BlockPos wpos = bPos.offset(start); - - if (!blocks.contains(bPos) && canReplace.apply(world.getBlockState(wpos))) { - if (this.getDistance(bPos.getX(), bPos.getY(), bPos.getZ()) < 0) { - BlockState state = getBlockState(wpos); - PosInfo.create(mapWorld, addInfo, wpos).setState(state); - add.add(bPos.immutable()); - } - } - } - } - - blocks.addAll(ends); - ends.clear(); - ends.addAll(add); - add.clear(); - - run &= !ends.isEmpty(); - } - - List infos = new ArrayList(mapWorld.values()); - if (infos.size() > 0) { - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); - }); - - infos.clear(); - infos.addAll(addInfo.values()); - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - if (canReplace.apply(world.getBlockState(info.getPos()))) { - BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); - } - }); - } - } - - public void fillArea(ServerLevelAccessor world, BlockPos center, AABB box) { - Map mapWorld = Maps.newHashMap(); - Map addInfo = Maps.newHashMap(); - - MutableBlockPos mut = new MutableBlockPos(); - for (int y = (int) box.minY; y <= box.maxY; y++) { - mut.setY(y); - for (int x = (int) box.minX; x <= box.maxX; x++) { - mut.setX(x); - for (int z = (int) box.minZ; z <= box.maxZ; z++) { - mut.setZ(z); - if (canReplace.apply(world.getBlockState(mut))) { - BlockPos fpos = mut.subtract(center); - if (this.getDistance(fpos.getX(), fpos.getY(), fpos.getZ()) < 0) { - PosInfo.create(mapWorld, addInfo, mut.immutable()).setState(getBlockState(mut)); - } - } - } - } - } - - List infos = new ArrayList(mapWorld.values()); - if (infos.size() > 0) { - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); - }); - - infos.clear(); - infos.addAll(addInfo.values()); - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - if (canReplace.apply(world.getBlockState(info.getPos()))) { - BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); - } - }); - } - } - - public void fillRecursiveIgnore(ServerLevelAccessor world, BlockPos start, Function ignore) { - Map mapWorld = Maps.newHashMap(); - Map addInfo = Maps.newHashMap(); - Set blocks = Sets.newHashSet(); - Set ends = Sets.newHashSet(); - Set add = Sets.newHashSet(); - ends.add(new BlockPos(0, 0, 0)); - boolean run = true; - - MutableBlockPos bPos = new MutableBlockPos(); - - while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { - bPos.set(center).move(dir); - BlockPos wpos = bPos.offset(start); - BlockState state = world.getBlockState(wpos); - boolean ign = ignore.apply(state); - if (!blocks.contains(bPos) && (ign || canReplace.apply(state))) { - if (this.getDistance(bPos.getX(), bPos.getY(), bPos.getZ()) < 0) { - PosInfo.create(mapWorld, addInfo, wpos).setState(ign ? state : getBlockState(bPos)); - add.add(bPos.immutable()); - } - } - } - } - - blocks.addAll(ends); - ends.clear(); - ends.addAll(add); - add.clear(); - - run &= !ends.isEmpty(); - } - - List infos = new ArrayList(mapWorld.values()); - if (infos.size() > 0) { - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); - }); - - infos.clear(); - infos.addAll(addInfo.values()); - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - if (canReplace.apply(world.getBlockState(info.getPos()))) { - BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); - } - }); - } - } - - public void fillRecursive(StructureWorld world, BlockPos start) { - Map mapWorld = Maps.newHashMap(); - Map addInfo = Maps.newHashMap(); - Set blocks = Sets.newHashSet(); - Set ends = Sets.newHashSet(); - Set add = Sets.newHashSet(); - ends.add(new BlockPos(0, 0, 0)); - boolean run = true; - - MutableBlockPos bPos = new MutableBlockPos(); - - while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { - bPos.set(center).move(dir); - BlockPos wpos = bPos.offset(start); - - if (!blocks.contains(bPos)) { - if (this.getDistance(bPos.getX(), bPos.getY(), bPos.getZ()) < 0) { - BlockState state = getBlockState(wpos); - PosInfo.create(mapWorld, addInfo, wpos).setState(state); - add.add(bPos.immutable()); - } - } - } - } - - blocks.addAll(ends); - ends.clear(); - ends.addAll(add); - add.clear(); - - run &= !ends.isEmpty(); - } - - List infos = new ArrayList(mapWorld.values()); - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - world.setBlock(info.getPos(), info.getState()); - }); - - infos.clear(); - infos.addAll(addInfo.values()); - Collections.sort(infos); - postProcesses.forEach((postProcess) -> { - infos.forEach((info) -> { - info.setState(postProcess.apply(info)); - }); - }); - infos.forEach((info) -> { - world.setBlock(info.getPos(), info.getState()); - }); - } - - public Set getPositions(ServerLevelAccessor world, BlockPos start) { - Set blocks = Sets.newHashSet(); - Set ends = Sets.newHashSet(); - Set add = Sets.newHashSet(); - ends.add(new BlockPos(0, 0, 0)); - boolean run = true; - - MutableBlockPos bPos = new MutableBlockPos(); - - while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { - bPos.set(center).move(dir); - BlockPos wpos = bPos.offset(start); - BlockState state = world.getBlockState(wpos); - if (!blocks.contains(wpos) && canReplace.apply(state)) { - if (this.getDistance(bPos.getX(), bPos.getY(), bPos.getZ()) < 0) { - add.add(bPos.immutable()); - } - } - } - } - - ends.forEach((end) -> blocks.add(end.offset(start))); - ends.clear(); - ends.addAll(add); - add.clear(); - - run &= !ends.isEmpty(); - } - - return blocks; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFBinary.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFBinary.java deleted file mode 100644 index cff78329..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFBinary.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import org.betterx.bclib.sdf.SDF; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.state.BlockState; - -public abstract class SDFBinary extends SDF { - protected SDF sourceA; - protected SDF sourceB; - protected boolean firstValue; - - public SDFBinary setSourceA(SDF sourceA) { - this.sourceA = sourceA; - return this; - } - - public SDFBinary setSourceB(SDF sourceB) { - this.sourceB = sourceB; - return this; - } - - protected void selectValue(float a, float b) { - firstValue = a < b; - } - - @Override - public BlockState getBlockState(BlockPos pos) { - if (firstValue) { - return sourceA.getBlockState(pos); - } else { - return sourceB.getBlockState(pos); - } - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFCoordModify.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFCoordModify.java deleted file mode 100644 index b2b4a638..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFCoordModify.java +++ /dev/null @@ -1,22 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import com.mojang.math.Vector3f; - -import java.util.function.Consumer; - -public class SDFCoordModify extends SDFUnary { - private final Vector3f pos = new Vector3f(); - private Consumer function; - - public SDFCoordModify setFunction(Consumer function) { - this.function = function; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - pos.set(x, y, z); - function.accept(pos); - return this.source.getDistance(pos.x(), pos.y(), pos.z()); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFCopyRotate.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFCopyRotate.java deleted file mode 100644 index 906fd97d..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFCopyRotate.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import org.betterx.bclib.util.MHelper; - -public class SDFCopyRotate extends SDFUnary { - int count = 1; - - public SDFCopyRotate setCount(int count) { - this.count = count; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float px = (float) Math.atan2(x, z); - float pz = MHelper.length(x, z); - return this.source.getDistance(px, y, pz); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFDisplacement.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFDisplacement.java deleted file mode 100644 index a5c2477d..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFDisplacement.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import com.mojang.math.Vector3f; - -import java.util.function.Function; - -public class SDFDisplacement extends SDFUnary { - private final Vector3f pos = new Vector3f(); - private Function displace; - - public SDFDisplacement setFunction(Function displace) { - this.displace = displace; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - pos.set(x, y, z); - return this.source.getDistance(x, y, z) + displace.apply(pos); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFFlatWave.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFFlatWave.java deleted file mode 100644 index efe7ec4a..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFFlatWave.java +++ /dev/null @@ -1,28 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -public class SDFFlatWave extends SDFDisplacement { - private int rayCount = 1; - private float intensity; - private float angle; - - public SDFFlatWave() { - setFunction((pos) -> { - return (float) Math.cos(Math.atan2(pos.x(), pos.z()) * rayCount + angle) * intensity; - }); - } - - public SDFFlatWave setRaysCount(int count) { - this.rayCount = count; - return this; - } - - public SDFFlatWave setAngle(float angle) { - this.angle = angle; - return this; - } - - public SDFFlatWave setIntensity(float intensity) { - this.intensity = intensity; - return this; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFHeightmap.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFHeightmap.java deleted file mode 100644 index 2943720d..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFHeightmap.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import com.mojang.blaze3d.platform.NativeImage; -import net.minecraft.util.Mth; - -public class SDFHeightmap extends SDFDisplacement { - private float intensity = 1F; - private NativeImage map; - private float offsetX; - private float offsetZ; - private float scale; - private float cos = 1; - private float sin = 0; - - public SDFHeightmap() { - setFunction((pos) -> { - if (map == null) { - return 0F; - } - float px = Mth.clamp(pos.x() * scale + offsetX, 0, map.getWidth() - 2); - float pz = Mth.clamp(pos.z() * scale + offsetZ, 0, map.getHeight() - 2); - float dx = (px * cos - pz * sin); - float dz = (pz * cos + px * sin); - int x1 = Mth.floor(dx); - int z1 = Mth.floor(dz); - int x2 = x1 + 1; - int z2 = z1 + 1; - dx = dx - x1; - dz = dz - z1; - float a = (map.getPixelRGBA(x1, z1) & 255) / 255F; - float b = (map.getPixelRGBA(x2, z1) & 255) / 255F; - float c = (map.getPixelRGBA(x1, z2) & 255) / 255F; - float d = (map.getPixelRGBA(x2, z2) & 255) / 255F; - a = Mth.lerp(dx, a, b); - b = Mth.lerp(dx, c, d); - return -Mth.lerp(dz, a, b) * intensity; - }); - } - - public SDFHeightmap setMap(NativeImage map) { - this.map = map; - offsetX = map.getWidth() * 0.5F; - offsetZ = map.getHeight() * 0.5F; - scale = map.getWidth(); - return this; - } - - public SDFHeightmap setAngle(float angle) { - sin = Mth.sin(angle); - cos = Mth.cos(angle); - return this; - } - - public SDFHeightmap setScale(float scale) { - this.scale = map.getWidth() * scale; - return this; - } - - public SDFHeightmap setIntensity(float intensity) { - this.intensity = intensity; - return this; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFIntersection.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFIntersection.java deleted file mode 100644 index 3d6be14d..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFIntersection.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import org.betterx.bclib.util.MHelper; - -public class SDFIntersection extends SDFBinary { - @Override - public float getDistance(float x, float y, float z) { - float a = this.sourceA.getDistance(x, y, z); - float b = this.sourceB.getDistance(x, y, z); - this.selectValue(a, b); - return MHelper.max(a, b); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFInvert.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFInvert.java deleted file mode 100644 index 8ce1dfe6..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFInvert.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -public class SDFInvert extends SDFUnary { - @Override - public float getDistance(float x, float y, float z) { - return -this.source.getDistance(x, y, z); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFRadialNoiseMap.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFRadialNoiseMap.java deleted file mode 100644 index 8b8cc21b..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFRadialNoiseMap.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import org.betterx.bclib.noise.OpenSimplexNoise; -import org.betterx.bclib.util.MHelper; - -import net.minecraft.util.Mth; - -public class SDFRadialNoiseMap extends SDFDisplacement { - private static final float SIN = Mth.sin(0.5F); - private static final float COS = Mth.cos(0.5F); - - private OpenSimplexNoise noise; - private float intensity = 1F; - private float radius = 1F; - private short offsetX; - private short offsetZ; - - public SDFRadialNoiseMap() { - setFunction((pos) -> { - if (intensity == 0) { - return 0F; - } - float px = pos.x() / radius; - float pz = pos.z() / radius; - float distance = MHelper.lengthSqr(px, pz); - if (distance > 1) { - return 0F; - } - distance = 1 - Mth.sqrt(distance); - float nx = px * COS - pz * SIN; - float nz = pz * COS + px * SIN; - distance *= getNoise(nx * 0.75 + offsetX, nz * 0.75 + offsetZ); - return distance * intensity; - }); - } - - private float getNoise(double x, double z) { - return (float) noise.eval(x, z) + (float) noise.eval( - x * 3 + 1000, - z * 3 - ) * 0.5F + (float) noise.eval(x * 9 + 1000, z * 9) * 0.2F; - } - - public SDFRadialNoiseMap setSeed(long seed) { - noise = new OpenSimplexNoise(seed); - return this; - } - - public SDFRadialNoiseMap setIntensity(float intensity) { - this.intensity = intensity; - return this; - } - - public SDFRadialNoiseMap setRadius(float radius) { - this.radius = radius; - return this; - } - - public SDFRadialNoiseMap setOffset(int x, int z) { - offsetX = (short) (x & 32767); - offsetZ = (short) (z & 32767); - return this; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFRotation.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFRotation.java deleted file mode 100644 index fb782d4c..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFRotation.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import com.mojang.math.Quaternion; -import com.mojang.math.Vector3f; - -public class SDFRotation extends SDFUnary { - private final Vector3f pos = new Vector3f(); - private Quaternion rotation; - - public SDFRotation setRotation(Vector3f axis, float rotationAngle) { - rotation = new Quaternion(axis, rotationAngle, false); - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - pos.set(x, y, z); - pos.transform(rotation); - return source.getDistance(pos.x(), pos.y(), pos.z()); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFRound.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFRound.java deleted file mode 100644 index 36bd54b4..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFRound.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -public class SDFRound extends SDFUnary { - private float radius; - - public SDFRound setRadius(float radius) { - this.radius = radius; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - return this.source.getDistance(x, y, z) - radius; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFScale.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFScale.java deleted file mode 100644 index 7aa258f2..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFScale.java +++ /dev/null @@ -1,15 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -public class SDFScale extends SDFUnary { - private float scale; - - public SDFScale setScale(float scale) { - this.scale = scale; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - return source.getDistance(x / scale, y / scale, z / scale) * scale; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFScale3D.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFScale3D.java deleted file mode 100644 index 6defc4aa..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFScale3D.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -public class SDFScale3D extends SDFUnary { - private float x; - private float y; - private float z; - - public SDFScale3D setScale(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - return source.getDistance(x / this.x, y / this.y, z / this.z); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothIntersection.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothIntersection.java deleted file mode 100644 index e10f784d..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothIntersection.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import net.minecraft.util.Mth; - -public class SDFSmoothIntersection extends SDFBinary { - private float radius; - - public SDFSmoothIntersection setRadius(float radius) { - this.radius = radius; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float a = this.sourceA.getDistance(x, y, z); - float b = this.sourceB.getDistance(x, y, z); - this.selectValue(a, b); - float h = Mth.clamp(0.5F - 0.5F * (b - a) / radius, 0F, 1F); - return Mth.lerp(h, b, a) + radius * h * (1F - h); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothSubtraction.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothSubtraction.java deleted file mode 100644 index 3d12385a..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothSubtraction.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import net.minecraft.util.Mth; - -public class SDFSmoothSubtraction extends SDFBinary { - private float radius; - - public SDFSmoothSubtraction setRadius(float radius) { - this.radius = radius; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float a = this.sourceA.getDistance(x, y, z); - float b = this.sourceB.getDistance(x, y, z); - this.selectValue(a, b); - float h = Mth.clamp(0.5F - 0.5F * (b + a) / radius, 0F, 1F); - return Mth.lerp(h, b, -a) + radius * h * (1F - h); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothUnion.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothUnion.java deleted file mode 100644 index e09f22a2..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFSmoothUnion.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import net.minecraft.util.Mth; - -public class SDFSmoothUnion extends SDFBinary { - private float radius; - - public SDFSmoothUnion setRadius(float radius) { - this.radius = radius; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float a = this.sourceA.getDistance(x, y, z); - float b = this.sourceB.getDistance(x, y, z); - this.selectValue(a, b); - float h = Mth.clamp(0.5F + 0.5F * (b - a) / radius, 0F, 1F); - return Mth.lerp(h, b, a) - radius * h * (1F - h); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFSubtraction.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFSubtraction.java deleted file mode 100644 index 345c5670..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFSubtraction.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import org.betterx.bclib.util.MHelper; - -public class SDFSubtraction extends SDFBinary { - @Override - public float getDistance(float x, float y, float z) { - float a = this.sourceA.getDistance(x, y, z); - float b = this.sourceB.getDistance(x, y, z); - this.selectValue(a, b); - return MHelper.max(a, -b); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFTranslate.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFTranslate.java deleted file mode 100644 index 2bbc2c1c..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFTranslate.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -public class SDFTranslate extends SDFUnary { - float x; - float y; - float z; - - public SDFTranslate setTranslate(float x, float y, float z) { - this.x = x; - this.y = y; - this.z = z; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - return source.getDistance(x - this.x, y - this.y, z - this.z); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFUnary.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFUnary.java deleted file mode 100644 index 6dcaab91..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFUnary.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import org.betterx.bclib.sdf.SDF; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.state.BlockState; - -public abstract class SDFUnary extends SDF { - protected SDF source; - - public SDFUnary setSource(SDF source) { - this.source = source; - return this; - } - - @Override - public BlockState getBlockState(BlockPos pos) { - return source.getBlockState(pos); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/operator/SDFUnion.java b/src/main/java/org/betterx/bclib/sdf/operator/SDFUnion.java deleted file mode 100644 index c461aa8f..00000000 --- a/src/main/java/org/betterx/bclib/sdf/operator/SDFUnion.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.betterx.bclib.sdf.operator; - -import org.betterx.bclib.util.MHelper; - -public class SDFUnion extends SDFBinary { - @Override - public float getDistance(float x, float y, float z) { - float a = this.sourceA.getDistance(x, y, z); - float b = this.sourceB.getDistance(x, y, z); - this.selectValue(a, b); - return MHelper.min(a, b); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFCappedCone.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFCappedCone.java deleted file mode 100644 index 712fba02..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFCappedCone.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.util.MHelper; - -import net.minecraft.util.Mth; - -public class SDFCappedCone extends SDFPrimitive { - private float radius1; - private float radius2; - private float height; - - public SDFCappedCone setRadius1(float radius) { - this.radius1 = radius; - return this; - } - - public SDFCappedCone setRadius2(float radius) { - this.radius2 = radius; - return this; - } - - public SDFCappedCone setHeight(float height) { - this.height = height; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float qx = MHelper.length(x, z); - float k2x = radius2 - radius1; - float k2y = 2 * height; - float cax = qx - MHelper.min(qx, (y < 0F) ? radius1 : radius2); - float cay = Math.abs(y) - height; - float mlt = Mth.clamp( - MHelper.dot(radius2 - qx, height - y, k2x, k2y) / MHelper.dot(k2x, k2y, k2x, k2y), - 0F, - 1F - ); - float cbx = qx - radius2 + k2x * mlt; - float cby = y - height + k2y * mlt; - float s = (cbx < 0F && cay < 0F) ? -1F : 1F; - return s * (float) Math.sqrt(MHelper.min(MHelper.dot(cax, cay, cax, cay), MHelper.dot(cbx, cby, cbx, cby))); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFCapsule.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFCapsule.java deleted file mode 100644 index e1a50ff0..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFCapsule.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.util.MHelper; - -import net.minecraft.util.Mth; - -public class SDFCapsule extends SDFPrimitive { - private float radius; - private float height; - - public SDFCapsule setRadius(float radius) { - this.radius = radius; - return this; - } - - public SDFCapsule setHeight(float height) { - this.height = height; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - return MHelper.length(x, y - Mth.clamp(y, 0, height), z) - radius; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFFlatland.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFFlatland.java deleted file mode 100644 index a1aac88c..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFFlatland.java +++ /dev/null @@ -1,8 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -public class SDFFlatland extends SDFPrimitive { - @Override - public float getDistance(float x, float y, float z) { - return y; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFHexPrism.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFHexPrism.java deleted file mode 100644 index ad2bd24a..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFHexPrism.java +++ /dev/null @@ -1,26 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.util.MHelper; - -public class SDFHexPrism extends SDFPrimitive { - private float radius; - private float height; - - public SDFHexPrism setRadius(float radius) { - this.radius = radius; - return this; - } - - public SDFHexPrism setHeight(float height) { - this.height = height; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float px = Math.abs(x); - float py = Math.abs(y); - float pz = Math.abs(z); - return MHelper.max(py - height, MHelper.max((px * 0.866025F + pz * 0.5F), pz) - radius); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFLine.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFLine.java deleted file mode 100644 index 16094bea..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFLine.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.util.MHelper; - -import net.minecraft.util.Mth; - -public class SDFLine extends SDFPrimitive { - private float radius; - private float x1; - private float y1; - private float z1; - private float x2; - private float y2; - private float z2; - - public SDFLine setRadius(float radius) { - this.radius = radius; - return this; - } - - public SDFLine setStart(float x, float y, float z) { - this.x1 = x; - this.y1 = y; - this.z1 = z; - return this; - } - - public SDFLine setEnd(float x, float y, float z) { - this.x2 = x; - this.y2 = y; - this.z2 = z; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float pax = x - x1; - float pay = y - y1; - float paz = z - z1; - - float bax = x2 - x1; - float bay = y2 - y1; - float baz = z2 - z1; - - float dpb = MHelper.dot(pax, pay, paz, bax, bay, baz); - float dbb = MHelper.dot(bax, bay, baz, bax, bay, baz); - float h = Mth.clamp(dpb / dbb, 0F, 1F); - return MHelper.length(pax - bax * h, pay - bay * h, paz - baz * h) - radius; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFPie.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFPie.java deleted file mode 100644 index aaa3419d..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFPie.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.util.MHelper; - -import net.minecraft.util.Mth; - -public class SDFPie extends SDFPrimitive { - private float sin; - private float cos; - private float radius; - - public SDFPie setAngle(float angle) { - this.sin = (float) Math.sin(angle); - this.cos = (float) Math.cos(angle); - return this; - } - - public SDFPie setRadius(float radius) { - this.radius = radius; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float px = Math.abs(x); - float l = MHelper.length(px, y, z) - radius; - float m = MHelper.dot(px, z, sin, cos); - m = Mth.clamp(m, 0, radius); - m = MHelper.length(px - sin * m, z - cos * m); - return MHelper.max(l, m * Math.signum(cos * px - sin * z)); - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFPrimitive.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFPrimitive.java deleted file mode 100644 index 716c7610..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFPrimitive.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.sdf.SDF; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; - -import java.util.function.Function; - -public abstract class SDFPrimitive extends SDF { - protected Function placerFunction; - - public SDFPrimitive setBlock(Function placerFunction) { - this.placerFunction = placerFunction; - return this; - } - - public SDFPrimitive setBlock(BlockState state) { - this.placerFunction = (pos) -> { - return state; - }; - return this; - } - - public SDFPrimitive setBlock(Block block) { - this.placerFunction = (pos) -> { - return block.defaultBlockState(); - }; - return this; - } - - public BlockState getBlockState(BlockPos pos) { - return placerFunction.apply(pos); - } - - /*public abstract CompoundTag toNBT(CompoundTag root) { - - }*/ -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFSphere.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFSphere.java deleted file mode 100644 index 08d2731d..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFSphere.java +++ /dev/null @@ -1,17 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.util.MHelper; - -public class SDFSphere extends SDFPrimitive { - private float radius; - - public SDFSphere setRadius(float radius) { - this.radius = radius; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - return MHelper.length(x, y, z) - radius; - } -} diff --git a/src/main/java/org/betterx/bclib/sdf/primitive/SDFTorus.java b/src/main/java/org/betterx/bclib/sdf/primitive/SDFTorus.java deleted file mode 100644 index 424dad67..00000000 --- a/src/main/java/org/betterx/bclib/sdf/primitive/SDFTorus.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.sdf.primitive; - -import org.betterx.bclib.util.MHelper; - -public class SDFTorus extends SDFPrimitive { - private float radiusSmall; - private float radiusBig; - - public SDFTorus setBigRadius(float radius) { - this.radiusBig = radius; - return this; - } - - public SDFTorus setSmallRadius(float radius) { - this.radiusSmall = radius; - return this; - } - - @Override - public float getDistance(float x, float y, float z) { - float nx = MHelper.length(x, z) - radiusBig; - return MHelper.length(nx, y) - radiusSmall; - } -} diff --git a/src/main/java/org/betterx/bclib/server/BCLibServer.java b/src/main/java/org/betterx/bclib/server/BCLibServer.java deleted file mode 100644 index 63ca5724..00000000 --- a/src/main/java/org/betterx/bclib/server/BCLibServer.java +++ /dev/null @@ -1,18 +0,0 @@ -package org.betterx.bclib.server; - -import org.betterx.bclib.api.v2.ModIntegrationAPI; -import org.betterx.bclib.api.v2.PostInitAPI; -import org.betterx.bclib.api.v2.dataexchange.DataExchangeAPI; - -import net.fabricmc.api.DedicatedServerModInitializer; - -public class BCLibServer implements DedicatedServerModInitializer { - @Override - public void onInitializeServer() { - ModIntegrationAPI.registerAll(); - DataExchangeAPI.prepareServerside(); - - PostInitAPI.postInit(false); - } - -} diff --git a/src/main/java/org/betterx/bclib/util/BackgroundInfo.java b/src/main/java/org/betterx/bclib/util/BackgroundInfo.java deleted file mode 100644 index 4e4d2054..00000000 --- a/src/main/java/org/betterx/bclib/util/BackgroundInfo.java +++ /dev/null @@ -1,9 +0,0 @@ -package org.betterx.bclib.util; - -public class BackgroundInfo { - public static float fogColorRed; - public static float fogColorGreen; - public static float fogColorBlue; - public static float fogDensity = 1; - public static float blindness; -} diff --git a/src/main/java/org/betterx/bclib/util/BlocksHelper.java b/src/main/java/org/betterx/bclib/util/BlocksHelper.java deleted file mode 100644 index d385855b..00000000 --- a/src/main/java/org/betterx/bclib/util/BlocksHelper.java +++ /dev/null @@ -1,351 +0,0 @@ -package org.betterx.bclib.util; - -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.core.Direction; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.BlockGetter; -import net.minecraft.world.level.LevelAccessor; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.block.state.properties.Property; -import net.minecraft.world.level.material.LavaFluid; - -import com.google.common.collect.Maps; - -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.function.Predicate; - -public class BlocksHelper { - private static final Map COLOR_BY_BLOCK = Maps.newHashMap(); - - public static final int FLAG_UPDATE_BLOCK = 1; - public static final int FLAG_SEND_CLIENT_CHANGES = 2; - public static final int FLAG_NO_RERENDER = 4; - public static final int FORSE_RERENDER = 8; - public static final int FLAG_IGNORE_OBSERVERS = 16; - - public static final int SET_SILENT = FLAG_IGNORE_OBSERVERS | FLAG_SEND_CLIENT_CHANGES; - public static final int SET_OBSERV = FLAG_UPDATE_BLOCK | FLAG_SEND_CLIENT_CHANGES; - public static final Direction[] HORIZONTAL = makeHorizontal(); - public static final Direction[] DIRECTIONS = Direction.values(); - - private static final ThreadLocal TL_POS = ThreadLocal.withInitial(() -> new MutableBlockPos()); - - protected static final BlockState AIR = Blocks.AIR.defaultBlockState(); - protected static final BlockState WATER = Blocks.WATER.defaultBlockState(); - - public static void addBlockColor(Block block, int color) { - COLOR_BY_BLOCK.put(block, color); - } - - public static int getBlockColor(Block block) { - return COLOR_BY_BLOCK.getOrDefault(block, 0xFF000000); - } - - public static void setWithoutUpdate(LevelAccessor world, BlockPos pos, BlockState state) { - world.setBlock(pos, state, SET_SILENT); - } - - public static void setWithoutUpdate(LevelAccessor world, BlockPos pos, Block block) { - world.setBlock(pos, block.defaultBlockState(), SET_SILENT); - } - - public static void setWithUpdate(LevelAccessor world, BlockPos pos, BlockState state) { - world.setBlock(pos, state, SET_OBSERV); - } - - public static void setWithUpdate(LevelAccessor world, BlockPos pos, Block block) { - world.setBlock(pos, block.defaultBlockState(), SET_OBSERV); - } - - public static int upRay(LevelAccessor world, BlockPos pos, int maxDist) { - int length = 0; - for (int j = 1; j < maxDist && (world.isEmptyBlock(pos.above(j))); j++) { - length++; - } - return length; - } - - public static int downRay(LevelAccessor world, BlockPos pos, int maxDist) { - int length = 0; - for (int j = 1; j < maxDist && (world.isEmptyBlock(pos.below(j))); j++) { - length++; - } - return length; - } - - public static int downRayRep(LevelAccessor world, BlockPos pos, int maxDist) { - final MutableBlockPos POS = TL_POS.get(); - POS.set(pos); - for (int j = 1; j < maxDist && (world.getBlockState(POS)).getMaterial().isReplaceable(); j++) { - POS.setY(POS.getY() - 1); - } - return pos.getY() - POS.getY(); - } - - public static int raycastSqr(LevelAccessor world, BlockPos pos, int dx, int dy, int dz, int maxDist) { - final MutableBlockPos POS = TL_POS.get(); - POS.set(pos); - for (int j = 1; j < maxDist && (world.getBlockState(POS)).getMaterial().isReplaceable(); j++) { - POS.move(dx, dy, dz); - } - return (int) pos.distSqr(POS); - } - - /** - * Rotates {@link BlockState} horizontally. Used in block classes with {@link Direction} {@link Property} in rotate function. - * - * @param state - {@link BlockState} to mirror; - * @param rotation - {@link Rotation}; - * @param facing - Block {@link Direction} {@link Property}. - * @return Rotated {@link BlockState}. - */ - public static BlockState rotateHorizontal(BlockState state, Rotation rotation, Property facing) { - return state.setValue(facing, rotation.rotate(state.getValue(facing))); - } - - /** - * Mirrors {@link BlockState} horizontally. Used in block classes with {@link Direction} {@link Property} in mirror function. - * - * @param state - {@link BlockState} to mirror; - * @param mirror - {@link Mirror}; - * @param facing - Block {@link Direction} {@link Property}. - * @return Mirrored {@link BlockState}. - */ - public static BlockState mirrorHorizontal(BlockState state, Mirror mirror, Property facing) { - return state.rotate(mirror.getRotation(state.getValue(facing))); - } - - /** - * Counts the amount of same block down. - * - * @param world - {@link LevelAccessor} world; - * @param pos - {@link BlockPos} start position; - * @param block - {@link Block} to count. - * @return Integer amount of blocks. - */ - public static int getLengthDown(LevelAccessor world, BlockPos pos, Block block) { - int count = 1; - while (world.getBlockState(pos.below(count)).getBlock() == block) { - count++; - } - return count; - } - - /** - * Creates a new {@link Direction} array with clockwise order: - * NORTH, EAST, SOUTH, WEST - * - * @return Array of {@link Direction}. - */ - public static Direction[] makeHorizontal() { - return new Direction[]{Direction.NORTH, Direction.EAST, Direction.SOUTH, Direction.WEST}; - } - - /** - * Get any random horizontal {@link Direction}. - * - * @param random - {@link Random}. - * @return {@link Direction}. - */ - public static Direction randomHorizontal(RandomSource random) { - return HORIZONTAL[random.nextInt(4)]; - } - - /** - * Get any random {@link Direction} including vertical and horizontal. - * - * @param random - {@link Random}. - * @return {@link Direction}. - */ - public static Direction randomDirection(RandomSource random) { - return DIRECTIONS[random.nextInt(6)]; - } - - - /** - * Check if block is "invulnerable" like Bedrock. - * - * @param state - {@link BlockState} to check; - * @param world - {@link BlockGetter} world where BlockState exist; - * @param pos - {@link BlockPos} where BlockState is. - * @return {@code true} if block is "invulnerable" and {@code false} if not. - */ - public static boolean isInvulnerable(BlockState state, BlockGetter world, BlockPos pos) { - return state.getDestroySpeed(world, pos) < 0; - } - - /** - * Check if block is "invulnerable" like Bedrock. Unlike safe function will pass world and position parameters as {@code null}. - * - * @param state - {@link BlockState} to check. - * @return {@code true} if block is "invulnerable" and {@code false} if not. - */ - public static boolean isInvulnerableUnsafe(BlockState state) { - try { - return isInvulnerable(state, null, null); - } catch (Exception e) { - return false; - } - } - - public static Optional findSurfaceBelow( - LevelAccessor level, - BlockPos startPos, - int minY, - Predicate surface - ) { - final MutableBlockPos POS = new MutableBlockPos(startPos.getX(), startPos.getY(), startPos.getZ()); - for (int y = startPos.getY(); y >= minY; y--) { - POS.setY(y); - if (surface.test(level.getBlockState(POS))) return Optional.of(POS); - } - return Optional.empty(); - } - - public static boolean findSurface( - LevelAccessor level, - MutableBlockPos startPos, - Direction dir, - int length, - Predicate surface - ) { - for (int len = 0; len < length; len++) { - if (surface.test(level.getBlockState(startPos))) return true; - startPos.move(dir, 1); - } - return false; - } - - public static boolean findOnSurroundingSurface( - LevelAccessor level, - MutableBlockPos startPos, - Direction dir, - int length, - Predicate surface - ) { - for (int len = 0; len < length; len++) { - if (surface.test(level.getBlockState(startPos))) { - if (len == 0) { //we started inside of the surface - for (int lenUp = 0; lenUp < length; lenUp++) { - startPos.move(dir, -1); - if (!surface.test(level.getBlockState(startPos))) { - return true; - } - } - return false; - } - startPos.move(dir, -1); - return true; - } - - startPos.move(dir, 1); - } - return false; - } - - public static boolean findSurroundingSurface( - LevelAccessor level, - MutableBlockPos startPos, - Direction dir, - int length, - Predicate surface - ) { - BlockState beforeState = null; - BlockState nowState; - for (int len = 0; len < length; len++) { - nowState = level.getBlockState(startPos); - if (surface.test(nowState)) { - if (len == 0) { //we started inside of the surface - beforeState = nowState; - for (int lenUp = 0; lenUp < length; lenUp++) { - startPos.move(dir, -1); - nowState = level.getBlockState(startPos); - if (BlocksHelper.isFree(nowState)) { - return surface.test(beforeState); - } - beforeState = nowState; - } - return false; - } else { - startPos.move(dir, -1); - return BlocksHelper.isFree(beforeState); - } - } - beforeState = nowState; - startPos.move(dir, 1); - } - return false; - } - - - public static boolean isFreeSpace( - LevelAccessor level, - BlockPos startPos, - Direction dir, - int length, - Predicate freeSurface - ) { - MutableBlockPos POS = startPos.mutable(); - for (int len = 0; len < length; len++) { - if (!freeSurface.test(level.getBlockState(POS))) { - return false; - } - POS.move(dir, 1); - } - return true; - } - - public static int blockCount( - LevelAccessor level, - BlockPos startPos, - Direction dir, - int length, - Predicate freeSurface - ) { - MutableBlockPos POS = startPos.mutable(); - for (int len = 0; len < length; len++) { - if (!freeSurface.test(level.getBlockState(POS))) { - return len; - } - POS.move(dir, 1); - } - return length; - } - - public static boolean isLava(BlockState state) { - return state.getFluidState().getType() instanceof LavaFluid; - } - - public static boolean isFluid(BlockState state) { - return state.getMaterial().isLiquid(); - } - - public static boolean isFree(BlockState state) { - return state.isAir(); - } - - public static boolean isFreeOrReplaceable(BlockState state) { - return state.isAir() || state.getMaterial().isReplaceable(); - } - - public static boolean isFreeOrFluid(BlockState state) { - return state.isAir() || isFluid(state); - } - - public static boolean isTerrain(BlockState state) { - return state.is(CommonBlockTags.TERRAIN); - } - - public static boolean isTerrainOrFluid(BlockState state) { - return state.is(CommonBlockTags.TERRAIN) || isFluid(state); - } -} diff --git a/src/main/java/org/betterx/bclib/util/CollectionsUtil.java b/src/main/java/org/betterx/bclib/util/CollectionsUtil.java deleted file mode 100644 index f2076877..00000000 --- a/src/main/java/org/betterx/bclib/util/CollectionsUtil.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.betterx.bclib.util; - -import java.util.*; - -public class CollectionsUtil { - /** - * Will return mutable copy of list. - * - * @param list {@link List} to make mutable. - * @return {@link ArrayList} or original {@link List} if it is mutable. - */ - public static List getMutable(List list) { - if (list instanceof ArrayList) { - return list; - } - return new ArrayList<>(list); - } - - /** - * Will return mutable copy of set. - * - * @param set {@link Set} to make mutable. - * @return {@link HashSet} or original {@link Set} if it is mutable. - */ - public static Set getMutable(Set set) { - if (set instanceof HashSet) { - return set; - } - return new HashSet<>(set); - } - - /** - * Will return mutable copy of map. - * - * @param map {@link Map} to make mutable. - * @return {@link HashMap} or original {@link Map} if it is mutable. - */ - public static Map getMutable(Map map) { - if (map instanceof HashMap) { - return map; - } - return new HashMap<>(map); - } -} diff --git a/src/main/java/org/betterx/bclib/util/ColorExtractor.java b/src/main/java/org/betterx/bclib/util/ColorExtractor.java deleted file mode 100644 index 9c1d0132..00000000 --- a/src/main/java/org/betterx/bclib/util/ColorExtractor.java +++ /dev/null @@ -1,150 +0,0 @@ -package org.betterx.bclib.util; - -import org.betterx.ui.ColorUtil; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Random; - -public class ColorExtractor { - private final List

centers = new ArrayList<>(); - private final List colors; - private Integer result; - - public ColorExtractor(List colors) { - this.colors = colors; - Random rnd = new Random(); - int size = colors.size(); - for (int i = 0; i < 4; i++) { - int color = colors.get(rnd.nextInt(size)); - this.centers.add(new Center(color)); - } - } - - public int analize() { - boolean moved = true; - while (moved) { - this.remap(); - moved = false; - for (Center center : centers) { - if (center.move()) { - moved = true; - } - } - } - List
toClear = new ArrayList<>(); - this.centers.forEach(center -> { - if (center.colors.isEmpty()) { - toClear.add(center); - } - }); - if (toClear.size() > 0) { - toClear.forEach(clear -> centers.remove(clear)); - } - this.centers.sort(Center.COMPARATOR); - - return this.getResult(); - } - - public int getResult() { - if (result == null) { - double weights = 0; - double alpha = 0; - double red = 0; - double green = 0; - double blue = 0; - for (Center center : centers) { - double weight = (double) center.colors.size() / colors.size(); - weights += weight; - alpha += center.a * weight; - red += center.r * weight; - green += center.g * weight; - blue += center.b * weight; - } - - int a = (int) Math.round(alpha / weights); - int r = (int) Math.round(red / weights); - int g = (int) Math.round(green / weights); - int b = (int) Math.round(blue / weights); - - this.result = a << 24 | r << 16 | g << 8 | b; - } - - return this.result; - } - - private void remap() { - this.centers.forEach(entry -> entry.colors.clear()); - this.colors.forEach(color -> { - int id = 0; - int base = centers.get(0).getColor(); - int dst = ColorUtil.colorDistance(color, base); - for (Center center : centers) { - base = center.getColor(); - int dst1 = ColorUtil.colorDistance(color, base); - if (dst1 < dst) { - dst = dst1; - id = centers.indexOf(center); - } - } - this.centers.get(id).colors.add(color); - }); - } - - private static class Center { - static final Comparator
COMPARATOR = new Comparator
() { - @Override - public int compare(Center c1, Center c2) { - return Integer.compare(c1.getColor(), c2.getColor()); - } - }; - - List colors = new ArrayList<>(); - double a, r, g, b; - - Center(int color) { - this.a = (color >> 24) & 255; - this.r = (color >> 16) & 255; - this.g = (color >> 8) & 255; - this.b = color & 255; - } - - private void update(double a, double r, double g, double b) { - this.a = a; - this.r = r; - this.g = g; - this.b = b; - } - - public int getColor() { - int a = (int) Math.round(this.a); - int r = (int) Math.round(this.r); - int g = (int) Math.round(this.g); - int b = (int) Math.round(this.b); - return a << 24 | r << 16 | g << 8 | b; - } - - public boolean move() { - double or = r; - double og = g; - double ob = b; - double a = 0, r = 0, g = 0, b = 0; - int size = this.colors.size(); - for (int col : colors) { - a += (col >> 24) & 255; - r += (col >> 16) & 255; - g += (col >> 8) & 255; - b += col & 255; - } - a /= size; - r /= size; - g /= size; - b /= size; - - this.update(a, r, g, b); - - return Math.abs(r - or) > 0.1 || Math.abs(g - og) > 0.1 || Math.abs(b - ob) > 0.1; - } - } -} diff --git a/src/main/java/org/betterx/bclib/util/ItemUtil.java b/src/main/java/org/betterx/bclib/util/ItemUtil.java deleted file mode 100644 index 0d964bb6..00000000 --- a/src/main/java/org/betterx/bclib/util/ItemUtil.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.betterx.bclib.util; - -import org.betterx.bclib.BCLib; - -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.GsonHelper; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; - -import com.google.gson.JsonObject; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public class ItemUtil { - - public static String toStackString(@NotNull ItemStack stack) { - try { - if (stack == null) { - throw new IllegalStateException("Stack can't be null!"); - } - Item item = stack.getItem(); - return Registry.ITEM.getKey(item) + ":" + stack.getCount(); - } catch (Exception ex) { - BCLib.LOGGER.error("ItemStack serialization error!", ex); - } - return ""; - } - - @Nullable - public static ItemStack fromStackString(String stackString) { - if (stackString == null || stackString.equals("")) { - return null; - } - try { - String[] parts = stackString.split(":"); - if (parts.length < 2) return null; - if (parts.length == 2) { - ResourceLocation itemId = new ResourceLocation(stackString); - Item item = Registry.ITEM.getOptional(itemId).orElseThrow(() -> { - return new IllegalStateException("Output item " + itemId + " does not exists!"); - }); - return new ItemStack(item); - } - ResourceLocation itemId = new ResourceLocation(parts[0], parts[1]); - Item item = Registry.ITEM.getOptional(itemId).orElseThrow(() -> { - return new IllegalStateException("Output item " + itemId + " does not exists!"); - }); - return new ItemStack(item, Integer.valueOf(parts[2])); - } catch (Exception ex) { - BCLib.LOGGER.error("ItemStack deserialization error!", ex); - } - return null; - } - - @Nullable - public static ItemStack fromJsonRecipe(JsonObject recipe) { - try { - if (!recipe.has("item")) { - throw new IllegalStateException("Invalid JsonObject. Entry 'item' does not exists!"); - } - ResourceLocation itemId = new ResourceLocation(GsonHelper.getAsString(recipe, "item")); - Item item = Registry.ITEM.getOptional(itemId).orElseThrow(() -> { - return new IllegalStateException("Output item " + itemId + " does not exists!"); - }); - int count = GsonHelper.getAsInt(recipe, "count", 1); - return new ItemStack(item, count); - } catch (Exception ex) { - BCLib.LOGGER.error("ItemStack deserialization error!", ex); - } - return null; - } -} diff --git a/src/main/java/org/betterx/bclib/util/JsonFactory.java b/src/main/java/org/betterx/bclib/util/JsonFactory.java deleted file mode 100644 index 5c7304da..00000000 --- a/src/main/java/org/betterx/bclib/util/JsonFactory.java +++ /dev/null @@ -1,132 +0,0 @@ -package org.betterx.bclib.util; - -import org.betterx.bclib.BCLib; - -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import org.jetbrains.annotations.Nullable; - -public class JsonFactory { - public final static Gson GSON = new GsonBuilder().setPrettyPrinting() - .create(); - - public static JsonObject getJsonObject(InputStream stream) { - try { - Reader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); - JsonElement json = loadJson(reader); - if (json != null && json.isJsonObject()) { - JsonObject jsonObject = json.getAsJsonObject(); - return jsonObject != null ? jsonObject : new JsonObject(); - } - } catch (Exception ex) { - BCLib.LOGGER.catching(ex); - } - return new JsonObject(); - } - - public static JsonObject getJsonObject(File jsonFile) { - if (jsonFile.exists()) { - JsonElement json = loadJson(jsonFile); - if (json != null && json.isJsonObject()) { - JsonObject jsonObject = json.getAsJsonObject(); - return jsonObject != null ? jsonObject : new JsonObject(); - } - } - return new JsonObject(); - } - - /** - * Loads {@link JsonObject} from resource location using Minecraft resource manager. Can be used to load JSON from resourcepacks and resources. - * - * @param location {@link ResourceLocation} to JSON file - * @return {@link JsonObject} - */ - @Nullable - @Environment(EnvType.CLIENT) - public static JsonObject getJsonObject(ResourceLocation location) { - ResourceManager manager = Minecraft.getInstance() - .getResourceManager(); - JsonObject obj = null; - try { - Resource resource = manager.getResource(location).orElse(null); - if (resource != null) { - InputStream stream = resource.open(); - InputStreamReader reader = new InputStreamReader(stream, StandardCharsets.UTF_8); - obj = JsonFactory.GSON.fromJson(reader, JsonObject.class); - reader.close(); - stream.close(); - } - } catch (IOException ex) { - } - return obj; - } - - public static JsonElement loadJson(File jsonFile) { - if (jsonFile.exists()) { - try (Reader reader = new FileReader(jsonFile, StandardCharsets.UTF_8)) { - return loadJson(reader); - } catch (Exception ex) { - BCLib.LOGGER.catching(ex); - } - } - return null; - } - - public static JsonElement loadJson(Reader reader) { - return GSON.fromJson(reader, JsonElement.class); - } - - public static void storeJson(File jsonFile, JsonElement jsonObject) { - try (FileWriter writer = new FileWriter(jsonFile, StandardCharsets.UTF_8)) { - String json = GSON.toJson(jsonObject); - writer.write(json); - writer.flush(); - } catch (IOException ex) { - BCLib.LOGGER.catching(ex); - } - } - - public static void storeJson(OutputStream outStream, JsonElement jsonObject) { - OutputStreamWriter writer = new OutputStreamWriter(outStream, StandardCharsets.UTF_8); - GSON.toJson(jsonObject, writer); - try { - writer.flush(); - } catch (IOException e) { - BCLib.LOGGER.error(e.getMessage()); - e.printStackTrace(); - } - } - - public static int getInt(JsonObject object, String member, int def) { - JsonElement elem = object.get(member); - return elem == null ? def : elem.getAsInt(); - } - - public static float getFloat(JsonObject object, String member, float def) { - JsonElement elem = object.get(member); - return elem == null ? def : elem.getAsFloat(); - } - - public static boolean getBoolean(JsonObject object, String member, boolean def) { - JsonElement elem = object.get(member); - return elem == null ? def : elem.getAsBoolean(); - } - - public static String getString(JsonObject object, String member, String def) { - JsonElement elem = object.get(member); - return elem == null ? def : elem.getAsString(); - } -} diff --git a/src/main/java/org/betterx/bclib/util/LootUtil.java b/src/main/java/org/betterx/bclib/util/LootUtil.java deleted file mode 100644 index 7d1b16a2..00000000 --- a/src/main/java/org/betterx/bclib/util/LootUtil.java +++ /dev/null @@ -1,75 +0,0 @@ -package org.betterx.bclib.util; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.interfaces.LootPoolAccessor; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.state.BlockBehaviour; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.storage.loot.BuiltInLootTables; -import net.minecraft.world.level.storage.loot.LootContext; -import net.minecraft.world.level.storage.loot.LootPool; -import net.minecraft.world.level.storage.loot.LootTable; -import net.minecraft.world.level.storage.loot.entries.LootPoolEntryContainer; -import net.minecraft.world.level.storage.loot.parameters.LootContextParamSets; -import net.minecraft.world.level.storage.loot.parameters.LootContextParams; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -public class LootUtil { - public static Optional> getDrops( - BlockBehaviour block, - BlockState state, - LootContext.Builder builder - ) { - ResourceLocation tableID = block.getLootTable(); - if (tableID == BuiltInLootTables.EMPTY) { - return Optional.empty(); - } - - final LootContext ctx = builder.withParameter(LootContextParams.BLOCK_STATE, state) - .create(LootContextParamSets.BLOCK); - final ServerLevel level = ctx.getLevel(); - final LootTable table = level.getServer().getLootTables().get(tableID); - - if (table == LootTable.EMPTY) return Optional.empty(); - return Optional.of(table.getRandomItems(ctx)); - } - - public static boolean addToPool(LootTable.Builder table, int index, ArrayList newEntries) { - List pools = new ArrayList<>(0); - try { - for (Field f : table.getClass() - .getDeclaredFields()) { - if (List.class.isAssignableFrom(f.getType())) { - f.setAccessible(true); - List list = (List) f.get(table); - if (list != null && list.size() > 0) { - Object first = list.get(0); - if (first != null && LootPool.class.isAssignableFrom(first.getClass())) { - pools = (List) list; - break; - } - } - } - } - - if (pools != null && pools.size() > index) { - LootPool pool = pools.get(index); - LootPoolAccessor acc = (LootPoolAccessor) pool; - pools.set(index, acc.bcl_mergeEntries(newEntries)); - - return true; - } - } catch (Throwable t) { - BCLib.LOGGER.error("ERROR building loot table: " + t.getMessage()); - } - - return false; - } -} diff --git a/src/main/java/org/betterx/bclib/util/MHelper.java b/src/main/java/org/betterx/bclib/util/MHelper.java deleted file mode 100644 index 16b3555a..00000000 --- a/src/main/java/org/betterx/bclib/util/MHelper.java +++ /dev/null @@ -1,282 +0,0 @@ -package org.betterx.bclib.util; - -import com.mojang.math.Vector3f; -import net.minecraft.core.Vec3i; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.levelgen.PositionalRandomFactory; - -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; - -public class MHelper { - static class ThreadLocalRandomSource implements RandomSource { - ThreadLocalRandomSource(long seed) { - - } - - @Override - public RandomSource fork() { - return this; - } - - @Override - public PositionalRandomFactory forkPositional() { - return null; - } - - @Override - public void setSeed(long l) { - ThreadLocalRandom.current().setSeed(l); - } - - @Override - public int nextInt() { - return ThreadLocalRandom.current().nextInt(); - } - - @Override - public int nextInt(int i) { - return ThreadLocalRandom.current().nextInt(i); - } - - @Override - public long nextLong() { - return ThreadLocalRandom.current().nextLong(); - } - - @Override - public boolean nextBoolean() { - return ThreadLocalRandom.current().nextBoolean(); - } - - @Override - public float nextFloat() { - return ThreadLocalRandom.current().nextFloat(); - } - - @Override - public double nextDouble() { - return ThreadLocalRandom.current().nextDouble(); - } - - @Override - public double nextGaussian() { - return ThreadLocalRandom.current().nextGaussian(); - } - } - - private static final Vec3i[] RANDOM_OFFSETS = new Vec3i[3 * 3 * 3 - 1]; - private static final float RAD_TO_DEG = 57.295779513082320876798154814105F; - public static final float PHI = (float) (Math.PI * (3 - Math.sqrt(5))); - public static final float PI2 = (float) (Math.PI * 2); - public static final Random RANDOM = new Random(); - public static final RandomSource RANDOM_SOURCE = new ThreadLocalRandomSource(RANDOM.nextLong()); - - public static int randRange(int min, int max, RandomSource random) { - return min + random.nextInt(max - min + 1); - } - - public static double randRange(double min, double max, RandomSource random) { - return min + random.nextDouble() * (max - min); - } - - public static float randRange(float min, float max, RandomSource random) { - return min + random.nextFloat() * (max - min); - } - - public static byte setBit(byte source, int pos, boolean value) { - return value ? setBitTrue(source, pos) : setBitFalse(source, pos); - } - - public static byte setBitTrue(byte source, int pos) { - source |= 1 << pos; - return source; - } - - public static byte setBitFalse(byte source, int pos) { - source &= ~(1 << pos); - return source; - } - - public static boolean getBit(byte source, int pos) { - return ((source >> pos) & 1) == 1; - } - - public static float wrap(float x, float side) { - return x - floor(x / side) * side; - } - - public static int floor(double x) { - return x < 0 ? (int) (x - 1) : (int) x; - } - - public static int min(int a, int b) { - return a < b ? a : b; - } - - public static int min(int a, int b, int c) { - return min(a, min(b, c)); - } - - public static int max(int a, int b) { - return a > b ? a : b; - } - - public static float min(float a, float b) { - return a < b ? a : b; - } - - public static float max(float a, float b) { - return a > b ? a : b; - } - - public static float max(float a, float b, float c) { - return max(a, max(b, c)); - } - - public static int max(int a, int b, int c) { - return max(a, max(b, c)); - } - - public static boolean isEven(int num) { - return (num & 1) == 0; - } - - public static float lengthSqr(float x, float y, float z) { - return x * x + y * y + z * z; - } - - public static double lengthSqr(double x, double y, double z) { - return x * x + y * y + z * z; - } - - public static float length(float x, float y, float z) { - return (float) Math.sqrt(lengthSqr(x, y, z)); - } - - public static double length(double x, double y, double z) { - return Math.sqrt(lengthSqr(x, y, z)); - } - - public static float lengthSqr(float x, float y) { - return x * x + y * y; - } - - public static double lengthSqr(double x, double y) { - return x * x + y * y; - } - - public static float length(float x, float y) { - return (float) Math.sqrt(lengthSqr(x, y)); - } - - public static double length(double x, double y) { - return Math.sqrt(lengthSqr(x, y)); - } - - public static float dot(float x1, float y1, float z1, float x2, float y2, float z2) { - return x1 * x2 + y1 * y2 + z1 * z2; - } - - public static float dot(float x1, float y1, float x2, float y2) { - return x1 * x2 + y1 * y2; - } - - public static int getRandom(int x, int z) { - int h = x * 374761393 + z * 668265263; - h = (h ^ (h >> 13)) * 1274126177; - return h ^ (h >> 16); - } - - public static int getSeed(int seed, int x, int y) { - int h = seed + x * 374761393 + y * 668265263; - h = (h ^ (h >> 13)) * 1274126177; - return h ^ (h >> 16); - } - - public static int getSeed(int seed, int x, int y, int z) { - int h = seed + x * 374761393 + y * 668265263 + z; - h = (h ^ (h >> 13)) * 1274126177; - return h ^ (h >> 16); - } - - public static void shuffle(T[] array, RandomSource random) { - for (int i = 0; i < array.length; i++) { - int i2 = random.nextInt(array.length); - T element = array[i]; - array[i] = array[i2]; - array[i2] = element; - } - } - - public static int sqr(int i) { - return i * i; - } - - public static float sqr(float f) { - return f * f; - } - - public static double sqr(double d) { - return d * d; - } - - public static final float radiansToDegrees(float value) { - return value * RAD_TO_DEG; - } - - public static final float degreesToRadians(float value) { - return value / RAD_TO_DEG; - } - - public static Vector3f cross(Vector3f vec1, Vector3f vec2) { - float cx = vec1.y() * vec2.z() - vec1.z() * vec2.y(); - float cy = vec1.z() * vec2.x() - vec1.x() * vec2.z(); - float cz = vec1.x() * vec2.y() - vec1.y() * vec2.x(); - return new Vector3f(cx, cy, cz); - } - - public static Vector3f normalize(Vector3f vec) { - float length = lengthSqr(vec.x(), vec.y(), vec.z()); - if (length > 0) { - length = (float) Math.sqrt(length); - float x = vec.x() / length; - float y = vec.y() / length; - float z = vec.z() / length; - vec.set(x, y, z); - } - return vec; - } - - public static float angle(Vector3f vec1, Vector3f vec2) { - float dot = vec1.x() * vec2.x() + vec1.y() * vec2.y() + vec1.z() * vec2.z(); - float length1 = lengthSqr(vec1.x(), vec1.y(), vec1.z()); - float length2 = lengthSqr(vec2.x(), vec2.y(), vec2.z()); - return (float) Math.acos(dot / Math.sqrt(length1 * length2)); - } - - public static Vector3f randomHorizontal(RandomSource random) { - float angleY = randRange(0, PI2, random); - float vx = (float) Math.sin(angleY); - float vz = (float) Math.cos(angleY); - return new Vector3f(vx, 0, vz); - } - - public static Vec3i[] getOffsets(RandomSource random) { - shuffle(RANDOM_OFFSETS, random); - return RANDOM_OFFSETS; - } - - static { - int index = 0; - for (int x = -1; x <= 1; x++) { - for (int y = -1; y <= 1; y++) { - for (int z = -1; z <= 1; z++) { - if (x != 0 || y != 0 || z != 0) { - RANDOM_OFFSETS[index++] = new Vec3i(x, y, z); - } - } - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/util/MethodReplace.java b/src/main/java/org/betterx/bclib/util/MethodReplace.java deleted file mode 100644 index 05c933ec..00000000 --- a/src/main/java/org/betterx/bclib/util/MethodReplace.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.betterx.bclib.util; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockBehaviour.BlockStateBase; - -import java.util.function.Function; -import org.jetbrains.annotations.Nullable; - -public class MethodReplace { - private static Function itemReplace; - private static Function blockReplace; - private static Block block; - private static Item item; - - public static void addItemReplace(Item item, Function itemReplace) { - MethodReplace.itemReplace = itemReplace; - MethodReplace.item = item; - } - - @Nullable - public static Function getItemReplace(Item item) { - if (MethodReplace.item != item) { - return null; - } - Function replace = itemReplace; - itemReplace = null; - return replace; - } -} diff --git a/src/main/java/org/betterx/bclib/util/Pair.java b/src/main/java/org/betterx/bclib/util/Pair.java deleted file mode 100644 index 5495c16b..00000000 --- a/src/main/java/org/betterx/bclib/util/Pair.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.betterx.bclib.util; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; - -import java.util.Objects; - -public class Pair { - public static Codec> pairCodec(Codec a, Codec b, String first, String second) { - return RecordCodecBuilder.create(instance -> instance - .group( - a.fieldOf(first).forGetter(o -> o.first), - b.fieldOf(second).forGetter(o -> o.second) - ) - .apply(instance, Pair::new)); - } - - public final A first; - public final B second; - - public Pair(A first, B second) { - this.first = first; - this.second = second; - } - - @Override - public String toString() { - return "Pair{" + "first=" + first + ", second=" + second + '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Pair)) return false; - Pair pair = (Pair) o; - return Objects.equals(first, pair.first) && Objects.equals(second, pair.second); - } - - @Override - public int hashCode() { - return Objects.hash(first, second); - } -} diff --git a/src/main/java/org/betterx/bclib/util/RecipeHelper.java b/src/main/java/org/betterx/bclib/util/RecipeHelper.java deleted file mode 100644 index 340e090b..00000000 --- a/src/main/java/org/betterx/bclib/util/RecipeHelper.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.betterx.bclib.util; - -import net.minecraft.core.Registry; -import net.minecraft.world.level.ItemLike; -import net.minecraft.world.level.block.Block; - -public class RecipeHelper { - public static boolean exists(ItemLike item) { - if (item instanceof Block) { - return Registry.BLOCK.getKey((Block) item) != Registry.BLOCK.getDefaultKey(); - } else { - return Registry.ITEM.getKey(item.asItem()) != Registry.ITEM.getDefaultKey(); - } - } - - public static boolean exists(ItemLike... items) { - for (ItemLike item : items) { - if (!exists(item)) { - return false; - } - } - return true; - } -} diff --git a/src/main/java/org/betterx/bclib/util/RomanNumeral.java b/src/main/java/org/betterx/bclib/util/RomanNumeral.java deleted file mode 100644 index 819ffbd9..00000000 --- a/src/main/java/org/betterx/bclib/util/RomanNumeral.java +++ /dev/null @@ -1,45 +0,0 @@ -package org.betterx.bclib.util; - -import java.util.TreeMap; - -/** - * base on ... - */ - -public class RomanNumeral { - private final static TreeMap LITERALS = new TreeMap<>(); - - private static void lazyInit() { - if (LITERALS.isEmpty()) { - LITERALS.put(1000, "M"); - LITERALS.put(900, "CM"); - LITERALS.put(500, "D"); - LITERALS.put(400, "CD"); - LITERALS.put(100, "C"); - LITERALS.put(90, "XC"); - LITERALS.put(50, "L"); - LITERALS.put(40, "XL"); - LITERALS.put(10, "X"); - LITERALS.put(9, "IX"); - LITERALS.put(5, "V"); - LITERALS.put(4, "IV"); - LITERALS.put(1, "I"); - } - } - - public static String toRoman(int number) { - lazyInit(); - return _toRoman(number); - } - - private static String _toRoman(int number) { - //there is no 0 in roman, but we need it anyway ;) - if (number == 0) return "0"; - - int l = LITERALS.floorKey(number); - if (number == l) { - return LITERALS.get(number); - } - return LITERALS.get(l) + _toRoman(number - l); - } -} diff --git a/src/main/java/org/betterx/bclib/util/SplineHelper.java b/src/main/java/org/betterx/bclib/util/SplineHelper.java deleted file mode 100644 index 54576e0d..00000000 --- a/src/main/java/org/betterx/bclib/util/SplineHelper.java +++ /dev/null @@ -1,387 +0,0 @@ -package org.betterx.bclib.util; - -import org.betterx.bclib.sdf.SDF; -import org.betterx.bclib.sdf.operator.SDFUnion; -import org.betterx.bclib.sdf.primitive.SDFLine; - -import com.mojang.math.Vector3f; -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.util.Mth; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.state.BlockState; - -import com.google.common.collect.Lists; - -import java.util.ArrayList; -import java.util.List; -import java.util.function.Function; - -public class SplineHelper { - public static List makeSpline(float x1, float y1, float z1, float x2, float y2, float z2, int points) { - List spline = Lists.newArrayList(); - spline.add(new Vector3f(x1, y1, z1)); - int count = points - 1; - for (int i = 1; i < count; i++) { - float delta = (float) i / (float) count; - float x = Mth.lerp(delta, x1, x2); - float y = Mth.lerp(delta, y1, y2); - float z = Mth.lerp(delta, z1, z2); - spline.add(new Vector3f(x, y, z)); - } - spline.add(new Vector3f(x2, y2, z2)); - return spline; - } - - public static List smoothSpline(List spline, int segmentPoints) { - List result = Lists.newArrayList(); - Vector3f start = spline.get(0); - for (int i = 1; i < spline.size(); i++) { - Vector3f end = spline.get(i); - for (int j = 0; j < segmentPoints; j++) { - float delta = (float) j / segmentPoints; - delta = 0.5F - 0.5F * Mth.cos(delta * 3.14159F); - result.add(lerp(start, end, delta)); - } - start = end; - } - result.add(start); - return result; - } - - private static Vector3f lerp(Vector3f start, Vector3f end, float delta) { - float x = Mth.lerp(delta, start.x(), end.x()); - float y = Mth.lerp(delta, start.y(), end.y()); - float z = Mth.lerp(delta, start.z(), end.z()); - return new Vector3f(x, y, z); - } - - public static void offsetParts(List spline, RandomSource random, float dx, float dy, float dz) { - int count = spline.size(); - for (int i = 1; i < count; i++) { - Vector3f pos = spline.get(i); - float x = pos.x() + (float) random.nextGaussian() * dx; - float y = pos.y() + (float) random.nextGaussian() * dy; - float z = pos.z() + (float) random.nextGaussian() * dz; - pos.set(x, y, z); - } - } - - public static void powerOffset(List spline, float distance, float power) { - int count = spline.size(); - float max = count + 1; - for (int i = 1; i < count; i++) { - Vector3f pos = spline.get(i); - float x = (float) i / max; - float y = pos.y() + (float) Math.pow(x, power) * distance; - pos.set(pos.x(), y, pos.z()); - } - } - - public static SDF buildSDF( - List spline, - float radius1, - float radius2, - Function placerFunction - ) { - int count = spline.size(); - float max = count - 2; - SDF result = null; - Vector3f start = spline.get(0); - for (int i = 1; i < count; i++) { - Vector3f pos = spline.get(i); - float delta = (float) (i - 1) / max; - SDF line = new SDFLine().setRadius(Mth.lerp(delta, radius1, radius2)) - .setStart(start.x(), start.y(), start.z()) - .setEnd(pos.x(), pos.y(), pos.z()) - .setBlock(placerFunction); - result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line); - start = pos; - } - return result; - } - - public static SDF buildSDF( - List spline, - Function radiusFunction, - Function placerFunction - ) { - int count = spline.size(); - float max = count - 2; - SDF result = null; - Vector3f start = spline.get(0); - for (int i = 1; i < count; i++) { - Vector3f pos = spline.get(i); - float delta = (float) (i - 1) / max; - SDF line = new SDFLine().setRadius(radiusFunction.apply(delta)) - .setStart(start.x(), start.y(), start.z()) - .setEnd(pos.x(), pos.y(), pos.z()) - .setBlock(placerFunction); - result = result == null ? line : new SDFUnion().setSourceA(result).setSourceB(line); - start = pos; - } - return result; - } - - public static boolean fillSpline( - List spline, - WorldGenLevel world, - BlockState state, - BlockPos pos, - Function replace - ) { - Vector3f startPos = spline.get(0); - for (int i = 1; i < spline.size(); i++) { - Vector3f endPos = spline.get(i); - if (!(fillLine(startPos, endPos, world, state, pos, replace))) { - return false; - } - startPos = endPos; - } - - return true; - } - - public static void fillSplineForce( - List spline, - WorldGenLevel world, - BlockState state, - BlockPos pos, - Function replace - ) { - Vector3f startPos = spline.get(0); - for (int i = 1; i < spline.size(); i++) { - Vector3f endPos = spline.get(i); - fillLineForce(startPos, endPos, world, state, pos, replace); - startPos = endPos; - } - } - - public static boolean fillLine( - Vector3f start, - Vector3f end, - WorldGenLevel world, - BlockState state, - BlockPos pos, - Function replace - ) { - float dx = end.x() - start.x(); - float dy = end.y() - start.y(); - float dz = end.z() - start.z(); - float max = MHelper.max(Math.abs(dx), Math.abs(dy), Math.abs(dz)); - int count = MHelper.floor(max + 1); - dx /= max; - dy /= max; - dz /= max; - float x = start.x(); - float y = start.y(); - float z = start.z(); - boolean down = Math.abs(dy) > 0.2; - - BlockState bState; - MutableBlockPos bPos = new MutableBlockPos(); - for (int i = 0; i < count; i++) { - bPos.set(x + pos.getX(), y + pos.getY(), z + pos.getZ()); - bState = world.getBlockState(bPos); - if (bState.equals(state) || replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - bPos.setY(bPos.getY() - 1); - bState = world.getBlockState(bPos); - if (down && bState.equals(state) || replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - } - } else { - return false; - } - x += dx; - y += dy; - z += dz; - } - bPos.set(end.x() + pos.getX(), end.y() + pos.getY(), end.z() + pos.getZ()); - bState = world.getBlockState(bPos); - if (bState.equals(state) || replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - bPos.setY(bPos.getY() - 1); - bState = world.getBlockState(bPos); - if (down && bState.equals(state) || replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - } - return true; - } else { - return false; - } - } - - public static void fillLineForce( - Vector3f start, - Vector3f end, - WorldGenLevel world, - BlockState state, - BlockPos pos, - Function replace - ) { - float dx = end.x() - start.x(); - float dy = end.y() - start.y(); - float dz = end.z() - start.z(); - float max = MHelper.max(Math.abs(dx), Math.abs(dy), Math.abs(dz)); - int count = MHelper.floor(max + 1); - dx /= max; - dy /= max; - dz /= max; - float x = start.x(); - float y = start.y(); - float z = start.z(); - boolean down = Math.abs(dy) > 0.2; - - BlockState bState; - MutableBlockPos bPos = new MutableBlockPos(); - for (int i = 0; i < count; i++) { - bPos.set(x + pos.getX(), y + pos.getY(), z + pos.getZ()); - bState = world.getBlockState(bPos); - if (replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - bPos.setY(bPos.getY() - 1); - bState = world.getBlockState(bPos); - if (down && replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - } - } - x += dx; - y += dy; - z += dz; - } - bPos.set(end.x() + pos.getX(), end.y() + pos.getY(), end.z() + pos.getZ()); - bState = world.getBlockState(bPos); - if (replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - bPos.setY(bPos.getY() - 1); - bState = world.getBlockState(bPos); - if (down && replace.apply(bState)) { - BlocksHelper.setWithoutUpdate(world, bPos, state); - } - } - } - - public static boolean canGenerate( - List spline, - float scale, - BlockPos start, - WorldGenLevel world, - Function canReplace - ) { - int count = spline.size(); - Vector3f vec = spline.get(0); - MutableBlockPos mut = new MutableBlockPos(); - float x1 = start.getX() + vec.x() * scale; - float y1 = start.getY() + vec.y() * scale; - float z1 = start.getZ() + vec.z() * scale; - for (int i = 1; i < count; i++) { - vec = spline.get(i); - float x2 = start.getX() + vec.x() * scale; - float y2 = start.getY() + vec.y() * scale; - float z2 = start.getZ() + vec.z() * scale; - - for (float py = y1; py < y2; py += 3) { - if (py - start.getY() < 10) continue; - float lerp = (py - y1) / (y2 - y1); - float x = Mth.lerp(lerp, x1, x2); - float z = Mth.lerp(lerp, z1, z2); - mut.set(x, py, z); - if (!canReplace.apply(world.getBlockState(mut))) { - return false; - } - } - - x1 = x2; - y1 = y2; - z1 = z2; - } - return true; - } - - public static boolean canGenerate( - List spline, - BlockPos start, - WorldGenLevel world, - Function canReplace - ) { - int count = spline.size(); - Vector3f vec = spline.get(0); - MutableBlockPos mut = new MutableBlockPos(); - float x1 = start.getX() + vec.x(); - float y1 = start.getY() + vec.y(); - float z1 = start.getZ() + vec.z(); - for (int i = 1; i < count; i++) { - vec = spline.get(i); - float x2 = start.getX() + vec.x(); - float y2 = start.getY() + vec.y(); - float z2 = start.getZ() + vec.z(); - - for (float py = y1; py < y2; py += 3) { - if (py - start.getY() < 10) continue; - float lerp = (py - y1) / (y2 - y1); - float x = Mth.lerp(lerp, x1, x2); - float z = Mth.lerp(lerp, z1, z2); - mut.set(x, py, z); - if (!canReplace.apply(world.getBlockState(mut))) { - return false; - } - } - - x1 = x2; - y1 = y2; - z1 = z2; - } - return true; - } - - public static Vector3f getPos(List spline, float index) { - int i = (int) index; - int last = spline.size() - 1; - if (i >= last) { - return spline.get(last); - } - float delta = index - i; - Vector3f p1 = spline.get(i); - Vector3f p2 = spline.get(i + 1); - float x = Mth.lerp(delta, p1.x(), p2.x()); - float y = Mth.lerp(delta, p1.y(), p2.y()); - float z = Mth.lerp(delta, p1.z(), p2.z()); - return new Vector3f(x, y, z); - } - - public static void rotateSpline(List spline, float angle) { - for (Vector3f v : spline) { - float sin = (float) Math.sin(angle); - float cos = (float) Math.cos(angle); - float x = v.x() * cos + v.z() * sin; - float z = v.x() * sin + v.z() * cos; - v.set(x, v.y(), z); - } - } - - public static List copySpline(List spline) { - List result = new ArrayList(spline.size()); - for (Vector3f v : spline) { - result.add(new Vector3f(v.x(), v.y(), v.z())); - } - return result; - } - - public static void scale(List spline, float scale) { - scale(spline, scale, scale, scale); - } - - public static void scale(List spline, float x, float y, float z) { - for (Vector3f v : spline) { - v.set(v.x() * x, v.y() * y, v.z() * z); - } - } - - public static void offset(List spline, Vector3f offset) { - for (Vector3f v : spline) { - v.set(offset.x() + v.x(), offset.y() + v.y(), offset.z() + v.z()); - } - } -} diff --git a/src/main/java/org/betterx/bclib/util/StructureErode.java b/src/main/java/org/betterx/bclib/util/StructureErode.java deleted file mode 100644 index 0a451a22..00000000 --- a/src/main/java/org/betterx/bclib/util/StructureErode.java +++ /dev/null @@ -1,277 +0,0 @@ -package org.betterx.bclib.util; - -import org.betterx.bclib.api.v2.levelgen.biomes.BiomeAPI; -import org.betterx.worlds.together.tag.v3.CommonBlockTags; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.BlockPos.MutableBlockPos; -import net.minecraft.core.Direction; -import net.minecraft.tags.BlockTags; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.state.BlockState; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.material.Material; - -import com.google.common.collect.Sets; - -import java.util.Set; - -public class StructureErode { - private static final Direction[] DIR = BlocksHelper.makeHorizontal(); - - public static void erode(WorldGenLevel world, BoundingBox bounds, int iterations, RandomSource random) { - MutableBlockPos mut = new MutableBlockPos(); - boolean canDestruct = true; - for (int i = 0; i < iterations; i++) { - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - mut.setX(x); - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - mut.setZ(z); - for (int y = bounds.maxY(); y >= bounds.minY(); y--) { - mut.setY(y); - BlockState state = world.getBlockState(mut); - boolean ignore = ignore(state, world, mut); - if (canDestruct && BlocksHelper.isInvulnerable( - state, - world, - mut - ) && random.nextInt(8) == 0 && world.isEmptyBlock( - mut.below(2))) { - int r = MHelper.randRange(1, 4, random); - int cx = mut.getX(); - int cy = mut.getY(); - int cz = mut.getZ(); - int x1 = cx - r; - int y1 = cy - r; - int z1 = cz - r; - int x2 = cx + r; - int y2 = cy + r; - int z2 = cz + r; - for (int px = x1; px <= x2; px++) { - int dx = px - cx; - dx *= dx; - mut.setX(px); - for (int py = y1; py <= y2; py++) { - int dy = py - cy; - dy *= dy; - mut.setY(py); - for (int pz = z1; pz <= z2; pz++) { - int dz = pz - cz; - dz *= dz; - mut.setZ(pz); - if (dx + dy + dz <= r && BlocksHelper.isInvulnerable( - world.getBlockState(mut), - world, - mut - )) { - BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - } - } - } - } - mut.setX(cx); - mut.setY(cy); - mut.setZ(cz); - canDestruct = false; - continue; - } else if (ignore) { - continue; - } - if (!state.isAir() && random.nextBoolean()) { - MHelper.shuffle(DIR, random); - for (Direction dir : DIR) { - if (world.isEmptyBlock(mut.relative(dir)) && world.isEmptyBlock(mut.below() - .relative(dir))) { - BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - mut.move(dir).move(Direction.DOWN); - for (int py = mut.getY(); y >= bounds.minY() - 10; y--) { - mut.setY(py - 1); - if (!world.isEmptyBlock(mut)) { - mut.setY(py); - BlocksHelper.setWithoutUpdate(world, mut, state); - break; - } - } - } - } - break; - } else if (random.nextInt(8) == 0 && !BlocksHelper.isInvulnerable( - world.getBlockState(mut.above()), - world, - mut - )) { - BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - } - } - } - } - } - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - mut.setX(x); - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - mut.setZ(z); - for (int y = bounds.maxY(); y >= bounds.minY(); y--) { - mut.setY(y); - BlockState state = world.getBlockState(mut); - if (!ignore(state, world, mut) && world.isEmptyBlock(mut.below())) { - BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - for (int py = mut.getY(); py >= bounds.minY() - 10; py--) { - mut.setY(py - 1); - if (!world.isEmptyBlock(mut)) { - mut.setY(py); - BlocksHelper.setWithoutUpdate(world, mut, state); - break; - } - } - } - } - } - } - } - - public static void erodeIntense(WorldGenLevel world, BoundingBox bounds, RandomSource random) { - MutableBlockPos mut = new MutableBlockPos(); - MutableBlockPos mut2 = new MutableBlockPos(); - int minY = bounds.minY() - 10; - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - mut.setX(x); - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - mut.setZ(z); - for (int y = bounds.maxY(); y >= bounds.minY(); y--) { - mut.setY(y); - BlockState state = world.getBlockState(mut); - if (!ignore(state, world, mut)) { - if (random.nextInt(6) == 0) { - BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - if (random.nextBoolean()) { - int px = MHelper.floor(random.nextGaussian() * 2 + x + 0.5); - int pz = MHelper.floor(random.nextGaussian() * 2 + z + 0.5); - mut2.set(px, y, pz); - while (world.getBlockState(mut2).getMaterial().isReplaceable() && mut2.getY() > minY) { - mut2.setY(mut2.getY() - 1); - } - if (!world.getBlockState(mut2).isAir() && state.canSurvive(world, mut2)) { - mut2.setY(mut2.getY() + 1); - BlocksHelper.setWithoutUpdate(world, mut2, state); - } - } - } else if (random.nextInt(8) == 0) { - BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - } - } - } - } - } - - drop(world, bounds); - } - - private static void drop(WorldGenLevel world, BoundingBox bounds) { - MutableBlockPos mut = new MutableBlockPos(); - - Set blocks = Sets.newHashSet(); - Set edge = Sets.newHashSet(); - Set add = Sets.newHashSet(); - - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - mut.setX(x); - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - mut.setZ(z); - for (int y = bounds.minY(); y <= bounds.maxY(); y++) { - mut.setY(y); - BlockState state = world.getBlockState(mut); - if (!ignore(state, world, mut) && isTerrainNear(world, mut)) { - edge.add(mut.immutable()); - } - } - } - } - - if (edge.isEmpty()) { - return; - } - - while (!edge.isEmpty()) { - for (BlockPos center : edge) { - for (Direction dir : BlocksHelper.DIRECTIONS) { - BlockState state = world.getBlockState(center); - if (state.isCollisionShapeFullBlock(world, center)) { - mut.set(center).move(dir); - if (bounds.isInside(mut)) { - state = world.getBlockState(mut); - if (!ignore(state, world, mut) && !blocks.contains(mut)) { - add.add(mut.immutable()); - } - } - } - } - } - - blocks.addAll(edge); - edge.clear(); - edge.addAll(add); - add.clear(); - } - - int minY = bounds.minY() - 10; - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - mut.setX(x); - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - mut.setZ(z); - for (int y = bounds.minY(); y <= bounds.maxY(); y++) { - mut.setY(y); - BlockState state = world.getBlockState(mut); - if (!ignore(state, world, mut) && !blocks.contains(mut)) { - BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); - while (world.getBlockState(mut).getMaterial().isReplaceable() && mut.getY() > minY) { - mut.setY(mut.getY() - 1); - } - if (mut.getY() > minY) { - mut.setY(mut.getY() + 1); - BlocksHelper.setWithoutUpdate(world, mut, state); - } - } - } - } - } - } - - private static boolean ignore(BlockState state, WorldGenLevel world, BlockPos pos) { - if (state.is(CommonBlockTags.GEN_END_STONES) || state.is(BlockTags.NYLIUM)) { - return true; - } - return !state.getMaterial().equals(Material.STONE) || BlocksHelper.isInvulnerable(state, world, pos); - } - - private static boolean isTerrainNear(WorldGenLevel world, BlockPos pos) { - for (Direction dir : BlocksHelper.DIRECTIONS) { - if (world.getBlockState(pos.relative(dir)).is(CommonBlockTags.GEN_END_STONES)) { - return true; - } - } - return false; - } - - public static void cover(WorldGenLevel world, BoundingBox bounds, RandomSource random, BlockState defaultBlock) { - MutableBlockPos mut = new MutableBlockPos(); - for (int x = bounds.minX(); x <= bounds.maxX(); x++) { - mut.setX(x); - for (int z = bounds.minZ(); z <= bounds.maxZ(); z++) { - mut.setZ(z); - BlockState top = BiomeAPI.findTopMaterial(world.getBiome(mut)).orElse(defaultBlock); - if (top == null) continue; - for (int y = bounds.maxY(); y >= bounds.minY(); y--) { - mut.setY(y); - BlockState state = world.getBlockState(mut); - if (state.is(CommonBlockTags.TERRAIN) && !world.getBlockState(mut.above()) - .getMaterial() - .isSolidBlocking()) { - BlocksHelper.setWithoutUpdate(world, mut, top); - } - } - } - } - } -} diff --git a/src/main/java/org/betterx/bclib/util/StructureHelper.java b/src/main/java/org/betterx/bclib/util/StructureHelper.java deleted file mode 100644 index d0ac7019..00000000 --- a/src/main/java/org/betterx/bclib/util/StructureHelper.java +++ /dev/null @@ -1,143 +0,0 @@ -package org.betterx.bclib.util; - -import net.minecraft.core.BlockPos; -import net.minecraft.core.Vec3i; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.RandomSource; -import net.minecraft.world.level.WorldGenLevel; -import net.minecraft.world.level.block.Mirror; -import net.minecraft.world.level.block.Rotation; -import net.minecraft.world.level.levelgen.structure.BoundingBox; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlaceSettings; -import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; -import net.minecraft.world.phys.Vec3; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -public class StructureHelper { - public static StructureTemplate readStructure(ResourceLocation resource) { - String ns = resource.getNamespace(); - String nm = resource.getPath(); - return readStructure("/data/" + ns + "/structures/" + nm + ".nbt"); - } - - public static StructureTemplate readStructure(File datapack, String path) { - if (datapack.isDirectory()) { - return readStructure(datapack + "/" + path); - } else if (datapack.isFile() && datapack.getName().endsWith(".zip")) { - try { - ZipFile zipFile = new ZipFile(datapack); - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - String name = entry.getName(); - long compressedSize = entry.getCompressedSize(); - long normalSize = entry.getSize(); - String type = entry.isDirectory() ? "DIR" : "FILE"; - - System.out.println(name); - System.out.format("\t %s - %d - %d\n", type, compressedSize, normalSize); - } - zipFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - return null; - } - - public static StructureTemplate readStructure(String path) { - try { - InputStream inputstream = StructureHelper.class.getResourceAsStream(path); - return readStructureFromStream(inputstream); - } catch (IOException e) { - e.printStackTrace(); - } - return null; - } - - private static StructureTemplate readStructureFromStream(InputStream stream) throws IOException { - CompoundTag nbttagcompound = NbtIo.readCompressed(stream); - - StructureTemplate template = new StructureTemplate(); - template.load(nbttagcompound); - - return template; - } - - public static BlockPos offsetPos(BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror) { - Vec3 offset = StructureTemplate.transform( - Vec3.atCenterOf(structure.getSize()), - mirror, - rotation, - BlockPos.ZERO - ); - return pos.offset(-offset.x * 0.5, 0, -offset.z * 0.5); - } - - public static void placeCenteredBottom( - WorldGenLevel world, - BlockPos pos, - StructureTemplate structure, - Rotation rotation, - Mirror mirror, - RandomSource random - ) { - placeCenteredBottom(world, pos, structure, rotation, mirror, makeBox(pos), random); - } - - public static void placeCenteredBottom( - WorldGenLevel world, - BlockPos pos, - StructureTemplate structure, - Rotation rotation, - Mirror mirror, - BoundingBox bounds, - RandomSource random - ) { - BlockPos offset = offsetPos(pos, structure, rotation, mirror); - StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation) - .setMirror(mirror) - .setBoundingBox(bounds); - structure.placeInWorld(world, offset, offset, placementData, random, 4); - } - - private static BoundingBox makeBox(BlockPos pos) { - int sx = ((pos.getX() >> 4) << 4) - 16; - int sz = ((pos.getZ() >> 4) << 4) - 16; - int ex = sx + 47; - int ez = sz + 47; - return BoundingBox.fromCorners(new Vec3i(sx, 0, sz), new Vec3i(ex, 255, ez)); - } - - public static BoundingBox getStructureBounds( - BlockPos pos, - StructureTemplate structure, - Rotation rotation, - Mirror mirror - ) { - Vec3i max = structure.getSize(); - Vec3 min = StructureTemplate.transform(Vec3.atCenterOf(structure.getSize()), mirror, rotation, BlockPos.ZERO); - max = max.offset(-min.x, -min.y, -min.z); - return BoundingBox.fromCorners(pos.offset(min.x, min.y, min.z), max.offset(pos)); - } - - public static BoundingBox intersectBoxes(BoundingBox box1, BoundingBox box2) { - int x1 = MHelper.max(box1.minX(), box2.minX()); - int y1 = MHelper.max(box1.minY(), box2.minY()); - int z1 = MHelper.max(box1.minZ(), box2.minZ()); - - int x2 = MHelper.min(box1.maxX(), box2.maxX()); - int y2 = MHelper.min(box1.maxY(), box2.maxY()); - int z2 = MHelper.min(box1.maxZ(), box2.maxZ()); - - return BoundingBox.fromCorners(new Vec3i(x1, y1, z1), new Vec3i(x2, y2, z2)); - } -} diff --git a/src/main/java/org/betterx/bclib/util/TranslationHelper.java b/src/main/java/org/betterx/bclib/util/TranslationHelper.java deleted file mode 100644 index 28339d19..00000000 --- a/src/main/java/org/betterx/bclib/util/TranslationHelper.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.betterx.bclib.util; - -import net.minecraft.core.Registry; -import net.minecraft.data.BuiltinRegistries; -import net.minecraft.resources.ResourceLocation; - -import com.google.common.collect.Sets; -import com.google.gson.Gson; -import com.google.gson.JsonObject; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Set; - -public class TranslationHelper { - /** - * Print English translation file lines. Translation is "auto-beautified" text (example "strange_thing" -> "Strange Thing"). - * - * @param modID {@link String} mod ID string. - */ - public static void printMissingEnNames(String modID) { - printMissingNames(modID, "en_us"); - } - - /** - * Prints translation file lines for specified language. - * - * @param modID {@link String} mod ID string; - * @param languageCode {@link String} language code (example "en_us", "ru_ru"). - */ - public static void printMissingNames(String modID, String languageCode) { - Set missingNames = Sets.newHashSet(); - - Gson gson = new Gson(); - InputStream inputStream = TranslationHelper.class.getResourceAsStream("/assets/" + modID + "/lang/" + languageCode + ".json"); - JsonObject translation = inputStream == null - ? new JsonObject() - : gson.fromJson(new InputStreamReader(inputStream), JsonObject.class); - - Registry.BLOCK.forEach(block -> { - if (Registry.BLOCK.getKey(block).getNamespace().equals(modID)) { - String name = block.getName().getString(); - if (!translation.has(name)) { - missingNames.add(name); - } - } - }); - - Registry.ITEM.forEach(item -> { - if (Registry.ITEM.getKey(item).getNamespace().equals(modID)) { - String name = item.getDescription().getString(); - if (!translation.has(name)) { - missingNames.add(name); - } - } - }); - - BuiltinRegistries.BIOME.forEach(biome -> { - ResourceLocation id = BuiltinRegistries.BIOME.getKey(biome); - if (id.getNamespace().equals(modID)) { - String name = "biome." + modID + "." + id.getPath(); - if (!translation.has(name)) { - missingNames.add(name); - } - } - }); - - Registry.ENTITY_TYPE.forEach((entity) -> { - ResourceLocation id = Registry.ENTITY_TYPE.getKey(entity); - if (id.getNamespace().equals(modID)) { - String name = "entity." + modID + "." + id.getPath(); - if (!translation.has(name)) { - missingNames.add(name); - } - } - }); - - if (!missingNames.isEmpty()) { - - System.out.println("========================================"); - System.out.println(" MISSING NAMES LIST"); - - if (!missingNames.isEmpty()) { - if (languageCode.equals("en_us")) { - System.out.println("========================================"); - System.out.println(" AUTO ENGLISH BEAUTIFICATION"); - System.out.println("========================================"); - missingNames.stream().sorted().forEach(name -> { - System.out.println(" \"" + name + "\": \"" + fastTranslateEn(name) + "\","); - }); - } else { - System.out.println("========================================"); - System.out.println(" TEMPLATE: [" + languageCode + "]"); - System.out.println("========================================"); - missingNames.stream().sorted().forEach(name -> { - System.out.println(" \"" + name + "\": \"\","); - }); - } - } - - System.out.println("========================================"); - } - } - - /** - * Simple fast text beautification (example "strange_thing" -> "Strange Thing"). - * - * @param text {@link String} to process; - * @return {@link String} result. - */ - public static String fastTranslateEn(String text) { - String[] words = text.substring(text.lastIndexOf('.') + 1).split("_"); - StringBuilder builder = new StringBuilder(); - for (int i = 0; i < words.length; i++) { - String word = words[i]; - builder.append(Character.toUpperCase(word.charAt(0))); - builder.append(word, 1, word.length()); - if (i < words.length - 1) { - builder.append(' '); - } - } - return builder.toString(); - } -} diff --git a/src/main/java/org/betterx/bclib/util/TriFunction.java b/src/main/java/org/betterx/bclib/util/TriFunction.java deleted file mode 100644 index 6e568e13..00000000 --- a/src/main/java/org/betterx/bclib/util/TriFunction.java +++ /dev/null @@ -1,6 +0,0 @@ -package org.betterx.bclib.util; - -@FunctionalInterface -public interface TriFunction { - R apply(A a, B b, C c); -} diff --git a/src/main/java/org/betterx/bclib/util/Triple.java b/src/main/java/org/betterx/bclib/util/Triple.java deleted file mode 100644 index b47d5a81..00000000 --- a/src/main/java/org/betterx/bclib/util/Triple.java +++ /dev/null @@ -1,31 +0,0 @@ -package org.betterx.bclib.util; - -import java.util.Objects; - -public class Triple extends Pair { - public final C third; - - public Triple(A first, B second, C third) { - super(first, second); - this.third = third; - } - - @Override - public String toString() { - return "Triple{" + "first=" + first + ", second=" + second + ", third=" + third + '}'; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof Triple)) return false; - if (!super.equals(o)) return false; - Triple triple = (Triple) o; - return Objects.equals(third, triple.third); - } - - @Override - public int hashCode() { - return Objects.hash(super.hashCode(), third); - } -} diff --git a/src/main/java/org/betterx/bclib/util/WeighTree.java b/src/main/java/org/betterx/bclib/util/WeighTree.java deleted file mode 100644 index f02655ff..00000000 --- a/src/main/java/org/betterx/bclib/util/WeighTree.java +++ /dev/null @@ -1,91 +0,0 @@ -package org.betterx.bclib.util; - -import net.minecraft.world.level.levelgen.WorldgenRandom; - -import java.util.Locale; -import java.util.Random; - -public class WeighTree { - private final float maxWeight; - private final Node root; - - public WeighTree(WeightedList list) { - maxWeight = list.getMaxWeight(); - root = getNode(list); - } - - /** - * Get eandom value from tree. - * - * @param random - {@link Random}. - * @return {@link T} value. - */ - public T get(WorldgenRandom random) { - return root.get(random.nextFloat() * maxWeight); - } - - private Node getNode(WeightedList list) { - int size = list.size(); - if (size == 1) { - return new Leaf(list.get(0)); - } else if (size == 2) { - T first = list.get(0); - return new Branch(list.getWeight(0), new Leaf(first), new Leaf(list.get(1))); - } else { - int index = size >> 1; - float separator = list.getWeight(index); - Node a = getNode(list.subList(0, index + 1)); - Node b = getNode(list.subList(index, size)); - return new Branch(separator, a, b); - } - } - - private abstract class Node { - abstract T get(float value); - } - - private class Branch extends Node { - final float separator; - final Node min; - final Node max; - - public Branch(float separator, Node min, Node max) { - this.separator = separator; - this.min = min; - this.max = max; - } - - @Override - T get(float value) { - return value < separator ? min.get(value) : max.get(value); - } - - @Override - public String toString() { - return String.format(Locale.ROOT, "[%f, %s, %s]", separator, min.toString(), max.toString()); - } - } - - private class Leaf extends Node { - final T biome; - - Leaf(T value) { - this.biome = value; - } - - @Override - T get(float value) { - return biome; - } - - @Override - public String toString() { - return String.format(Locale.ROOT, "[%s]", biome.toString()); - } - } - - @Override - public String toString() { - return root.toString(); - } -} diff --git a/src/main/java/org/betterx/bclib/util/WeightedList.java b/src/main/java/org/betterx/bclib/util/WeightedList.java deleted file mode 100644 index a78d5428..00000000 --- a/src/main/java/org/betterx/bclib/util/WeightedList.java +++ /dev/null @@ -1,182 +0,0 @@ -package org.betterx.bclib.util; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.util.RandomSource; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.function.Consumer; -import java.util.function.Function; - -public class WeightedList { - - - private final List weights = new ArrayList(); - private final List values = new ArrayList(); - private float maxWeight; - - public static Codec> pairCodec(Codec elementCodec, String fieldName) { - return Pair.pairCodec(Codec.FLOAT, elementCodec, "weight", fieldName); - } - - public static Codec> listCodec(Codec elementCodec, String fieldName, String elementName) { - return RecordCodecBuilder.create(instance -> instance - .group( - pairCodec(elementCodec, elementName).listOf() - .fieldOf(fieldName) - .forGetter(WeightedList::pairs) - ) - .apply(instance, WeightedList::new) - ); - } - - private List> pairs() { - List> pairs = new ArrayList<>(weights.size()); - for (int i = 0; i < weights.size(); i++) { - pairs.add(new Pair<>(weights.get(i), values.get(i))); - } - return pairs; - } - - private WeightedList(List> pairs) { - maxWeight = 0; - for (var pair : pairs) { - maxWeight += pair.first; - weights.add(pair.first); - values.add(pair.second); - } - } - - public WeightedList() { - } - - public WeightedList map(Function map) { - List> pairs = new ArrayList<>(weights.size()); - for (int i = 0; i < weights.size(); i++) { - pairs.add(new Pair<>(weights.get(i), map.apply(values.get(i)))); - } - return new WeightedList<>(pairs); - } - - public void addAll(WeightedList other) { - weights.addAll(other.weights); - values.addAll(other.values); - maxWeight += other.maxWeight; - } - - /** - * Adds value with specified weight to the list - * - * @param value - * @param weight - */ - public void add(T value, float weight) { - maxWeight += weight; - weights.add(maxWeight); - values.add(value); - } - - /** - * Get random value. - * - * @param random - {@link Random}. - * @return {@link T} value. - */ - public T get(RandomSource random) { - if (maxWeight < 1) { - return null; - } - float weight = random.nextFloat() * maxWeight; - for (int i = 0; i < weights.size(); i++) { - if (weight <= weights.get(i)) { - return values.get(i); - } - weight -= weights.get(i); - } - return null; - } - - /** - * Get value by index. - * - * @param index - {@code int} index. - * @return {@link T} value. - */ - public T get(int index) { - return values.get(index); - } - - /** - * Get value weight. Weight is summed with all previous values weights. - * - * @param index - {@code int} index. - * @return {@code float} weight. - */ - public float getWeight(int index) { - return weights.get(index); - } - - /** - * Chech if the list is empty. - * - * @return {@code true} if list is empty and {@code false} if not. - */ - public boolean isEmpty() { - return maxWeight == 0; - } - - /** - * Get the list size. - * - * @return {@code int} list size. - */ - public int size() { - return values.size(); - } - - /** - * Makes a sublist of this list with same weights. Used only in {@link WeighTree} - * - * @param start - {@code int} start index (inclusive). - * @param end - {@code int} end index (exclusive). - * @return {@link WeightedList}. - */ - protected WeightedList subList(int start, int end) { - WeightedList list = new WeightedList(); - for (int i = start; i < end; i++) { - list.weights.add(weights.get(i)); - list.values.add(values.get(i)); - } - return list; - } - - /** - * Check if list contains certain value. - * - * @param value - {@link T} value. - * @return {@code true} if value is in list and {@code false} if not. - */ - public boolean contains(T value) { - return values.contains(value); - } - - /** - * Applies {@link Consumer} to all values in list. - * - * @param function - {@link Consumer}. - */ - public void forEach(Consumer function) { - values.forEach(function); - } - - /** - * Get the maximum weight of the tree. - * - * @return {@code float} maximum weight. - */ - public float getMaxWeight() { - return maxWeight; - } -} diff --git a/src/main/java/org/betterx/bclib/world/structures/BCLStructure.java b/src/main/java/org/betterx/bclib/world/structures/BCLStructure.java deleted file mode 100644 index 29fd1565..00000000 --- a/src/main/java/org/betterx/bclib/world/structures/BCLStructure.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.betterx.bclib.world.structures; - -import org.betterx.bclib.api.v2.levelgen.structures.BCLStructureBuilder; -import org.betterx.worlds.together.tag.v3.TagManager; - -import com.mojang.serialization.Codec; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.TagKey; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.levelgen.GenerationStep; -import net.minecraft.world.level.levelgen.structure.Structure; -import net.minecraft.world.level.levelgen.structure.TerrainAdjustment; -import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement; -import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadType; - -import java.util.function.Function; - -@Deprecated(forRemoval = true) -/** - * Please use the {@link org.betterx.bclib.api.v2.levelgen.structures.BCLStructure} and - * {@link BCLStructureBuilder} instead. - * @deprecated Use {@link org.betterx.bclib.api.v2.levelgen.structures.BCLStructure} instead - */ -public class BCLStructure extends org.betterx.bclib.api.v2.levelgen.structures.BCLStructure { - - @Deprecated(forRemoval = true) - /** - * Please use the {@link BCLStructureBuilder} instead: - * - * BCLStructureBuilder - * .start(id, structureBuilder) - * .step(step) - * .randomPlacement(spacing, separation) - * .build(); - */ - public BCLStructure( - ResourceLocation id, - Function structureBuilder, - GenerationStep.Decoration step, - int spacing, - int separation - ) { - this(id, structureBuilder, step, spacing, separation, false); - } - - @Deprecated(forRemoval = true) - /** - * Please use the {@link BCLStructureBuilder} instead: - * - * BCLStructureBuilder - * .start(id, structureBuilder) - * .step(step) - * .randomPlacement(spacing, separation) - * .build(); - */ - public BCLStructure( - ResourceLocation id, - Function structureBuilder, - GenerationStep.Decoration step, - int spacing, - int separation, - boolean adaptNoise - ) { - this( - id, - structureBuilder, - step, - spacing, - separation, - adaptNoise, - Structure.simpleCodec(structureBuilder), - TagManager.BIOMES.makeStructureTag(id.getNamespace(), id.getPath()) - ); - } - - @Deprecated(forRemoval = true) - /** - * - * Please use the {@link BCLStructureBuilder} instead: - * - * BCLStructureBuilder - * .start(id, structureBuilder) - * .step(step) - * .randomPlacement(spacing, separation) - * .codec(codec) - * .biomeTag(biomeTag) - * .build(); - * - */ - public BCLStructure( - ResourceLocation id, - Function structureBuilder, - GenerationStep.Decoration step, - int spacing, - int separation, - boolean adaptNoise, - Codec codec, - TagKey biomeTag - ) { - super(id, structureBuilder, step, new RandomSpreadStructurePlacement( - spacing, - separation, - RandomSpreadType.LINEAR, - id.toString().hashCode() - ), codec, biomeTag, TerrainAdjustment.NONE); - } - -} diff --git a/src/main/java/org/betterx/ui/ColorUtil.java b/src/main/java/org/betterx/ui/ColorUtil.java deleted file mode 100644 index e218412b..00000000 --- a/src/main/java/org/betterx/ui/ColorUtil.java +++ /dev/null @@ -1,349 +0,0 @@ -package org.betterx.ui; - -import org.betterx.bclib.BCLib; -import org.betterx.bclib.util.ColorExtractor; -import org.betterx.bclib.util.MHelper; - -import com.mojang.blaze3d.platform.NativeImage; -import net.minecraft.ChatFormatting; -import net.minecraft.client.Minecraft; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.util.Mth; -import net.minecraft.world.item.BlockItem; -import net.minecraft.world.item.Item; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import com.google.common.collect.Maps; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class ColorUtil { - public static final int BLACK = ChatFormatting.BLACK.getColor() | 0xFF000000; - public static final int DARK_BLUE = ChatFormatting.DARK_BLUE.getColor() | 0xFF000000; - public static final int DARK_GREEN = ChatFormatting.DARK_GREEN.getColor() | 0xFF000000; - public static final int DARK_AQUA = ChatFormatting.DARK_AQUA.getColor() | 0xFF000000; - public static final int DARK_RED = ChatFormatting.DARK_RED.getColor() | 0xFF000000; - public static final int DARK_PURPLE = ChatFormatting.DARK_PURPLE.getColor() | 0xFF000000; - public static final int GOLD = ChatFormatting.GOLD.getColor() | 0xFF000000; - public static final int GRAY = ChatFormatting.GRAY.getColor() | 0xFF000000; - public static final int DARK_GRAY = ChatFormatting.DARK_GRAY.getColor() | 0xFF000000; - public static final int BLUE = ChatFormatting.BLUE.getColor() | 0xFF000000; - public static final int GREEN = ChatFormatting.GREEN.getColor() | 0xFF000000; - public static final int AQUA = ChatFormatting.AQUA.getColor() | 0xFF000000; - public static final int RED = ChatFormatting.RED.getColor() | 0xFF000000; - public static final int LIGHT_PURPLE = ChatFormatting.LIGHT_PURPLE.getColor() | 0xFF000000; - public static final int YELLOW = ChatFormatting.YELLOW.getColor() | 0xFF000000; - public static final int WHITE = ChatFormatting.WHITE.getColor() | 0xFF000000; - public static final int DEFAULT_TEXT = WHITE; - private static final float[] FLOAT_BUFFER = new float[4]; - private static final int ALPHA = 255 << 24; - - public static int color(int r, int g, int b) { - return ALPHA | (r << 16) | (g << 8) | b; - } - - public static int color(String hex) { - int r = Integer.parseInt(hex.substring(0, 2), 16); - int g = Integer.parseInt(hex.substring(2, 4), 16); - int b = Integer.parseInt(hex.substring(4, 6), 16); - return color(r, g, b); - } - - public static int[] toIntArray(int color) { - return new int[]{(color >> 24) & 255, (color >> 16) & 255, (color >> 8) & 255, color & 255}; - } - - public static float[] toFloatArray(int color) { - FLOAT_BUFFER[0] = ((color >> 16 & 255) / 255.0F); - FLOAT_BUFFER[1] = ((color >> 8 & 255) / 255.0F); - FLOAT_BUFFER[2] = ((color & 255) / 255.0F); - FLOAT_BUFFER[3] = ((color >> 24 & 255) / 255.0F); - - return FLOAT_BUFFER; - } - - public static float[] RGBtoHSB(int r, int g, int b, float[] hsbvals) { - float hue, saturation, brightness; - if (hsbvals == null) { - hsbvals = FLOAT_BUFFER; - } - int cmax = (r > g) ? r : g; - if (b > cmax) cmax = b; - int cmin = (r < g) ? r : g; - if (b < cmin) cmin = b; - - brightness = ((float) cmax) / 255.0F; - if (cmax != 0) saturation = ((float) (cmax - cmin)) / ((float) cmax); - else saturation = 0; - if (saturation == 0) hue = 0; - else { - float redc = ((float) (cmax - r)) / ((float) (cmax - cmin)); - float greenc = ((float) (cmax - g)) / ((float) (cmax - cmin)); - float bluec = ((float) (cmax - b)) / ((float) (cmax - cmin)); - if (r == cmax) hue = bluec - greenc; - else if (g == cmax) hue = 2.0F + redc - bluec; - else hue = 4.0F + greenc - redc; - hue = hue / 6.0F; - if (hue < 0) hue = hue + 1.0F; - } - hsbvals[0] = hue; - hsbvals[1] = saturation; - hsbvals[2] = brightness; - return hsbvals; - } - - public static int HSBtoRGB(float hue, float saturation, float brightness) { - int r = 0, g = 0, b = 0; - if (saturation == 0) { - r = g = b = (int) (brightness * 255.0F + 0.5F); - } else { - float h = (hue - (float) Math.floor(hue)) * 6.0F; - float f = h - (float) Math.floor(h); - float p = brightness * (1.0F - saturation); - float q = brightness * (1.0F - saturation * f); - float t = brightness * (1.0F - (saturation * (1.0F - f))); - switch ((int) h) { - case 0: - r = (int) (brightness * 255.0F + 0.5F); - g = (int) (t * 255.0F + 0.5F); - b = (int) (p * 255.0F + 0.5F); - break; - case 1: - r = (int) (q * 255.0F + 0.5F); - g = (int) (brightness * 255.0F + 0.5F); - b = (int) (p * 255.0F + 0.5F); - break; - case 2: - r = (int) (p * 255.0F + 0.5F); - g = (int) (brightness * 255.0F + 0.5F); - b = (int) (t * 255.0F + 0.5F); - break; - case 3: - r = (int) (p * 255.0F + 0.5F); - g = (int) (q * 255.0F + 0.5F); - b = (int) (brightness * 255.0F + 0.5F); - break; - case 4: - r = (int) (t * 255.0F + 0.5F); - g = (int) (p * 255.0F + 0.5F); - b = (int) (brightness * 255.0F + 0.5F); - break; - case 5: - r = (int) (brightness * 255.0F + 0.5F); - g = (int) (p * 255.0F + 0.5F); - b = (int) (q * 255.0F + 0.5F); - break; - } - } - return 0xFF000000 | (r << 16) | (g << 8) | (b << 0); - } - - public static String toRGBHex(int color) { - return "#" - + Integer.toHexString((color >> 16) & 0xFF) - + Integer.toHexString((color >> 8) & 0xFF) - + Integer.toHexString(color & 0xFF); - } - - public static boolean validHexColor(String hexColor) { - if (hexColor.startsWith("#")) hexColor = hexColor.substring(1); - if (hexColor.startsWith("0x")) hexColor = hexColor.substring(2); - - int len = hexColor.length(); - if (len != 6 && len != 8 && len != 3 && len != 4) { - return false; - } - - int color, shift; - if (len == 3) { - hexColor = "" - + hexColor.charAt(0) + hexColor.charAt(0) - + hexColor.charAt(1) + hexColor.charAt(1) - + hexColor.charAt(2) + hexColor.charAt(2); - len = 6; - } else if (len == 4) { - hexColor = "" - + hexColor.charAt(0) + hexColor.charAt(0) - + hexColor.charAt(1) + hexColor.charAt(1) - + hexColor.charAt(2) + hexColor.charAt(2) - + hexColor.charAt(3) + hexColor.charAt(3); - len = 8; - } - - if (len == 6) { - color = 0xFF000000; - shift = 16; - } else { - color = 0; - shift = 24; - } - - try { - String[] splited = hexColor.split("(?<=\\G.{2})"); - for (String digit : splited) { - color |= Integer.valueOf(digit, 16) << shift; - shift -= 8; - } - } catch (NumberFormatException ex) { - return false; - } - - return true; - } - - public static int parseHex(String hexColor) { - if (hexColor.startsWith("#")) hexColor = hexColor.substring(1); - if (hexColor.startsWith("0x")) hexColor = hexColor.substring(2); - int len = hexColor.length(); - if (len != 6 && len != 8 && len != 3 && len != 4) { - return -1; - } - - int color, shift; - if (len == 3) { - hexColor = "" - + hexColor.charAt(0) + hexColor.charAt(0) - + hexColor.charAt(1) + hexColor.charAt(1) - + hexColor.charAt(2) + hexColor.charAt(2); - len = 6; - } else if (len == 4) { - hexColor = "" - + hexColor.charAt(0) + hexColor.charAt(0) - + hexColor.charAt(1) + hexColor.charAt(1) - + hexColor.charAt(2) + hexColor.charAt(2) - + hexColor.charAt(3) + hexColor.charAt(3); - len = 8; - } - - if (len == 6) { - color = 0xFF000000; - shift = 16; - } else { - color = 0; - shift = 24; - } - - try { - String[] splited = hexColor.split("(?<=\\G.{2})"); - for (String digit : splited) { - color |= Integer.valueOf(digit, 16) << shift; - shift -= 8; - } - } catch (NumberFormatException ex) { - BCLib.LOGGER.catching(ex); - return -1; - } - - return color; - } - - public static int toABGR(int color) { - int r = (color >> 16) & 255; - int g = (color >> 8) & 255; - int b = color & 255; - return 0xFF000000 | b << 16 | g << 8 | r; - } - - public static int ABGRtoARGB(int color) { - int a = (color >> 24) & 255; - int b = (color >> 16) & 255; - int g = (color >> 8) & 255; - int r = color & 255; - return a << 24 | r << 16 | g << 8 | b; - } - - public static int colorBrigtness(int color, float val) { - RGBtoHSB((color >> 16) & 255, (color >> 8) & 255, color & 255, FLOAT_BUFFER); - FLOAT_BUFFER[2] += val / 10.0F; - FLOAT_BUFFER[2] = Mth.clamp(FLOAT_BUFFER[2], 0.0F, 1.0F); - return HSBtoRGB(FLOAT_BUFFER[0], FLOAT_BUFFER[1], FLOAT_BUFFER[2]); - } - - public static int multiplyColor(int color1, int color2) { - if (color1 == -1) { - return color2; - } else if (color2 == -1) { - return color1; - } - - final int alpha = ((color1 >> 24) & 0xFF) * ((color2 >> 24) & 0xFF) / 0xFF; - final int red = ((color1 >> 16) & 0xFF) * ((color2 >> 16) & 0xFF) / 0xFF; - final int green = ((color1 >> 8) & 0xFF) * ((color2 >> 8) & 0xFF) / 0xFF; - final int blue = (color1 & 0xFF) * (color2 & 0xFF) / 0xFF; - - return (alpha << 24) | (red << 16) | (green << 8) | blue; - } - - public static int applyTint(int color, int tint) { - return colorBrigtness(multiplyColor(color, tint), 1.5F); - } - - public static int colorDistance(int color1, int color2) { - int r1 = (color1 >> 16) & 255; - int g1 = (color1 >> 8) & 255; - int b1 = color1 & 255; - int r2 = (color2 >> 16) & 255; - int g2 = (color2 >> 8) & 255; - int b2 = color2 & 255; - return MHelper.sqr(r1 - r2) + MHelper.sqr(g1 - g2) + MHelper.sqr(b1 - b2); - } - - private static final Map colorPalette = Maps.newHashMap(); - - @Environment(EnvType.CLIENT) - public static int extractColor(Item item) { - ResourceLocation id = Registry.ITEM.getKey(item); - if (id.equals(Registry.ITEM.getDefaultKey())) return -1; - if (colorPalette.containsKey(id)) { - return colorPalette.get(id); - } - ResourceLocation texture; - if (item instanceof BlockItem) { - texture = new ResourceLocation(id.getNamespace(), "textures/block/" + id.getPath() + ".png"); - } else { - texture = new ResourceLocation(id.getNamespace(), "textures/item/" + id.getPath() + ".png"); - } - NativeImage image = loadImage(texture, 16, 16); - List colors = new ArrayList<>(); - for (int i = 0; i < image.getWidth(); i++) { - for (int j = 0; j < 16; j++) { - int col = image.getPixelRGBA(i, j); - if (((col >> 24) & 255) > 0) { - colors.add(ABGRtoARGB(col)); - } - } - } - image.close(); - - if (colors.size() == 0) return -1; - - ColorExtractor extractor = new ColorExtractor(colors); - int color = extractor.analize(); - colorPalette.put(id, color); - - return color; - } - - @Environment(EnvType.CLIENT) - public static NativeImage loadImage(ResourceLocation image, int w, int h) { - Minecraft minecraft = Minecraft.getInstance(); - ResourceManager resourceManager = minecraft.getResourceManager(); - var imgResource = resourceManager.getResource(image); - if (imgResource.isPresent()) { - try { - return NativeImage.read(imgResource.get().open()); - } catch (IOException e) { - BCLib.LOGGER.warning("Can't load texture image: {}. Will be created empty image.", image); - BCLib.LOGGER.warning("Cause: {}.", e.getMessage()); - } - } - return new NativeImage(w, h, false); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/ui/layout/components/AbstractHorizontalStack.java b/src/main/java/org/betterx/ui/layout/components/AbstractHorizontalStack.java deleted file mode 100644 index a7a4debf..00000000 --- a/src/main/java/org/betterx/ui/layout/components/AbstractHorizontalStack.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.input.RelativeContainerEventHandler; -import org.betterx.ui.layout.components.render.NullRenderer; -import org.betterx.ui.layout.values.Alignment; -import org.betterx.ui.layout.values.Value; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class AbstractHorizontalStack> extends AbstractStack implements RelativeContainerEventHandler { - public AbstractHorizontalStack(Value width, Value height) { - super(width, height); - } - - @Override - public int updateContainerWidth(int containerWidth) { - int myWidth = width.calculateOrFill(containerWidth); - int fixedWidth = components.stream().map(c -> c.width.calculate(myWidth)).reduce(0, Integer::sum); - - int freeWidth = Math.max(0, myWidth - fixedWidth); - fillWidth(myWidth, freeWidth); - - for (LayoutComponent c : components) { - c.updateContainerWidth(c.width.calculatedSize()); - } - - return myWidth; - } - - @Override - protected int updateContainerHeight(int containerHeight) { - int myHeight = height.calculateOrFill(containerHeight); - components.stream().forEach(c -> c.height.calculateOrFill(myHeight)); - for (LayoutComponent c : components) { - c.updateContainerHeight(c.height.calculatedSize()); - } - return myHeight; - } - - - @Override - void setRelativeBounds(int left, int top) { - super.setRelativeBounds(left, top); - - int offset = 0; - for (LayoutComponent c : components) { - int delta = relativeBounds.height - c.height.calculatedSize(); - if (c.vAlign == Alignment.MIN) delta = 0; - else if (c.vAlign == Alignment.CENTER) delta /= 2; - c.setRelativeBounds(offset, delta); - offset += c.relativeBounds.width; - } - } - - @Override - public int getContentWidth() { - int fixedWidth = components.stream().map(c -> c.width.calculateFixed()).reduce(0, Integer::sum); - double percentage = components.stream().map(c -> c.width.calculateRelative()).reduce(0.0, Double::sum); - - return (int) (fixedWidth / (1 - percentage)); - } - - @Override - public int getContentHeight() { - return components.stream().map(c -> c.height.calculateFixed()).reduce(0, Integer::max); - } - - - protected S addEmpty(Value size) { - this.components.add(new Empty(size, Value.fixed(0))); - return (S) this; - } - - protected VerticalStack addColumn(Value width, Value height) { - VerticalStack stack = new VerticalStack(width, height); - add(stack); - return stack; - } - - - protected VerticalStack addColumn() { - return addColumn(Value.fit(), Value.fit()); - } -} - diff --git a/src/main/java/org/betterx/ui/layout/components/AbstractStack.java b/src/main/java/org/betterx/ui/layout/components/AbstractStack.java deleted file mode 100644 index 980974b5..00000000 --- a/src/main/java/org/betterx/ui/layout/components/AbstractStack.java +++ /dev/null @@ -1,287 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.input.RelativeContainerEventHandler; -import org.betterx.ui.layout.components.render.ComponentRenderer; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Size; -import org.betterx.ui.layout.values.Value; -import org.betterx.ui.vanilla.VanillaScrollerRenderer; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.LinkedList; -import java.util.List; -import org.jetbrains.annotations.Nullable; - -@Environment(EnvType.CLIENT) -public abstract class AbstractStack> extends LayoutComponent implements RelativeContainerEventHandler { - protected final List> components = new LinkedList<>(); - - public AbstractStack(Value width, Value height) { - this(width, height, null); - } - - public AbstractStack(Value width, Value height, R renderer) { - super(width, height, renderer); - } - - @Override - public int fillWidth(int parentSize, int fillSize) { - double totalFillWeight = components.stream().map(c -> c.width.fillWeight()).reduce(0.0, Double::sum); - return components.stream() - .map(c -> c.width.fill(fillSize, totalFillWeight)) - .reduce(0, Integer::sum); - } - - @Override - public int fillHeight(int parentSize, int fillSize) { - double totalFillHeight = components.stream().map(c -> c.height.fillWeight()).reduce(0.0, Double::sum); - return components.stream() - .map(c -> c.height.fill(fillSize, totalFillHeight)) - .reduce(0, Integer::sum); - } - - @Override - public void updateScreenBounds(int worldX, int worldY) { - super.updateScreenBounds(worldX, worldY); - for (LayoutComponent c : components) { - c.updateScreenBounds(screenBounds.left, screenBounds.top); - } - } - - - @Override - protected void renderInBounds( - PoseStack poseStack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle renderBounds, - Rectangle clipRect - ) { - super.renderInBounds(poseStack, mouseX, mouseY, deltaTicks, renderBounds, clipRect); - for (LayoutComponent c : components) { - c.render(poseStack, mouseX, mouseY, deltaTicks, renderBounds, clipRect); - } - } - - @Override - public List children() { - return components; - } - - @Override - public Rectangle getInputBounds() { - return relativeBounds; - } - - boolean dragging; - - @Override - public boolean isDragging() { - return dragging; - } - - @Override - public void setDragging(boolean bl) { - dragging = bl; - } - - GuiEventListener focused; - - @Nullable - @Override - public GuiEventListener getFocused() { - return focused; - } - - @Override - public void setFocused(@Nullable GuiEventListener guiEventListener) { - focused = guiEventListener; - } - - public boolean isEmpty() { - return components.isEmpty(); - } - - protected abstract T addEmpty(Value size); - - protected T add(LayoutComponent c) { - this.components.add(c); - return (T) this; - } - - protected T addSpacer(int size) { - return addEmpty(Value.fixed(size)); - } - - protected T addSpacer(float percentage) { - return addEmpty(Value.relative(percentage)); - } - - protected T addFiller() { - return addEmpty(Value.fill()); - } - - - protected Image addIcon(ResourceLocation location, Size resourceSize) { - Image i = new Image(Value.fixed(24), Value.fixed(24), location, resourceSize); - add(i); - return i; - } - - protected Image addImage(Value width, Value height, ResourceLocation location, Size resourceSize) { - Image i = new Image(width, height, location, resourceSize); - add(i); - return i; - } - - protected Checkbox addCheckbox( - Value width, Value height, Component component, - boolean selected - ) { - Checkbox c = new Checkbox(width, height, component, selected, true); - add(c); - return c; - } - - protected Button addButton( - Value width, Value height, - Component component - ) { - Button b = new Button(width, height, component); - add(b); - return b; - } - - protected VerticalScroll addScrollable(LayoutComponent content) { - return addScrollable(Value.fill(), Value.fill(), content); - } - - protected VerticalScroll addScrollable( - Value width, - Value height, - LayoutComponent content - ) { - VerticalScroll s = VerticalScroll.create(width, height, content); - add(s); - return s; - } - - protected Text addText(Value width, Value height, net.minecraft.network.chat.Component text) { - Text t = new Text(width, height, text); - add(t); - return t; - } - - protected MultiLineText addMultilineText(Value width, Value height, net.minecraft.network.chat.Component text) { - MultiLineText t = new MultiLineText(width, height, text); - add(t); - return t; - } - - protected Range addRange( - Value width, Value height, - net.minecraft.network.chat.Component titleOrNull, - int minValue, int maxValue, int initialValue - ) { - Range r = new Range<>(width, height, titleOrNull, minValue, maxValue, initialValue); - add(r); - return r; - } - - protected Range addRange( - Value width, Value height, - net.minecraft.network.chat.Component titleOrNull, - float minValue, float maxValue, float initialValue - ) { - Range r = new Range<>(width, height, titleOrNull, minValue, maxValue, initialValue); - add(r); - return r; - } - - protected Range addRange( - Value width, Value height, - net.minecraft.network.chat.Component titleOrNull, - double minValue, double maxValue, double initialValue - ) { - Range r = new Range<>(width, height, titleOrNull, minValue, maxValue, initialValue); - add(r); - return r; - } - - protected Input addInput( - Value width, Value height, net.minecraft.network.chat.Component titleOrNull, String initialValue - ) { - Input i = new Input(width, height, titleOrNull, initialValue); - add(i); - return i; - } - - protected ColorSwatch addColorSwatch(Value width, Value height, int color) { - ColorSwatch c = new ColorSwatch(width, height, color); - add(c); - return c; - } - - protected ColorPicker addColorPicker( - Value width, - Value height, - net.minecraft.network.chat.Component titleOrNull, - int color - ) { - ColorPicker c = new ColorPicker(width, height, titleOrNull, color); - add(c); - return c; - } - - protected HLine addHorizontalSeparator(int height) { - return addHLine(Value.relative(1.0 / 1.618033988749894), Value.fixed(height)); - } - - protected HLine addHorizontalLine(int height) { - return addHLine(Value.fill(), Value.fixed(height)); - } - - protected HLine addHLine(Value width, Value height) { - HLine l = new HLine(width, height); - add(l); - return l; - } - - protected VLine addVerticalSeparator(int width) { - return addVLine(Value.fixed(width), Value.relative(1.0 / 1.618033988749894)); - } - - protected VLine addVerticalLine(int width) { - return addVLine(Value.fixed(width), Value.fill()); - } - - protected VLine addVLine(Value width, Value height) { - VLine l = new VLine(width, height); - add(l); - return l; - } - - protected Container addContainered(Value width, Value height, LayoutComponent content) { - Container c = new Container(width, height); - c.addChild(content); - add(c); - return c; - } - - protected Item addItem(ItemStack stack) { - Item i = new Item(Value.fit(), Value.fit()); - i.setItem(stack); - add(i); - return i; - } -} - diff --git a/src/main/java/org/betterx/ui/layout/components/AbstractVanillaComponent.java b/src/main/java/org/betterx/ui/layout/components/AbstractVanillaComponent.java deleted file mode 100644 index 59a4a7e0..00000000 --- a/src/main/java/org/betterx/ui/layout/components/AbstractVanillaComponent.java +++ /dev/null @@ -1,142 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.values.Value; - -import net.minecraft.client.gui.components.AbstractWidget; - -public abstract class AbstractVanillaComponent> extends LayoutComponent, V> { - protected C vanillaComponent; - protected final net.minecraft.network.chat.Component component; - protected float alpha = 1.0f; - protected boolean enabled = true; - - public AbstractVanillaComponent( - Value width, - Value height, - AbstractVanillaComponentRenderer renderer, - net.minecraft.network.chat.Component component - ) { - super(width, height, renderer); - this.component = component; - renderer.linkedComponent = (V) this; - } - - protected abstract C createVanillaComponent(); - - @Override - protected void onBoundsChanged() { - vanillaComponent = createVanillaComponent(); - vanillaComponent.setAlpha(this.alpha); - } - - protected net.minecraft.network.chat.Component contentComponent() { - return component; - } - - @Override - public int getContentWidth() { - return renderer.getWidth(contentComponent()); - } - - @Override - public int getContentHeight() { - return renderer.getHeight(contentComponent()); - } - - public float getAlpha() { - return alpha; - } - - public V setAlpha(float alpha) { - this.alpha = alpha; - if (vanillaComponent != null) { - vanillaComponent.setAlpha(alpha); - } - return (V) this; - } - - public boolean isEnabled() { - return enabled; - } - - public V setEnabled(boolean enabled) { - this.enabled = enabled; - return (V) this; - } - - @Override - public void mouseMoved(double x, double y) { - if (vanillaComponent != null && enabled) - vanillaComponent.mouseMoved(x - relativeBounds.left, y - relativeBounds.top); - } - - @Override - public boolean mouseClicked(double x, double y, int button) { - if (vanillaComponent != null && enabled) - return vanillaComponent.mouseClicked(x - relativeBounds.left, y - relativeBounds.top, button); - return false; - } - - @Override - public boolean mouseReleased(double x, double y, int button) { - if (vanillaComponent != null && enabled) - return vanillaComponent.mouseReleased(x - relativeBounds.left, y - relativeBounds.top, button); - return false; - } - - @Override - public boolean mouseDragged(double x, double y, int button, double x2, double y2) { - if (vanillaComponent != null && enabled) - return vanillaComponent.mouseDragged( - x - relativeBounds.left, - y - relativeBounds.top, - button, - x2 - relativeBounds.left, - y2 - relativeBounds.top - ); - return false; - } - - @Override - public boolean mouseScrolled(double x, double y, double f) { - if (vanillaComponent != null && enabled) - return vanillaComponent.mouseScrolled(x - relativeBounds.left, y - relativeBounds.top, f); - return false; - } - - @Override - public boolean keyPressed(int i, int j, int k) { - if (vanillaComponent != null && enabled) - return vanillaComponent.keyPressed(i, j, k); - return false; - } - - @Override - public boolean keyReleased(int i, int j, int k) { - if (vanillaComponent != null && enabled) - return vanillaComponent.keyReleased(i, j, k); - return false; - } - - @Override - public boolean charTyped(char c, int i) { - if (vanillaComponent != null && enabled) - return vanillaComponent.charTyped(c, i); - return false; - } - - @Override - public boolean changeFocus(boolean bl) { - if (vanillaComponent != null && enabled) - return vanillaComponent.changeFocus(bl); - return false; - } - - @Override - public boolean isMouseOver(double x, double y) { - if (vanillaComponent != null && enabled) - return vanillaComponent.isMouseOver(x - relativeBounds.left, y - relativeBounds.top); - return false; - } - -} diff --git a/src/main/java/org/betterx/ui/layout/components/AbstractVanillaComponentRenderer.java b/src/main/java/org/betterx/ui/layout/components/AbstractVanillaComponentRenderer.java deleted file mode 100644 index 822798b2..00000000 --- a/src/main/java/org/betterx/ui/layout/components/AbstractVanillaComponentRenderer.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.ComponentRenderer; -import org.betterx.ui.layout.components.render.TextProvider; -import org.betterx.ui.layout.values.Rectangle; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.components.AbstractWidget; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class AbstractVanillaComponentRenderer> implements ComponentRenderer, TextProvider { - V linkedComponent; - - protected V getLinkedComponent() { - return linkedComponent; - } - - @Override - public void renderInBounds( - PoseStack poseStack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle bounds, - Rectangle clipRect - ) { - if (linkedComponent != null) { - if (linkedComponent.vanillaComponent != null) { - if (!linkedComponent.enabled) { - linkedComponent.vanillaComponent.setAlpha(linkedComponent.alpha / 2); - } - linkedComponent.vanillaComponent.render(poseStack, mouseX, mouseY, deltaTicks); - if (!linkedComponent.enabled) { - linkedComponent.vanillaComponent.setAlpha(linkedComponent.alpha); - } - } - - } - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/AbstractVerticalStack.java b/src/main/java/org/betterx/ui/layout/components/AbstractVerticalStack.java deleted file mode 100644 index a42b69d7..00000000 --- a/src/main/java/org/betterx/ui/layout/components/AbstractVerticalStack.java +++ /dev/null @@ -1,83 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.input.RelativeContainerEventHandler; -import org.betterx.ui.layout.components.render.NullRenderer; -import org.betterx.ui.layout.values.Alignment; -import org.betterx.ui.layout.values.Value; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class AbstractVerticalStack> extends AbstractStack implements RelativeContainerEventHandler { - public AbstractVerticalStack(Value width, Value height) { - super(width, height); - } - - @Override - protected int updateContainerWidth(int containerWidth) { - int myWidth = width.calculateOrFill(containerWidth); - components.stream().forEach(c -> c.width.calculateOrFill(myWidth)); - for (LayoutComponent c : components) { - c.updateContainerWidth(c.width.calculatedSize()); - } - return myWidth; - } - - @Override - public int updateContainerHeight(int containerHeight) { - int myHeight = height.calculateOrFill(containerHeight); - int fixedHeight = components.stream().map(c -> c.height.calculate(myHeight)).reduce(0, Integer::sum); - - int freeHeight = Math.max(0, myHeight - fixedHeight); - fillHeight(myHeight, freeHeight); - - for (LayoutComponent c : components) { - c.updateContainerHeight(c.height.calculatedSize()); - } - - return myHeight; - } - - @Override - void setRelativeBounds(int left, int top) { - super.setRelativeBounds(left, top); - - int offset = 0; - for (LayoutComponent c : components) { - int delta = relativeBounds.width - c.width.calculatedSize(); - if (c.hAlign == Alignment.MIN) delta = 0; - else if (c.hAlign == Alignment.CENTER) delta /= 2; - c.setRelativeBounds(delta, offset); - offset += c.relativeBounds.height; - } - } - - @Override - public int getContentWidth() { - return components.stream().map(c -> c.width.calculateFixed()).reduce(0, Integer::max); - } - - @Override - public int getContentHeight() { - int fixedHeight = components.stream().map(c -> c.height.calculateFixed()).reduce(0, Integer::sum); - double percentage = components.stream().map(c -> c.height.calculateRelative()).reduce(0.0, Double::sum); - - return (int) (fixedHeight / (1 - percentage)); - } - - protected S addEmpty(Value size) { - this.components.add(new Empty(Value.fixed(0), size)); - return (S) this; - } - - protected HorizontalStack addRow(Value width, Value height) { - HorizontalStack stack = new HorizontalStack(width, height); - add(stack); - return stack; - } - - protected HorizontalStack addRow() { - return addRow(Value.fit(), Value.fit()); - } -} \ No newline at end of file diff --git a/src/main/java/org/betterx/ui/layout/components/Button.java b/src/main/java/org/betterx/ui/layout/components/Button.java deleted file mode 100644 index a63e0eff..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Button.java +++ /dev/null @@ -1,70 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.ButtonRenderer; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class Button extends AbstractVanillaComponent { - public static final OnTooltip NO_TOOLTIP = (button, poseStack, i, j) -> { - }; - public static final OnPress NO_ACTION = (button) -> { - }; - - @Environment(EnvType.CLIENT) - public interface OnTooltip { - void onTooltip(Button button, PoseStack poseStack, int mouseX, int mouseY); - } - - @Environment(EnvType.CLIENT) - public interface OnPress { - void onPress(Button button); - } - - OnPress onPress; - OnTooltip onTooltip; - - boolean glow = false; - - public Button( - Value width, - Value height, - net.minecraft.network.chat.Component component - ) { - super(width, height, new ButtonRenderer(), component); - this.onPress = NO_ACTION; - this.onTooltip = NO_TOOLTIP; - } - - public Button onPress(OnPress onPress) { - this.onPress = onPress; - return this; - } - - public Button onToolTip(OnTooltip onTooltip) { - this.onTooltip = onTooltip; - return this; - } - - @Override - protected net.minecraft.client.gui.components.Button createVanillaComponent() { - Button self = this; - return new net.minecraft.client.gui.components.Button( - 0, - 0, - relativeBounds.width, - relativeBounds.height, - component, - (bt) -> onPress.onPress(self), - (bt, stack, x, y) -> onTooltip.onTooltip(self, stack, x, y) - ); - } - - public boolean isGlowing() { - return glow; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/Checkbox.java b/src/main/java/org/betterx/ui/layout/components/Checkbox.java deleted file mode 100644 index 0bcdad2c..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Checkbox.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.CheckboxRenderer; -import org.betterx.ui.layout.values.Value; - -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class Checkbox extends AbstractVanillaComponent { - public static SelectionChanged IGNORE_CHANGE = (a, b) -> { - }; - - @FunctionalInterface - public interface SelectionChanged { - void now(Checkbox checkBox, boolean selected); - } - - private final boolean selected; - private final boolean showLabel; - - private SelectionChanged onSelectionChange; - - public Checkbox( - Value width, - Value height, - Component component, - boolean selected, boolean showLabel - ) { - super(width, height, new CheckboxRenderer(), component); - onSelectionChange = IGNORE_CHANGE; - this.selected = selected; - this.showLabel = showLabel; - } - - public Checkbox onChange(SelectionChanged onSelectionChange) { - this.onSelectionChange = onSelectionChange; - return this; - } - - public boolean isChecked() { - if (vanillaComponent != null) return vanillaComponent.selected(); - return selected; - } - - @Override - protected net.minecraft.client.gui.components.Checkbox createVanillaComponent() { - Checkbox self = this; - net.minecraft.client.gui.components.Checkbox cb = new net.minecraft.client.gui.components.Checkbox( - 0, 0, - relativeBounds.width, relativeBounds.height, - component, - selected, - showLabel - ) { - @Override - public void onPress() { - super.onPress(); - onSelectionChange.now(self, this.selected()); - } - }; - - onSelectionChange.now(this, cb.selected()); - return cb; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/ColorPicker.java b/src/main/java/org/betterx/ui/layout/components/ColorPicker.java deleted file mode 100644 index 45b7bffd..00000000 --- a/src/main/java/org/betterx/ui/layout/components/ColorPicker.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.values.Value; - -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class ColorPicker extends AbstractHorizontalStack { - ColorSwatch swatch; - Input input; - - public ColorPicker(Value width, Value height, Component title, int color) { - super(width, height); - swatch = addColorSwatch(Value.fixed(20), Value.fixed(20), color); - input = addInput(Value.fill(), Value.fit(), title, ColorUtil.toRGBHex(color)); - - //input.setFilter(ColorUtil::validHexColor); - input.setResponder(this::inputResponder); - } - - private void inputResponder(String value) { - if (ColorUtil.validHexColor(value)) { - int color = ColorUtil.parseHex(value); - swatch.setColor(color); - swatch.setOffsetInner(false); - swatch.setBorderColor(ColorUtil.BLACK); - } else { - swatch.setOffsetInner(true); - swatch.setBorderColor(ColorUtil.RED); - } - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/ColorSwatch.java b/src/main/java/org/betterx/ui/layout/components/ColorSwatch.java deleted file mode 100644 index ce30ad0c..00000000 --- a/src/main/java/org/betterx/ui/layout/components/ColorSwatch.java +++ /dev/null @@ -1,68 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.render.RenderHelper; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.GuiComponent; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class ColorSwatch extends CustomRenderComponent { - private int color; - private int borderColor = ColorUtil.BLACK; - private boolean offsetInner = false; - - public ColorSwatch(Value width, Value height, int color) { - super(width, height); - this.color = color; - } - - @Override - protected void customRender(PoseStack stack, int x, int y, float deltaTicks, Rectangle bounds, Rectangle clipRect) { - int o = offsetInner ? 2 : 1; - RenderHelper.outline(stack, 0, 0, bounds.width, bounds.height, borderColor); - GuiComponent.fill(stack, o, o, bounds.width - o, bounds.height - o, color); - } - - public int getColor() { - return color; - } - - public ColorSwatch setColor(int color) { - this.color = color; - return this; - } - - public int getBorderColor() { - return borderColor; - } - - public ColorSwatch setBorderColor(int color) { - this.borderColor = color; - return this; - } - - public boolean getOffsetInner() { - return offsetInner; - } - - public ColorSwatch setOffsetInner(boolean val) { - this.offsetInner = val; - return this; - } - - @Override - public int getContentWidth() { - return 20; - } - - @Override - public int getContentHeight() { - return 20; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/ComponentWithBounds.java b/src/main/java/org/betterx/ui/layout/components/ComponentWithBounds.java deleted file mode 100644 index af9ed645..00000000 --- a/src/main/java/org/betterx/ui/layout/components/ComponentWithBounds.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.values.Rectangle; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public interface ComponentWithBounds { - Rectangle getRelativeBounds(); -} diff --git a/src/main/java/org/betterx/ui/layout/components/Container.java b/src/main/java/org/betterx/ui/layout/components/Container.java deleted file mode 100644 index 40d25a0f..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Container.java +++ /dev/null @@ -1,291 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.input.RelativeContainerEventHandler; -import org.betterx.ui.layout.components.render.ComponentRenderer; -import org.betterx.ui.layout.components.render.RenderHelper; -import org.betterx.ui.layout.values.Alignment; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.client.gui.components.events.GuiEventListener; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.LinkedList; -import java.util.List; -import org.jetbrains.annotations.Nullable; - -@Environment(EnvType.CLIENT) -public class Container extends LayoutComponent implements RelativeContainerEventHandler { - public static class ContainerRenderer implements ComponentRenderer { - Container linkedContainer; - - @Override - public void renderInBounds( - PoseStack stack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle bounds, - Rectangle clipRect - ) { - if (linkedContainer != null) { - if ((linkedContainer.backgroundColor & 0xFF000000) != 0) - GuiComponent.fill(stack, 0, 0, bounds.width, bounds.height, linkedContainer.backgroundColor); - - if ((linkedContainer.outlineColor & 0xFF000000) != 0) - RenderHelper.outline(stack, 0, 0, bounds.width, bounds.height, linkedContainer.outlineColor); - } - } - } - - record Positional(int left, int top, LayoutComponent component) { - public int getMaxX() { - return left + component().getContentWidth(); - } - - public int getMaxY() { - return top + component().getContentHeight(); - } - } - - private final List children = new LinkedList<>(); - boolean dragging = false; - GuiEventListener focused = null; - boolean visible = true; - - int paddingLeft, paddingTop, paddingRight, paddingBottom; - - int backgroundColor = 0; - int outlineColor = 0; - - public Container( - Value width, - Value height - ) { - super(width, height, new ContainerRenderer()); - renderer.linkedContainer = this; - } - - public Container addChild(LayoutComponent child) { - children.add(new Positional(0, 0, child)); - return this; - } - - public Container addChild(int left, int top, LayoutComponent child) { - children.add(new Positional(left, top, child)); - return this; - } - - public Container setVisible(boolean v) { - this.visible = v; - return this; - } - - public boolean getVisible() { - return this.visible; - } - - public Container setBackgroundColor(int color) { - this.backgroundColor = color; - return this; - } - - public int getBackgroundColor() { - return backgroundColor; - } - - public Container setOutlineColor(int color) { - this.outlineColor = color; - return this; - } - - public int getOutlineColor() { - return outlineColor; - } - - public Container setPadding(int padding) { - return setPadding(padding, padding, padding, padding); - } - - public Container setPadding(int left, int top, int right, int bottom) { - this.paddingLeft = left; - this.paddingTop = top; - this.paddingRight = right; - this.paddingBottom = bottom; - return this; - } - - @Override - public int getContentWidth() { - return children.stream() - .map(Positional::getMaxX) - .reduce(0, Math::max) + paddingLeft + paddingRight; - } - - @Override - public int getContentHeight() { - return children.stream() - .map(Positional::getMaxY) - .reduce(0, Math::max) + paddingTop + paddingBottom; - } - - @Override - public Rectangle getInputBounds() { - return relativeBounds; - } - - @Override - public List children() { - return children.stream().map(p -> p.component).toList(); - } - - @Override - public boolean isDragging() { - return dragging; - } - - @Override - public void setDragging(boolean bl) { - dragging = bl; - } - - @Nullable - @Override - public GuiEventListener getFocused() { - return focused; - } - - @Override - public void setFocused(@Nullable GuiEventListener guiEventListener) { - focused = guiEventListener; - } - - @Override - protected int updateContainerWidth(int containerWidth) { - int myWidth = width.calculateOrFill(containerWidth); - for (var child : children) { - child.component.width.calculateOrFill(myWidth - (paddingLeft + paddingRight)); - child.component.updateContainerWidth(child.component.width.calculatedSize()); - } - return myWidth; - } - - @Override - protected int updateContainerHeight(int containerHeight) { - int myHeight = height.calculateOrFill(containerHeight); - for (var child : children) { - child.component.height.calculateOrFill(myHeight - (paddingTop + paddingBottom)); - child.component.updateContainerHeight(child.component.height.calculatedSize()); - } - return myHeight; - } - - @Override - protected void renderInBounds( - PoseStack poseStack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle renderBounds, - Rectangle clipRect - ) { - if (visible) { - super.renderInBounds(poseStack, mouseX, mouseY, deltaTicks, renderBounds, clipRect); - - setClippingRect(clipRect); - for (var child : children) { - child.component.render( - poseStack, mouseX, mouseY, deltaTicks, - renderBounds, clipRect - ); - } - setClippingRect(null); - } - } - - @Override - void setRelativeBounds(int left, int top) { - super.setRelativeBounds(left, top); - - for (var child : children) { - int childLeft = (relativeBounds.width - (paddingLeft + paddingRight)) - child.component.width.calculatedSize(); - if (child.component.hAlign == Alignment.MIN) childLeft = 0; - else if (child.component.hAlign == Alignment.CENTER) childLeft /= 2; - - int childTop = (relativeBounds.height - (paddingTop + paddingBottom)) - child.component.height.calculatedSize(); - if (child.component.vAlign == Alignment.MIN) childTop = 0; - else if (child.component.vAlign == Alignment.CENTER) childTop /= 2; - - child.component.setRelativeBounds(child.left + paddingLeft + childLeft, child.top + paddingTop + childTop); - } - } - - @Override - public void updateScreenBounds(int worldX, int worldY) { - super.updateScreenBounds(worldX, worldY); - for (Positional p : children) { - p.component.updateScreenBounds(p.left + screenBounds.left, p.top + screenBounds.top); - } - } - - @Override - public void mouseMoved(double d, double e) { - if (visible) - RelativeContainerEventHandler.super.mouseMoved(d, e); - } - - @Override - public boolean mouseClicked(double d, double e, int i) { - if (visible) - return RelativeContainerEventHandler.super.mouseClicked(d, e, i); - return false; - } - - @Override - public boolean mouseReleased(double d, double e, int i) { - if (visible) - return RelativeContainerEventHandler.super.mouseReleased(d, e, i); - return false; - } - - @Override - public boolean mouseScrolled(double d, double e, double f) { - if (visible) - return RelativeContainerEventHandler.super.mouseScrolled(d, e, f); - return false; - } - - @Override - public boolean mouseDragged(double d, double e, int i, double f, double g) { - if (visible) - return RelativeContainerEventHandler.super.mouseDragged(d, e, i, f, g); - return false; - } - - @Override - public boolean isMouseOver(double x, double y) { - if (visible) { - boolean res = false; - for (var child : children) { - res |= child.component.isMouseOver(x, y); - } - - return res || relativeBounds.contains(x, y); - } - return false; - } - - public static Container create(LayoutComponent content) { - return create(Value.fit(), Value.fit(), content); - } - - public static Container create(Value width, Value height, LayoutComponent content) { - Container c = new Container(width, height); - c.addChild(content); - return c; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/CustomRenderComponent.java b/src/main/java/org/betterx/ui/layout/components/CustomRenderComponent.java deleted file mode 100644 index d7a234f3..00000000 --- a/src/main/java/org/betterx/ui/layout/components/CustomRenderComponent.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.ComponentRenderer; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public abstract class CustomRenderComponent> extends LayoutComponent, C> { - public CustomRenderComponent( - Value width, - Value height - ) { - super(width, height, new CustomRenderRenderer<>()); - renderer.linkedComponent = (C) this; - } - - protected abstract void customRender( - PoseStack stack, - int x, - int y, - float deltaTicks, - Rectangle bounds, - Rectangle clipRect - ); - - protected static class CustomRenderRenderer> implements ComponentRenderer { - C linkedComponent; - - @Override - public void renderInBounds( - PoseStack stack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle bounds, - Rectangle clipRect - ) { - if (linkedComponent != null) { - linkedComponent.customRender(stack, mouseX, mouseY, deltaTicks, bounds, clipRect); - } - } - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/Empty.java b/src/main/java/org/betterx/ui/layout/components/Empty.java deleted file mode 100644 index fca87bfd..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Empty.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.NullRenderer; -import org.betterx.ui.layout.values.Value; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class Empty extends LayoutComponent { - public Empty( - Value width, - Value height - ) { - super(width, height, null); - } - - @Override - public int getContentWidth() { - return 0; - } - - @Override - public int getContentHeight() { - return 0; - } - - @Override - public boolean isMouseOver(double d, double e) { - return false; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/HLine.java b/src/main/java/org/betterx/ui/layout/components/HLine.java deleted file mode 100644 index fb2093ed..00000000 --- a/src/main/java/org/betterx/ui/layout/components/HLine.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.render.RenderHelper; -import org.betterx.ui.layout.values.Alignment; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class HLine extends CustomRenderComponent { - private int color = ColorUtil.DEFAULT_TEXT; - - public HLine(Value width, Value height) { - super(width, height); - this.vAlign = Alignment.CENTER; - this.hAlign = Alignment.CENTER; - } - - public HLine setColor(int color) { - this.color = color; - return this; - } - - @Override - protected void customRender(PoseStack stack, int x, int y, float deltaTicks, Rectangle bounds, Rectangle clipRect) { - int top = bounds.height - getContentHeight(); - if (vAlign == Alignment.CENTER) top /= 2; - else if (vAlign == Alignment.MIN) top = 0; - RenderHelper.hLine(stack, 0, bounds.width, top, color); - } - - @Override - public int getContentWidth() { - return 0; - } - - @Override - public int getContentHeight() { - return 1; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/HorizontalStack.java b/src/main/java/org/betterx/ui/layout/components/HorizontalStack.java deleted file mode 100644 index da3ca063..00000000 --- a/src/main/java/org/betterx/ui/layout/components/HorizontalStack.java +++ /dev/null @@ -1,205 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.values.Size; -import org.betterx.ui.layout.values.Value; -import org.betterx.ui.vanilla.VanillaScrollerRenderer; - -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class HorizontalStack extends AbstractHorizontalStack { - public HorizontalStack(Value width, Value height) { - super(width, height); - } - - - public static HorizontalStack centered(LayoutComponent c) { - return new HorizontalStack(Value.fill(), Value.fill()).addFiller().add(c).addFiller(); - } - - public static HorizontalStack bottom(LayoutComponent c) { - return new HorizontalStack(Value.fill(), Value.fill()).add(c).addFiller(); - } - - protected HorizontalStack addEmpty(Value size) { - this.components.add(new Empty(size, Value.fixed(0))); - return this; - } - - @Override - public HorizontalStack add(LayoutComponent c) { - return super.add(c); - } - - public VerticalStack addColumn(Value width, Value height) { - return super.addColumn(width, height); - } - - public VerticalStack addColumn() { - return super.addColumn(); - } - - @Override - public HorizontalStack addSpacer(int size) { - return super.addSpacer(size); - } - - @Override - public HorizontalStack addSpacer(float percentage) { - return super.addSpacer(percentage); - } - - @Override - public HorizontalStack addFiller() { - return super.addFiller(); - } - - @Override - public Button addButton( - Value width, - Value height, - Component component - ) { - return super.addButton(width, height, component); - } - - @Override - public Checkbox addCheckbox( - Value width, - Value height, - Component component, - boolean selected - ) { - return super.addCheckbox(width, height, component, selected); - } - - @Override - public ColorPicker addColorPicker(Value width, Value height, Component titleOrNull, int color) { - return super.addColorPicker(width, height, titleOrNull, color); - } - - @Override - public ColorSwatch addColorSwatch(Value width, Value height, int color) { - return super.addColorSwatch(width, height, color); - } - - @Override - public Container addContainered(Value width, Value height, LayoutComponent content) { - return super.addContainered(width, height, content); - } - - @Override - public HLine addHLine(Value width, Value height) { - return super.addHLine(width, height); - } - - @Override - public HLine addHorizontalLine(int height) { - return super.addHorizontalLine(height); - } - - @Override - public HLine addHorizontalSeparator(int height) { - return super.addHorizontalSeparator(height); - } - - @Override - public Image addIcon(ResourceLocation location, Size resourceSize) { - return super.addIcon(location, resourceSize); - } - - @Override - public Image addImage(Value width, Value height, ResourceLocation location, Size resourceSize) { - return super.addImage(width, height, location, resourceSize); - } - - @Override - public Input addInput(Value width, Value height, Component titleOrNull, String initialValue) { - return super.addInput(width, height, titleOrNull, initialValue); - } - - @Override - public MultiLineText addMultilineText(Value width, Value height, Component text) { - return super.addMultilineText(width, height, text); - } - - @Override - public Range addRange( - Value width, - Value height, - Component titleOrNull, - double minValue, - double maxValue, - double initialValue - ) { - return super.addRange(width, height, titleOrNull, minValue, maxValue, initialValue); - } - - @Override - public Range addRange( - Value width, - Value height, - Component titleOrNull, - float minValue, - float maxValue, - float initialValue - ) { - return super.addRange(width, height, titleOrNull, minValue, maxValue, initialValue); - } - - @Override - public Range addRange( - Value width, - Value height, - Component titleOrNull, - int minValue, - int maxValue, - int initialValue - ) { - return super.addRange(width, height, titleOrNull, minValue, maxValue, initialValue); - } - - @Override - public Text addText(Value width, Value height, Component text) { - return super.addText(width, height, text); - } - - @Override - public VerticalScroll addScrollable(LayoutComponent content) { - return super.addScrollable(content); - } - - @Override - public VLine addVerticalLine(int width) { - return super.addVerticalLine(width); - } - - @Override - public VLine addVerticalSeparator(int width) { - return super.addVerticalSeparator(width); - } - - @Override - public VLine addVLine(Value width, Value height) { - return super.addVLine(width, height); - } - - @Override - public VerticalScroll addScrollable( - Value width, - Value height, - LayoutComponent content - ) { - return super.addScrollable(width, height, content); - } - - @Override - public Item addItem(ItemStack stack) { - return super.addItem(stack); - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/Image.java b/src/main/java/org/betterx/ui/layout/components/Image.java deleted file mode 100644 index 74d9e279..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Image.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.RenderHelper; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Size; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.resources.ResourceLocation; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class Image extends CustomRenderComponent { - protected Rectangle uvRect; - public final ResourceLocation location; - protected float alpha; - protected Size resourceSize; - - public Image(Value width, Value height, ResourceLocation location) { - this(width, height, location, new Size(16, 16)); - } - - public Image(Value width, Value height, ResourceLocation location, Size resourceSize) { - super(width, height); - this.location = location; - this.uvRect = new Rectangle(0, 0, resourceSize.width(), resourceSize.height()); - this.resourceSize = resourceSize; - this.alpha = 1f; - } - - - public Image setAlpha(float a) { - alpha = a; - return this; - } - - public float getAlpha() { - return alpha; - } - - - public Image setUvRect(int left, int top, int width, int height) { - setUvRect(new Rectangle(left, top, width, height)); - return this; - } - - public Image setUvRect(Rectangle rect) { - uvRect = rect; - return this; - } - - public Rectangle getUvRect() { - return uvRect; - } - - public Image setResourceSize(int width, int height) { - return setResourceSize(new Size(width, height)); - } - - public Image setResourceSize(Size sz) { - resourceSize = sz; - return this; - } - - public Size getResourceSize() { - return resourceSize; - } - - @Override - public int getContentWidth() { - return uvRect.width; - } - - @Override - public int getContentHeight() { - return uvRect.height; - } - - - @Override - protected void customRender( - PoseStack stack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle bounds, - Rectangle clipRect - ) { - RenderHelper.renderImage(stack, 0, 0, bounds.width, bounds.height, location, resourceSize, uvRect, alpha); - } - - @Override - public boolean isMouseOver(double d, double e) { - return false; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/Input.java b/src/main/java/org/betterx/ui/layout/components/Input.java deleted file mode 100644 index ce07475a..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Input.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.EditBoxRenderer; -import org.betterx.ui.layout.values.Value; - -import net.minecraft.client.gui.components.EditBox; -import net.minecraft.network.chat.Component; -import net.minecraft.util.FormattedCharSequence; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.function.BiFunction; -import java.util.function.Consumer; -import java.util.function.Predicate; - -@Environment(EnvType.CLIENT) -public class Input extends AbstractVanillaComponent { - private Consumer responder; - private BiFunction formatter; - private Predicate filter; - private String initialValue = ""; - - public Input( - Value width, - Value height, - Component component, - String initialValue - ) { - super(width, height, new EditBoxRenderer(), component); - this.initialValue = initialValue; - } - - @Override - protected EditBox createVanillaComponent() { - EditBox eb = new EditBox(renderer.getFont(), - 0, 0, - relativeBounds.width, relativeBounds.height, - null, - component - ); - if (responder != null) eb.setResponder(responder); - if (filter != null) eb.setFilter(filter); - if (formatter != null) eb.setFormatter(formatter); - eb.setValue(initialValue); - eb.setBordered(true); - eb.setEditable(true); - - return eb; - } - - public Input setResponder(Consumer consumer) { - this.responder = consumer; - if (vanillaComponent != null) vanillaComponent.setResponder(responder); - return this; - } - - public Input setFormatter(BiFunction formatter) { - this.formatter = formatter; - if (vanillaComponent != null) vanillaComponent.setFormatter(formatter); - return this; - } - - public Input setFilter(Predicate filter) { - this.filter = filter; - if (vanillaComponent != null) vanillaComponent.setFilter(filter); - return this; - } - - public String getValue() { - if (vanillaComponent != null) return vanillaComponent.getValue(); - return ""; - } - - public Input setValue(String value) { - if (vanillaComponent != null) vanillaComponent.setValue(value); - else initialValue = value; - - return this; - } - - @Override - protected Component contentComponent() { - return Component.literal(initialValue + ".."); - } - - @Override - public boolean changeFocus(boolean bl) { - return super.changeFocus(bl); - } - - @Override - public boolean mouseClicked(double x, double y, int button) { - return super.mouseClicked(x, y, button); - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/Item.java b/src/main/java/org/betterx/ui/layout/components/Item.java deleted file mode 100644 index 352cad48..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Item.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.betterx.ui.layout.components; - - -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.renderer.entity.ItemRenderer; -import net.minecraft.world.item.ItemStack; - -public class Item extends CustomRenderComponent { - private ItemStack itemStack; - - public Item(Value width, Value height) { - super(width, height); - } - - public Item setItem(ItemStack item) { - this.itemStack = item; - return this; - } - - @Override - protected void customRender(PoseStack stack, int x, int y, float deltaTicks, Rectangle bounds, Rectangle clipRect) { - final ItemRenderer itemRenderer = Minecraft.getInstance().getItemRenderer(); - itemRenderer.renderAndDecorateItem(Minecraft.getInstance().player, itemStack, bounds.left, bounds.top, 0); - itemRenderer.renderGuiItemDecorations( - Minecraft.getInstance().font, - itemStack, - bounds.left, - bounds.top, - "" + itemStack.getCount() - ); - } - - @Override - public int getContentWidth() { - return 16; - } - - @Override - public int getContentHeight() { - return 16; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/LayoutComponent.java b/src/main/java/org/betterx/ui/layout/components/LayoutComponent.java deleted file mode 100644 index 48e68ada..00000000 --- a/src/main/java/org/betterx/ui/layout/components/LayoutComponent.java +++ /dev/null @@ -1,184 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.ComponentRenderer; -import org.betterx.ui.layout.values.Alignment; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.events.GuiEventListener; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public abstract class LayoutComponent> implements ComponentWithBounds, GuiEventListener { - protected final R renderer; - protected final Value width; - protected final Value height; - protected String debugName; - protected Rectangle relativeBounds; - protected Rectangle screenBounds; - protected Alignment vAlign = Alignment.MIN; - protected Alignment hAlign = Alignment.MIN; - - public LayoutComponent(Value width, Value height, R renderer) { - this.width = width.attachComponent(this::getContentWidth); - this.height = height.attachComponent(this::getContentHeight); - this.renderer = renderer; - } - - public void reCalculateLayout() { - updateContainerWidth(relativeBounds.width); - updateContainerHeight(relativeBounds.height); - setRelativeBounds(relativeBounds.left, relativeBounds.top); - updateScreenBounds(screenBounds.left, screenBounds.top); - } - - protected int updateContainerWidth(int containerWidth) { - return width.setCalculatedSize(containerWidth); - } - - protected int updateContainerHeight(int containerHeight) { - return height.setCalculatedSize(containerHeight); - } - - void setRelativeBounds(int left, int top) { - relativeBounds = new Rectangle(left, top, width.calculatedSize(), height.calculatedSize()); - onBoundsChanged(); - } - - public void updateScreenBounds(int worldX, int worldY) { - screenBounds = relativeBounds.movedBy(worldX, worldY); - } - - protected void onBoundsChanged() { - } - - public Rectangle getRelativeBounds() { - return relativeBounds; - } - - public Rectangle getScreenBounds() { - return screenBounds; - } - - public abstract int getContentWidth(); - public abstract int getContentHeight(); - - public int fillWidth(int parentSize, int fillSize) { - return width.fill(fillSize); - } - - public int fillHeight(int parentSize, int fillSize) { - return height.fill(fillSize); - } - - public int getWidth() { - return width.calculatedSize(); - } - - public int getHeight() { - return height.calculatedSize(); - } - - protected final void setClippingRect(Rectangle clippingRect) { - if (clippingRect == null) { - RenderSystem.disableScissor(); - return; - } - final double uiScale = Minecraft.getInstance().getWindow().getGuiScale(); - final int windowHeight = Minecraft.getInstance().getWindow().getHeight(); - RenderSystem.enableScissor( - (int) (clippingRect.left * uiScale), - (int) (windowHeight - (clippingRect.bottom()) * uiScale), - (int) (clippingRect.width * uiScale), - (int) ((clippingRect.height) * uiScale) - ); - } - - public void render( - PoseStack poseStack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle parentBounds, - Rectangle clipRect - ) { - Rectangle r = relativeBounds.movedBy(parentBounds.left, parentBounds.top); - Rectangle clip = r.intersect(clipRect); - poseStack.pushPose(); - poseStack.translate(relativeBounds.left, relativeBounds.top, 0); - //if (r.overlaps(clip)) - { - renderInBounds(poseStack, mouseX - relativeBounds.left, mouseY - relativeBounds.top, deltaTicks, r, clip); - } - poseStack.popPose(); - } - - protected void renderInBounds( - PoseStack poseStack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle renderBounds, - Rectangle clipRect - ) { - if (renderer != null) { - setClippingRect(clipRect); - renderer.renderInBounds(poseStack, mouseX, mouseY, deltaTicks, renderBounds, clipRect); - setClippingRect(null); - } - } - - @Override - public String toString() { - return super.toString() + "(" + - (debugName == null ? "" : debugName + " - ") + - relativeBounds + ", " + - width.calculatedSize() + "x" + height.calculatedSize() + - ")"; - } - - public L alignTop() { - vAlign = Alignment.MIN; - return (L) this; - } - - public L alignBottom() { - vAlign = Alignment.MAX; - return (L) this; - } - - public L centerVertical() { - vAlign = Alignment.CENTER; - return (L) this; - } - - public L alignLeft() { - hAlign = Alignment.MIN; - return (L) this; - } - - public L alignRight() { - hAlign = Alignment.MAX; - return (L) this; - } - - public L centerHorizontal() { - hAlign = Alignment.CENTER; - return (L) this; - } - - public L setDebugName(String d) { - debugName = d; - return (L) this; - } - - @Override - public boolean isMouseOver(double d, double e) { - return relativeBounds.contains(d, e); - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/MultiLineText.java b/src/main/java/org/betterx/ui/layout/components/MultiLineText.java deleted file mode 100644 index 0f63d4d6..00000000 --- a/src/main/java/org/betterx/ui/layout/components/MultiLineText.java +++ /dev/null @@ -1,180 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.ColorUtil; -import org.betterx.ui.layout.components.render.ComponentRenderer; -import org.betterx.ui.layout.components.render.TextProvider; -import org.betterx.ui.layout.values.Alignment; -import org.betterx.ui.layout.values.Rectangle; -import org.betterx.ui.layout.values.Value; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.MutableComponent; -import net.minecraft.network.chat.Style; -import net.minecraft.util.FormattedCharSequence; - -import com.google.common.collect.ImmutableList; - -import java.util.Iterator; -import java.util.List; - -record LineWithWidth(FormattedCharSequence text, int width) { -} - -public class MultiLineText extends LayoutComponent { - net.minecraft.network.chat.Component text; - int color = ColorUtil.DEFAULT_TEXT; - protected MultiLineLabel multiLineLabel; - int bufferedContentWidth = 0; - List lines = List.of(); - - public MultiLineText( - Value width, - Value height, - final net.minecraft.network.chat.Component text - ) { - super(width, height, new MultiLineTextRenderer()); - renderer.linkedComponent = this; - this.text = text; - updatedContentWidth(); - } - - public MultiLineText setColor(int cl) { - this.color = cl; - return this; - } - - public static Component parse(Component text) { - String[] parts = text.getString().split("\\*\\*"); - if (parts.length > 0) { - boolean bold = false; - MutableComponent c = Component.literal(parts[0]); - - for (int i = 1; i < parts.length; i++) { - bold = !bold; - c.append(Component.literal(parts[i]).setStyle(Style.EMPTY.withBold(bold))); - } - return c; - } - return text; - } - - public MultiLineText setText(Component text) { - this.text = text; - this.updatedContentWidth(); - - if (multiLineLabel != null) { - multiLineLabel = createVanillaComponent(); - } - - return this; - } - - protected MultiLineLabel createVanillaComponent() { - final int wd = relativeBounds == null ? width.calculatedSize() : relativeBounds.width; - lines = renderer.getFont() - .split(text, wd) - .stream() - .map((component) -> new LineWithWidth(component, renderer.getFont().width(component))) - .collect(ImmutableList.toImmutableList()); - - return MultiLineLabel.create(renderer.getFont(), text, wd); - } - - protected void updatedContentWidth() { - String[] lines = text.getString().split("\n"); - if (lines.length == 0) bufferedContentWidth = 0; - else { - String line = lines[0]; - for (int i = 1; i < lines.length; i++) - if (lines[i].length() > line.length()) - line = lines[i]; - - bufferedContentWidth = renderer.getWidth(Component.literal(line)); - } - } - - @Override - protected void onBoundsChanged() { - super.onBoundsChanged(); - multiLineLabel = createVanillaComponent(); - } - - @Override - public int getContentWidth() { - return bufferedContentWidth; - } - - @Override - public int getContentHeight() { - return renderer.getHeight(text); - } - - protected static class MultiLineTextRenderer implements ComponentRenderer, TextProvider { - MultiLineText linkedComponent; - - @Override - public int getWidth(Component c) { - return getFont().width(c.getVisualOrderText()); - } - - @Override - public int getHeight(net.minecraft.network.chat.Component c) { - if (linkedComponent == null) return 20; - MultiLineLabel ml; - if (linkedComponent.multiLineLabel != null) ml = linkedComponent.multiLineLabel; - else ml = linkedComponent.createVanillaComponent(); - return ml.getLineCount() * getLineHeight(c); - } - - @Override - public void renderInBounds( - PoseStack stack, - int mouseX, - int mouseY, - float deltaTicks, - Rectangle bounds, - Rectangle clipRect - ) { - if (linkedComponent != null && linkedComponent.multiLineLabel != null) { - int top = bounds.height - getHeight(linkedComponent.text); - if (linkedComponent.vAlign == Alignment.MIN) top = 0; - if (linkedComponent.vAlign == Alignment.CENTER) top /= 2; - - if (linkedComponent.hAlign == Alignment.CENTER) { - linkedComponent.multiLineLabel.renderCentered( - stack, bounds.width / 2, top, - getLineHeight(linkedComponent.text), - linkedComponent.color - ); - } else if (linkedComponent.hAlign == Alignment.MAX) { - int lineY = 0; - int lineHeight = getLineHeight(linkedComponent.text); - - for (Iterator iter = linkedComponent.lines.iterator(); iter.hasNext(); lineY += lineHeight) { - LineWithWidth textWithWidth = iter.next(); - getFont().drawShadow( - stack, - textWithWidth.text(), - linkedComponent.width.calculatedSize() - textWithWidth.width(), - lineY, - linkedComponent.color - ); - } - } else { - linkedComponent.multiLineLabel.renderLeftAligned( - stack, 0, top, - getLineHeight(linkedComponent.text), - linkedComponent.color - ); - } - } - } - } - - @Override - public boolean isMouseOver(double d, double e) { - return false; - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/Panel.java b/src/main/java/org/betterx/ui/layout/components/Panel.java deleted file mode 100644 index a5e6b501..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Panel.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.betterx.ui.layout.components; - - -import org.betterx.ui.layout.components.input.RelativeContainerEventHandler; -import org.betterx.ui.layout.values.Rectangle; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.minecraft.client.gui.components.Widget; -import net.minecraft.client.gui.components.events.GuiEventListener; -import net.minecraft.client.gui.narration.NarratableEntry; -import net.minecraft.client.gui.narration.NarrationElementOutput; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.List; -import org.jetbrains.annotations.Nullable; - -@Environment(EnvType.CLIENT) -public class Panel implements ComponentWithBounds, RelativeContainerEventHandler, NarratableEntry, Widget { - protected LayoutComponent child; - List listeners = List.of(); - public final Rectangle bounds; - - public Panel(int width, int height) { - this(0, 0, width, height); - } - - public Panel(int left, int top, int width, int height) { - bounds = new Rectangle(left, top, width, height); - } - - public void setChild(LayoutComponent c) { - this.child = c; - listeners = List.of(c); - } - - public void calculateLayout() { - if (child != null) { - child.updateContainerWidth(bounds.width); - child.updateContainerHeight(bounds.height); - child.setRelativeBounds(0, 0); - child.updateScreenBounds(bounds.left, bounds.top); - } - } - - @Override - public Rectangle getRelativeBounds() { - return bounds; - } - - @Override - public List children() { - return listeners; - } - - @Override - public Rectangle getInputBounds() { - return bounds; - } - - boolean dragging = false; - - @Override - public boolean isDragging() { - return dragging; - } - - @Override - public void setDragging(boolean bl) { - dragging = bl; - } - - GuiEventListener focused; - - @Nullable - @Override - public GuiEventListener getFocused() { - return focused; - } - - @Override - public void setFocused(@Nullable GuiEventListener guiEventListener) { - focused = guiEventListener; - } - - @Override - public NarrationPriority narrationPriority() { - return NarrationPriority.NONE; - } - - @Override - public void updateNarration(NarrationElementOutput narrationElementOutput) { - - } - - @Override - public void render(PoseStack poseStack, int mouseX, int mouseY, float deltaTicks) { - if (child != null) { - poseStack.pushPose(); - poseStack.translate(bounds.left, bounds.top, 0); - child.render(poseStack, mouseX - bounds.left, mouseY - bounds.top, deltaTicks, bounds, bounds); - poseStack.popPose(); - } - } - - -} diff --git a/src/main/java/org/betterx/ui/layout/components/Range.java b/src/main/java/org/betterx/ui/layout/components/Range.java deleted file mode 100644 index c80d430b..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Range.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.components.render.RangeRenderer; -import org.betterx.ui.layout.values.Value; -import org.betterx.ui.vanilla.Slider; - -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class Range extends AbstractVanillaComponent, Range> { - @FunctionalInterface - public interface ValueChanged { - void now(Range range, N newValue); - } - - private ValueChanged onChange; - private final N minValue; - private final N maxValue; - private final N initialValue; - - public Range( - Value width, - Value height, - Component component, - N minValue, - N maxValue, - N initialValue - ) { - super(width, height, new RangeRenderer<>(), component); - this.onChange = (a, b) -> { - }; - this.minValue = minValue; - this.maxValue = maxValue; - this.initialValue = initialValue; - } - - public Range( - Value width, - Value height, - N minValue, - N maxValue, - N initialValue - ) { - this(width, height, null, minValue, maxValue, initialValue); - } - - public Range onChange(ValueChanged onChange) { - this.onChange = onChange; - return this; - } - - @Override - protected Slider createVanillaComponent() { - Range self = this; - return new Slider<>( - 0, - 0, - relativeBounds.width, - relativeBounds.height, - component, - minValue, - maxValue, - initialValue, - (s, v) -> onChange.now(self, v) - ); - } - - public N getValue() { - return vanillaComponent.currentValue(); - } - - - @Override - protected Component contentComponent() { - Slider dummy = new Slider<>( - 0, - 0, - 100, - 20, - component, - minValue, - maxValue, - initialValue, - (a, b) -> { - } - ); - return dummy.getValueComponent(maxValue); - } -} diff --git a/src/main/java/org/betterx/ui/layout/components/Tabs.java b/src/main/java/org/betterx/ui/layout/components/Tabs.java deleted file mode 100644 index ec5af1b0..00000000 --- a/src/main/java/org/betterx/ui/layout/components/Tabs.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.betterx.ui.layout.components; - -import org.betterx.ui.layout.values.Value; - -import net.minecraft.network.chat.Component; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -import java.util.LinkedList; -import java.util.List; - -@Environment(EnvType.CLIENT) -public class Tabs extends AbstractVerticalStack { - @FunctionalInterface - public interface OnPageChange { - void now(Tabs tabs, int pageIndex); - } - - private final HorizontalStack buttons; - private final Container content; - - private final List pageList = new LinkedList<>(); - private final List