diff --git a/.gitignore b/.gitignore index f6fb6cba..6019df58 100644 --- a/.gitignore +++ b/.gitignore @@ -27,6 +27,5 @@ bin/ # fabric run/ -run-client/ output/ *.log diff --git a/README.md b/README.md index 0521236a..814d89b5 100644 --- a/README.md +++ b/README.md @@ -1,98 +1,33 @@ [![](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.17.1 +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: - * 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; +* Custom surface builders; +* Translation helper; +* Weighted list; +* Block helper. -### 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). +### Rendering: +* Procedural block models (from paterns or from code); +* Block render layer interface. ## Importing: * Clone repo 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 2f8a64ae..00000000 --- a/bclib.gradle +++ /dev/null @@ -1,184 +0,0 @@ -buildscript { - dependencies { - classpath 'org.kohsuke:github-api:1.114' - } - - repositories { - gradlePluginPortal() - } -} -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.shedaniel.me/" } - maven { url 'https://maven.blamejared.com' } - maven { url 'https://jitpack.io' } -} - -minecraft { - accessWidener = file("src/main/resources/bclib.accesswidener") -} - -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.cloth' - 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.cloth' - 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.cloth' - exclude group: 'me.shedaniel' - } - } -} - -processResources { - println "Version: ${project.mod_version}" - inputs.property "version", project.mod_version - // duplicatesStrategy = 'WARN' - - // from(sourceSets.main.resources.srcDirs) { - // include "fabric.mod.json" - // expand "version": version - // } - - // from(sourceSets.main.resources.srcDirs) { - // exclude "fabric.mod.json" - // } - 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 = 16 -} - -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" -} - -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 - } - } - } -} - -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 a20ca271..f0252152 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,19 +1,18 @@ # Done to increase the memory available to gradle. org.gradle.jvmargs=-Xmx2G -#Loom -loom_version=0.8-SNAPSHOT - # Fabric Properties -# check these on https://fabricmc.net/versions.html -minecraft_version= 1.17.1 -loader_version= 0.12.4 -fabric_version = 0.41.3+1.17 +# check these on https://fabricmc.net/use +minecraft_version= 1.17 +yarn_mappings= 6 +loader_version= 0.11.6 # Mod Properties -mod_version = 0.5.0 +mod_version = 0.2.0 maven_group = ru.bclib archives_base_name = bclib # Dependencies -patchouli_version = 50-FABRIC \ 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/javadoc.css b/javadoc.css deleted file mode 100644 index 922bc6bb..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 b0b045eb..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 16.0.1.hs-adpt - - sdk use java 16.0.1.hs-adpt \ No newline at end of file diff --git a/src/main/java/com/terraformersmc/modmenu/util/ModMenuApiMarker.java b/src/main/java/com/terraformersmc/modmenu/util/ModMenuApiMarker.java deleted file mode 100644 index 54a17f17..00000000 --- a/src/main/java/com/terraformersmc/modmenu/util/ModMenuApiMarker.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.terraformersmc.modmenu.util; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -//This File was included from TerraformersMC/ModMenu -// to enable a ModMenu-Integration without having to -// compile against the actual plugin - -@Environment(EnvType.CLIENT) -public interface ModMenuApiMarker {} 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 9cc8f4fa..00000000 --- a/src/main/java/org/anti_ad/mc/ipn/api/IPNIgnore.java +++ /dev/null @@ -1,11 +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/ru/bclib/BCLib.java b/src/main/java/ru/bclib/BCLib.java index 1e450f96..e3bbee16 100644 --- a/src/main/java/ru/bclib/BCLib.java +++ b/src/main/java/ru/bclib/BCLib.java @@ -5,25 +5,13 @@ import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.resources.ResourceLocation; import ru.bclib.api.TagAPI; -import ru.bclib.api.WorldDataAPI; -import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.dataexchange.handler.autosync.Chunker; -import ru.bclib.api.dataexchange.handler.autosync.HelloClient; -import ru.bclib.api.dataexchange.handler.autosync.HelloServer; -import ru.bclib.api.dataexchange.handler.autosync.RequestFiles; -import ru.bclib.api.dataexchange.handler.autosync.SendFiles; import ru.bclib.config.Configs; import ru.bclib.recipes.CraftingRecipes; import ru.bclib.registry.BaseBlockEntities; import ru.bclib.registry.BaseRegistry; import ru.bclib.util.Logger; -import ru.bclib.world.generator.BCLibEndBiomeSource; -import ru.bclib.world.generator.BCLibNetherBiomeSource; -import ru.bclib.world.generator.GeneratorOptions; import ru.bclib.world.surface.BCLSurfaceBuilders; -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); @@ -31,25 +19,10 @@ public class BCLib implements ModInitializer { @Override public void onInitialize() { BaseRegistry.register(); - GeneratorOptions.init(); BaseBlockEntities.register(); BCLSurfaceBuilders.register(); - BCLibEndBiomeSource.register(); - BCLibNetherBiomeSource.register(); TagAPI.init(); CraftingRecipes.init(); - WorldDataAPI.registerModCache(MOD_ID); - DataExchangeAPI.registerMod(MOD_ID); - - DataExchangeAPI.registerDescriptors(List.of( - HelloClient.DESCRIPTOR, - HelloServer.DESCRIPTOR, - RequestFiles.DESCRIPTOR, - SendFiles.DESCRIPTOR, - Chunker.DESCRIPTOR - )); - - BCLibPatch.register(); Configs.save(); } @@ -60,7 +33,7 @@ public class BCLib implements ModInitializer { 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/ru/bclib/BCLibPatch.java b/src/main/java/ru/bclib/BCLibPatch.java deleted file mode 100644 index d7db7d40..00000000 --- a/src/main/java/ru/bclib/BCLibPatch.java +++ /dev/null @@ -1,82 +0,0 @@ -package ru.bclib; - -import net.minecraft.nbt.CompoundTag; -import ru.bclib.api.datafixer.DataFixerAPI; -import ru.bclib.api.datafixer.Patch; -import ru.bclib.api.datafixer.PatchFunction; - - - -public final class BCLibPatch { - public static void register(){ - DataFixerAPI.registerPatch(BiomeSourcePatch::new); - } -} - -final class BiomeSourcePatch extends Patch { - private static final String NETHER_BIOME_SOURCE = "bclib:nether_biome_source"; - private static final String END_BIOME_SOURCE = "bclib:end_biome_source"; - - protected BiomeSourcePatch() { - super(BCLib.MOD_ID, "0.4.0"); - } - - public PatchFunction getLevelDatPatcher() { - return (root, profile) -> { - CompoundTag worldGenSettings = root.getCompound("Data").getCompound("WorldGenSettings"); - CompoundTag dimensions = worldGenSettings.getCompound("dimensions"); - long seed = worldGenSettings.getLong("seed"); - boolean result = false; - - if (dimensions.contains("minecraft:the_nether")) { - CompoundTag dimRoot = dimensions.getCompound("minecraft:the_nether"); - CompoundTag biomeSource = dimRoot.getCompound("generator").getCompound("biome_source"); - if (!biomeSource.getString("type").equals(NETHER_BIOME_SOURCE)) { - BCLib.LOGGER.info("Applying Nether biome source patch"); - dimRoot.put("generator", makeNetherGenerator(seed)); - result = true; - } - } - - if (dimensions.contains("minecraft:the_end")) { - CompoundTag dimRoot = dimensions.getCompound("minecraft:the_end"); - CompoundTag biomeSource = dimRoot.getCompound("generator").getCompound("biome_source"); - if (!biomeSource.getString("type").equals(END_BIOME_SOURCE)) { - BCLib.LOGGER.info("Applying End biome source patch"); - dimRoot.put("generator", makeEndGenerator(seed)); - result = true; - } - } - - return result; - }; - } - - private 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; - } - - private 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/ru/bclib/api/BiomeAPI.java b/src/main/java/ru/bclib/api/BiomeAPI.java index eb4ff13e..0a1cb7b5 100644 --- a/src/main/java/ru/bclib/api/BiomeAPI.java +++ b/src/main/java/ru/bclib/api/BiomeAPI.java @@ -1,6 +1,10 @@ package ru.bclib.api; +import java.util.HashMap; +import java.util.Random; + import com.google.common.collect.Maps; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.biome.InternalBiomeData; @@ -13,14 +17,8 @@ import net.minecraft.server.MinecraftServer; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome.ClimateParameters; import net.minecraft.world.level.biome.Biomes; -import org.jetbrains.annotations.Nullable; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; -import ru.bclib.world.biomes.FabricBiomesData; -import ru.bclib.world.generator.BiomePicker; - -import java.util.Map; -import java.util.Random; public class BiomeAPI { /** @@ -29,30 +27,12 @@ public class BiomeAPI { */ public static final BCLBiome EMPTY_BIOME = new BCLBiome(Biomes.THE_VOID.location(), BuiltinRegistries.BIOME.get(Biomes.THE_VOID), 1, 0); - public static final BiomePicker NETHER_BIOME_PICKER = new BiomePicker(); - public static final BiomePicker END_LAND_BIOME_PICKER = new BiomePicker(); - public static final BiomePicker END_VOID_BIOME_PICKER = new BiomePicker(); - - private static final Map ID_MAP = Maps.newHashMap(); - private static final Map CLIENT = Maps.newHashMap(); + private static final HashMap ID_MAP = Maps.newHashMap(); + private static final HashMap CLIENT = Maps.newHashMap(); private static Registry biomeRegistry; - public static final BCLBiome NETHER_WASTES_BIOME = registerNetherBiome(getFromRegistry(Biomes.NETHER_WASTES)); - public static final BCLBiome CRIMSON_FOREST_BIOME = registerNetherBiome(getFromRegistry(Biomes.CRIMSON_FOREST)); - public static final BCLBiome WARPED_FOREST_BIOME = registerNetherBiome(getFromRegistry(Biomes.WARPED_FOREST)); - public static final BCLBiome SOUL_SAND_VALLEY_BIOME = registerNetherBiome(getFromRegistry(Biomes.SOUL_SAND_VALLEY)); - public static final BCLBiome BASALT_DELTAS_BIOME = registerNetherBiome(getFromRegistry(Biomes.BASALT_DELTAS)); - - public static final BCLBiome THE_END = registerEndLandBiome(getFromRegistry(Biomes.THE_END)); - public static final BCLBiome END_MIDLANDS = registerSubBiome(THE_END, getFromRegistry(Biomes.END_MIDLANDS), 0.5F); - public static final BCLBiome END_HIGHLANDS = registerSubBiome(THE_END, getFromRegistry(Biomes.END_HIGHLANDS), 0.5F); - - public static final BCLBiome END_BARRENS = registerEndVoidBiome(getFromRegistry(new ResourceLocation("end_barrens"))); - public static final BCLBiome SMALL_END_ISLANDS = registerEndVoidBiome(getFromRegistry(new ResourceLocation("small_end_islands"))); - /** * Initialize registry for current server. - * * @param server - {@link MinecraftServer} */ public static void initRegistry(MinecraftServer server) { @@ -60,159 +40,53 @@ public class BiomeAPI { CLIENT.clear(); } - /** - * Register {@link BCLBiome} instance and its {@link Biome} if necessary. - * @param biome {@link BCLBiome} - * @return {@link BCLBiome} - */ - public static BCLBiome registerBiome(BCLBiome biome) { + public static void registerBiome(BCLBiome biome) { if (BuiltinRegistries.BIOME.get(biome.getID()) == null) { Registry.register(BuiltinRegistries.BIOME, biome.getID(), biome.getBiome()); } ID_MAP.put(biome.getID(), biome); - return biome; - } - - public static BCLBiome registerSubBiome(BCLBiome parent, BCLBiome subBiome) { - registerBiome(subBiome); - parent.addSubBiome(subBiome); - return subBiome; - } - - public static BCLBiome registerSubBiome(BCLBiome parent, Biome biome, float chance) { - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome).get(); - BCLBiome subBiome = new BCLBiome(key.location(), biome, 1, chance); - return registerSubBiome(parent, subBiome); } /** - * 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 biome {@link BCLBiome} - * @return {@link BCLBiome} + * Adds {@link BCLBiome} to FabricAPI biomes as the Nether biome (with random {@link ClimateParameters}). + * @param biome - {@link BCLBiome}. */ - public static BCLBiome registerNetherBiome(BCLBiome biome) { - registerBiome(biome); - NETHER_BIOME_PICKER.addBiome(biome); - Random random = new Random(biome.getID().hashCode()); - ClimateParameters parameters = new ClimateParameters( - MHelper.randRange(-1.5F, 1.5F, random), - MHelper.randRange(-1.5F, 1.5F, random), - MHelper.randRange(-1.5F, 1.5F, random), - MHelper.randRange(-1.5F, 1.5F, random), - random.nextFloat() - ); + public static void addNetherBiomeToFabricApi(BCLBiome biome) { ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).get(); + Random random = new Random(biome.getID().toString().hashCode()); + ClimateParameters parameters = new ClimateParameters( + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random), + MHelper.randRange(-2F, 2F, random) + ); InternalBiomeData.addNetherBiome(key, parameters); - 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 biome {@link BCLBiome} - * @return {@link BCLBiome} + * Adds {@link BCLBiome} to FabricAPI biomes as an End land biome (generating on islands). + * @param biome - {@link BCLBiome}. */ - public static BCLBiome registerNetherBiome(Biome biome) { - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome).get(); - BCLBiome bclBiome = new BCLBiome(key.location(), biome, 1, 1); - NETHER_BIOME_PICKER.addBiome(bclBiome); - registerBiome(bclBiome); - return bclBiome; - } - - /** - * 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) { - registerBiome(biome); - END_LAND_BIOME_PICKER.addBiome(biome); + public static void addEndLandBiomeToFabricApi(BCLBiome biome) { float weight = biome.getGenChance(); ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).get(); InternalBiomeData.addEndBiomeReplacement(Biomes.END_HIGHLANDS, key, weight); InternalBiomeData.addEndBiomeReplacement(Biomes.END_MIDLANDS, key, weight); - return biome; } /** - * 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 biome {@link BCLBiome} - * @return {@link BCLBiome} + * Adds {@link BCLBiome} to FabricAPI biomes as an End void biome (generating between islands in the void). + * @param biome - {@link BCLBiome}. */ - public static BCLBiome registerEndLandBiome(Biome biome) { - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome).get(); - BCLBiome bclBiome = new BCLBiome(key.location(), biome, 1, 1); - END_LAND_BIOME_PICKER.addBiome(bclBiome); - registerBiome(bclBiome); - return bclBiome; - } - - /** - * 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 biome {@link BCLBiome}; - * @param weight float generation chance. - * @return {@link BCLBiome} - */ - public static BCLBiome registerEndLandBiome(Biome biome, float weight) { - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome).get(); - BCLBiome bclBiome = new BCLBiome(key.location(), biome, 1, weight); - END_LAND_BIOME_PICKER.addBiome(bclBiome); - registerBiome(bclBiome); - return bclBiome; - } - - /** - * 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) { - registerBiome(biome); - END_VOID_BIOME_PICKER.addBiome(biome); + public static void addEndVoidBiomeToFabricApi(BCLBiome biome) { float weight = biome.getGenChance(); ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome.getBiome()).get(); InternalBiomeData.addEndBiomeReplacement(Biomes.SMALL_END_ISLANDS, 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(Biome biome) { - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome).get(); - BCLBiome bclBiome = new BCLBiome(key.location(), biome, 1, 1); - END_VOID_BIOME_PICKER.addBiome(bclBiome); - registerBiome(bclBiome); - return bclBiome; - } - - /** - * 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}; - * @param weight float generation chance. - * @return {@link BCLBiome} - */ - public static BCLBiome registerEndVoidBiome(Biome biome, float weight) { - ResourceKey key = BuiltinRegistries.BIOME.getResourceKey(biome).get(); - BCLBiome bclBiome = new BCLBiome(key.location(), biome, 1, weight); - END_VOID_BIOME_PICKER.addBiome(bclBiome); - registerBiome(bclBiome); - return bclBiome; } /** * Get {@link BCLBiome} from {@link Biome} instance on server. Used to convert world biomes to BCLBiomes. - * * @param biome - {@link Biome} from world. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. */ @@ -225,7 +99,6 @@ public class BiomeAPI { /** * 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}. */ @@ -243,7 +116,6 @@ public class BiomeAPI { /** * Get biome {@link ResourceLocation} from given {@link Biome}. - * * @param biome - {@link Biome} from server world. * @return biome {@link ResourceLocation}. */ @@ -251,10 +123,9 @@ public class BiomeAPI { ResourceLocation id = biomeRegistry.getKey(biome); return id == null ? EMPTY_BIOME.getID() : id; } - + /** * Get {@link BCLBiome} from given {@link ResourceLocation}. - * * @param biomeID - biome {@link ResourceLocation}. * @return {@link BCLBiome} or {@code BiomeAPI.EMPTY_BIOME}. */ @@ -262,62 +133,26 @@ public class BiomeAPI { return ID_MAP.getOrDefault(biomeID, EMPTY_BIOME); } + /** + * Get actual {@link Biome} from given {@link BCLBiome}. If it is null it will request it from current {@link Registry}. + * @param biome - {@link BCLBiome}. + * @return {@link Biome}. + */ + public static Biome getActualBiome(BCLBiome biome) { + Biome actual = biome.getActualBiome(); + if (actual == null) { + biome.updateActualBiomes(biomeRegistry); + actual = biome.getActualBiome(); + } + return actual; + } + /** * 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 ID_MAP.containsKey(biomeID); } - - /** - * Load biomes from Fabric API. For internal usage only. - */ - public static void loadFabricAPIBiomes() { - FabricBiomesData.NETHER_BIOMES.forEach((key) -> { - if (!hasBiome(key.location())) { - registerNetherBiome(BuiltinRegistries.BIOME.get(key.location())); - } - }); - - FabricBiomesData.END_LAND_BIOMES.forEach((key, weight) -> { - if (!hasBiome(key.location())) { - registerEndLandBiome(BuiltinRegistries.BIOME.get(key.location()), weight); - } - }); - - FabricBiomesData.END_VOID_BIOMES.forEach((key, weight) -> { - if (!hasBiome(key.location())) { - registerEndVoidBiome(BuiltinRegistries.BIOME.get(key.location()), weight); - } - }); - } - - @Nullable - public static Biome getFromRegistry(ResourceLocation key) { - return BuiltinRegistries.BIOME.get(key); - } - - @Nullable - public static Biome getFromRegistry(ResourceKey key) { - return BuiltinRegistries.BIOME.get(key); - } - - public static boolean isDatapackBiome(ResourceLocation biomeID) { - return getFromRegistry(biomeID) == null; - } - - public static boolean isNetherBiome(ResourceLocation biomeID) { - return pickerHasBiome(NETHER_BIOME_PICKER, biomeID); - } - - public static boolean isEndBiome(ResourceLocation biomeID) { - return pickerHasBiome(END_LAND_BIOME_PICKER, biomeID) || pickerHasBiome(END_VOID_BIOME_PICKER, biomeID); - } - - private static boolean pickerHasBiome(BiomePicker picker, ResourceLocation key) { - return picker.getBiomes().stream().filter(biome -> biome.getID().equals(key)).findFirst().isPresent(); - } } diff --git a/src/main/java/ru/bclib/api/BonemealAPI.java b/src/main/java/ru/bclib/api/BonemealAPI.java index b6a5232e..4e9a200f 100644 --- a/src/main/java/ru/bclib/api/BonemealAPI.java +++ b/src/main/java/ru/bclib/api/BonemealAPI.java @@ -1,65 +1,53 @@ package ru.bclib.api; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.block.Block; -import ru.bclib.util.WeightedList; - import java.util.Map; import java.util.Random; import java.util.Set; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.level.block.Block; +import ru.bclib.util.WeightedList; + 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(); + private static final Set SPREADABLE_BLOCKS = 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 void addSpreadableBlock(Block block) { + SPREADABLE_BLOCKS.add(block); } - 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 boolean isSpreadable(Block block) { + return SPREADABLE_BLOCKS.contains(block); } public static void addLandGrass(Block plant, Block... terrain) { - for (Block block : terrain) { - addLandGrass(plant, block, 1F); + for (Block block: terrain) { + addLandGrass(block, plant, 1F); } } public static void addLandGrass(ResourceLocation biome, Block plant, Block... terrain) { - for (Block block : terrain) { - addLandGrass(biome, plant, block, 1F); + for (Block block: terrain) { + addLandGrass(biome, block, plant, 1F); } } - public static void addLandGrass(Block plant, Block terrain, float chance) { + public static void addLandGrass(Block terrain, Block plant, 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) { + public static void addLandGrass(ResourceLocation biome, Block terrain, Block plant, float chance) { Map> map = LAND_GRASS_BIOMES.get(biome); if (map == null) { map = Maps.newHashMap(); @@ -70,33 +58,31 @@ public class BonemealAPI { list = new WeightedList(); map.put(terrain, list); } - TERRAIN.add(terrain); list.add(plant, chance); } public static void addWaterGrass(Block plant, Block... terrain) { - for (Block block : terrain) { - addWaterGrass(plant, block, 1F); + for (Block block: terrain) { + addWaterGrass(block, plant, 1F); } } public static void addWaterGrass(ResourceLocation biome, Block plant, Block... terrain) { - for (Block block : terrain) { - addWaterGrass(biome, plant, block, 1F); + for (Block block: terrain) { + addWaterGrass(biome, block, plant, 1F); } } - public static void addWaterGrass(Block plant, Block terrain, float chance) { + public static void addWaterGrass(Block terrain, Block plant, 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) { + public static void addWaterGrass(ResourceLocation biome, Block terrain, Block plant, float chance) { Map> map = WATER_GRASS_BIOMES.get(biome); if (map == null) { map = Maps.newHashMap(); @@ -107,7 +93,6 @@ public class BonemealAPI { list = new WeightedList(); map.put(terrain, list); } - TERRAIN.add(terrain); list.add(plant, chance); } @@ -127,16 +112,16 @@ public class BonemealAPI { } public static Block getWaterGrass(ResourceLocation biomeID, Block terrain, Random random) { - Map> map = WATER_GRASS_BIOMES.get(biomeID); + Map> map = LAND_GRASS_BIOMES.get(biomeID); WeightedList list = null; if (map != null) { list = map.get(terrain); if (list == null) { - list = WATER_GRASS_TYPES.get(terrain); + list = LAND_GRASS_TYPES.get(terrain); } } else { - list = WATER_GRASS_TYPES.get(terrain); + list = LAND_GRASS_TYPES.get(terrain); } return list == null ? null : list.get(random); } diff --git a/src/main/java/ru/bclib/api/DataFixerAPI.java b/src/main/java/ru/bclib/api/DataFixerAPI.java new file mode 100644 index 00000000..cf644539 --- /dev/null +++ b/src/main/java/ru/bclib/api/DataFixerAPI.java @@ -0,0 +1,149 @@ +package ru.bclib.api; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.ListTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.chunk.storage.RegionFile; + +public class DataFixerAPI { + private static final Map REPLACEMENT = Maps.newHashMap(); + private static final Map FIX_VERSIONS = Maps.newHashMap(); + + public static void fixData(File dir) { + REPLACEMENT.clear(); // API is not finished yet! + if (REPLACEMENT.isEmpty()) { + return; + } + + boolean shoudFix = false; + Collection mods = FabricLoader.getInstance().getAllMods(); + for (ModContainer mod: mods) { + String name = mod.getMetadata().getId(); + int preVersion = WorldDataAPI.getIntModVersion(name); + int version = getModVersion(mod.getMetadata().getVersion().toString()); + if (version > preVersion) { + int fixVersion = FIX_VERSIONS.getOrDefault(name, version); + shoudFix |= fixVersion < version && fixVersion >= preVersion; + } + }; + if (!shoudFix) { + return; + } + + List regions = getAllRegions(dir, null); + regions.parallelStream().forEach((file) -> { + try { + System.out.println("Fixing " + file); + boolean[] changed = new boolean[1]; + RegionFile region = new RegionFile(file, file.getParentFile(), 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)) { + DataInputStream input = region.getChunkDataInputStream(pos); + CompoundTag root = NbtIo.read(input); + input.close(); + ListTag sections = root.getCompound("Level").getList("Sections", 10); + sections.forEach((tag) -> { + ListTag palette = ((CompoundTag) tag).getList("Palette", 10); + palette.forEach((blockTag) -> { + CompoundTag blockTagCompound = ((CompoundTag) blockTag); + String name = blockTagCompound.getString("Name"); + String replace = REPLACEMENT.get(name); + if (replace != null) { + blockTagCompound.putString("Name", replace); + changed[0] = true; + } + }); + }); + if (changed[0]) { + System.out.println("Write!"); + DataOutputStream output = region.getChunkDataOutputStream(pos); + NbtIo.write(root, output); + output.close(); + } + } + } + } + region.close(); + } + catch (Exception e) { + e.printStackTrace(); + } + }); + } + + /** + * Register block data fix. Fix will be applied on world load if current mod version will be newer than specified one. + * @param modID - {@link String} mod id; + * @param modVersion - {@link String} mod version, should be in format: %d.%d.%d + * @param result - {@link String} new block name; + * @param names - array of {@link String}, old block names to convert. + */ + protected static void addFix(String modID, String modVersion, String result, String... names) { + FIX_VERSIONS.put(modID, getModVersion(modVersion)); + for (String name: names) { + REPLACEMENT.put(name, result); + } + } + + private static List getAllRegions(File dir, List list) { + if (list == null) { + list = Lists.newArrayList(); + } + for (File file: dir.listFiles()) { + if (file.isDirectory()) { + getAllRegions(file, list); + } + else if (file.isFile() && file.getName().endsWith(".mca")) { + list.add(file); + } + } + return list; + } + + /** + * Get mod version from string. String should be in format: %d.%d.%d + * @param version - {@link String} mod version. + * @return int mod version. + */ + public static int getModVersion(String version) { + if (version.isEmpty()) { + return 0; + } + try { + String[] values = version.split("\\."); + return Integer.parseInt(values[0]) << 12 | Integer.parseInt(values[1]) << 6 | Integer.parseInt(values[2]); + } + catch (Exception e) { + return 0; + } + } + + /** + * Get mod version from integer. String will be in format %d.%d.%d + * @param version - mod version in integer form. + * @return {@link String} mod version. + */ + public static String getModVersion(int version) { + int a = (version >> 12) & 63; + int b = (version >> 6) & 63; + int c = version & 63; + return String.format(Locale.ROOT, "%d.%d.%d", a, b, c); + } +} diff --git a/src/main/java/ru/bclib/api/ModIntegrationAPI.java b/src/main/java/ru/bclib/api/ModIntegrationAPI.java index b36eec68..eff311dc 100644 --- a/src/main/java/ru/bclib/api/ModIntegrationAPI.java +++ b/src/main/java/ru/bclib/api/ModIntegrationAPI.java @@ -1,18 +1,16 @@ package ru.bclib.api; -import com.google.common.collect.Lists; -import net.fabricmc.loader.api.FabricLoader; -import ru.bclib.integration.ModIntegration; - import java.util.List; +import com.google.common.collect.Lists; + +import ru.bclib.integration.ModIntegration; + 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 */ @@ -23,7 +21,6 @@ public class ModIntegrationAPI { /** * Get all registered mod integrations. - * * @return {@link List} of {@link ModIntegration}. */ public static List getIntegrations() { @@ -40,8 +37,4 @@ public class ModIntegrationAPI { } }); } - - public static boolean hasCanvas() { - return HAS_CANVAS; - } } diff --git a/src/main/java/ru/bclib/api/PostInitAPI.java b/src/main/java/ru/bclib/api/PostInitAPI.java deleted file mode 100644 index 29adf17b..00000000 --- a/src/main/java/ru/bclib/api/PostInitAPI.java +++ /dev/null @@ -1,86 +0,0 @@ -package ru.bclib.api; - -import com.google.common.collect.Lists; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; -import net.minecraft.client.renderer.RenderType; -import net.minecraft.core.Registry; -import net.minecraft.world.level.block.Block; -import ru.bclib.blocks.BaseBarrelBlock; -import ru.bclib.blocks.BaseChestBlock; -import ru.bclib.blocks.BaseFurnaceBlock; -import ru.bclib.blocks.BaseSignBlock; -import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.client.render.BaseChestBlockEntityRenderer; -import ru.bclib.client.render.BaseSignBlockEntityRenderer; -import ru.bclib.interfaces.PostInitable; -import ru.bclib.interfaces.RenderLayerProvider; -import ru.bclib.registry.BaseBlockEntities; - -import java.util.List; -import java.util.function.Consumer; - -public class PostInitAPI { - private static List> postInitFunctions = 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) { - if (postInitFunctions == null) { - return; - } - postInitFunctions.forEach(function -> function.accept(isClient)); - Registry.BLOCK.forEach(block -> { - processBlockCommon(block); - if (isClient) { - processBlockClient(block); - } - }); - postInitFunctions = null; - BiomeAPI.loadFabricAPIBiomes(); - } - - @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 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); - } - } -} diff --git a/src/main/java/ru/bclib/api/TagAPI.java b/src/main/java/ru/bclib/api/TagAPI.java index 6da6e070..8a4accba 100644 --- a/src/main/java/ru/bclib/api/TagAPI.java +++ b/src/main/java/ru/bclib/api/TagAPI.java @@ -1,11 +1,9 @@ package ru.bclib.api; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; +import java.util.function.Supplier; + import net.fabricmc.fabric.api.tag.TagRegistry; -import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; import net.minecraft.tags.BlockTags; import net.minecraft.tags.ItemTags; import net.minecraft.tags.Tag; @@ -13,76 +11,45 @@ import net.minecraft.tags.Tag.Named; import net.minecraft.tags.TagCollection; import net.minecraft.world.item.Item; import net.minecraft.world.item.Items; -import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import ru.bclib.BCLib; - -import java.util.Map; -import java.util.Set; -import java.util.function.Supplier; +import ru.bclib.util.TagHelper; public class TagAPI { - private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); - private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); - // Block Tags - public static final Tag.Named BLOCK_BOOKSHELVES = makeCommonBlockTag("bookshelves"); - public static final Tag.Named BLOCK_GEN_TERRAIN = makeBlockTag(BCLib.MOD_ID, "gen_terrain"); - public static final Tag.Named BLOCK_NETHER_GROUND = makeBlockTag(BCLib.MOD_ID, "nether_ground"); - public static final Tag.Named BLOCK_END_GROUND = makeBlockTag(BCLib.MOD_ID, "end_ground"); + public static final Tag.Named BOOKSHELVES = makeCommonBlockTag("bookshelves"); + public static final Tag.Named GEN_TERRAIN = makeBlockTag(BCLib.MOD_ID, "gen_terrain"); + public static final Tag.Named NETHER_GROUND = makeBlockTag(BCLib.MOD_ID, "nether_ground"); + public static final Tag.Named END_GROUND = makeBlockTag(BCLib.MOD_ID, "end_ground"); public static final Tag.Named BLOCK_CHEST = makeCommonBlockTag("chest"); - public static final Tag.Named BLOCK_WOODEN_CHEST = makeCommonBlockTag("wooden_chests"); - public static final Tag.Named BLOCK_BARREL = makeCommonBlockTag("barrel"); - public static final Tag.Named BLOCK_WOODEN_BARREL = makeCommonBlockTag("wooden_barrels"); - public static final Tag.Named BLOCK_END_STONES = makeCommonBlockTag("end_stones"); - public static final Tag.Named BLOCK_NETHER_STONES = makeCommonBlockTag("nether_stones"); - public static final Tag.Named BLOCK_NETHER_PORTAL_FRAME = makeCommonBlockTag("nether_pframe"); - public static final Tag.Named BLOCK_WORKBENCHES = makeCommonBlockTag("workbench"); - public static final Tag.Named BLOCK_SAPLINGS = makeCommonBlockTag("saplings"); - public static final Tag.Named BLOCK_LEAVES = makeCommonBlockTag("leaves"); - public static final Tag.Named BLOCK_IMMOBILE = makeCommonBlockTag("immobile"); + public static final Tag.Named END_STONES = makeCommonBlockTag("end_stones"); + public static final Tag.Named NETHER_STONES = makeCommonBlockTag("nether_stones"); - public static final Tag.Named BLOCK_DRAGON_IMMUNE = getMCBlockTag("dragon_immune"); - - public static final Tag.Named MINEABLE_AXE = getMCBlockTag("mineable/axe"); - public static final Tag.Named MINEABLE_PICKAXE = getMCBlockTag("mineable/pickaxe"); - public static final Tag.Named MINEABLE_SHOVEL = getMCBlockTag("mineable/shovel"); - public static final Tag.Named MINEABLE_HOE = getMCBlockTag("mineable/hoe"); + public static final Tag.Named DRAGON_IMMUNE = getMCBlockTag("dragon_immune"); // Item Tags public static final Tag.Named ITEM_CHEST = makeCommonItemTag("chest"); - public static final Tag.Named ITEM_WOODEN_CHEST = makeCommonItemTag("wooden_chests"); - public static final Tag.Named ITEM_BARREL = makeCommonItemTag("barrel"); - public static final Tag.Named ITEM_WOODEN_BARREL = makeCommonItemTag("wooden_barrels"); - public static final Tag.Named ITEM_IRON_INGOTS = makeCommonItemTag("iron_ingots"); - public static final Tag.Named ITEM_FURNACES = makeCommonItemTag("furnaces"); - public static final Tag.Named ITEM_WORKBENCHES = makeCommonItemTag("workbench"); - public final static Tag.Named ITEM_HAMMERS = makeCommonItemTag("hammers"); - public static final Tag.Named ITEM_SAPLINGS = makeCommonItemTag("saplings"); - public static final Tag.Named ITEM_LEAVES = makeCommonItemTag("leaves"); - public static final Tag.Named ITEM_SHEARS = getMCItemTag("shears"); - public static final Tag.Named ITEM_COMMON_SHEARS = makeCommonItemTag("shears"); - + public static final Tag.Named IRON_INGOTS = makeCommonItemTag("iron_ingots"); + public static final Tag.Named FURNACES = makeCommonItemTag("furnaces"); + public final static Tag.Named HAMMERS = makeItemTag("fabric", "hammers"); /** * Get or create {@link Tag.Named}. - * * @param containerSupplier - {@link TagCollection} {@link Supplier} tag collection; - * @param id - {@link ResourceLocation} tag id. + * @param id - {@link ResourceLocation} tag id. * @return {@link Tag.Named}. */ public static Tag.Named makeTag(Supplier> containerSupplier, ResourceLocation id) { Tag tag = containerSupplier.get().getTag(id); return tag == null ? TagRegistry.create(id, containerSupplier) : (Named) tag; } - + /** * Get or create {@link Block} {@link Tag.Named} with mod namespace. - * * @param modID - {@link String} mod namespace (mod id); - * @param name - {@link String} tag name. + * @param name - {@link String} tag name. * @return {@link Block} {@link Tag.Named}. */ public static Tag.Named makeBlockTag(String modID, String name) { @@ -91,9 +58,8 @@ public class TagAPI { /** * Get or create {@link Item} {@link Tag.Named} with mod namespace. - * * @param modID - {@link String} mod namespace (mod id); - * @param name - {@link String} tag name. + * @param name - {@link String} tag name. * @return {@link Item} {@link Tag.Named}. */ public static Tag.Named makeItemTag(String modID, String name) { @@ -102,10 +68,9 @@ public class TagAPI { /** * Get or create {@link Block} {@link Tag.Named}. - * + * @see Fabric Wiki (Tags) * @param name - {@link String} tag name. * @return {@link Block} {@link Tag.Named}. - * @see Fabric Wiki (Tags) */ public static Tag.Named makeCommonBlockTag(String name) { return makeTag(BlockTags::getAllTags, new ResourceLocation("c", name)); @@ -113,10 +78,9 @@ public class TagAPI { /** * Get or create {@link Item} {@link Tag.Named}. - * + * @see Fabric Wiki (Tags) * @param name - {@link String} tag name. * @return {@link Item} {@link Tag.Named}. - * @see Fabric Wiki (Tags) */ public static Tag.Named makeCommonItemTag(String name) { return makeTag(ItemTags::getAllTags, new ResourceLocation("c", name)); @@ -124,7 +88,6 @@ public class TagAPI { /** * Get or create Minecraft {@link Block} {@link Tag.Named}. - * * @param name - {@link String} tag name. * @return {@link Block} {@link Tag.Named}. */ @@ -134,165 +97,35 @@ public class TagAPI { return tag == null ? (Named) TagRegistry.block(id) : (Named) tag; } - /** - * Get or create Minecraft {@link Item} {@link Tag.Named}. - * - * @param name - {@link String} tag name. - * @return {@link Item} {@link Tag.Named}. - */ - public static Tag.Named getMCItemTag(String name) { - ResourceLocation id = new ResourceLocation(name); - Tag tag = ItemTags.getAllTags().getTag(id); - return tag == null ? (Named) TagRegistry.item(id) : (Named) tag; - } - /** * Adds {@link Block} to NETHER_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic. - * * @param block - {@link Block}. */ public static void addNetherGround(Block block) { - addTag(BLOCK_NETHER_GROUND, block); - addTag(BLOCK_GEN_TERRAIN, block); + TagHelper.addTag(NETHER_GROUND, block); + TagHelper.addTag(GEN_TERRAIN, block); } /** * Adds {@link Block} to END_GROUND and GEN_TERRAIN tags to process it properly in terrain generators and block logic. - * * @param block - {@link Block}. */ public static void addEndGround(Block block) { - addTag(BLOCK_GEN_TERRAIN, block); - addTag(BLOCK_END_GROUND, block); + TagHelper.addTag(GEN_TERRAIN, block); + TagHelper.addTag(END_GROUND, block); } /** * Initializes basic tags. Should be called only in BCLib main class. */ public static void init() { - addTag(BLOCK_BOOKSHELVES, Blocks.BOOKSHELF); - addTag(BLOCK_GEN_TERRAIN, Blocks.END_STONE, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); - addTag(BLOCK_NETHER_GROUND, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); - addTag(BLOCK_END_GROUND, Blocks.END_STONE); - addTag(BLOCK_CHEST, Blocks.CHEST); - addTag(ITEM_CHEST, Items.CHEST); - addTag(ITEM_IRON_INGOTS, Items.IRON_INGOT); - addTag(ITEM_FURNACES, Blocks.FURNACE); - } - - /** - * Adds one Tag to multiple Blocks. - *

- * Example: - *

{@code  Tag.Named DIMENSION_STONE = makeBlockTag("mymod", "dim_stone");
-	 * addTag(DIMENSION_STONE, Blocks.END_STONE, Blocks.NETHERRACK);}
- *

- * The call will reserve the Tag. The Tag is added to the blocks once - * {@link #apply(String, Map)} was executed. - * - * @param tag The new Tag - * @param blocks One or more blocks that should receive the Tag. - */ - public static void addTag(Tag.Named tag, Block... blocks) { - ResourceLocation tagID = tag.getName(); - Set set = TAGS_BLOCK.computeIfAbsent(tagID, k -> Sets.newHashSet()); - for (Block block : blocks) { - ResourceLocation id = Registry.BLOCK.getKey(block); - if (id != Registry.BLOCK.getDefaultKey()) { - set.add(id); - } - } - } - - /** - * Adds one Tag to multiple Items. - *

- * Example: - *

{@code  Tag.Named METALS = makeBlockTag("mymod", "metals");
-	 * addTag(METALS, Items.IRON_INGOT, Items.GOLD_INGOT, Items.COPPER_INGOT);}
- *

- * The call will reserve the Tag. The Tag is added to the items once - * {@link #apply(String, Map)} was executed. - * - * @param tag The new Tag - * @param items One or more item that should receive the Tag. - */ - public static void addTag(Tag.Named tag, ItemLike... items) { - ResourceLocation tagID = tag.getName(); - Set set = TAGS_ITEM.computeIfAbsent(tagID, k -> Sets.newHashSet()); - for (ItemLike item : items) { - ResourceLocation id = Registry.ITEM.getKey(item.asItem()); - if (id != Registry.ITEM.getDefaultKey()) { - set.add(id); - } - } - } - - /** - * Adds multiple Tags to one Item. - *

- * The call will reserve the Tags. The Tags are added to the Item once - * * {@link #apply(String, Map)} was executed. - * - * @param item The Item that will receive all Tags - * @param tags One or more Tags - */ - @SafeVarargs - public static void addTags(ItemLike item, Tag.Named... tags) { - for (Tag.Named tag : tags) { - addTag(tag, item); - } - } - - /** - * Adds multiple Tags to one Block. - *

- * The call will reserve the Tags. The Tags are added to the Block once - * * {@link #apply(String, Map)} was executed. - * - * @param block The Block that will receive all Tags - * @param tags One or more Tags - */ - @SafeVarargs - public static void addTags(Block block, Tag.Named... tags) { - for (Tag.Named tag : tags) { - addTag(tag, block); - } - } - - /** - * Adds all {@code ids} to the {@code builder}. - * - * @param builder - * @param ids - * @return The Builder passed as {@code builder}. - */ - public static Tag.Builder apply(Tag.Builder builder, Set ids) { - ids.forEach(value -> builder.addElement(value, "Better End Code")); - return builder; - } - - /** - * Automatically called in {@link net.minecraft.tags.TagLoader#loadAndBuild(ResourceManager)}. - *

- * In most cases there is no need to call this Method manually. - * - * @param directory The name of the Tag-directory. Should be either "tags/blocks" or - * "tags/items". - * @param tagsMap The map that will hold the registered Tags - * @return The {@code tagsMap} Parameter. - */ - public static Map apply(String directory, Map tagsMap) { - Map> endTags = null; - if ("tags/blocks".equals(directory)) { - endTags = TAGS_BLOCK; - } - else if ("tags/items".equals(directory)) { - endTags = TAGS_ITEM; - } - if (endTags != null) { - endTags.forEach((id, ids) -> apply(tagsMap.computeIfAbsent(id, key -> Tag.Builder.tag()), ids)); - } - return tagsMap; + TagHelper.addTag(BOOKSHELVES, Blocks.BOOKSHELF); + TagHelper.addTag(GEN_TERRAIN, Blocks.END_STONE, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); + TagHelper.addTag(NETHER_GROUND, Blocks.NETHERRACK, Blocks.SOUL_SAND, Blocks.SOUL_SOIL); + TagHelper.addTag(END_GROUND, Blocks.END_STONE); + TagHelper.addTag(BLOCK_CHEST, Blocks.CHEST); + TagHelper.addTag(ITEM_CHEST, Items.CHEST); + TagHelper.addTag(IRON_INGOTS, Items.IRON_INGOT); + TagHelper.addTag(FURNACES, Blocks.FURNACE); } } diff --git a/src/main/java/ru/bclib/api/WorldDataAPI.java b/src/main/java/ru/bclib/api/WorldDataAPI.java index b1794df7..6927c9ed 100644 --- a/src/main/java/ru/bclib/api/WorldDataAPI.java +++ b/src/main/java/ru/bclib/api/WorldDataAPI.java @@ -1,30 +1,20 @@ package ru.bclib.api; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; -import ru.bclib.BCLib; -import ru.bclib.api.datafixer.DataFixerAPI; -import ru.bclib.util.ModUtil; - import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.function.Consumer; -/** - * Mod-specifix data-storage for a world. - *

- * This class provides the ability for mod to store persistent data inside a world. The Storage for the world is - * currently initialized as part of the {@link DataFixerAPI} in {@link DataFixerAPI#fixData(LevelStorageAccess, boolean, Consumer)} - * or {@link DataFixerAPI#initializeWorldData(File, boolean)} - */ +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import net.fabricmc.loader.api.FabricLoader; +import net.fabricmc.loader.api.ModContainer; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtIo; +import ru.bclib.BCLib; + public class WorldDataAPI { private static final Map TAGS = Maps.newHashMap(); private static final List MODS = Lists.newArrayList(); @@ -32,43 +22,36 @@ public class WorldDataAPI { public static void load(File dataDir) { WorldDataAPI.dataDir = dataDir; - MODS.stream() - .parallel() - .forEach(modID -> { - File file = new File(dataDir, modID + ".nbt"); - CompoundTag root = new CompoundTag(); - if (file.exists()) { - try { - root = NbtIo.readCompressed(file); - } - catch (IOException e) { - BCLib.LOGGER.error("World data loading failed", e); - } + MODS.stream().parallel().forEach(modID -> { + File file = new File(dataDir, modID + ".nbt"); + CompoundTag root = new CompoundTag(); + TAGS.put(modID, root); + if (file.exists()) { + try { + root = NbtIo.readCompressed(file); } - else { - Optional optional = FabricLoader.getInstance() - .getModContainer(modID); - if (optional.isPresent()) { - ModContainer modContainer = optional.get(); - if (BCLib.isDevEnvironment()) { - root.putString("version", "255.255.9999"); - } - else { - root.putString("version", modContainer.getMetadata() - .getVersion() - .toString()); - } - saveFile(modID); - } + catch (IOException e) { + BCLib.LOGGER.error("World data loading failed", e); } - - TAGS.put(modID, root); - }); + } + else { + Optional optional = FabricLoader.getInstance().getModContainer(modID); + if (optional.isPresent()) { + ModContainer modContainer = optional.get(); + if (BCLib.isDevEnvironment()) { + root.putString("version", "63.63.63"); + } + else { + root.putString("version", modContainer.getMetadata().getVersion().toString()); + } + saveFile(modID); + } + } + }); } /** * Register mod cache, world cache is located in world data folder. - * * @param modID - {@link String} modID. */ public static void registerModCache(String modID) { @@ -77,7 +60,6 @@ public class WorldDataAPI { /** * Get root {@link CompoundTag} for mod cache in world data folder. - * * @param modID - {@link String} modID. * @return {@link CompoundTag} */ @@ -92,14 +74,13 @@ public class WorldDataAPI { /** * Get {@link CompoundTag} with specified path from mod cache in world data folder. - * * @param modID - {@link String} path to tag, dot-separated. * @return {@link CompoundTag} */ public static CompoundTag getCompoundTag(String modID, String path) { String[] parts = path.split("\\."); CompoundTag tag = getRootTag(modID); - for (String part : parts) { + for (String part: parts) { if (tag.contains(part)) { tag = tag.getCompound(part); } @@ -114,14 +95,10 @@ public class WorldDataAPI { /** * Forces mod cache file to be saved. - * * @param modID {@link String} mod ID. */ public static void saveFile(String modID) { try { - if (!dataDir.exists()) { - dataDir.mkdirs(); - } NbtIo.writeCompressed(getRootTag(modID), new File(dataDir, modID + ".nbt")); } catch (IOException e) { @@ -131,7 +108,6 @@ public class WorldDataAPI { /** * Get stored mod version (only for mods with registered cache). - * * @return {@link String} mod version. */ public static String getModVersion(String modID) { @@ -140,10 +116,9 @@ public class WorldDataAPI { /** * Get stored mod version as integer (only for mods with registered cache). - * * @return {@code int} mod version. */ public static int getIntModVersion(String modID) { - return ModUtil.convertModVersion(getModVersion(modID)); + return DataFixerAPI.getModVersion(getModVersion(modID)); } } diff --git a/src/main/java/ru/bclib/api/dataexchange/BaseDataHandler.java b/src/main/java/ru/bclib/api/dataexchange/BaseDataHandler.java deleted file mode 100644 index 47ca87af..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/BaseDataHandler.java +++ /dev/null @@ -1,99 +0,0 @@ -package ru.bclib.api.dataexchange; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -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 org.jetbrains.annotations.NotNull; - -import java.nio.charset.StandardCharsets; -import java.util.Objects; - -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/ru/bclib/api/dataexchange/Connector.java b/src/main/java/ru/bclib/api/dataexchange/Connector.java deleted file mode 100644 index 6f933489..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/Connector.java +++ /dev/null @@ -1,18 +0,0 @@ -package ru.bclib.api.dataexchange; - -import ru.bclib.api.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/ru/bclib/api/dataexchange/ConnectorClientside.java b/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java deleted file mode 100644 index 6e192b91..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/ConnectorClientside.java +++ /dev/null @@ -1,70 +0,0 @@ -package ru.bclib.api.dataexchange; - -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; -import net.minecraft.client.Minecraft; -import net.minecraft.client.multiplayer.ClientPacketListener; -import net.minecraft.network.FriendlyByteBuf; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.handler.DataExchange; - -/** - * 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/ru/bclib/api/dataexchange/ConnectorServerside.java b/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java deleted file mode 100644 index f8debc99..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/ConnectorServerside.java +++ /dev/null @@ -1,67 +0,0 @@ -package ru.bclib.api.dataexchange; - -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.ServerPlayer; -import net.minecraft.server.network.ServerGamePacketListenerImpl; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.handler.DataExchange; - -/** - * 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/ru/bclib/api/dataexchange/DataExchangeAPI.java b/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java deleted file mode 100644 index 4a22c6db..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/DataExchangeAPI.java +++ /dev/null @@ -1,211 +0,0 @@ -package ru.bclib.api.dataexchange; - -import com.google.common.collect.Lists; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.network.FriendlyByteBuf; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.handler.DataExchange; -import ru.bclib.api.dataexchange.handler.autosync.AutoSync; -import ru.bclib.api.dataexchange.handler.autosync.AutoSync.NeedTransferPredicate; -import ru.bclib.api.dataexchange.handler.autosync.AutoSyncID; -import ru.bclib.config.Config; -import ru.bclib.util.ModUtil; - -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, 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, 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/ru/bclib/api/dataexchange/DataHandler.java b/src/main/java/ru/bclib/api/dataexchange/DataHandler.java deleted file mode 100644 index b1043fc3..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/DataHandler.java +++ /dev/null @@ -1,274 +0,0 @@ -package ru.bclib.api.dataexchange; - -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 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 ru.bclib.BCLib; -import ru.bclib.api.dataexchange.handler.autosync.Chunker; -import ru.bclib.api.dataexchange.handler.autosync.Chunker.PacketChunkSender; - -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 PacketChunkSender sender = new 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, 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); - - abstract protected void deserializeIncomingDataOnServer(FriendlyByteBuf buf, PacketSender responseSender); - - abstract protected void runOnServerGameThread(MinecraftServer server); - - - @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, responseSender); - final Runnable runner = () -> runOnServerGameThread(server); - - 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/ru/bclib/api/dataexchange/DataHandlerDescriptor.java b/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java deleted file mode 100644 index 2f9f80e5..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/DataHandlerDescriptor.java +++ /dev/null @@ -1,49 +0,0 @@ -package ru.bclib.api.dataexchange; - -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.NotNull; - -import java.util.Objects; -import java.util.function.Supplier; - -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/ru/bclib/api/dataexchange/FileHash.java b/src/main/java/ru/bclib/api/dataexchange/FileHash.java deleted file mode 100644 index de87f686..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/FileHash.java +++ /dev/null @@ -1,161 +0,0 @@ -package ru.bclib.api.dataexchange; - -import net.minecraft.network.FriendlyByteBuf; -import org.jetbrains.annotations.NotNull; -import ru.bclib.BCLib; - -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; - -public class FileHash { - private static int ERR_DOES_NOT_EXIST = -10; - private static 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/ru/bclib/api/dataexchange/SyncFileHash.java b/src/main/java/ru/bclib/api/dataexchange/SyncFileHash.java deleted file mode 100644 index 81a3c853..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/SyncFileHash.java +++ /dev/null @@ -1,108 +0,0 @@ -package ru.bclib.api.dataexchange; - -import net.minecraft.network.FriendlyByteBuf; -import ru.bclib.api.dataexchange.handler.autosync.AutoSync.NeedTransferPredicate; -import ru.bclib.api.dataexchange.handler.autosync.AutoSyncID; - -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 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/ru/bclib/api/dataexchange/handler/DataExchange.java b/src/main/java/ru/bclib/api/dataexchange/handler/DataExchange.java deleted file mode 100644 index a11ddb6d..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/DataExchange.java +++ /dev/null @@ -1,113 +0,0 @@ -package ru.bclib.api.dataexchange.handler; - -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 net.minecraft.resources.ResourceLocation; -import ru.bclib.api.dataexchange.BaseDataHandler; -import ru.bclib.api.dataexchange.ConnectorClientside; -import ru.bclib.api.dataexchange.ConnectorServerside; -import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.api.dataexchange.DataHandlerDescriptor; - -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 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/ru/bclib/api/dataexchange/handler/autosync/AutoFileSyncEntry.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoFileSyncEntry.java deleted file mode 100644 index 83e4ff0b..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoFileSyncEntry.java +++ /dev/null @@ -1,237 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -import net.minecraft.network.FriendlyByteBuf; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.api.dataexchange.SyncFileHash; -import ru.bclib.api.dataexchange.handler.autosync.AutoSync.NeedTransferPredicate; -import ru.bclib.api.dataexchange.handler.autosync.SyncFolderDescriptor.SubFile; -import ru.bclib.util.ModUtil; -import ru.bclib.util.ModUtil.ModInfo; -import ru.bclib.util.Pair; -import ru.bclib.util.PathUtil; -import ru.bclib.util.Triple; - -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 NeedTransferPredicate needTransfer; - public final File fileName; - public final boolean requestContent; - private SyncFileHash hash; - - AutoFileSyncEntry(String modID, File fileName, boolean requestContent, NeedTransferPredicate needTransfer) { - this(modID, fileName.getName(), fileName, requestContent, needTransfer); - } - - AutoFileSyncEntry(String modID, String uniqueID, File fileName, boolean requestContent, 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 (!PathUtil.isChildOf(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) { - 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/ru/bclib/api/dataexchange/handler/autosync/AutoSync.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSync.java deleted file mode 100644 index 89a33463..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSync.java +++ /dev/null @@ -1,187 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -import net.fabricmc.loader.api.FabricLoader; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.dataexchange.SyncFileHash; -import ru.bclib.config.Configs; -import ru.bclib.config.ServerConfig; -import ru.bclib.util.PathUtil; - -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 { - public 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/ru/bclib/api/dataexchange/handler/autosync/AutoSyncID.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSyncID.java deleted file mode 100644 index 9ffbc64f..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/AutoSyncID.java +++ /dev/null @@ -1,142 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -import net.minecraft.network.FriendlyByteBuf; -import org.jetbrains.annotations.NotNull; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.config.Config; -import ru.bclib.util.ModUtil; - -import java.io.File; -import java.util.Objects; - -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/ru/bclib/api/dataexchange/handler/autosync/Chunker.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/Chunker.java deleted file mode 100644 index 33a16719..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/Chunker.java +++ /dev/null @@ -1,270 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -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 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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.BaseDataHandler; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.api.dataexchange.DataHandlerDescriptor; -import ru.bclib.api.dataexchange.handler.DataExchange; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; - -/** - * 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 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 - * 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 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()); - final boolean protocolVersion_0_4_1 = ModUtil.isLargerOrEqualVersion(bclibVersion, "0.4.1"); - - - //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 - if (protocolVersion_0_4_1) { - size = buf.readInt(); - canDownload = buf.readBoolean(); - } - else { - size = 0; - canDownload = true; - } - 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 - if (protocolVersion_0_4_1) { - 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 -> { - 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.getModVersion(e.getKey()); - final OfferedModInfo serverInfo = e.getValue(); - final boolean requestMod = !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")+ ")"); - 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, new TranslatableComponent("title.bclib.modmissmatch"), new TranslatableComponent("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 WithContentOverride) { - final WithContentOverride aidc = (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, new TranslatableComponent("title.bclib.filesync.progress"), new TranslatableComponent("message.bclib.filesync.progress")); - progress.progressStart(new TranslatableComponent("message.bclib.filesync.progress.stage.empty")); - ChunkerProgress.setProgressScreen(progress); - - DataExchangeAPI.send(new RequestFiles(files)); - } -} diff --git a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloServer.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloServer.java deleted file mode 100644 index a3abd668..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/HelloServer.java +++ /dev/null @@ -1,108 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.api.dataexchange.DataHandlerDescriptor; -import ru.bclib.config.Configs; -import ru.bclib.util.ModUtil; - -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 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, PacketSender responseSender) { - bclibVersion = ModUtil.convertModVersion(buf.readInt()); - } - - @Override - protected void runOnServerGameThread(MinecraftServer server) { - 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/ru/bclib/api/dataexchange/handler/autosync/RequestFiles.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/RequestFiles.java deleted file mode 100644 index 45579906..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/RequestFiles.java +++ /dev/null @@ -1,98 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.MinecraftServer; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.api.dataexchange.DataHandlerDescriptor; -import ru.bclib.config.Configs; - -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 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, 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) { - 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/ru/bclib/api/dataexchange/handler/autosync/SendFiles.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SendFiles.java deleted file mode 100644 index 000be5c0..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SendFiles.java +++ /dev/null @@ -1,216 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.networking.v1.PacketSender; -import net.minecraft.client.Minecraft; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.api.dataexchange.DataHandlerDescriptor; -import ru.bclib.config.Configs; -import ru.bclib.gui.screens.ConfirmRestartScreen; -import ru.bclib.util.Pair; -import ru.bclib.util.PathUtil; -import ru.bclib.util.Triple; - -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 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:"); - - //TODO: Reject files that were not in the last RequestFiles. - 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/ru/bclib/api/dataexchange/handler/autosync/SyncFolderDescriptor.java b/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SyncFolderDescriptor.java deleted file mode 100644 index bba41d5e..00000000 --- a/src/main/java/ru/bclib/api/dataexchange/handler/autosync/SyncFolderDescriptor.java +++ /dev/null @@ -1,206 +0,0 @@ -package ru.bclib.api.dataexchange.handler.autosync; - -import net.minecraft.network.FriendlyByteBuf; -import org.jetbrains.annotations.NotNull; -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.DataHandler; -import ru.bclib.api.dataexchange.FileHash; -import ru.bclib.api.dataexchange.handler.autosync.AutoSyncID.ForDirectFileRequest; -import ru.bclib.config.Configs; -import ru.bclib.util.PathUtil; - -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Stream; - -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/ru/bclib/api/datafixer/DataFixerAPI.java b/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java deleted file mode 100644 index b63505c9..00000000 --- a/src/main/java/ru/bclib/api/datafixer/DataFixerAPI.java +++ /dev/null @@ -1,612 +0,0 @@ -package ru.bclib.api.datafixer; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.Util; -import net.minecraft.client.Minecraft; -import net.minecraft.client.gui.components.toasts.SystemToast; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.client.gui.screens.worldselection.EditWorldScreen; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.nbt.StringTag; -import net.minecraft.nbt.Tag; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TranslatableComponent; -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 org.jetbrains.annotations.NotNull; -import ru.bclib.BCLib; -import ru.bclib.api.WorldDataAPI; -import ru.bclib.config.Configs; -import ru.bclib.gui.screens.AtomicProgressListener; -import ru.bclib.gui.screens.ConfirmFixScreen; -import ru.bclib.gui.screens.LevelFixErrorScreen; -import ru.bclib.gui.screens.LevelFixErrorScreen.Listener; -import ru.bclib.gui.screens.ProgressScreen; -import ru.bclib.util.Logger; - -import java.io.DataInputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -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; - -/** - * 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 static interface Callback { - public 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(); - File levelDat = levelStorageAccess.getLevelPath(LevelResource.LEVEL_DATA_FILE).toFile(); - boolean newWorld = false; - if (!levelDat.exists()) { - BCLib.LOGGER.info("Creating a new World, no fixes needed"); - newWorld = true; - } - - initializeWorldData(levelPath, newWorld); - if (newWorld) return false; - - return fixData(levelPath, levelStorageAccess.getLevelId(), showUI, onResume); - } - /** - * Initializes the DataStorage for this world. If the world is new, the patch registry is initialized to the - * current versions of the plugins. - *

- * This implementation will create a new {@link LevelStorageAccess} and call {@link #initializeWorldData(File, boolean)} - * using the provided root path. - * @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 newWorld {@code true} if this is a fresh world - */ - public static void initializeWorldData(LevelStorageSource levelSource, String levelID, boolean newWorld) { - wrapCall(levelSource, levelID, (levelStorageAccess) -> { - initializeWorldData(levelStorageAccess.getLevelPath(LevelResource.ROOT).toFile(), newWorld); - return true; - }); - } - - /** - * Initializes the DataStorage for this world. If the world is new, the patch registry is initialized to the - * current versions of the plugins. - * @param levelBaseDir Folder of the world - * @param newWorld {@code true} if this is a fresh world - * - */ - public static void initializeWorldData(File levelBaseDir, boolean newWorld){ - WorldDataAPI.load(new File(levelBaseDir, "data")); - - if (newWorld){ - getMigrationProfile().markApplied(); - WorldDataAPI.saveFile(BCLib.MOD_ID); - } - } - - @Environment(EnvType.CLIENT) - private static AtomicProgressListener showProgressScreen(){ - ProgressScreen ps = new ProgressScreen(Minecraft.getInstance().screen, new TranslatableComponent("title.bclib.datafixer.progress"), new TranslatableComponent("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((String) "Patching... {}%", percentage); - } - } - - @Override - public void resetAtomic() { - counter = new AtomicInteger(0); - } - - public void stop() { - } - - public void progressStage(Component component) { - BCLib.LOGGER.info((String) "Patcher Stage... {}%", component.getString()); - } - }; - } - } else { - progress = null; - } - - Supplier runner = () -> { - if (createBackup) { - progress.progressStage(new TranslatableComponent("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.getBoolean(Configs.MAIN_PATCH_CATEGORY, "applyPatches", true)) { - 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 = WorldDataAPI.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((Screen) null, whenFinished::accept)); - } - - private static State runDataFixes(File dir, MigrationProfile profile, AtomicProgressListener progress) { - State state = new State(); - progress.resetAtomic(); - - progress.progressStage(new TranslatableComponent("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(new TranslatableComponent("message.bclib.datafixer.progress.players")); - players.parallelStream().forEach((file) -> { - fixPlayer(profile, state, file); - progress.incAtomic(maxProgress); - }); - - progress.progressStage(new TranslatableComponent("message.bclib.datafixer.progress.level")); - fixLevel(profile, state, dir); - progress.incAtomic(maxProgress); - - progress.progressStage(new TranslatableComponent("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(new TranslatableComponent("message.bclib.datafixer.progress.regions")); - regions.parallelStream().forEach((file) -> { - fixRegion(profile, state, file); - progress.incAtomic(maxProgress); - }); - - if (!state.didFail) { - progress.progressStage(new TranslatableComponent("message.bclib.datafixer.progress.saving")); - profile.markApplied(); - WorldDataAPI.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 { - LOGGER.info("Inspecting " + file); - boolean[] changed = new boolean[1]; - RegionFile region = new RegionFile(file, file.getParentFile(), 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 = WorldDataAPI.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"); - 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 e){ - return NbtIo.read(file); - } - } - -} diff --git a/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java b/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java deleted file mode 100644 index 34951454..00000000 --- a/src/main/java/ru/bclib/api/datafixer/ForcedLevelPatch.java +++ /dev/null @@ -1,47 +0,0 @@ -package ru.bclib.api.datafixer; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import org.jetbrains.annotations.NotNull; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -/** - * 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/ru/bclib/api/datafixer/MigrationProfile.java b/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java deleted file mode 100644 index 26065093..00000000 --- a/src/main/java/ru/bclib/api/datafixer/MigrationProfile.java +++ /dev/null @@ -1,320 +0,0 @@ -package ru.bclib.api.datafixer; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import net.minecraft.nbt.NbtIo; -import net.minecraft.nbt.Tag; -import org.jetbrains.annotations.NotNull; -import ru.bclib.BCLib; -import ru.bclib.api.WorldDataAPI; -import ru.bclib.util.ModUtil; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -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}; - if (root.contains("palette")){ - ListTag items = root.getList("palette", Tag.TAG_COMPOUND); - items.forEach(inTag -> { - CompoundTag tag = (CompoundTag)inTag; - changed[0] |= profile.replaceStringFromIDs(tag, "Name"); - }); - } - - 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; i0) { - 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 = WorldDataAPI.getRootTag(patch.modID); - boolean changed = patch.getWorldDataPatcher().apply(root, this); - if (changed) { - WorldDataAPI.saveFile(patch.modID); - } - } - - for (Map.Entry> entry : worldDataIDPaths.entrySet()){ - CompoundTag root = WorldDataAPI.getRootTag(entry.getKey()); - boolean[] changed = {false}; - entry.getValue().forEach(path -> { - changed[0] |= replaceIDatPath(root, path); - }); - - if (changed[0]){ - WorldDataAPI.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/ru/bclib/api/datafixer/Patch.java b/src/main/java/ru/bclib/api/datafixer/Patch.java deleted file mode 100644 index bc64e3c5..00000000 --- a/src/main/java/ru/bclib/api/datafixer/Patch.java +++ /dev/null @@ -1,241 +0,0 @@ -package ru.bclib.api.datafixer; - -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.ListTag; -import org.jetbrains.annotations.NotNull; -import ru.bclib.util.ModUtil; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public abstract class Patch { - - private static 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 || "".equals(modID)) { - throw new RuntimeException("[INTERNAL ERROR] Patches need a valid modID!"); - } - - if (version == null || "".equals(version)) { - 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 ru.bclib.api.WorldDataAPI} 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 ru.bclib.api.WorldDataAPI}-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 ru.bclib.api.WorldDataAPI}-File. - * Paths are dot-seperated (see {@link ru.bclib.api.WorldDataAPI#getCompoundTag(String, String)}). - */ - public List getWorldDataIDPaths() { - return null; - } - -} diff --git a/src/main/java/ru/bclib/api/datafixer/PatchBiFunction.java b/src/main/java/ru/bclib/api/datafixer/PatchBiFunction.java deleted file mode 100644 index 6bd8da12..00000000 --- a/src/main/java/ru/bclib/api/datafixer/PatchBiFunction.java +++ /dev/null @@ -1,6 +0,0 @@ -package ru.bclib.api.datafixer; - -@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/ru/bclib/api/datafixer/PatchDidiFailException.java b/src/main/java/ru/bclib/api/datafixer/PatchDidiFailException.java deleted file mode 100644 index 737ba402..00000000 --- a/src/main/java/ru/bclib/api/datafixer/PatchDidiFailException.java +++ /dev/null @@ -1,10 +0,0 @@ -package ru.bclib.api.datafixer; - -public class PatchDidiFailException extends Exception { - public PatchDidiFailException(){ - super(); - } - public PatchDidiFailException(Exception e){ - super(e); - } -} diff --git a/src/main/java/ru/bclib/api/datafixer/PatchFunction.java b/src/main/java/ru/bclib/api/datafixer/PatchFunction.java deleted file mode 100644 index 7d429d68..00000000 --- a/src/main/java/ru/bclib/api/datafixer/PatchFunction.java +++ /dev/null @@ -1,6 +0,0 @@ -package ru.bclib.api.datafixer; - -@FunctionalInterface -public interface PatchFunction { - R apply(T t, MigrationProfile profile) throws PatchDidiFailException; -} diff --git a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java index 314503d4..c181a7a7 100644 --- a/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseBarrelBlockEntity.java @@ -26,25 +26,25 @@ import ru.bclib.registry.BaseBlockEntities; public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { private NonNullList inventory; private int viewerCount; - + 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); } - + public CompoundTag save(CompoundTag tag) { super.save(tag); if (!this.trySaveLootTable(tag)) { ContainerHelper.saveAllItems(tag, this.inventory); } - + return tag; } - + public void load(CompoundTag tag) { super.load(tag); this.inventory = NonNullList.withSize(this.getContainerSize(), ItemStack.EMPTY); @@ -52,57 +52,56 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { ContainerHelper.loadAllItems(tag, this.inventory); } } - + public int getContainerSize() { return 27; } - + protected NonNullList getItems() { return this.inventory; } - + protected void setItems(NonNullList list) { this.inventory = list; } - + protected Component getDefaultName() { return new TranslatableComponent("container.barrel"); } - + protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { return ChestMenu.threeRows(syncId, playerInventory, this); } - + public void startOpen(Player player) { if (!player.isSpectator()) { if (viewerCount < 0) { viewerCount = 0; } - + ++viewerCount; BlockState blockState = this.getBlockState(); if (!blockState.getValue(BarrelBlock.OPEN)) { playSound(blockState, SoundEvents.BARREL_OPEN); setOpen(blockState, true); } - + if (level != null) { scheduleUpdate(); } } } - + private void scheduleUpdate() { level.getBlockTicks().scheduleTick(getBlockPos(), getBlockState().getBlock(), 5); } - + public void tick() { if (level != null) { viewerCount = ChestBlockEntity.getOpenCount(level, worldPosition); if (viewerCount > 0) { scheduleUpdate(); - } - else { + } else { BlockState blockState = getBlockState(); if (!(blockState.getBlock() instanceof BaseBarrelBlock)) { setRemoved(); @@ -115,35 +114,27 @@ public class BaseBarrelBlockEntity extends RandomizableContainerBlockEntity { } } } - + public void stopOpen(Player player) { if (!player.isSpectator()) { --this.viewerCount; } } - + private void setOpen(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 vec3i = blockState.getValue(BarrelBlock.FACING).getNormal(); double d = (double) this.worldPosition.getX() + 0.5D + (double) vec3i.getX() / 2.0D; double e = (double) this.worldPosition.getY() + 0.5D + (double) vec3i.getY() / 2.0D; double f = (double) this.worldPosition.getZ() + 0.5D + (double) vec3i.getZ() / 2.0D; - level.playSound( - null, - d, - e, - f, - soundEvent, - SoundSource.BLOCKS, - 0.5F, - this.level.random.nextFloat() * 0.1F + 0.9F - ); + level.playSound(null, d, e, f, 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/ru/bclib/blockentities/BaseFurnaceBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java index f6d2f469..fa681007 100644 --- a/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseFurnaceBlockEntity.java @@ -15,11 +15,11 @@ public class BaseFurnaceBlockEntity extends AbstractFurnaceBlockEntity { public BaseFurnaceBlockEntity(BlockPos blockPos, BlockState blockState) { super(BaseBlockEntities.FURNACE, blockPos, blockState, RecipeType.SMELTING); } - + protected Component getDefaultName() { return new TranslatableComponent("container.furnace"); } - + protected AbstractContainerMenu createMenu(int syncId, Inventory playerInventory) { return new FurnaceMenu(syncId, playerInventory, this, this.dataAccess); } diff --git a/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java b/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java index a2ebfb31..64a9b75f 100644 --- a/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java +++ b/src/main/java/ru/bclib/blockentities/BaseSignBlockEntity.java @@ -10,7 +10,7 @@ public class BaseSignBlockEntity extends SignBlockEntity { public BaseSignBlockEntity(BlockPos blockPos, BlockState blockState) { super(blockPos, blockState); } - + @Override public BlockEntityType getType() { return BaseBlockEntities.SIGN; diff --git a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java index ad656251..2f992c86 100644 --- a/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java +++ b/src/main/java/ru/bclib/blockentities/DynamicBlockEntityType.java @@ -1,6 +1,11 @@ package ru.bclib.blockentities; +import java.util.Collections; +import java.util.Set; +import java.util.function.Supplier; + import com.google.common.collect.Sets; + import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; @@ -8,36 +13,33 @@ import net.minecraft.world.level.block.entity.BlockEntityType; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.Nullable; -import java.util.Collections; -import java.util.Set; - 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) { + @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 { + public + interface BlockEntitySupplier { T create(BlockPos blockPos, BlockState blockState); } } diff --git a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java index 9aca2c1d..5dafc0d5 100644 --- a/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAnvilBlock.java @@ -1,17 +1,22 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; 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.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; @@ -20,25 +25,15 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.CustomItemProvider; import ru.bclib.items.BaseAnvilItem; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; - -public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider, CustomItemProvider { +public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelProvider { public static final IntegerProperty DESTRUCTION = BlockProperties.DESTRUCTION; - public IntegerProperty durability; - + public BaseAnvilBlock(MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.ANVIL).mapColor(color)); } @@ -46,21 +41,35 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro @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); + builder.add(DESTRUCTION); } - + + @Override + @SuppressWarnings("deprecation") + public List getDrops(BlockState state, LootContext.Builder builder) { + ItemStack dropStack = new ItemStack(this); + int destruction = state.getValue(DESTRUCTION); + dropStack.getOrCreateTag().putInt(BaseAnvilItem.DESTRUCTION, destruction); + return Lists.newArrayList(dropStack); + } + + protected String getTop(ResourceLocation blockId, String block) { + if (block.contains("item")) { + return blockId.getPath() + "_top_0"; + } + char last = block.charAt(block.length() - 1); + return blockId.getPath() + "_top_" + last; + } + + @Override + public abstract Item asItem(); + @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) { @@ -73,7 +82,7 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro 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) { @@ -84,47 +93,4 @@ public abstract class BaseAnvilBlock extends AnvilBlock implements BlockModelPro registerBlockModel(stateId, modelLocation, blockState, modelCache); return ModelsHelper.createFacingModel(modelLocation, blockState.getValue(FACING), false, false); } - - @Override - public BlockItem getCustomItem(ResourceLocation blockID, FabricItemSettings 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, Random 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/ru/bclib/blocks/BaseAttachedBlock.java b/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java index a0e2b1af..ecf12d48 100644 --- a/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseAttachedBlock.java @@ -45,14 +45,14 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull { } 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)) { @@ -62,13 +62,13 @@ public abstract class BaseAttachedBlock extends BaseBlockNotFull { 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/ru/bclib/blocks/BaseBarkBlock.java b/src/main/java/ru/bclib/blocks/BaseBarkBlock.java index 7adca093..743ff0af 100644 --- a/src/main/java/ru/bclib/blocks/BaseBarkBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBarkBlock.java @@ -1,23 +1,23 @@ package ru.bclib.blocks; +import java.util.Optional; + import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.PatternsHelper; -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/ru/bclib/blocks/BaseBarrelBlock.java b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java index c5d8dd8b..b36f8843 100644 --- a/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBarrelBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -17,6 +24,7 @@ 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.BlockGetter; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.BarrelBlock; import net.minecraft.world.level.block.Block; @@ -25,29 +33,23 @@ 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.minecraft.world.phys.BlockHitResult; -import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseBarrelBlockEntity; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.registry.BaseBlockEntities; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; - public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { public BaseBarrelBlock(Block source) { super(FabricBlockSettings.copyOf(source).noOcclusion()); } - + @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) { @@ -55,24 +57,24 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { drop.add(new ItemStack(this.asItem())); return drop; } - + @Override - public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, BlockHitResult hit) { + public InteractionResult use(BlockState state, Level world, BlockPos pos, Player player, InteractionHand hand, + BlockHitResult hit) { if (world.isClientSide) { return InteractionResult.SUCCESS; - } - else { + } else { BlockEntity blockEntity = world.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, Random random) { BlockEntity blockEntity = world.getBlockEntity(pos); @@ -80,14 +82,15 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { ((BaseBarrelBlockEntity) blockEntity).tick(); } } - + @Override public RenderShape getRenderShape(BlockState state) { return RenderShape.MODEL; } - + @Override - public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { + 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) { @@ -95,52 +98,41 @@ public class BaseBarrelBlock extends BarrelBlock implements BlockModelProvider { } } } - + @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 { + } 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); + 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; + 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/ru/bclib/blocks/BaseBlock.java b/src/main/java/ru/bclib/blocks/BaseBlock.java index 7dd51813..97878a79 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBlock.java @@ -1,73 +1,29 @@ package ru.bclib.blocks; -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +import java.util.Collections; +import java.util.List; + 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 ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.client.models.BlockModelProvider; -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 FabricBlockSettings acceptAndReturn(Consumer customizeProperties, FabricBlockSettings settings) { - customizeProperties.accept(settings); - return settings; - } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java b/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java index 0ddc700c..6d1a0a38 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java +++ b/src/main/java/ru/bclib/blocks/BaseBlockNotFull.java @@ -6,19 +6,19 @@ 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/ru/bclib/blocks/BaseBlockWithEntity.java b/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java index 26b9cf22..718a58f7 100644 --- a/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java +++ b/src/main/java/ru/bclib/blocks/BaseBlockWithEntity.java @@ -1,25 +1,26 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; + import net.minecraft.core.BlockPos; import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.BlockGetter; 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) { diff --git a/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java b/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java index 68999421..a1b68b1d 100644 --- a/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseBookshelfBlock.java @@ -1,5 +1,11 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -13,15 +19,10 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import java.util.Collections; -import java.util.List; -import java.util.Optional; - public class BaseBookshelfBlock extends BaseBlock { public BaseBookshelfBlock(Block source) { super(FabricBlockSettings.copyOf(source)); @@ -38,14 +39,14 @@ public class BaseBookshelfBlock extends BaseBlock { } 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); } - + private ResourceLocation replacePath(ResourceLocation blockId) { String newPath = blockId.getPath().replace("_bookshelf", ""); return new ResourceLocation(blockId.getNamespace(), newPath); diff --git a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java index 289eef21..5f8642ce 100644 --- a/src/main/java/ru/bclib/blocks/BaseButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseButtonBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -13,32 +20,26 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelProvider { - + private final Block parent; - + protected BaseButtonBlock(Block parent, Properties properties, boolean sensitive) { super(sensitive, properties); 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) { @@ -46,56 +47,38 @@ public abstract class BaseButtonBlock extends ButtonBlock implements BlockModelP 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); + 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); + 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; + 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; + 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/ru/bclib/blocks/BaseChainBlock.java b/src/main/java/ru/bclib/blocks/BaseChainBlock.java index 9abdb58e..c2a14fe3 100644 --- a/src/main/java/ru/bclib/blocks/BaseChainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChainBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -13,52 +20,47 @@ import net.minecraft.world.level.block.ChainBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.MaterialColor; import net.minecraft.world.level.storage.loot.LootContext; -import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class BaseChainBlock extends ChainBlock implements BlockModelProvider, RenderLayerProvider { +public class BaseChainBlock extends ChainBlock implements BlockModelProvider, IRenderTyped { public BaseChainBlock(MaterialColor color) { super(FabricBlockSettings.copyOf(Blocks.CHAIN).mapColor(color)); } - + @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()); + 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/ru/bclib/blocks/BaseChestBlock.java b/src/main/java/ru/bclib/blocks/BaseChestBlock.java index 6ebc000d..2b89b5d2 100644 --- a/src/main/java/ru/bclib/blocks/BaseChestBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseChestBlock.java @@ -1,28 +1,30 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Optional; + +import net.minecraft.core.BlockPos; +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; 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.BlockGetter; 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; import ru.bclib.registry.BaseBlockEntities; -import java.util.List; -import java.util.Optional; - public class BaseChestBlock extends ChestBlock implements BlockModelProvider { private final Block parent; @@ -35,22 +37,23 @@ public class BaseChestBlock extends ChestBlock implements BlockModelProvider { public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return BaseBlockEntities.CHEST.create(blockPos, blockState); } - + @Override @SuppressWarnings("deprecation") - public List getDrops(BlockState state, LootContext.Builder builder) { + 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) { diff --git a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java index 8a977e30..faecc6e5 100644 --- a/src/main/java/ru/bclib/blocks/BaseComposterBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseComposterBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -11,63 +18,56 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseComposterBlock extends ComposterBlock implements BlockModelProvider { public BaseComposterBlock(Block source) { super(FabricBlockSettings.copyOf(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); - + MultiPartBuilder builder = MultiPartBuilder.create(stateDefinition); LEVEL.getPossibleValues().forEach(level -> { if (level > 0) { ResourceLocation contentId; if (level > 7) { contentId = new ResourceLocation("block/composter_contents_ready"); - } - else { + } 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/ru/bclib/blocks/BaseCraftingTableBlock.java b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java index 6be8cbb9..570758fe 100644 --- a/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCraftingTableBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -10,41 +17,34 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.CraftingTableBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; -import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Optional; public class BaseCraftingTableBlock extends CraftingTableBlock implements BlockModelProvider { public BaseCraftingTableBlock(Block source) { super(FabricBlockSettings.copyOf(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) { 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"); diff --git a/src/main/java/ru/bclib/blocks/BaseCropBlock.java b/src/main/java/ru/bclib/blocks/BaseCropBlock.java index 18a16c06..e395d338 100644 --- a/src/main/java/ru/bclib/blocks/BaseCropBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseCropBlock.java @@ -1,6 +1,11 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Random; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -26,10 +31,6 @@ import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.util.BlocksHelper; import ru.bclib.util.MHelper; -import java.util.Collections; -import java.util.List; -import java.util.Random; - public class BaseCropBlock extends BasePlantBlock { private static final VoxelShape SHAPE = Block.box(2, 0, 2, 14, 14, 14); public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3); @@ -39,11 +40,11 @@ public class BaseCropBlock extends BasePlantBlock { public BaseCropBlock(Item drop, Block... terrain) { super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.HOES) - .breakByHand(true) - .sound(SoundType.GRASS) - .randomTicks() - .noCollission()); + .breakByTool(FabricToolTags.HOES) + .breakByHand(true) + .sound(SoundType.GRASS) + .randomTicks() + .noCollission()); this.drop = drop; this.terrain = terrain; this.registerDefaultState(defaultBlockState().setValue(AGE, 0)); @@ -56,7 +57,7 @@ public class BaseCropBlock extends BasePlantBlock { @Override protected boolean isTerrain(BlockState state) { - for (Block block : terrain) { + for (Block block: terrain) { if (state.is(block)) { return true; } @@ -105,7 +106,7 @@ public class BaseCropBlock extends BasePlantBlock { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return state.getValue(AGE) < 3; } - + @Override @SuppressWarnings("deprecation") public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { diff --git a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java index 2e8f8d8b..1c2c6245 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoorBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -16,37 +23,32 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class BaseDoorBlock extends DoorBlock implements RenderLayerProvider, BlockModelProvider { +public class BaseDoorBlock extends DoorBlock implements IRenderTyped, BlockModelProvider { public BaseDoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3F, 3F).noOcclusion()); } - + @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(); + else + return Collections.emptyList(); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation resourceLocation, BlockState blockState) { @@ -62,12 +64,11 @@ public class BaseDoorBlock extends DoorBlock implements RenderLayerProvider, Blo case TOP: pattern = PatternsHelper.createJson(BasePatterns.BLOCK_DOOR_TOP, resourceLocation); break; - default: - break; + default: break; } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { @@ -80,27 +81,23 @@ public class BaseDoorBlock extends DoorBlock implements RenderLayerProvider, Blo case EAST: if (hinge && open) { rotation = BlockModelRotation.X0_Y90; - } - else if (open) { + } else if (open) { rotation = BlockModelRotation.X0_Y270; } break; case SOUTH: if (!hinge && !open || hinge && !open) { rotation = BlockModelRotation.X0_Y90; - } - else if (hinge) { + } else if (hinge) { rotation = BlockModelRotation.X0_Y180; } break; case WEST: if (!hinge && !open || hinge && !open) { rotation = BlockModelRotation.X0_Y180; - } - else if (hinge) { + } else if (hinge) { rotation = BlockModelRotation.X0_Y270; - } - else { + } else { rotation = BlockModelRotation.X0_Y90; } break; @@ -108,20 +105,17 @@ public class BaseDoorBlock extends DoorBlock implements RenderLayerProvider, Blo default: if (!hinge && !open || hinge && !open) { rotation = BlockModelRotation.X0_Y270; - } - else if (!hinge) { + } else if (!hinge) { rotation = BlockModelRotation.X0_Y180; } break; } - ResourceLocation modelId = new ResourceLocation( - stateId.getNamespace(), - "block/" + stateId.getPath() + "_" + doorType - ); + 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)) { @@ -134,30 +128,34 @@ public class BaseDoorBlock extends DoorBlock implements RenderLayerProvider, Blo } return DoorType.BOTTOM; } - + private boolean isHinge(DoorHingeSide hingeSide, boolean open) { boolean isHinge = hingeSide == DoorHingeSide.RIGHT; return isHinge && !open || !isHinge && open; } - + protected enum DoorType implements StringRepresentable { - BOTTOM_HINGE("bottom_hinge"), TOP_HINGE("top_hinge"), BOTTOM("bottom"), TOP("top"); - + 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; + 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/ru/bclib/blocks/BaseDoublePlantBlock.java b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java index ad065758..73f0ed6c 100644 --- a/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseDoublePlantBlock.java @@ -1,6 +1,10 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Random; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -31,34 +35,31 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; -import java.util.List; -import java.util.Random; - @SuppressWarnings("deprecation") -public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { +public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); public static final IntegerProperty ROTATION = BlockProperties.ROTATION; public static final BooleanProperty TOP = BooleanProperty.create("top"); public BaseDoublePlantBlock() { super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); } public BaseDoublePlantBlock(int light) { super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .lightLevel((state) -> state.getValue(TOP) ? light : 0) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .lightLevel((state) -> state.getValue(TOP) ? light : 0) + .noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(TOP, false)); } @@ -66,18 +67,18 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements R protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { stateManager.add(TOP, ROTATION); } - + @Override 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 public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); @@ -90,7 +91,7 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements R 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 @@ -110,10 +111,7 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements R } ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { @@ -125,26 +123,20 @@ public abstract class BaseDoublePlantBlock extends BaseBlockNotFull implements R 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 world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity( - world, - pos.getX() + 0.5, - pos.getY() + 0.5, - pos.getZ() + 0.5, - new ItemStack(this) - ); + ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); world.addFreshEntity(item); } diff --git a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java index 8308330e..85adff6e 100644 --- a/src/main/java/ru/bclib/blocks/BaseFenceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFenceBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -13,17 +20,11 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.ModelsHelper.MultiPartBuilder; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { private final Block parent; @@ -32,13 +33,13 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { super(FabricBlockSettings.copyOf(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) { @@ -46,7 +47,7 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_FENCE, parentId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -61,34 +62,27 @@ public class BaseFenceBlock extends FenceBlock implements BlockModelProvider { } 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 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); - + MultiPartBuilder builder = 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(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/ru/bclib/blocks/BaseFurnaceBlock.java b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java index 09958ec8..925a3e45 100644 --- a/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseFurnaceBlock.java @@ -26,22 +26,22 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseFurnaceBlockEntity; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; import ru.bclib.registry.BaseBlockEntities; import java.util.List; import java.util.Map; import java.util.Optional; -public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider, RenderLayerProvider { +public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider, IRenderTyped { public BaseFurnaceBlock(Block source) { super(FabricBlockSettings.copyOf(source).luminance(state -> state.getValue(LIT) ? 13 : 0)); } - + @Override public BlockEntity newBlockEntity(BlockPos blockPos, BlockState blockState) { return new BaseFurnaceBlockEntity(blockPos, blockState); @@ -55,7 +55,7 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider player.awardStat(Stats.INTERACT_WITH_FURNACE); } } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -69,34 +69,34 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider textures.put("%front%", blockName + "_front_on"); textures.put("%glow%", blockName + "_glow"); pattern = PatternsHelper.createJson(BasePatterns.BLOCK_FURNACE_LIT, textures); - } - else { + } 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); + 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) { @@ -110,19 +110,15 @@ public class BaseFurnaceBlock extends FurnaceBlock implements BlockModelProvider } 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 - ); + return level.isClientSide ? null : createTickerHelper(blockEntityType, blockEntityType2, AbstractFurnaceBlockEntity::serverTick); } } diff --git a/src/main/java/ru/bclib/blocks/BaseGateBlock.java b/src/main/java/ru/bclib/blocks/BaseGateBlock.java index b49e5b51..d765ca2d 100644 --- a/src/main/java/ru/bclib/blocks/BaseGateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseGateBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -12,16 +19,10 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider { private final Block parent; @@ -30,19 +31,19 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider super(FabricBlockSettings.copyOf(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) { @@ -51,27 +52,23 @@ public class BaseGateBlock extends FenceGateBlock implements BlockModelProvider 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); + 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); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), + "block/" + stateId.getPath() + state); registerBlockModel(stateId, modelId, blockState, modelCache); return ModelsHelper.createFacingModel(modelId, blockState.getValue(FACING), true, false); } diff --git a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java index d43d8fdf..93939d8f 100644 --- a/src/main/java/ru/bclib/blocks/BaseLadderBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLadderBlock.java @@ -1,52 +1,159 @@ package ru.bclib.blocks; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; 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.resources.ResourceLocation; -import net.minecraft.world.item.ItemStack; +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.Block; -import net.minecraft.world.level.block.LadderBlock; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.HorizontalDirectionalBlock; +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.storage.loot.LootContext; -import org.jetbrains.annotations.Nullable; +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.DirectionProperty; +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 ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; +import ru.bclib.util.BlocksHelper; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; +@SuppressWarnings("deprecation") +public class BaseLadderBlock extends BaseBlockNotFull implements IRenderTyped, BlockModelProvider { + public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; + public static final BooleanProperty WATERLOGGED = BlockStateProperties.WATERLOGGED; + protected static final VoxelShape EAST_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 3.0D, 16.0D, 16.0D); + protected static final VoxelShape WEST_SHAPE = Block.box(13.0D, 0.0D, 0.0D, 16.0D, 16.0D, 16.0D); + protected static final VoxelShape SOUTH_SHAPE = Block.box(0.0D, 0.0D, 0.0D, 16.0D, 16.0D, 3.0D); + protected static final VoxelShape NORTH_SHAPE = Block.box(0.0D, 0.0D, 13.0D, 16.0D, 16.0D, 16.0D); -public class BaseLadderBlock extends LadderBlock implements RenderLayerProvider, BlockModelProvider { public BaseLadderBlock(Block block) { super(FabricBlockSettings.copyOf(block).noOcclusion()); } - + + @Override + protected void createBlockStateDefinition(StateDefinition.Builder stateManager) { + stateManager.add(FACING); + stateManager.add(WATERLOGGED); + } + + @Override + public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { + return switch (state.getValue(FACING)) { + case SOUTH -> SOUTH_SHAPE; + case WEST -> WEST_SHAPE; + case EAST -> EAST_SHAPE; + default -> NORTH_SHAPE; + }; + } + + private boolean canPlaceOn(BlockGetter world, BlockPos pos, Direction side) { + BlockState blockState = world.getBlockState(pos); + return !blockState.isSignalSource() && blockState.isFaceSturdy(world, pos, side); + } + + @Override + public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { + Direction direction = state.getValue(FACING); + return canPlaceOn(world, pos.relative(direction.getOpposite()), direction); + } + + @Override + public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, + LevelAccessor world, BlockPos pos, BlockPos neighborPos) { + if (facing.getOpposite() == state.getValue(FACING) && !state.canSurvive(world, pos)) { + return Blocks.AIR.defaultBlockState(); + } else { + if (state.getValue(WATERLOGGED)) { + world.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); + } + + return super.updateShape(state, facing, neighborState, world, pos, neighborPos); + } + } + + @Override + public BlockState getStateForPlacement(BlockPlaceContext ctx) { + BlockState blockState; + if (!ctx.replacingClickedOnBlock()) { + blockState = ctx.getLevel().getBlockState(ctx.getClickedPos().relative(ctx.getClickedFace().getOpposite())); + if (blockState.getBlock() == this && blockState.getValue(FACING) == ctx.getClickedFace()) { + return null; + } + } + + blockState = defaultBlockState(); + LevelReader worldView = ctx.getLevel(); + BlockPos blockPos = ctx.getClickedPos(); + FluidState fluidState = ctx.getLevel().getFluidState(ctx.getClickedPos()); + Direction[] directions = ctx.getNearestLookingDirections(); + + for (Direction direction : directions) { + if (direction.getAxis().isHorizontal()) { + blockState = blockState.setValue(FACING, direction.getOpposite()); + if (blockState.canSurvive(worldView, blockPos)) { + return blockState.setValue(WATERLOGGED, fluidState.getType() == Fluids.WATER); + } + } + } + + return null; + } + + @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); + } + + @Override + public FluidState getFluidState(BlockState state) { + return state.getValue(WATERLOGGED) ? Fluids.WATER.getSource(false) : super.getFluidState(state); + } + @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) { @@ -54,10 +161,4 @@ public class BaseLadderBlock extends LadderBlock implements RenderLayerProvider, 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/ru/bclib/blocks/BaseLeavesBlock.java b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java index 3dd32197..4e644f8e 100644 --- a/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseLeavesBlock.java @@ -1,6 +1,10 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.client.renderer.block.model.BlockModel; @@ -15,63 +19,49 @@ 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 ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.MHelper; -import java.util.Collections; -import java.util.List; -import java.util.function.Consumer; - -public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, RenderLayerProvider { - protected final Block sapling; - - private static FabricBlockSettings makeLeaves(MaterialColor color) { - return FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) - .mapColor(color) - .breakByTool(FabricToolTags.HOES) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .allowsSpawning((state, world, pos, type) -> false) - .suffocates((state, world, pos) -> false) - .blockVision((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).luminance(light))); - this.sapling = sapling; - } +public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, IRenderTyped { + private final Block sapling; public BaseLeavesBlock(Block sapling, MaterialColor color) { - super(makeLeaves(color)); + super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) + .mapColor(color) + .breakByTool(FabricToolTags.HOES) + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .isValidSpawn((state, world, pos, type) -> false) + .isSuffocating((state, world, pos) -> false) + .isViewBlocking((state, world, pos) -> false)); this.sapling = sapling; } public BaseLeavesBlock(Block sapling, MaterialColor color, int light) { - super(makeLeaves(color).lightLevel(light)); + super(FabricBlockSettings.copyOf(Blocks.OAK_LEAVES) + .mapColor(color) + .luminance(light) + .breakByTool(FabricToolTags.HOES) + .breakByTool(FabricToolTags.SHEARS) + .isValidSpawn((state, world, pos, type) -> false) + .isSuffocating((state, world, pos) -> false) + .isViewBlocking((state, world, pos) -> false)); this.sapling = sapling; } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); if (tool != null) { - if (FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { + if (FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Collections.singletonList(new ItemStack(this)); } int fortune = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); @@ -82,7 +72,7 @@ public class BaseLeavesBlock extends LeavesBlock implements BlockModelProvider, } return MHelper.RANDOM.nextInt(16) == 0 ? Lists.newArrayList(new ItemStack(sapling)) : Lists.newArrayList(); } - + @Override public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); diff --git a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java index 5c64bf7f..d4ecb9bf 100644 --- a/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseMetalBarsBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -14,30 +21,24 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.IronBarsBlock; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.storage.loot.LootContext; -import org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, RenderLayerProvider { +public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvider, IRenderTyped { public BaseMetalBarsBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(5.0F, 6.0F).noOcclusion()); } - + @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")) { @@ -50,13 +51,13 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi 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) { @@ -71,40 +72,32 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi } 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 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(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(); - + 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)) { @@ -112,7 +105,7 @@ public class BaseMetalBarsBlock extends IronBarsBlock implements BlockModelProvi } return super.skipRendering(state, stateFrom, direction); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; diff --git a/src/main/java/ru/bclib/blocks/BaseOreBlock.java b/src/main/java/ru/bclib/blocks/BaseOreBlock.java index f529c082..9f0bfaf2 100644 --- a/src/main/java/ru/bclib/blocks/BaseOreBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseOreBlock.java @@ -1,5 +1,9 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Random; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; @@ -9,7 +13,6 @@ 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.OreBlock; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.block.state.BlockState; @@ -17,44 +20,32 @@ 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 ru.bclib.interfaces.BlockModelProvider; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.util.MHelper; -import java.util.Collections; -import java.util.List; - public class BaseOreBlock extends OreBlock implements BlockModelProvider { private final Item dropItem; private final int minCount; private final int maxCount; public BaseOreBlock(Item drop, int minCount, int maxCount, int experience) { - this(drop, minCount, maxCount, experience, FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) - .hardness(3F) - .resistance(9F) - .requiresCorrectToolForDrops() - .sound(SoundType.STONE)); - - } - - public BaseOreBlock(Item drop, int minCount, int maxCount, int experience, Properties properties) { - super(properties, UniformInt.of(experience>0?1:0, experience)); + super(FabricBlockSettings.of(Material.STONE, MaterialColor.SAND) + .hardness(3F) + .resistance(9F) + .requiresCorrectToolForDrops() + .sound(SoundType.STONE), UniformInt.of(1, experience)); this.dropItem = drop; this.minCount = minCount; this.maxCount = maxCount; } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { - return getDroppedItems(this, dropItem, maxCount, minCount, state, builder); - } - - public static List getDroppedItems(ItemLike block, Item dropItem, int maxCount, int minCount, BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); if (tool != null && tool.isCorrectToolForDrops(state)) { if (EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { - return Collections.singletonList(new ItemStack(block)); + return Collections.singletonList(new ItemStack(this)); } int count; int enchantment = EnchantmentHelper.getItemEnchantmentLevel(Enchantments.BLOCK_FORTUNE, tool); @@ -65,15 +56,14 @@ public class BaseOreBlock extends OreBlock implements BlockModelProvider { return Collections.singletonList(new ItemStack(dropItem, max)); } count = MHelper.randRange(min, max, MHelper.RANDOM); - } - else { + } else { count = MHelper.randRange(minCount, maxCount, MHelper.RANDOM); } return Collections.singletonList(new ItemStack(dropItem, count)); } return Collections.emptyList(); } - + @Override public BlockModel getItemModel(ResourceLocation resourceLocation) { return getBlockModel(resourceLocation, defaultBlockState()); diff --git a/src/main/java/ru/bclib/blocks/BasePathBlock.java b/src/main/java/ru/bclib/blocks/BasePathBlock.java index d39e1891..75060542 100644 --- a/src/main/java/ru/bclib/blocks/BasePathBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePathBlock.java @@ -1,6 +1,14 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import com.google.common.collect.Maps; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -20,22 +28,16 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; - @SuppressWarnings("deprecation") public class BasePathBlock extends BaseBlockNotFull { private static final VoxelShape SHAPE = Block.box(0, 0, 0, 16, 15, 16); - + private Block baseBlock; - + public BasePathBlock(Block source) { super(FabricBlockSettings.copyOf(source).isValidSpawn((state, world, pos, type) -> false)); this.baseBlock = Blocks.DIRT; @@ -70,7 +72,7 @@ public class BasePathBlock extends BaseBlockNotFull { public BlockModel getItemModel(ResourceLocation blockId) { return getBlockModel(blockId, defaultBlockState()); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -85,7 +87,7 @@ public class BasePathBlock extends BaseBlockNotFull { 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) { diff --git a/src/main/java/ru/bclib/blocks/BasePlantBlock.java b/src/main/java/ru/bclib/blocks/BasePlantBlock.java index 23114bfb..b3181e9d 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantBlock.java @@ -1,14 +1,14 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Random; + import com.google.common.collect.Lists; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; -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.world.entity.item.ItemEntity; import net.minecraft.world.item.ItemStack; @@ -30,19 +30,11 @@ 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 org.jetbrains.annotations.Nullable; -import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.ModelsHelper; -import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerProvider; - -import java.util.List; -import java.util.Optional; -import java.util.Random; +import ru.bclib.interfaces.IRenderTyped; @SuppressWarnings("deprecation") -public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { +public abstract class BasePlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public BasePlantBlock() { @@ -55,44 +47,44 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderL public BasePlantBlock(boolean replaceable) { super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .noCollission()); } public BasePlantBlock(boolean replaceable, int light) { super(FabricBlockSettings.of(replaceable ? Material.REPLACEABLE_PLANT : Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.GRASS) + .noCollission()); } public BasePlantBlock(Properties settings) { super(settings); } - + protected abstract boolean isTerrain(BlockState state); - + @Override 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 public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); return isTerrain(down); } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -106,10 +98,7 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderL @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { @@ -121,40 +110,20 @@ public abstract class BasePlantBlock extends BaseBlockNotFull implements RenderL 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 world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity( - world, - pos.getX() + 0.5, - pos.getY() + 0.5, - pos.getZ() + 0.5, - new ItemStack(this) - ); + ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); world.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/ru/bclib/blocks/BasePlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java index 4d8ce1b0..e78a0189 100644 --- a/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePlantWithAgeBlock.java @@ -1,5 +1,7 @@ package ru.bclib.blocks; +import java.util.Random; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -13,18 +15,16 @@ import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.material.Material; -import java.util.Random; - public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public static final IntegerProperty AGE = BlockProperties.AGE; public BasePlantWithAgeBlock() { this(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .randomTicks() - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .randomTicks() + .noCollission()); } public BasePlantWithAgeBlock(Properties settings) { @@ -53,7 +53,7 @@ public abstract class BasePlantWithAgeBlock extends BasePlantBlock { public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override @SuppressWarnings("deprecation") public void tick(BlockState state, ServerLevel world, BlockPos pos, Random random) { diff --git a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java index 77d2cacb..9cd483f4 100644 --- a/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BasePressurePlateBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -12,16 +19,10 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BasePressurePlateBlock extends PressurePlateBlock implements BlockModelProvider { private final Block parent; @@ -30,19 +31,19 @@ public class BasePressurePlateBlock extends PressurePlateBlock implements BlockM super(rule, FabricBlockSettings.copyOf(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) { @@ -50,18 +51,18 @@ public class BasePressurePlateBlock extends PressurePlateBlock implements BlockM Optional pattern; if (blockState.getValue(POWERED)) { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); - } - else { + } 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); + 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/ru/bclib/blocks/BaseRotatedPillarBlock.java b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java index dc1560fa..e5d3af50 100644 --- a/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseRotatedPillarBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -11,15 +18,9 @@ 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 org.jetbrains.annotations.Nullable; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockModelProvider { public BaseRotatedPillarBlock(Properties settings) { @@ -29,26 +30,26 @@ public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockM public BaseRotatedPillarBlock(Block block) { super(FabricBlockSettings.copyOf(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) { @@ -56,7 +57,7 @@ public class BaseRotatedPillarBlock extends RotatedPillarBlock implements BlockM 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/ru/bclib/blocks/BaseSignBlock.java b/src/main/java/ru/bclib/blocks/BaseSignBlock.java index 655dff5a..5eeb16a0 100644 --- a/src/main/java/ru/bclib/blocks/BaseSignBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSignBlock.java @@ -1,8 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.core.BlockPos; @@ -14,7 +18,6 @@ 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.ItemStack; import net.minecraft.world.item.context.BlockPlaceContext; import net.minecraft.world.level.BlockGetter; @@ -39,18 +42,14 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.blockentities.BaseSignBlockEntity; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.CustomItemProvider; +import ru.bclib.interfaces.ISpetialItem; import ru.bclib.util.BlocksHelper; -import java.util.Collections; -import java.util.List; - @SuppressWarnings("deprecation") -public class BaseSignBlock extends SignBlock implements BlockModelProvider, CustomItemProvider { +public class BaseSignBlock extends SignBlock implements BlockModelProvider, ISpetialItem { public static final IntegerProperty ROTATION = BlockStateProperties.ROTATION_16; public static final BooleanProperty FLOOR = BooleanProperty.create("floor"); private static final VoxelShape[] WALL_SHAPES = new VoxelShape[] { @@ -59,28 +58,25 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, Cust 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(FabricBlockSettings.copyOf(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.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); @@ -94,26 +90,24 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, Cust if (!world.isClientSide) { sign.setAllowedPlayerEditor(placer.getUUID()); ((ServerPlayer) placer).connection.send(new ClientboundOpenSignEditorPacket(pos)); - } - else { + } 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.getLiquidTicks().scheduleTick(pos, Fluids.WATER, Fluids.WATER.getTickDelay(world)); } if (!canSurvive(state, world, pos)) { - return state.getValue(WATERLOGGED) ? state.getFluidState() - .createLegacyBlock() : Blocks.AIR.defaultBlockState(); + 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)) { @@ -124,51 +118,48 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, Cust 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) { + 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 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((Integer) state.getValue(ROTATION), 16)); } - + @Override public BlockState mirror(BlockState state, Mirror mirror) { return state.setValue(ROTATION, mirror.mirror((Integer) state.getValue(ROTATION), 16)); @@ -178,21 +169,26 @@ public class BaseSignBlock extends SignBlock implements BlockModelProvider, Cust 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) { // TODO Auto-generated method stub return super.canPlaceLiquid(world, pos, state, fluid); } - + @Override public boolean placeLiquid(LevelAccessor world, BlockPos pos, BlockState state, FluidState fluidState) { // TODO Auto-generated method stub return super.placeLiquid(world, pos, state, fluidState); } - + @Override - public BlockItem getCustomItem(ResourceLocation blockID, FabricItemSettings settings) { - return new BlockItem(this, settings.maxCount(16)); + public int getStackSize() { + return 16; + } + + @Override + public boolean canPlaceOnWater() { + return false; } } \ No newline at end of file diff --git a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java index 80550b77..73c2e109 100644 --- a/src/main/java/ru/bclib/blocks/BaseSlabBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseSlabBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -14,16 +21,10 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { private final Block parent; @@ -32,19 +33,19 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { super(FabricBlockSettings.copyOf(source)); 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) { @@ -52,21 +53,18 @@ public class BaseSlabBlock extends SlabBlock implements BlockModelProvider { Optional pattern; if (blockState.getValue(TYPE) == SlabType.DOUBLE) { pattern = PatternsHelper.createBlockSimple(parentId); - } - else { + } 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 - ); + 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); diff --git a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java index 7e9de0a0..2f057e78 100644 --- a/src/main/java/ru/bclib/blocks/BaseStairsBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStairsBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -15,16 +22,10 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseStairsBlock extends StairBlock implements BlockModelProvider { @@ -40,13 +41,13 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider { 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) { @@ -67,7 +68,7 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider { } return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public UnbakedModel getModelVariant(ResourceLocation stateId, BlockState blockState, Map modelCache) { @@ -76,21 +77,21 @@ public class BaseStairsBlock extends StairBlock implements BlockModelProvider { switch (shape) { case INNER_LEFT: case INNER_RIGHT: - state = "_inner"; - break; + state = "_inner"; break; case OUTER_LEFT: case OUTER_RIGHT: - state = "_outer"; - break; + state = "_outer"; break; default: state = ""; } 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; + 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)) { diff --git a/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java index 6c6bf59b..aabc865b 100644 --- a/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStoneButtonBlock.java @@ -6,11 +6,11 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.world.level.block.Block; public class BaseStoneButtonBlock extends BaseButtonBlock { - + public BaseStoneButtonBlock(Block source) { super(source, FabricBlockSettings.copyOf(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/ru/bclib/blocks/BaseStripableLogBlock.java b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java index eb82ebbe..a552e9fc 100644 --- a/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseStripableLogBlock.java @@ -30,11 +30,7 @@ public class BaseStripableLogBlock extends BaseRotatedPillarBlock { if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { 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 - ); + world.setBlock(pos, striped.defaultBlockState().setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), 11); if (!player.isCreative()) { player.getMainHandItem().hurt(1, world.random, (ServerPlayer) player); } diff --git a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java index 96b77c0e..fd0537c1 100644 --- a/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTerrainBlock.java @@ -1,6 +1,15 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +import org.jetbrains.annotations.Nullable; + import com.google.common.collect.Maps; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -32,41 +41,30 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.sound.BlockSounds; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; - @SuppressWarnings("deprecation") public class BaseTerrainBlock extends BaseBlock { + private final Block baseBlock; private Block pathBlock; public BaseTerrainBlock(Block baseBlock, MaterialColor color) { - super(FabricBlockSettings - .copyOf(baseBlock) - .materialColor(color) - .sound(BlockSounds.TERRAIN_SOUND) - .randomTicks() - ); + super(FabricBlockSettings.copyOf(baseBlock).materialColor(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 && FabricToolTags.SHOVELS.contains(player.getMainHandItem().getItem())) { @@ -88,16 +86,16 @@ public class BaseTerrainBlock extends BaseBlock { if (tool != null && EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Collections.singletonList(new ItemStack(this)); } - return Collections.singletonList(new ItemStack(getBaseBlock())); + return Collections.singletonList(new ItemStack(Blocks.END_STONE)); } @Override public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { if (random.nextInt(16) == 0 && !canStay(state, world, pos)) { - world.setBlockAndUpdate(pos, getBaseBlock().defaultBlockState()); + world.setBlockAndUpdate(pos, Blocks.END_STONE.defaultBlockState()); } } - + public boolean canStay(BlockState state, LevelReader worldView, BlockPos pos) { BlockPos blockPos = pos.above(); BlockState blockState = worldView.getBlockState(blockPos); @@ -108,15 +106,7 @@ public class BaseTerrainBlock extends BaseBlock { return false; } else { - int i = LayerLightEngine.getLightBlockInto( - worldView, - state, - pos, - blockState, - blockPos, - Direction.UP, - blockState.getLightBlock(worldView, blockPos) - ); + int i = LayerLightEngine.getLightBlockInto(worldView, state, pos, blockState, blockPos, Direction.UP, blockState.getLightBlock(worldView, blockPos)); return i < 5; } } @@ -126,11 +116,11 @@ public class BaseTerrainBlock extends BaseBlock { 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()); + ResourceLocation baseId = Registry.BLOCK.getKey(baseBlock); String modId = blockId.getNamespace(); String path = blockId.getPath(); String bottom = baseId.getNamespace() + ":block/" + baseId.getPath(); @@ -141,7 +131,7 @@ public class BaseTerrainBlock extends BaseBlock { 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) { diff --git a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java index 7e4c0ba7..b0167f0e 100644 --- a/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseTrapdoorBlock.java @@ -1,5 +1,13 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -13,25 +21,18 @@ import net.minecraft.world.level.block.TrapDoorBlock; 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class BaseTrapdoorBlock extends TrapDoorBlock implements RenderLayerProvider, BlockModelProvider { +public class BaseTrapdoorBlock extends TrapDoorBlock implements IRenderTyped, BlockModelProvider { public BaseTrapdoorBlock(Block source) { super(FabricBlockSettings.copyOf(source).strength(3.0F, 3.0F).noOcclusion()); } - + @Override @SuppressWarnings("deprecation") public List getDrops(BlockState state, LootContext.Builder builder) { @@ -42,32 +43,28 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements RenderLayerProvi 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")); - } + 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) { @@ -90,8 +87,7 @@ public class BaseTrapdoorBlock extends TrapDoorBlock implements RenderLayerProvi case WEST: y = (isTop && isOpen) ? 90 : 270; break; - default: - break; + default: break; } BlockModelRotation rotation = BlockModelRotation.by(x, y); return ModelsHelper.createMultiVariant(modelId, rotation.getRotation(), false); diff --git a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java index 2c226cf4..2254146b 100644 --- a/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseUnderwaterWallPlantBlock.java @@ -18,19 +18,19 @@ public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock im public BaseUnderwaterWallPlantBlock() { super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .noCollission()); } public BaseUnderwaterWallPlantBlock(int light) { super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.WET_GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.WET_GRASS) + .noCollission()); } public BaseUnderwaterWallPlantBlock(Properties settings) { @@ -41,7 +41,7 @@ public abstract class BaseUnderwaterWallPlantBlock extends BaseWallPlantBlock im 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; diff --git a/src/main/java/ru/bclib/blocks/BaseVineBlock.java b/src/main/java/ru/bclib/blocks/BaseVineBlock.java index 67688cba..108dc183 100644 --- a/src/main/java/ru/bclib/blocks/BaseVineBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseVineBlock.java @@ -1,6 +1,10 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Random; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -30,14 +34,11 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.blocks.BlockProperties.TripleShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; import ru.bclib.util.BlocksHelper; -import java.util.List; -import java.util.Random; - @SuppressWarnings("deprecation") -public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock { +public class BaseVineBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock { public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; private static final VoxelShape VOXEL_SHAPE = Block.box(2, 0, 2, 14, 16, 14); @@ -51,11 +52,11 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid public BaseVineBlock(int light, boolean bottomOnly) { super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .lightLevel((state) -> bottomOnly ? state.getValue(SHAPE) == TripleShape.BOTTOM ? light : 0 : light) + .noCollission()); this.registerDefaultState(this.stateDefinition.any().setValue(SHAPE, TripleShape.BOTTOM)); } @@ -63,13 +64,13 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid 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); } - + @Override public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; @@ -78,7 +79,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid 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); @@ -88,15 +89,17 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid 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); + 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); } } @@ -104,10 +107,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { @@ -119,7 +119,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; } - + @Override public boolean isValidBonemealTarget(BlockGetter world, BlockPos pos, BlockState state, boolean isClient) { while (world.getBlockState(pos).getBlock() == this) { @@ -127,7 +127,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid } return world.getBlockState(pos).isAir(); } - + @Override public boolean isBonemealSuccess(Level world, Random random, BlockPos pos, BlockState state) { while (world.getBlockState(pos).getBlock() == this) { @@ -135,7 +135,7 @@ public class BaseVineBlock extends BaseBlockNotFull implements RenderLayerProvid } return world.isEmptyBlock(pos); } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { while (world.getBlockState(pos).getBlock() == this) { diff --git a/src/main/java/ru/bclib/blocks/BaseWallBlock.java b/src/main/java/ru/bclib/blocks/BaseWallBlock.java index 3f0eea73..031f4d31 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -14,16 +21,10 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseWallBlock extends WallBlock implements BlockModelProvider { @@ -33,13 +34,13 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { super(FabricBlockSettings.copyOf(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) { @@ -47,7 +48,7 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { Optional pattern = PatternsHelper.createJson(BasePatterns.ITEM_WALL, parentId); return ModelsHelper.fromPattern(pattern); } - + @Override @Environment(EnvType.CLIENT) public @Nullable BlockModel getBlockModel(ResourceLocation blockId, BlockState blockState) { @@ -65,58 +66,37 @@ public class BaseWallBlock extends WallBlock implements BlockModelProvider { } 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" - ); + 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(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/ru/bclib/blocks/BaseWallPlantBlock.java b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java index ee022070..9adb0c91 100644 --- a/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWallPlantBlock.java @@ -1,7 +1,10 @@ package ru.bclib.blocks; +import java.util.EnumMap; + import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -25,36 +28,29 @@ import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.util.BlocksHelper; -import java.util.EnumMap; - public abstract class BaseWallPlantBlock extends BasePlantBlock { private static final EnumMap SHAPES = Maps.newEnumMap(ImmutableMap.of( - Direction.NORTH, - Block.box(1, 1, 8, 15, 15, 16), - Direction.SOUTH, - Block.box(1, 1, 0, 15, 15, 8), - Direction.WEST, - Block.box(8, 1, 1, 16, 15, 15), - Direction.EAST, - Block.box(0, 1, 1, 8, 15, 15) - )); + Direction.NORTH, Block.box(1, 1, 8, 15, 15, 16), + Direction.SOUTH, Block.box(1, 1, 0, 15, 15, 8), + Direction.WEST, Block.box(8, 1, 1, 16, 15, 15), + Direction.EAST, Block.box(0, 1, 1, 8, 15, 15))); public static final DirectionProperty FACING = HorizontalDirectionalBlock.FACING; public BaseWallPlantBlock() { this(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .noCollission()); } public BaseWallPlantBlock(int light) { this(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.GRASS) + .noCollission()); } public BaseWallPlantBlock(Properties settings) { @@ -65,17 +61,17 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock { 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 BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.NONE; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { Direction direction = state.getValue(FACING); @@ -105,7 +101,7 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock { } return null; } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -121,7 +117,7 @@ public abstract class BaseWallPlantBlock extends BasePlantBlock { public BlockState rotate(BlockState state, Rotation rotation) { return BlocksHelper.rotateHorizontal(state, rotation, FACING); } - + @Override @SuppressWarnings("deprecation") public BlockState mirror(BlockState state, Mirror mirror) { diff --git a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java index 4e4b9d99..28bbe68e 100644 --- a/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWeightedPlateBlock.java @@ -1,5 +1,12 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -12,40 +19,31 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.BlockModelProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implements BlockModelProvider { private final Block parent; public BaseWeightedPlateBlock(Block source) { - super( - 15, - FabricBlockSettings.copyOf(source).noCollission().noOcclusion().requiresCorrectToolForDrops().strength(0.5F) - ); + super(15, FabricBlockSettings.copyOf(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) { @@ -53,18 +51,18 @@ public class BaseWeightedPlateBlock extends WeightedPressurePlateBlock implement Optional pattern; if (blockState.getValue(POWER) > 0) { pattern = PatternsHelper.createJson(BasePatterns.BLOCK_PLATE_DOWN, parentId); - } - else { + } 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); + 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/ru/bclib/blocks/BaseWoodenButtonBlock.java b/src/main/java/ru/bclib/blocks/BaseWoodenButtonBlock.java index 3d92013b..daab12c0 100644 --- a/src/main/java/ru/bclib/blocks/BaseWoodenButtonBlock.java +++ b/src/main/java/ru/bclib/blocks/BaseWoodenButtonBlock.java @@ -6,11 +6,11 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.world.level.block.Block; public class BaseWoodenButtonBlock extends BaseButtonBlock { - + public BaseWoodenButtonBlock(Block source) { super(source, FabricBlockSettings.copyOf(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/ru/bclib/blocks/BlockProperties.java b/src/main/java/ru/bclib/blocks/BlockProperties.java index 15a16c0f..7bf55492 100644 --- a/src/main/java/ru/bclib/blocks/BlockProperties.java +++ b/src/main/java/ru/bclib/blocks/BlockProperties.java @@ -16,7 +16,6 @@ public class BlockProperties { 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); @@ -25,7 +24,9 @@ public class BlockProperties { public static final IntegerProperty AGE = IntegerProperty.create("age", 0, 3); public enum TripleShape implements StringRepresentable { - TOP("top", 0), MIDDLE("middle", 1), BOTTOM("bottom", 2); + TOP("top", 0), + MIDDLE("middle", 1), + BOTTOM("bottom", 2); private final String name; private final int index; @@ -34,7 +35,7 @@ public class BlockProperties { this.name = name; this.index = index; } - + @Override public String getSerializedName() { return name; @@ -55,14 +56,18 @@ public class BlockProperties { } public enum PentaShape implements StringRepresentable { - BOTTOM("bottom"), PRE_BOTTOM("pre_bottom"), MIDDLE("middle"), PRE_TOP("pre_top"), TOP("top"); + 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; diff --git a/src/main/java/ru/bclib/blocks/FeatureHangingSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureHangingSaplingBlock.java deleted file mode 100644 index 049f8c10..00000000 --- a/src/main/java/ru/bclib/blocks/FeatureHangingSaplingBlock.java +++ /dev/null @@ -1,32 +0,0 @@ -package ru.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.BlockState; -import net.minecraft.world.phys.shapes.CollisionContext; -import net.minecraft.world.phys.shapes.VoxelShape; - -public abstract class FeatureHangingSaplingBlock extends FeatureSaplingBlockCommon{ - private static final VoxelShape SHAPE = Block.box(4, 2, 4, 12, 16, 12); - public FeatureHangingSaplingBlock() { - super(); - } - - public FeatureHangingSaplingBlock(int light) { - super(light); - } - - @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/ru/bclib/blocks/FeatureSaplingBlock.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java index f0045a0e..38548c2f 100644 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java +++ b/src/main/java/ru/bclib/blocks/FeatureSaplingBlock.java @@ -1,26 +1,124 @@ package ru.bclib.blocks; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Random; + +import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; +import org.jetbrains.annotations.Nullable; + +import net.fabricmc.api.EnvType; +import net.fabricmc.api.Environment; +import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; +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.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.BlockState; +import net.minecraft.world.level.levelgen.feature.Feature; +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 ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.BlockModelProvider; +import ru.bclib.client.models.ModelsHelper; +import ru.bclib.client.models.PatternsHelper; +import ru.bclib.client.render.BCLRenderLayer; +import ru.bclib.interfaces.IRenderTyped; @SuppressWarnings("deprecation") -public abstract class FeatureSaplingBlock extends FeatureSaplingBlockCommon { +public abstract class FeatureSaplingBlock extends SaplingBlock implements IRenderTyped, BlockModelProvider { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); - + public FeatureSaplingBlock() { - super(); + super(null, FabricBlockSettings.of(Material.PLANT) + .breakByHand(true) + .collidable(false) + .instabreak() + .sound(SoundType.GRASS) + .randomTicks()); } - + public FeatureSaplingBlock(int light) { - super(light); + super(null, FabricBlockSettings.of(Material.PLANT) + .breakByHand(true) + .collidable(false) + .luminance(light) + .instabreak() + .sound(SoundType.GRASS) + .randomTicks()); } + + protected abstract Feature getFeature(); + @Override + public List getDrops(BlockState state, LootContext.Builder builder) { + return Collections.singletonList(new ItemStack(this)); + } + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPE; } + + @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 world, Random random, BlockPos pos, BlockState state) { + return random.nextInt(16) == 0; + } + + @Override + public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { + FeaturePlaceContext context = new FeaturePlaceContext(world, world.getChunkSource().getGenerator(), random, pos, null); + getFeature().place(context); + } + + @Override + public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { + this.tick(state, world, pos, random); + } + + @Override + public void tick(BlockState state, ServerLevel world, BlockPos pos, Random 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); + } } diff --git a/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java b/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java deleted file mode 100644 index fcc7f3af..00000000 --- a/src/main/java/ru/bclib/blocks/FeatureSaplingBlockCommon.java +++ /dev/null @@ -1,129 +0,0 @@ -package ru.bclib.blocks; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -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.world.item.ItemStack; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.LevelAccessor; -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.BlockState; -import net.minecraft.world.level.levelgen.feature.Feature; -import net.minecraft.world.level.levelgen.feature.FeaturePlaceContext; -import net.minecraft.world.level.material.Material; -import net.minecraft.world.level.storage.loot.LootContext; -import org.jetbrains.annotations.Nullable; -import ru.bclib.client.models.BasePatterns; -import ru.bclib.client.models.ModelsHelper; -import ru.bclib.client.models.PatternsHelper; -import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.RenderLayerProvider; - -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.Random; - -abstract class FeatureSaplingBlockCommon extends SaplingBlock implements RenderLayerProvider, BlockModelProvider { - public FeatureSaplingBlockCommon() { - super( - null, - FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) - .collidable(false) - .instabreak() - .sound(SoundType.GRASS) - .randomTicks() - ); - } - - public FeatureSaplingBlockCommon(int light) { - super( - null, - FabricBlockSettings.of(Material.PLANT) - .breakByHand(true) - .collidable(false) - .luminance(light) - .instabreak() - .sound(SoundType.GRASS) - .randomTicks() - ); - } - - @Deprecated - /** - * Override {@link #getFeature(BlockState)} directly. Will be removed in 5.x - */ - protected Feature getFeature() { return null; } - - protected Feature getFeature(BlockState state){ - return getFeature(); - } - - @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 world, Random random, BlockPos pos, BlockState state) { - return random.nextInt(16) == 0; - } - - @Override - public void advanceTree(ServerLevel world, BlockPos pos, BlockState blockState, Random random) { - FeaturePlaceContext context = new FeaturePlaceContext( - world, - world.getChunkSource().getGenerator(), - random, - pos, - null - ); - getFeature(blockState).place(context); - } - - @Override - public void randomTick(BlockState state, ServerLevel world, BlockPos pos, Random random) { - this.tick(state, world, pos, random); - } - - @Override - public void tick(BlockState state, ServerLevel world, BlockPos pos, Random 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); - } -} diff --git a/src/main/java/ru/bclib/blocks/LeveledAnvilBlock.java b/src/main/java/ru/bclib/blocks/LeveledAnvilBlock.java deleted file mode 100644 index 6d71663a..00000000 --- a/src/main/java/ru/bclib/blocks/LeveledAnvilBlock.java +++ /dev/null @@ -1,16 +0,0 @@ -package ru.bclib.blocks; - -import net.minecraft.world.level.material.MaterialColor; - -public class LeveledAnvilBlock extends BaseAnvilBlock{ - protected final int level; - - public LeveledAnvilBlock(MaterialColor color, int level) { - super(color); - this.level = level; - } - - public int getCraftingLevel() { - return level; - } -} diff --git a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java index 4f4d1128..ac46338c 100644 --- a/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java +++ b/src/main/java/ru/bclib/blocks/SimpleLeavesBlock.java @@ -4,38 +4,33 @@ import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.minecraft.world.level.block.SoundType; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.material.MaterialColor; -import ru.bclib.api.TagAPI; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerProvider; +import ru.bclib.interfaces.IRenderTyped; -public class SimpleLeavesBlock extends BaseBlockNotFull implements RenderLayerProvider { +public class SimpleLeavesBlock extends BaseBlockNotFull implements IRenderTyped { public SimpleLeavesBlock(MaterialColor color) { super(FabricBlockSettings.of(Material.LEAVES) - .strength(0.2F) - .mapColor(color) - .sound(SoundType.GRASS) - .noOcclusion() - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false)); - - TagAPI.addTags(this, TagAPI.BLOCK_LEAVES); + .strength(0.2F) + .mapColor(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) { super(FabricBlockSettings.of(Material.LEAVES) - .luminance(light) - .mapColor(color) - .strength(0.2F) - .sound(SoundType.GRASS) - .noOcclusion() - .isValidSpawn((state, world, pos, type) -> false) - .isSuffocating((state, world, pos) -> false) - .isViewBlocking((state, world, pos) -> false)); - - TagAPI.addTags(this, TagAPI.BLOCK_LEAVES); + .luminance(light) + .mapColor(color) + .strength(0.2F) + .sound(SoundType.GRASS) + .noOcclusion() + .isValidSpawn((state, world, pos, type) -> false) + .isSuffocating((state, world, pos) -> false) + .isViewBlocking((state, world, pos) -> false)); } - + @Override public BCLRenderLayer getRenderLayer() { return BCLRenderLayer.CUTOUT; diff --git a/src/main/java/ru/bclib/blocks/StalactiteBlock.java b/src/main/java/ru/bclib/blocks/StalactiteBlock.java index be53dd4f..50401565 100644 --- a/src/main/java/ru/bclib/blocks/StalactiteBlock.java +++ b/src/main/java/ru/bclib/blocks/StalactiteBlock.java @@ -1,5 +1,10 @@ package ru.bclib.blocks; +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; @@ -32,36 +37,29 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerProvider; - -import java.util.Map; -import java.util.Optional; +import ru.bclib.interfaces.IRenderTyped; @SuppressWarnings("deprecation") -public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, RenderLayerProvider { +public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterloggedBlock, LiquidBlockContainer, IRenderTyped { 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) { super(FabricBlockSettings.copy(source).noOcclusion()); - this.registerDefaultState(getStateDefinition().any() - .setValue(SIZE, 0) - .setValue(IS_FLOOR, true) - .setValue(WATERLOGGED, false)); + 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)]; @@ -97,7 +95,7 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg } } } - + @Override public void setPlacedBy(Level world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack itemStack) { boolean hasUp = isThis(world, pos.above()); @@ -185,7 +183,7 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg } return state; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { int size = state.getValue(SIZE); @@ -210,24 +208,22 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg 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) - ); + 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; @@ -237,12 +233,12 @@ public class StalactiteBlock extends BaseBlockNotFull implements SimpleWaterlogg 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; diff --git a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java index d87f973a..d0195177 100644 --- a/src/main/java/ru/bclib/blocks/StripableBarkBlock.java +++ b/src/main/java/ru/bclib/blocks/StripableBarkBlock.java @@ -30,11 +30,7 @@ public class StripableBarkBlock extends BaseBarkBlock { if (FabricToolTags.AXES.contains(player.getMainHandItem().getItem())) { 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 - ); + world.setBlock(pos, striped.defaultBlockState().setValue(RotatedPillarBlock.AXIS, state.getValue(RotatedPillarBlock.AXIS)), 11); if (!player.isCreative()) { player.getMainHandItem().hurt(1, world.random, (ServerPlayer) player); } diff --git a/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java b/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java index 9cc581c2..252ec776 100644 --- a/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java +++ b/src/main/java/ru/bclib/blocks/TripleTerrainBlock.java @@ -1,7 +1,15 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Random; + +import org.jetbrains.annotations.Nullable; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -26,17 +34,11 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BlockProperties.TripleShape; import ru.bclib.client.models.BasePatterns; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Random; - public class TripleTerrainBlock extends BaseTerrainBlock { public static final EnumProperty SHAPE = BlockProperties.TRIPLE_SHAPE; @@ -44,7 +46,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock { 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)); @@ -61,7 +63,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock { 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); @@ -76,8 +78,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock { TripleShape shape = state.getValue(SHAPE); if (shape == TripleShape.BOTTOM) { super.randomTick(state, world, pos, random); - } - else if (random.nextInt(16) == 0) { + } else if (random.nextInt(16) == 0) { boolean bottom = canStayBottom(world, pos); if (shape == TripleShape.TOP) { if (!bottom) { @@ -88,11 +89,9 @@ public class TripleTerrainBlock extends BaseTerrainBlock { 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) { + } else if (top && !bottom) { world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.BOTTOM)); - } - else if (!top) { + } else if (!top) { world.setBlockAndUpdate(pos, state.setValue(SHAPE, TripleShape.TOP)); } } @@ -104,21 +103,19 @@ public class TripleTerrainBlock extends BaseTerrainBlock { BlockState blockState = world.getBlockState(blockPos); if (isMiddle(blockState)) { return true; - } - else if (blockState.getFluidState().getAmount() == 8) { + } else if (blockState.getFluidState().getAmount() == 8) { return false; - } - else { + } 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) { @@ -127,8 +124,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock { if (isMiddle(blockState)) { ResourceLocation topId = new ResourceLocation(blockId.getNamespace(), path + "_top"); pattern = PatternsHelper.createBlockSimple(topId); - } - else { + } else { Map textures = Maps.newHashMap(); textures.put("%top%", "betterend:block/" + path + "_top"); textures.put("%side%", "betterend:block/" + path + "_side"); @@ -137,13 +133,14 @@ public class TripleTerrainBlock extends BaseTerrainBlock { } 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); + ResourceLocation modelId = new ResourceLocation(stateId.getNamespace(), + "block/" + stateId.getPath() + middle); registerBlockModel(stateId, modelId, blockState, modelCache); if (isMiddle) { List variants = Lists.newArrayList(); @@ -151,15 +148,9 @@ public class TripleTerrainBlock extends BaseTerrainBlock { variants.add(new Variant(modelId, rotation.getRotation(), false, 1)); } return new MultiVariant(variants); - } - else if (blockState.getValue(SHAPE) == TripleShape.TOP) { + } 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_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) @@ -167,7 +158,7 @@ public class TripleTerrainBlock extends BaseTerrainBlock { } return ModelsHelper.createRandomTopModel(modelId); } - + protected boolean isMiddle(BlockState blockState) { return blockState.is(this) && blockState.getValue(SHAPE) == TripleShape.MIDDLE; } diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java index 957ee59d..4d168107 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantBlock.java @@ -1,6 +1,10 @@ package ru.bclib.blocks; +import java.util.List; +import java.util.Random; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -31,47 +35,44 @@ import net.minecraft.world.phys.Vec3; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerProvider; - -import java.util.List; -import java.util.Random; +import ru.bclib.interfaces.IRenderTyped; @SuppressWarnings("deprecation") -public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements RenderLayerProvider, BonemealableBlock, LiquidBlockContainer { +public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements IRenderTyped, BonemealableBlock, LiquidBlockContainer { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 14, 12); public UnderwaterPlantBlock() { super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .noCollission()); } public UnderwaterPlantBlock(int light) { super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .luminance(light) - .sound(SoundType.WET_GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .luminance(light) + .sound(SoundType.WET_GRASS) + .noCollission()); } public UnderwaterPlantBlock(Properties settings) { super(settings); } - + @Override 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 public BlockBehaviour.OffsetType getOffsetType() { return BlockBehaviour.OffsetType.XZ; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); @@ -80,7 +81,7 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements R } protected abstract boolean isTerrain(BlockState state); - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -95,10 +96,7 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements R @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { @@ -110,34 +108,28 @@ public abstract class UnderwaterPlantBlock extends BaseBlockNotFull implements R 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 world, Random random, BlockPos pos, BlockState state) { return true; } - + @Override public void performBonemeal(ServerLevel world, Random random, BlockPos pos, BlockState state) { - ItemEntity item = new ItemEntity( - world, - pos.getX() + 0.5, - pos.getY() + 0.5, - pos.getZ() + 0.5, - new ItemStack(this) - ); + ItemEntity item = new ItemEntity(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, new ItemStack(this)); world.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; diff --git a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java index a2ad3dd0..8b6499a2 100644 --- a/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java +++ b/src/main/java/ru/bclib/blocks/UnderwaterPlantWithAgeBlock.java @@ -1,5 +1,7 @@ package ru.bclib.blocks; +import java.util.Random; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -12,18 +14,16 @@ import net.minecraft.world.level.block.state.StateDefinition; import net.minecraft.world.level.block.state.properties.IntegerProperty; import net.minecraft.world.level.material.Material; -import java.util.Random; - public abstract class UnderwaterPlantWithAgeBlock extends UnderwaterPlantBlock { public static final IntegerProperty AGE = BlockProperties.AGE; public UnderwaterPlantWithAgeBlock() { super(FabricBlockSettings.of(Material.WATER_PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.WET_GRASS) - .randomTicks() - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.WET_GRASS) + .randomTicks() + .noCollission()); } @Override diff --git a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java index 758f06e5..0773a45b 100644 --- a/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java +++ b/src/main/java/ru/bclib/blocks/UpDownPlantBlock.java @@ -1,6 +1,9 @@ package ru.bclib.blocks; +import java.util.List; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -24,29 +27,27 @@ import net.minecraft.world.level.storage.loot.parameters.LootContextParams; import net.minecraft.world.phys.shapes.CollisionContext; import net.minecraft.world.phys.shapes.VoxelShape; import ru.bclib.client.render.BCLRenderLayer; -import ru.bclib.interfaces.RenderLayerProvider; - -import java.util.List; +import ru.bclib.interfaces.IRenderTyped; @SuppressWarnings("deprecation") -public abstract class UpDownPlantBlock extends BaseBlockNotFull implements RenderLayerProvider { +public abstract class UpDownPlantBlock extends BaseBlockNotFull implements IRenderTyped { private static final VoxelShape SHAPE = Block.box(4, 0, 4, 12, 16, 12); public UpDownPlantBlock() { super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.SHEARS) - .breakByHand(true) - .sound(SoundType.GRASS) - .noCollission()); + .breakByTool(FabricToolTags.SHEARS) + .breakByHand(true) + .sound(SoundType.GRASS) + .noCollission()); } - + protected abstract boolean isTerrain(BlockState state); - + @Override public VoxelShape getShape(BlockState state, BlockGetter view, BlockPos pos, CollisionContext ePos) { return SHAPE; } - + @Override public boolean canSurvive(BlockState state, LevelReader world, BlockPos pos) { BlockState down = world.getBlockState(pos.below()); @@ -57,7 +58,7 @@ public abstract class UpDownPlantBlock extends BaseBlockNotFull implements Rende protected boolean isSupport(BlockState state, LevelReader world, BlockPos pos) { return canSupportCenter(world, pos.above(), Direction.UP); } - + @Override public BlockState updateShape(BlockState state, Direction facing, BlockState neighborState, LevelAccessor world, BlockPos pos, BlockPos neighborPos) { if (!canSurvive(state, world, pos)) { @@ -71,10 +72,7 @@ public abstract class UpDownPlantBlock extends BaseBlockNotFull implements Rende @Override public List getDrops(BlockState state, LootContext.Builder builder) { ItemStack tool = builder.getParameter(LootContextParams.TOOL); - if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel( - Enchantments.SILK_TOUCH, - tool - ) > 0) { + if (tool != null && FabricToolTags.SHEARS.contains(tool.getItem()) || EnchantmentHelper.getItemEnchantmentLevel(Enchantments.SILK_TOUCH, tool) > 0) { return Lists.newArrayList(new ItemStack(this)); } else { diff --git a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java index a4aabaf3..5e910e70 100644 --- a/src/main/java/ru/bclib/blocks/WallMushroomBlock.java +++ b/src/main/java/ru/bclib/blocks/WallMushroomBlock.java @@ -1,6 +1,9 @@ package ru.bclib.blocks; +import java.util.List; + import com.google.common.collect.Lists; + import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; import net.minecraft.core.BlockPos; @@ -12,18 +15,16 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.material.Material; import net.minecraft.world.level.storage.loot.LootContext; -import java.util.List; - public abstract class WallMushroomBlock extends BaseWallPlantBlock { public WallMushroomBlock(int light) { super(FabricBlockSettings.of(Material.PLANT) - .breakByTool(FabricToolTags.AXES) - .breakByHand(true) - .luminance(light) - .hardness(0.2F) - .sound(SoundType.GRASS) - .sound(SoundType.WOOD) - .noCollission()); + .breakByTool(FabricToolTags.AXES) + .breakByHand(true) + .luminance(light) + .hardness(0.2F) + .sound(SoundType.GRASS) + .sound(SoundType.WOOD) + .noCollission()); } @Override diff --git a/src/main/java/ru/bclib/blocks/properties/StringProperty.java b/src/main/java/ru/bclib/blocks/properties/StringProperty.java deleted file mode 100644 index 8aaff298..00000000 --- a/src/main/java/ru/bclib/blocks/properties/StringProperty.java +++ /dev/null @@ -1,61 +0,0 @@ -package ru.bclib.blocks.properties; - -import com.google.common.collect.Sets; -import net.minecraft.world.level.block.state.properties.Property; - -import java.util.Collection; -import java.util.Collections; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -@Deprecated -public class StringProperty extends Property { - private final Set values; - - public static StringProperty create(String name, String... values) { - return new StringProperty(name, values); - } - - protected StringProperty(String string, String... values) { - super(string, String.class); - this.values = Sets.newHashSet(values); - } - - public void addValue(String name) { - values.add(name); - } - - @Override - public Collection getPossibleValues() { - return Collections.unmodifiableSet(values); - } - - @Override - public String getName(String comparable) { - return comparable; - } - - @Override - public Optional getValue(String string) { - if (values.contains(string)) { - return Optional.of(string); - } - else { - return Optional.empty(); - } - } - - @Override - public int generateHashCode() { - return super.generateHashCode() + Objects.hashCode(values); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof StringProperty that)) return false; - if (!super.equals(o)) return false; - return values.equals(that.values); - } -} diff --git a/src/main/java/ru/bclib/client/BCLibClient.java b/src/main/java/ru/bclib/client/BCLibClient.java index bb61f255..5b6249d6 100644 --- a/src/main/java/ru/bclib/client/BCLibClient.java +++ b/src/main/java/ru/bclib/client/BCLibClient.java @@ -1,42 +1,33 @@ package ru.bclib.client; import net.fabricmc.api.ClientModInitializer; -import net.fabricmc.fabric.api.client.model.ModelLoadingRegistry; -import net.fabricmc.fabric.api.client.model.ModelProviderContext; -import net.fabricmc.fabric.api.client.model.ModelProviderException; -import net.fabricmc.fabric.api.client.model.ModelResourceProvider; -import net.fabricmc.fabric.api.client.model.ModelVariantProvider; -import net.minecraft.client.resources.model.ModelResourceLocation; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; +import net.fabricmc.fabric.api.blockrenderlayer.v1.BlockRenderLayerMap; +import net.minecraft.client.renderer.RenderType; +import net.minecraft.core.Registry; import ru.bclib.api.ModIntegrationAPI; -import ru.bclib.api.PostInitAPI; -import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.client.models.CustomModelBakery; +import ru.bclib.client.render.BCLRenderLayer; +import ru.bclib.interfaces.IRenderTyped; import ru.bclib.registry.BaseBlockEntityRenders; -public class BCLibClient implements ClientModInitializer, ModelResourceProvider, ModelVariantProvider { - public static CustomModelBakery modelBakery; - +public class BCLibClient implements ClientModInitializer { @Override public void onInitializeClient() { ModIntegrationAPI.registerAll(); BaseBlockEntityRenders.register(); - DataExchangeAPI.prepareClientside(); - PostInitAPI.postInit(true); - modelBakery = new CustomModelBakery(); - ModelLoadingRegistry.INSTANCE.registerResourceProvider(rm -> this); - ModelLoadingRegistry.INSTANCE.registerVariantProvider(rm -> this); + registerRenderLayers(); } - @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); + private void registerRenderLayers() { + RenderType cutout = RenderType.cutout(); + RenderType translucent = RenderType.translucent(); + Registry.BLOCK.forEach(block -> { + if (block instanceof IRenderTyped) { + BCLRenderLayer layer = ((IRenderTyped) block).getRenderLayer(); + if (layer == BCLRenderLayer.CUTOUT) + BlockRenderLayerMap.INSTANCE.putBlock(block, cutout); + else if (layer == BCLRenderLayer.TRANSLUCENT) + BlockRenderLayerMap.INSTANCE.putBlock(block, translucent); + } + }); } } diff --git a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java index 76f22816..89954126 100644 --- a/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java +++ b/src/main/java/ru/bclib/client/gui/BlockSignEditScreen.java @@ -45,128 +45,109 @@ public class BlockSignEditScreen extends Screen { Arrays.fill(strings, ""); }); private SignRenderer.SignModel model; - + public BlockSignEditScreen(BaseSignBlockEntity sign) { super(new TranslatableComponent("sign.edit")); this.sign = sign; } - + protected void init() { //set up a default model - model = new SignRenderer.SignModel(this.minecraft.getEntityModels() - .bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); - + model = new SignRenderer.SignModel(this.minecraft.getEntityModels().bakeLayer(ModelLayers.createSignModelName(WoodType.OAK))); + minecraft.keyboardHandler.setSendRepeatsToGui(true); - this.addRenderableWidget(new Button( - this.width / 2 - 100, - this.height / 4 + 120, - 200, - 20, - CommonComponents.GUI_DONE, - (buttonWidget) -> { - this.finishEditing(); - } - )); + this.addRenderableWidget(new Button(this.width / 2 - 100, this.height / 4 + 120, 200, 20, CommonComponents.GUI_DONE, + (buttonWidget) -> { + this.finishEditing(); + })); this.sign.setEditable(false); - this.selectionManager = new TextFieldHelper( - () -> { - return this.text[this.currentRow]; - }, - (string) -> { - this.text[this.currentRow] = string; - this.sign.setMessage(this.currentRow, new TextComponent(string)); - }, - TextFieldHelper.createClipboardGetter(this.minecraft), - TextFieldHelper.createClipboardSetter(this.minecraft), - (string) -> { - return this.minecraft.font.width(string) <= 90; - } - ); + this.selectionManager = new TextFieldHelper(() -> { + return this.text[this.currentRow]; + }, (string) -> { + this.text[this.currentRow] = string; + this.sign.setMessage(this.currentRow, new TextComponent(string)); + }, TextFieldHelper.createClipboardGetter(this.minecraft), TextFieldHelper.createClipboardSetter(this.minecraft), + (string) -> { + return this.minecraft.font.width(string) <= 90; + }); } - + public void removed() { minecraft.keyboardHandler.setSendRepeatsToGui(false); ClientPacketListener clientPlayNetworkHandler = this.minecraft.getConnection(); if (clientPlayNetworkHandler != null) { - clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket( - this.sign.getBlockPos(), - this.text[0], - this.text[1], - this.text[2], - this.text[3] - )); + clientPlayNetworkHandler.send(new ServerboundSignUpdatePacket(this.sign.getBlockPos(), this.text[0], this.text[1], + this.text[2], this.text[3])); } - + this.sign.setEditable(true); } - + public void tick() { ++this.ticksSinceOpened; if (!this.sign.getType().isValid(this.sign.getBlockState())) { this.finishEditing(); } } - + private void finishEditing() { this.sign.setChanged(); this.minecraft.setScreen((Screen) null); } - + public boolean charTyped(char chr, int keyCode) { this.selectionManager.charTyped(chr); return true; } - + public void onClose() { this.finishEditing(); } - + public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (keyCode == 265) { this.currentRow = this.currentRow - 1 & 3; this.selectionManager.setCursorToEnd(); return true; - } - else if (keyCode != 264 && keyCode != 257 && keyCode != 335) { + } else if (keyCode != 264 && keyCode != 257 && keyCode != 335) { return selectionManager.keyPressed(keyCode) || super.keyPressed(keyCode, scanCode, modifiers); - } - else { + } else { this.currentRow = this.currentRow + 1 & 3; this.selectionManager.setCursorToEnd(); return true; } } - + public void render(PoseStack matrices, int mouseX, int mouseY, float delta) { Lighting.setupForFlatItems(); this.renderBackground(matrices); GuiComponent.drawCenteredString(matrices, this.font, this.title, this.width / 2, 40, 16777215); matrices.pushPose(); matrices.translate((double) (this.width / 2), 0.0D, 50.0D); - + matrices.scale(93.75F, -93.75F, 93.75F); matrices.translate(0.0D, -1.3125D, 0.0D); BlockState blockState = this.sign.getBlockState(); boolean bl = blockState.getValue(BaseSignBlock.FLOOR); - + if (!bl) { matrices.translate(0.0D, -0.3125D, 0.0D); } - + boolean bl2 = this.ticksSinceOpened / 6 % 2 == 0; - + matrices.pushPose(); matrices.scale(0.6666667F, -0.6666667F, -0.6666667F); MultiBufferSource.BufferSource immediate = minecraft.renderBuffers().bufferSource(); VertexConsumer vertexConsumer = BaseSignBlockEntityRenderer.getConsumer(immediate, blockState.getBlock()); model.root.getChild("sign").render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); - + if (bl) { model.stick.render(matrices, vertexConsumer, 15728880, OverlayTexture.NO_OVERLAY); } - + matrices.popPose(); - + matrices.translate(0.0D, 0.3333333432674408D, 0.046666666865348816D); matrices.scale(0.010416667F, -0.010416667F, 0.010416667F); int i = this.sign.getColor().getTextColor(); @@ -174,7 +155,7 @@ public class BlockSignEditScreen extends Screen { int k = this.selectionManager.getSelectionPos(); int l = this.currentRow * 10 - this.text.length * 5; Matrix4f matrix4f = matrices.last().pose(); - + int m; String string2; int s; @@ -185,49 +166,29 @@ public class BlockSignEditScreen extends Screen { if (this.font.isBidirectional()) { string2 = this.font.bidirectionalShaping(string2); } - + float n = (float) (-this.minecraft.font.width(string2) / 2); - this.minecraft.font.drawInBatch( - string2, - n, - (float) (m * 10 - this.text.length * 5), - i, - false, - matrix4f, - immediate, - false, - 0, - 15728880, - false - ); + this.minecraft.font.drawInBatch(string2, n, (float) (m * 10 - this.text.length * 5), i, false, matrix4f, + immediate, false, 0, 15728880, false); if (m == this.currentRow && j >= 0 && bl2) { - s = this.minecraft.font.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); + s = this.minecraft.font + .width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); t = s - this.minecraft.font.width(string2) / 2; if (j >= string2.length()) { - this.minecraft.font.drawInBatch( - "_", - (float) t, - (float) l, - i, - false, - matrix4f, - immediate, - false, - 0, - 15728880, - false - ); + this.minecraft.font.drawInBatch("_", (float) t, (float) l, i, false, matrix4f, immediate, false, + 0, 15728880, false); } } } } - + immediate.endBatch(); - + for (m = 0; m < this.text.length; ++m) { string2 = this.text[m]; if (string2 != null && m == this.currentRow && j >= 0) { - int r = this.minecraft.font.width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); + int r = this.minecraft.font + .width(string2.substring(0, Math.max(Math.min(j, string2.length()), 0))); s = r - this.minecraft.font.width(string2) / 2; if (bl2 && j < string2.length()) { int var31 = l - 1; @@ -235,12 +196,14 @@ public class BlockSignEditScreen extends Screen { this.minecraft.font.getClass(); fill(matrices, s, var31, var10003, l + 9, -16777216 | i); } - + if (k != j) { t = Math.min(j, k); int u = Math.max(j, k); - int v = this.minecraft.font.width(string2.substring(0, t)) - this.minecraft.font.width(string2) / 2; - int w = this.minecraft.font.width(string2.substring(0, u)) - this.minecraft.font.width(string2) / 2; + int v = this.minecraft.font.width(string2.substring(0, t)) + - this.minecraft.font.width(string2) / 2; + int w = this.minecraft.font.width(string2.substring(0, u)) + - this.minecraft.font.width(string2) / 2; int x = Math.min(v, w); int y = Math.max(v, w); Tesselator tessellator = Tesselator.getInstance(); @@ -262,7 +225,7 @@ public class BlockSignEditScreen extends Screen { } } } - + matrices.popPose(); Lighting.setupFor3DItems(); super.render(matrices, mouseX, mouseY, delta); diff --git a/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java index 745e12f0..ec5bf62d 100644 --- a/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java +++ b/src/main/java/ru/bclib/client/models/BaseChestBlockModel.java @@ -2,107 +2,90 @@ package ru.bclib.client.models; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.model.geom.PartPose; -import net.minecraft.client.model.geom.builders.CubeDeformation; -import net.minecraft.client.model.geom.builders.CubeListBuilder; -import net.minecraft.client.model.geom.builders.LayerDefinition; -import net.minecraft.client.model.geom.builders.MeshDefinition; -import net.minecraft.client.model.geom.builders.PartDefinition; +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"); - } + 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/ru/bclib/client/models/BasePatterns.java b/src/main/java/ru/bclib/client/models/BasePatterns.java index 5d3442a8..575e3b27 100644 --- a/src/main/java/ru/bclib/client/models/BasePatterns.java +++ b/src/main/java/ru/bclib/client/models/BasePatterns.java @@ -57,5 +57,5 @@ public class BasePatterns { 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"); - + } diff --git a/src/main/java/ru/bclib/interfaces/BlockModelProvider.java b/src/main/java/ru/bclib/client/models/BlockModelProvider.java similarity index 88% rename from src/main/java/ru/bclib/interfaces/BlockModelProvider.java rename to src/main/java/ru/bclib/client/models/BlockModelProvider.java index fda0f101..e139a923 100644 --- a/src/main/java/ru/bclib/interfaces/BlockModelProvider.java +++ b/src/main/java/ru/bclib/client/models/BlockModelProvider.java @@ -1,4 +1,11 @@ -package ru.bclib.interfaces; +package ru.bclib.client.models; + +import static net.minecraft.client.resources.model.ModelBakery.MISSING_MODEL_LOCATION; + +import java.util.Map; +import java.util.Optional; + +import org.jetbrains.annotations.Nullable; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; @@ -6,13 +13,7 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.BCLib; -import ru.bclib.client.models.ModelsHelper; -import ru.bclib.client.models.PatternsHelper; - -import java.util.Map; -import java.util.Optional; public interface BlockModelProvider extends ItemModelProvider { @Environment(EnvType.CLIENT) @@ -20,14 +21,14 @@ public interface BlockModelProvider extends ItemModelProvider { 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)) { @@ -35,9 +36,9 @@ public interface BlockModelProvider extends ItemModelProvider { if (model != null) { model.name = modelId.toString(); modelCache.put(modelId, model); - } - else { + } else { BCLib.LOGGER.warning("Error loading model: {}", modelId); + modelCache.put(modelId, modelCache.get(MISSING_MODEL_LOCATION)); } } } diff --git a/src/main/java/ru/bclib/client/models/CustomModelBakery.java b/src/main/java/ru/bclib/client/models/CustomModelBakery.java deleted file mode 100644 index 97d36d18..00000000 --- a/src/main/java/ru/bclib/client/models/CustomModelBakery.java +++ /dev/null @@ -1,132 +0,0 @@ -package ru.bclib.client.models; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -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 ru.bclib.api.ModIntegrationAPI; -import ru.bclib.client.render.EmissiveTextureInfo; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.ItemModelProvider; - -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.hasResource(storageID)) { - addBlockModel(blockID, block); - } - storageID = new ResourceLocation(blockID.getNamespace(), "models/item/" + blockID.getPath() + ".json"); - if (!resourceManager.hasResource(storageID)) { - addItemModel(blockID, (ItemModelProvider) block); - } - }); - - Registry.ITEM.stream().parallel().filter(item -> item instanceof ItemModelProvider).forEach(item -> { - ResourceLocation registryID = Registry.ITEM.getKey(item); - ResourceLocation storageID = new ResourceLocation(registryID.getNamespace(), "models/item/" + registryID.getPath() + ".json"); - if (!resourceManager.hasResource(storageID)) { - addItemModel(registryID, (ItemModelProvider) item); - } - }); - } - - 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/ru/bclib/client/models/CustomModelData.java b/src/main/java/ru/bclib/client/models/CustomModelData.java deleted file mode 100644 index 0fcf50f9..00000000 --- a/src/main/java/ru/bclib/client/models/CustomModelData.java +++ /dev/null @@ -1,23 +0,0 @@ -package ru.bclib.client.models; - -import com.google.common.collect.Sets; -import net.minecraft.resources.ResourceLocation; - -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/ru/bclib/interfaces/ItemModelProvider.java b/src/main/java/ru/bclib/client/models/ItemModelProvider.java similarity index 83% rename from src/main/java/ru/bclib/interfaces/ItemModelProvider.java rename to src/main/java/ru/bclib/client/models/ItemModelProvider.java index 5ef7873f..50930e6c 100644 --- a/src/main/java/ru/bclib/interfaces/ItemModelProvider.java +++ b/src/main/java/ru/bclib/client/models/ItemModelProvider.java @@ -1,10 +1,9 @@ -package ru.bclib.interfaces; +package ru.bclib.client.models; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; -import ru.bclib.client.models.ModelsHelper; public interface ItemModelProvider { @Environment(EnvType.CLIENT) diff --git a/src/main/java/ru/bclib/client/models/ModelsHelper.java b/src/main/java/ru/bclib/client/models/ModelsHelper.java index 8b99b720..f7bdec4d 100644 --- a/src/main/java/ru/bclib/client/models/ModelsHelper.java +++ b/src/main/java/ru/bclib/client/models/ModelsHelper.java @@ -1,7 +1,12 @@ package ru.bclib.client.models; +import java.util.List; +import java.util.Optional; +import java.util.function.Function; + import com.google.common.collect.Lists; import com.mojang.math.Transformation; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -17,43 +22,39 @@ import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.block.state.StateDefinition; -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(); @@ -61,22 +62,17 @@ public class ModelsHelper { 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; + 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), @@ -85,30 +81,26 @@ public class ModelsHelper { new Variant(resourceLocation, BlockModelRotation.X0_Y270.getRotation(), false, 1) )); } - + public static class MultiPartBuilder { - - //private final static MultiPartBuilder BUILDER = new 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); + BUILDER.stateDefinition = stateDefinition; + BUILDER.modelParts.clear(); + return BUILDER; } - + private final List modelParts = Lists.newArrayList(); private StateDefinition stateDefinition; - - private MultiPartBuilder(StateDefinition stateDefinition) { - this.stateDefinition = stateDefinition; - } - + + private MultiPartBuilder() {} + public ModelPart part(ResourceLocation modelId) { - ModelPart part = new ModelPart(modelId); - return part; + return new ModelPart(modelId); } - + public MultiPart build() { if (modelParts.size() > 0) { List selectors = Lists.newArrayList(); @@ -121,32 +113,32 @@ public class ModelsHelper { } 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/ru/bclib/client/models/OBJBlockModel.java b/src/main/java/ru/bclib/client/models/OBJBlockModel.java deleted file mode 100644 index 73497925..00000000 --- a/src/main/java/ru/bclib/client/models/OBJBlockModel.java +++ /dev/null @@ -1,308 +0,0 @@ -package ru.bclib.client.models; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.mojang.datafixers.util.Pair; -import com.mojang.math.Vector3f; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -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.BakedModel; -import net.minecraft.client.resources.model.Material; -import net.minecraft.client.resources.model.ModelBakery; -import net.minecraft.client.resources.model.ModelState; -import net.minecraft.client.resources.model.UnbakedModel; -import net.minecraft.core.Direction; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; -import ru.bclib.util.BlocksHelper; -import ru.bclib.util.MHelper; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.function.Function; - -@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, Random 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) { - Resource resource = null; - try { - resource = Minecraft.getInstance().getResourceManager().getResource(location); - } - catch (IOException e) { - e.printStackTrace(); - if (resource != null) { - try { - resource.close(); - } - catch (IOException ioException) { - ioException.printStackTrace(); - } - resource = null; - } - } - return resource; - } - - private void loadModel(ResourceLocation location, Vector3f offset, byte maxIndex) { - Resource resource = getResource(location); - if (resource == null) { - return; - } - InputStream input = resource.getInputStream(); - - 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(); - resource.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/ru/bclib/client/models/OBJModelBuilder.java b/src/main/java/ru/bclib/client/models/OBJModelBuilder.java deleted file mode 100644 index 7316985b..00000000 --- a/src/main/java/ru/bclib/client/models/OBJModelBuilder.java +++ /dev/null @@ -1,103 +0,0 @@ -package ru.bclib.client.models; - -import com.google.common.collect.Lists; -import com.mojang.math.Vector3f; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.resources.ResourceLocation; - -import java.util.List; - -@Environment(EnvType.CLIENT) -public class OBJModelBuilder { - private static final OBJModelBuilder INSTANCE = new OBJModelBuilder(); - private final List textures = Lists.newArrayList(); - private 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/ru/bclib/client/models/PatternsHelper.java b/src/main/java/ru/bclib/client/models/PatternsHelper.java index c6e7348d..771b7d80 100644 --- a/src/main/java/ru/bclib/client/models/PatternsHelper.java +++ b/src/main/java/ru/bclib/client/models/PatternsHelper.java @@ -1,10 +1,5 @@ package ru.bclib.client.models; -import com.google.common.collect.Maps; -import net.minecraft.client.Minecraft; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.ResourceManager; - import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; @@ -13,58 +8,58 @@ import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; +import com.google.common.collect.Maps; + +import net.minecraft.client.Minecraft; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; + 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(); try (InputStream input = resourceManager.getResource(patternId).getInputStream()) { - 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); - } + String json = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8)) + .lines().collect(Collectors.joining()); for (Map.Entry texture : textures.entrySet()) { json = json.replace(texture.getKey(), texture.getValue()); } return Optional.of(json); - } - catch (Exception ex) { + } catch (Exception ex) { return Optional.empty(); } } diff --git a/src/main/java/ru/bclib/client/models/UnbakedQuad.java b/src/main/java/ru/bclib/client/models/UnbakedQuad.java deleted file mode 100644 index 60b4ecc5..00000000 --- a/src/main/java/ru/bclib/client/models/UnbakedQuad.java +++ /dev/null @@ -1,68 +0,0 @@ -package ru.bclib.client.models; - -import com.mojang.math.Matrix4f; -import com.mojang.math.Vector3f; -import com.mojang.math.Vector4f; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -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; - -@Environment(EnvType.CLIENT) -public class UnbakedQuad { - private static final Vector4f POS = new Vector4f(); - private 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/ru/bclib/client/render/BCLRenderLayer.java b/src/main/java/ru/bclib/client/render/BCLRenderLayer.java index 796edfa5..3846d7d6 100644 --- a/src/main/java/ru/bclib/client/render/BCLRenderLayer.java +++ b/src/main/java/ru/bclib/client/render/BCLRenderLayer.java @@ -1,5 +1,6 @@ package ru.bclib.client.render; public enum BCLRenderLayer { - CUTOUT, TRANSLUCENT; + CUTOUT, + TRANSLUCENT; } diff --git a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java index 42e2f689..96d59f04 100644 --- a/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseChestBlockEntityRenderer.java @@ -18,11 +18,7 @@ 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.AbstractChestBlock; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.Blocks; -import net.minecraft.world.level.block.ChestBlock; -import net.minecraft.world.level.block.DoubleBlockCombiner; +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; @@ -35,27 +31,22 @@ 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 RenderType[] defaultLayer; + 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 - ); + 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) { @@ -63,73 +54,40 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer 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 { + } else { propertySource = DoubleBlockCombiner.Combiner::acceptNone; } - - float pitch = ((Float2FloatFunction) propertySource.apply(ChestBlock.opennessCombiner(entity))).get( - tickDelta); + + float pitch = ((Float2FloatFunction) 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); - + @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 - ); + 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); } - 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; @@ -137,7 +95,7 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer layers[ID_LEFT]; @@ -145,28 +103,25 @@ public class BaseChestBlockEntityRenderer implements BlockEntityRenderer layers[ID_NORMAL]; }; } - + public static VertexConsumer getConsumer(MultiBufferSource provider, Block block, ChestType chestType) { - RenderType[] layers = LAYERS.getOrDefault(block, RENDER_TYPES); + RenderType[] layers = LAYERS.getOrDefault(block, defaultLayer); 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")) - } - ); + 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[] { + defaultLayer = 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/ru/bclib/client/render/BaseSignBlockEntityRenderer.java b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java index 6d408a46..6d26f1d6 100644 --- a/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java +++ b/src/main/java/ru/bclib/client/render/BaseSignBlockEntityRenderer.java @@ -35,45 +35,50 @@ 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 static final HashMap LAYERS = Maps.newHashMap(); + private static final RenderType defaultLayer; private final Font font; - - + private final SignRenderer.SignModel model; + + + private static final int OUTLINE_RENDER_DISTANCE = Mth.square(16); + public BaseSignBlockEntityRenderer(BlockEntityRendererProvider.Context ctx) { super(); this.font = ctx.getFont(); + + //set up a default model 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) { + + 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 { + } 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); + //model.stick.render(matrixStack, vertexConsumer, light, overlay); matrixStack.popPose(); + //Font textRenderer = renderer.getFont(); matrixStack.translate(0.0D, 0.3333333432674408D, 0.046666666865348816D); matrixStack.scale(0.010416667F, -0.010416667F, 0.010416667F); int m = signBlockEntity.getColor().getTextColor(); @@ -81,15 +86,12 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer { - List list = this.font.split(component, 90); - return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); - } - ); + + FormattedCharSequence[] formattedCharSequences = signBlockEntity + .getRenderMessages(Minecraft.getInstance().isTextFilteringEnabled(), (component) -> { + List list = this.font.split(component, 90); + return list.isEmpty() ? FormattedCharSequence.EMPTY : (FormattedCharSequence) list.get(0); + }); int drawColor; boolean drawOutlined; int drawLight; @@ -97,93 +99,73 @@ public class BaseSignBlockEntityRenderer implements BlockEntityRenderer 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 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)); - return BiomeAPI.getRenderBiome(biome) == BiomeAPI.EMPTY_BIOME; - } - - private static float getFogDensityI(Level level, int x, int y, int z) { - Biome biome = level.getBiome(MUT_POS.set(x, y, z)); - 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/ru/bclib/client/render/EmissiveTextureInfo.java b/src/main/java/ru/bclib/client/render/EmissiveTextureInfo.java deleted file mode 100644 index 0623a9df..00000000 --- a/src/main/java/ru/bclib/client/render/EmissiveTextureInfo.java +++ /dev/null @@ -1,32 +0,0 @@ -package ru.bclib.client.render; - -import com.google.common.collect.Sets; -import net.minecraft.resources.ResourceLocation; - -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/ru/bclib/client/sound/BlockSounds.java b/src/main/java/ru/bclib/client/sound/BlockSounds.java index d7fc73a6..97c2cd20 100644 --- a/src/main/java/ru/bclib/client/sound/BlockSounds.java +++ b/src/main/java/ru/bclib/client/sound/BlockSounds.java @@ -4,13 +4,10 @@ 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 - ); + 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/ru/bclib/complexmaterials/ComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java deleted file mode 100644 index b4a3f633..00000000 --- a/src/main/java/ru/bclib/complexmaterials/ComplexMaterial.java +++ /dev/null @@ -1,341 +0,0 @@ -package ru.bclib.complexmaterials; - -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import org.jetbrains.annotations.Nullable; -import ru.bclib.complexmaterials.entry.BlockEntry; -import ru.bclib.complexmaterials.entry.ItemEntry; -import ru.bclib.complexmaterials.entry.RecipeEntry; -import ru.bclib.config.PathConfig; -import ru.bclib.registry.BlockRegistry; -import ru.bclib.registry.ItemRegistry; - -import java.util.Collection; -import java.util.List; -import java.util.Map; - -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 FabricBlockSettings blockSettings = getBlockSettings(); - final FabricItemSettings 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 FabricBlockSettings} default block settings for this material; - * @param itemSettings {@link FabricItemSettings} default item settings for this material. - */ - protected abstract void initDefault(FabricBlockSettings blockSettings, FabricItemSettings 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 ru.bclib.api.TagAPI} or you can use one of already created tags. - * @param tag {@link Tag.Named} for {@link Block} - */ - protected void addBlockTag(Tag.Named tag) { - String key = tag.getName().getPath().replace(getBaseName() + "_", ""); - blockTags.put(key, tag); - } - - /** - * Adds custom iten tag for this {@link ComplexMaterial}, tag can be created with {@link ru.bclib.api.TagAPI} or you can use one of already created tags. - * @param tag {@link Tag.Named} for {@link Item} - */ - protected void addItemTag(Tag.Named tag) { - String key = tag.getName().getPath().replace(getBaseName() + "_", ""); - itemTags.put(key, tag); - } - - /** - * Get custom {@link Block} {@link Tag.Named} 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 Tag.Named} for {@link Block} or {@code null} if nothing is stored. - */ - @Nullable - public Tag.Named getBlockTag(String key) { - return blockTags.get(key); - } - - /** - * Get custom {@link Item} {@link Tag.Named} 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 Tag.Named} for {@link Item} or {@code null} if nothing is stored. - */ - @Nullable - public Tag.Named 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 FabricBlockSettings} - */ - protected abstract FabricBlockSettings getBlockSettings(); - - /** - * Get default item settings for this material. - * @return {@link FabricItemSettings} - */ - protected FabricItemSettings 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/ru/bclib/complexmaterials/WoodenComplexMaterial.java b/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java deleted file mode 100644 index ba329585..00000000 --- a/src/main/java/ru/bclib/complexmaterials/WoodenComplexMaterial.java +++ /dev/null @@ -1,410 +0,0 @@ -package ru.bclib.complexmaterials; - -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.BlockTags; -import net.minecraft.tags.ItemTags; -import net.minecraft.tags.Tag; -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.material.MaterialColor; -import ru.bclib.BCLib; -import ru.bclib.api.TagAPI; -import ru.bclib.blocks.BaseBarkBlock; -import ru.bclib.blocks.BaseBarrelBlock; -import ru.bclib.blocks.BaseBlock; -import ru.bclib.blocks.BaseBookshelfBlock; -import ru.bclib.blocks.BaseChestBlock; -import ru.bclib.blocks.BaseComposterBlock; -import ru.bclib.blocks.BaseCraftingTableBlock; -import ru.bclib.blocks.BaseDoorBlock; -import ru.bclib.blocks.BaseFenceBlock; -import ru.bclib.blocks.BaseGateBlock; -import ru.bclib.blocks.BaseLadderBlock; -import ru.bclib.blocks.BaseRotatedPillarBlock; -import ru.bclib.blocks.BaseSignBlock; -import ru.bclib.blocks.BaseSlabBlock; -import ru.bclib.blocks.BaseStairsBlock; -import ru.bclib.blocks.BaseStripableLogBlock; -import ru.bclib.blocks.BaseTrapdoorBlock; -import ru.bclib.blocks.BaseWoodenButtonBlock; -import ru.bclib.blocks.StripableBarkBlock; -import ru.bclib.blocks.WoodenPressurePlateBlock; -import ru.bclib.complexmaterials.entry.BlockEntry; -import ru.bclib.complexmaterials.entry.RecipeEntry; -import ru.bclib.recipes.GridRecipe; - -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) - .materialColor(planksColor); - } - - @Override - public ResourceLocation getMaterialID() { - return MATERIAL_ID; - } - - @Override - protected void initTags() { - addBlockTag(TagAPI.makeBlockTag(getModID(), getBaseName() + "_logs")); - addItemTag(TagAPI.makeItemTag(getModID(), getBaseName() + "_logs")); - } - - @Override - protected void initDefault(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - initBase(blockSettings, itemSettings); - initStorage(blockSettings, itemSettings); - initDecorations(blockSettings, itemSettings); - } - - final protected void initBase(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - Tag.Named tagBlockLog = getBlockTag(TAG_LOGS); - Tag.Named tagItemLog = getItemTag(TAG_LOGS); - - addBlockEntry( - new BlockEntry(BLOCK_STRIPPED_LOG, (complexMaterial, settings) -> { - return 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) -> { - return 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) -> { - return 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) -> { - return 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) -> { - return new BaseBlock(settings); - }).setBlockTags(BlockTags.PLANKS) - .setItemTags(ItemTags.PLANKS)); - - addBlockEntry(new BlockEntry(BLOCK_STAIRS, (complexMaterial, settings) -> { - return new BaseStairsBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.WOODEN_STAIRS, BlockTags.STAIRS) - .setItemTags(ItemTags.WOODEN_STAIRS, ItemTags.STAIRS)); - addBlockEntry(new BlockEntry(BLOCK_SLAB, (complexMaterial, settings) -> { - return new BaseSlabBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.WOODEN_SLABS, BlockTags.SLABS) - .setItemTags(ItemTags.WOODEN_SLABS, ItemTags.SLABS)); - addBlockEntry(new BlockEntry(BLOCK_FENCE, (complexMaterial, settings) -> { - return new BaseFenceBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.FENCES, BlockTags.WOODEN_FENCES) - .setItemTags(ItemTags.FENCES, ItemTags.WOODEN_FENCES)); - addBlockEntry(new BlockEntry(BLOCK_GATE, (complexMaterial, settings) -> { - return new BaseGateBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.FENCE_GATES)); - addBlockEntry(new BlockEntry(BLOCK_BUTTON, (complexMaterial, settings) -> { - return 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) -> { - return 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) -> { - return new BaseTrapdoorBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.TRAPDOORS, BlockTags.WOODEN_TRAPDOORS) - .setItemTags(ItemTags.TRAPDOORS, ItemTags.WOODEN_TRAPDOORS)); - addBlockEntry(new BlockEntry(BLOCK_DOOR, (complexMaterial, settings) -> { - return new BaseDoorBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.DOORS, BlockTags.WOODEN_DOORS) - .setItemTags(ItemTags.DOORS, ItemTags.WOODEN_DOORS)); - - - addBlockEntry(new BlockEntry(BLOCK_LADDER, (complexMaterial, settings) -> { - return new BaseLadderBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.CLIMBABLE)); - addBlockEntry(new BlockEntry(BLOCK_SIGN, (complexMaterial, settings) -> { - return new BaseSignBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(BlockTags.SIGNS) - .setItemTags(ItemTags.SIGNS)); - - - } - - final protected void initStorage(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - addBlockEntry(new BlockEntry(BLOCK_CHEST, (complexMaterial, settings) -> { - return new BaseChestBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_CHEST, TagAPI.BLOCK_WOODEN_CHEST) - .setItemTags(TagAPI.ITEM_CHEST, TagAPI.ITEM_WOODEN_CHEST)); - - addBlockEntry(new BlockEntry(BLOCK_BARREL, (complexMaterial, settings) -> { - return new BaseBarrelBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_BARREL, TagAPI.BLOCK_WOODEN_BARREL) - .setItemTags(TagAPI.ITEM_BARREL, TagAPI.ITEM_WOODEN_BARREL)); - } - - final protected void initDecorations(FabricBlockSettings blockSettings, FabricItemSettings itemSettings) { - addBlockEntry(new BlockEntry(BLOCK_CRAFTING_TABLE, (complexMaterial, settings) -> { - return new BaseCraftingTableBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_WORKBENCHES) - .setItemTags(TagAPI.ITEM_WORKBENCHES)); - - addBlockEntry(new BlockEntry(BLOCK_BOOKSHELF, (complexMaterial, settings) -> { - return new BaseBookshelfBlock(getBlock(BLOCK_PLANKS)); - }).setBlockTags(TagAPI.BLOCK_BOOKSHELVES)); - - addBlockEntry(new BlockEntry(BLOCK_COMPOSTER, (complexMaterial, settings) -> { - return new BaseComposterBlock(getBlock(BLOCK_PLANKS)); - })); - } - - @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); - GridRecipe.make(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) -> { - GridRecipe.make(id, getBlock(BLOCK_STAIRS)) - .checkConfig(config) - .setOutputCount(4) - .setShape("# ", "## ", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_stairs") - .build(); - })); - addRecipeEntry(new RecipeEntry("slab", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_SLAB)) - .checkConfig(config) - .setOutputCount(6) - .setShape("###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_slabs") - .build(); - })); - addRecipeEntry(new RecipeEntry("fence", (material, config, id) -> { - GridRecipe.make(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) -> { - GridRecipe.make(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) -> { - GridRecipe.make(id, getBlock(BLOCK_BUTTON)) - .checkConfig(config) - .setList("#") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_buttons") - .build(); - })); - addRecipeEntry(new RecipeEntry("pressure_plate", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_PRESSURE_PLATE)) - .checkConfig(config) - .setShape("##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_planks_plates") - .build(); - })); - addRecipeEntry(new RecipeEntry("trapdoor", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_TRAPDOOR)) - .checkConfig(config) - .setOutputCount(2) - .setShape("###", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_trapdoors") - .build(); - })); - addRecipeEntry(new RecipeEntry("door", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_DOOR)) - .checkConfig(config) - .setOutputCount(3) - .setShape("##", "##", "##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_doors") - .build(); - })); - addRecipeEntry(new RecipeEntry("crafting_table", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_CRAFTING_TABLE)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_tables") - .build(); - })); - addRecipeEntry(new RecipeEntry("ladder", (material, config, id) -> { - GridRecipe.make(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) -> { - GridRecipe.make(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) -> { - GridRecipe.make(id, getBlock(BLOCK_CHEST)) - .checkConfig(config) - .setShape("###", "# #", "###") - .addMaterial('#', planks) - .setGroup(receipGroupPrefix + "_chests") - .build(); - })); - addRecipeEntry(new RecipeEntry("barrel", (material, config, id) -> { - GridRecipe.make(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) -> { - GridRecipe.make(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) -> { - GridRecipe.make(id, getBlock(BLOCK_BARK)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_LOG)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("log", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_LOG)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_BARK)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("stripped_bark", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_STRIPPED_BARK)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_STRIPPED_LOG)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("stripped_log", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_STRIPPED_LOG)) - .checkConfig(config) - .setShape("##", "##") - .addMaterial('#', getBlock(BLOCK_STRIPPED_BARK)) - .setOutputCount(3) - .build(); - })); - addRecipeEntry(new RecipeEntry("composter", (material, config, id) -> { - GridRecipe.make(id, getBlock(BLOCK_COMPOSTER)) - .checkConfig(config) - .setShape("# #", "# #", "###") - .addMaterial('#', getBlock(BLOCK_SLAB)) - .build(); - })); - addRecipeEntry(new RecipeEntry("shulker", (material, config, id) -> { - GridRecipe.make(id, Blocks.SHULKER_BOX) - .checkConfig(config) - .setShape("S", "#", "S") - .addMaterial('S', Items.SHULKER_SHELL) - .addMaterial('#', getBlock(BLOCK_CHEST)) - .build(); - })); - } -} \ No newline at end of file diff --git a/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java deleted file mode 100644 index edda7b8a..00000000 --- a/src/main/java/ru/bclib/complexmaterials/entry/BlockEntry.java +++ /dev/null @@ -1,58 +0,0 @@ -package ru.bclib.complexmaterials.entry; - -import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -import net.minecraft.world.item.Item; -import net.minecraft.world.level.block.Block; -import ru.bclib.api.TagAPI; -import ru.bclib.complexmaterials.ComplexMaterial; -import ru.bclib.registry.BlockRegistry; - -import java.util.function.BiFunction; - -public class BlockEntry extends ComplexMaterialEntry { - final BiFunction initFunction; - final boolean hasItem; - - Tag.Named[] blockTags; - Tag.Named[] 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; - } - - public BlockEntry setBlockTags(Tag.Named... blockTags) { - this.blockTags = blockTags; - return this; - } - - public BlockEntry setItemTags(Tag.Named... itemTags) { - this.itemTags = itemTags; - return this; - } - - public Block init(ComplexMaterial material, FabricBlockSettings 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) { - TagAPI.addTags(block, itemTags); - } - } - else { - registry.registerBlockOnly(location, block); - } - if (blockTags != null) { - TagAPI.addTags(block, blockTags); - } - return block; - } -} diff --git a/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java deleted file mode 100644 index d2158e7f..00000000 --- a/src/main/java/ru/bclib/complexmaterials/entry/ComplexMaterialEntry.java +++ /dev/null @@ -1,40 +0,0 @@ -package ru.bclib.complexmaterials.entry; - -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.NotNull; - -import java.util.Objects; - -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/ru/bclib/complexmaterials/entry/ItemEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java deleted file mode 100644 index a9be883b..00000000 --- a/src/main/java/ru/bclib/complexmaterials/entry/ItemEntry.java +++ /dev/null @@ -1,37 +0,0 @@ -package ru.bclib.complexmaterials.entry; - -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -import net.minecraft.world.item.Item; -import ru.bclib.api.TagAPI; -import ru.bclib.complexmaterials.ComplexMaterial; -import ru.bclib.registry.ItemRegistry; - -import java.util.function.BiFunction; - -public class ItemEntry extends ComplexMaterialEntry { - final BiFunction initFunction; - - Tag.Named[] itemTags; - - public ItemEntry(String suffix, BiFunction initFunction) { - super(suffix); - this.initFunction = initFunction; - } - - public ItemEntry setItemTags(Tag.Named[] itemTags) { - this.itemTags = itemTags; - return this; - } - - public Item init(ComplexMaterial material, FabricItemSettings itemSettings, ItemRegistry registry) { - ResourceLocation location = getLocation(material.getModID(), material.getBaseName()); - Item item = initFunction.apply(material, itemSettings); - registry.register(location, item); - if (itemTags != null) { - TagAPI.addTags(item, itemTags); - } - return item; - } -} diff --git a/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java b/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java deleted file mode 100644 index d3c08420..00000000 --- a/src/main/java/ru/bclib/complexmaterials/entry/RecipeEntry.java +++ /dev/null @@ -1,19 +0,0 @@ -package ru.bclib.complexmaterials.entry; - -import net.minecraft.resources.ResourceLocation; -import ru.bclib.complexmaterials.ComplexMaterial; -import ru.bclib.config.PathConfig; -import ru.bclib.interfaces.TriConsumer; - -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/ru/bclib/config/CategoryConfig.java b/src/main/java/ru/bclib/config/CategoryConfig.java index 54611ce1..ae2fb2e2 100644 --- a/src/main/java/ru/bclib/config/CategoryConfig.java +++ b/src/main/java/ru/bclib/config/CategoryConfig.java @@ -1,7 +1,7 @@ package ru.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/ru/bclib/config/ClientConfig.java b/src/main/java/ru/bclib/config/ClientConfig.java deleted file mode 100644 index 8ba337b1..00000000 --- a/src/main/java/ru/bclib/config/ClientConfig.java +++ /dev/null @@ -1,48 +0,0 @@ -package ru.bclib.config; - -import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.handler.autosync.AutoSync; - -public class ClientConfig extends NamedPathConfig { - 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(false, "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(topPadding = 12) - public static final ConfigToken DEBUG_HASHES = ConfigToken.Boolean(false, "debugHashes", AutoSync.SYNC_CATEGORY); - - - 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()*/; - } -} diff --git a/src/main/java/ru/bclib/config/Config.java b/src/main/java/ru/bclib/config/Config.java index ba2c8afb..968c45d7 100644 --- a/src/main/java/ru/bclib/config/Config.java +++ b/src/main/java/ru/bclib/config/Config.java @@ -1,86 +1,29 @@ package ru.bclib.config; import org.jetbrains.annotations.Nullable; + import ru.bclib.BCLib; -import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.dataexchange.SyncFileHash; -import ru.bclib.api.dataexchange.handler.autosync.AutoSyncID; -import ru.bclib.api.dataexchange.handler.autosync.FileContentWrapper; import ru.bclib.config.ConfigKeeper.BooleanEntry; import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.FloatEntry; import ru.bclib.config.ConfigKeeper.IntegerEntry; import ru.bclib.config.ConfigKeeper.RangeEntry; -import ru.bclib.config.ConfigKeeper.StringArrayEntry; import ru.bclib.config.ConfigKeeper.StringEntry; -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public abstract class Config { - public static final String CONFIG_SYNC_PREFIX = "CONFIG_"; - protected final static Map autoSyncConfigs = new HashMap<>(); 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; + public Config(String modID, String 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()); - - autoSyncConfigs.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 = autoSyncConfigs.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); @@ -112,15 +55,14 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } - catch (NullPointerException ex) { + } catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; } protected int getInt(ConfigKey key, int defaultValue) { - Integer val = keeper.getValue(key, IntegerEntry.class); + Integer val = keeper.getValue(key, IntegerEntry.class); if (val == null) { IntegerEntry entry = keeper.registerEntry(key, new IntegerEntry(defaultValue)); return entry.getValue(); @@ -129,7 +71,7 @@ public abstract class Config { } protected int getInt(ConfigKey key) { - Integer val = keeper.getValue(key, IntegerEntry.class); + Integer val = keeper.getValue(key, IntegerEntry.class); return val != null ? val : 0; } @@ -139,8 +81,7 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } - catch (NullPointerException ex) { + } catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; @@ -152,8 +93,7 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } - catch (NullPointerException | ClassCastException ex) { + } catch (NullPointerException | ClassCastException ex) { BCLib.LOGGER.catching(ex); } return false; @@ -179,8 +119,7 @@ public abstract class Config { if (entry == null) return false; entry.setValue(value); return true; - } - catch (NullPointerException ex) { + } catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; @@ -206,35 +145,7 @@ public abstract class Config { 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, StringArrayEntry.class); - if (str == null) { - StringArrayEntry entry = keeper.registerEntry(key, new StringArrayEntry(defaultValue)); - return entry.getValue(); - } - return str != null ? str : defaultValue; - } - - protected List getStringArray(ConfigKey key) { - List str = keeper.getValue(key, StringArrayEntry.class); - return str != null ? str : new ArrayList<>(0); - } - - protected boolean setStringArray(ConfigKey key, List value) { - try { - StringArrayEntry entry = keeper.getEntry(key, StringArrayEntry.class); - if (entry == null) return false; - entry.setValue(value); - return true; - } - catch (NullPointerException ex) { + } catch (NullPointerException ex) { BCLib.LOGGER.catching(ex); } return false; diff --git a/src/main/java/ru/bclib/config/ConfigKeeper.java b/src/main/java/ru/bclib/config/ConfigKeeper.java index f3e6263e..0fc7f049 100644 --- a/src/main/java/ru/bclib/config/ConfigKeeper.java +++ b/src/main/java/ru/bclib/config/ConfigKeeper.java @@ -1,134 +1,45 @@ package ru.bclib.config; -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 net.minecraft.util.GsonHelper; -import org.jetbrains.annotations.Nullable; -import ru.bclib.api.dataexchange.handler.autosync.FileContentWrapper; -import ru.bclib.util.JsonFactory; -import ru.bclib.util.Pair; - -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; + +import com.google.common.collect.Maps; +import com.google.common.reflect.TypeToken; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import net.minecraft.util.GsonHelper; +import ru.bclib.util.JsonFactory; + public final class ConfigKeeper { private final Map> configEntries = Maps.newHashMap(); - private JsonObject configObject; + private final JsonObject configObject; private final ConfigWriter writer; - + private boolean changed = false; - + public ConfigKeeper(String modID, String group) { this.writer = new ConfigWriter(modID, group); this.configObject = writer.load(); } - - 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) { - 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); @@ -139,13 +50,13 @@ public final class ConfigKeeper { obj = element.getAsJsonObject(); } } - + String paramKey = key.getEntry(); paramKey += " [default: " + entry.getDefault() + "]"; - + this.changed |= entry.setLocation(obj, paramKey); } - + private > void storeValue(E entry, T value) { if (configObject == null) { return; @@ -155,14 +66,14 @@ public final class ConfigKeeper { 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); @@ -171,7 +82,7 @@ public final class ConfigKeeper { } return null; } - + @Nullable public > T getValue(ConfigKey key, Class type) { Entry entry = this.getEntry(key, type); @@ -180,7 +91,7 @@ public final class ConfigKeeper { } return entry.getValue(); } - + public > E registerEntry(ConfigKey key, E entry) { entry.setWriter(value -> this.storeValue(entry, value)); entry.setReader(() -> { @@ -190,163 +101,119 @@ public final class ConfigKeeper { 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); - } - } - + public static class EnumEntry> extends Entry { - + private final Type type; - + public EnumEntry(T defaultValue) { super(defaultValue); TypeToken token = new TypeToken() { @@ -354,71 +221,71 @@ public final class ConfigKeeper { }; 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; @@ -428,23 +295,24 @@ public final class ConfigKeeper { } return false; } - + protected boolean hasLocation() { - return this.location != null && this.key != null; + 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); } diff --git a/src/main/java/ru/bclib/config/ConfigKey.java b/src/main/java/ru/bclib/config/ConfigKey.java index 5a1663c8..ed8b570d 100644 --- a/src/main/java/ru/bclib/config/ConfigKey.java +++ b/src/main/java/ru/bclib/config/ConfigKey.java @@ -1,10 +1,6 @@ package ru.bclib.config; import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.NotNull; -import ru.bclib.util.Pair; - -import java.util.Arrays; public class ConfigKey { private final String path[]; @@ -21,11 +17,11 @@ public class ConfigKey { public ConfigKey(String entry, ResourceLocation path) { this(entry, path.getNamespace(), path.getPath()); } - + public String[] getPath() { return path; } - + public String getEntry() { return entry; } @@ -33,16 +29,16 @@ public class ConfigKey { 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 + path.hashCode(); result = prime * result + entry.hashCode(); return result; } - + @Override public boolean equals(Object obj) { if (this == obj) { @@ -86,15 +82,4 @@ public class ConfigKey { 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/ru/bclib/config/ConfigUI.java b/src/main/java/ru/bclib/config/ConfigUI.java deleted file mode 100644 index b91975bc..00000000 --- a/src/main/java/ru/bclib/config/ConfigUI.java +++ /dev/null @@ -1,25 +0,0 @@ -package ru.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. - */ - public boolean hide() default false; - - /** - * When a Widget is generated for this option, it will be indented by this Value - */ - public int leftPadding() default 0; - - /** - * When a Widget is generated for this option, it will be indented by this Value - */ - public int topPadding() default 0; -} diff --git a/src/main/java/ru/bclib/config/ConfigWriter.java b/src/main/java/ru/bclib/config/ConfigWriter.java index 5a383ccc..ed4e125b 100644 --- a/src/main/java/ru/bclib/config/ConfigWriter.java +++ b/src/main/java/ru/bclib/config/ConfigWriter.java @@ -1,21 +1,22 @@ package ru.bclib.config; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import net.fabricmc.loader.api.FabricLoader; -import ru.bclib.util.JsonFactory; - import java.io.File; import java.nio.file.Path; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import net.fabricmc.loader.api.FabricLoader; +import ru.bclib.util.JsonFactory; + 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"); + this.configFile = new File(new File(GAME_CONFIG_DIR.toFile(), modID), configFile + ".json"); File parent = this.configFile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); @@ -23,14 +24,10 @@ public class ConfigWriter { this.load(); } - File getConfigFile(){ - return this.configFile; - } - public JsonObject getConfig() { return configObject; } - + public void save() { if (configObject == null) { return; @@ -38,31 +35,26 @@ public class ConfigWriter { 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("[,:&\"\\|\\<\\>\\?\\*]", "_"); diff --git a/src/main/java/ru/bclib/config/Configs.java b/src/main/java/ru/bclib/config/Configs.java index 2926b235..c847a620 100644 --- a/src/main/java/ru/bclib/config/Configs.java +++ b/src/main/java/ru/bclib/config/Configs.java @@ -1,28 +1,11 @@ package ru.bclib.config; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; import ru.bclib.BCLib; 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 PathConfig GENERATOR_CONFIG = new PathConfig(BCLib.MOD_ID, "generator", false); - public static final PathConfig MAIN_CONFIG = new PathConfig(BCLib.MOD_ID, "main", true, true); - public static final String MAIN_PATCH_CATEGORY = "patches"; - public static final PathConfig RECIPE_CONFIG = new PathConfig(BCLib.MOD_ID, "recipes"); - - public static void save() { - MAIN_CONFIG.saveChanges(); RECIPE_CONFIG.saveChanges(); - GENERATOR_CONFIG.saveChanges(); } } diff --git a/src/main/java/ru/bclib/config/IdConfig.java b/src/main/java/ru/bclib/config/IdConfig.java index cc8f8330..379d8551 100644 --- a/src/main/java/ru/bclib/config/IdConfig.java +++ b/src/main/java/ru/bclib/config/IdConfig.java @@ -1,13 +1,14 @@ package ru.bclib.config; -import net.minecraft.resources.ResourceLocation; +import java.util.function.BiFunction; + import org.jetbrains.annotations.Nullable; + +import net.minecraft.resources.ResourceLocation; import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.FloatRange; import ru.bclib.config.ConfigKeeper.IntegerRange; -import java.util.function.BiFunction; - public class IdConfig extends Config { protected final BiFunction keyFactory; @@ -15,48 +16,48 @@ public class IdConfig extends Config { 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, IntegerRange.class); } @@ -64,27 +65,27 @@ public class IdConfig extends Config { public boolean setRangedFloat(ResourceLocation id, String key, float value) { return this.setRanged(createKey(id, key), value, 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/ru/bclib/config/NamedPathConfig.java b/src/main/java/ru/bclib/config/NamedPathConfig.java deleted file mode 100644 index b7ce4404..00000000 --- a/src/main/java/ru/bclib/config/NamedPathConfig.java +++ /dev/null @@ -1,250 +0,0 @@ -package ru.bclib.config; - -import net.minecraft.resources.ResourceLocation; -import ru.bclib.BCLib; -import ru.bclib.config.ConfigKeeper.BooleanEntry; -import ru.bclib.config.ConfigKeeper.FloatEntry; -import ru.bclib.config.ConfigKeeper.IntegerEntry; -import ru.bclib.config.ConfigKeeper.StringArrayEntry; -import ru.bclib.config.ConfigKeeper.StringEntry; - -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; - - @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(); - } else { - this.hidden = false; - this.leftPadding = 0; - topPadding = 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(BooleanEntry.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(BooleanEntry.class, defaultValue, entry, path); - } - - public static ConfigToken Int(int defaultValue, String entry, String path) { - return new ConfigToken(IntegerEntry.class, defaultValue, entry, path); - } - - public static ConfigToken Float(float defaultValue, String entry, String path) { - return new ConfigToken(FloatEntry.class, defaultValue, entry, path); - } - - public static ConfigToken String(String defaultValue, String entry, String path) { - return new ConfigToken(StringEntry.class, defaultValue, entry, path); - } - - public static ConfigToken> StringArray(List defaultValue, String entry, String path) { - return new ConfigToken>(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 (BooleanEntry.class.isAssignableFrom(what.type)){ - return (T)_getBoolean((ConfigToken)what, raw); - } - if (IntegerEntry.class.isAssignableFrom(what.type)){ - return (T)_getInt((ConfigToken)what); - } - if (FloatEntry.class.isAssignableFrom(what.type)){ - return (T)_getFloat((ConfigToken)what); - } - if (StringEntry.class.isAssignableFrom(what.type)){ - return (T)_getString((ConfigToken)what); - } - if (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/ru/bclib/config/PathConfig.java b/src/main/java/ru/bclib/config/PathConfig.java index 062e60ec..3f7bc3e9 100644 --- a/src/main/java/ru/bclib/config/PathConfig.java +++ b/src/main/java/ru/bclib/config/PathConfig.java @@ -1,32 +1,25 @@ package ru.bclib.config; import org.jetbrains.annotations.Nullable; + import ru.bclib.config.ConfigKeeper.Entry; import ru.bclib.config.ConfigKeeper.FloatRange; import ru.bclib.config.ConfigKeeper.IntegerRange; 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) { + protected ConfigKey createKey(String category, String key) { return new ConfigKey(key, category.split("\\.")); } - protected static ConfigKey createKey(String key) { + protected ConfigKey createKey(String key) { return createKey("", key); } @@ -34,36 +27,36 @@ public class PathConfig extends Config { 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, IntegerRange.class); } @@ -71,27 +64,27 @@ public class PathConfig extends Config { public boolean setRangedFloat(String category, String key, float value) { return this.setRanged(createKey(category, key), value, 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); } @@ -101,27 +94,27 @@ public class PathConfig extends Config { 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, IntegerRange.class); } @@ -129,27 +122,27 @@ public class PathConfig extends Config { public boolean setRangedFloatRoot(String key, float value) { return this.setRanged(createKey(key), value, 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/ru/bclib/config/ServerConfig.java b/src/main/java/ru/bclib/config/ServerConfig.java deleted file mode 100644 index bf8a66b7..00000000 --- a/src/main/java/ru/bclib/config/ServerConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -package ru.bclib.config; - -import ru.bclib.BCLib; -import ru.bclib.api.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 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()*/; - } - -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridCell.java b/src/main/java/ru/bclib/gui/gridlayout/GridCell.java deleted file mode 100644 index 6e99bbea..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridCell.java +++ /dev/null @@ -1,27 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import ru.bclib.interfaces.TriConsumer; - -import java.util.List; -import java.util.function.Function; - -@Environment(EnvType.CLIENT) -class GridCell extends GridCellDefinition { - public final float height; - Function componentPlacer; - TriConsumer customRender; - - GridCell(double width, double height, GridLayout.GridValueType widthType, Function componentPlacer, TriConsumer customRender) { - super(width, widthType); - this.height = (float) height; - this.componentPlacer = componentPlacer; - this.customRender = customRender; - } - - protected GridElement buildElementAt(int left, int top, int width, final List collector) { - return new GridElement(left, top, width, (int) this.height, componentPlacer, customRender); - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridCheckboxCell.java b/src/main/java/ru/bclib/gui/gridlayout/GridCheckboxCell.java deleted file mode 100644 index dc6d3c23..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridCheckboxCell.java +++ /dev/null @@ -1,77 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.components.Checkbox; -import net.minecraft.network.chat.Component; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; - -import java.util.function.Consumer; - -@Environment(EnvType.CLIENT) -class SignalingCheckBox extends Checkbox{ - private Consumer onChange; - public SignalingCheckBox(int left, int top, int width, int height, Component component, boolean checked, Consumer onChange) { - super(left, top, width, height, component, checked); - this.onChange = onChange; - if (onChange!=null) - onChange.accept(checked); - } - - @Override - public void onPress() { - super.onPress(); - if (onChange!=null) - onChange.accept(this.selected()); - } -} - -@Environment(EnvType.CLIENT) -public class GridCheckboxCell extends GridCell implements GridWidgetWithEnabledState{ - private boolean checked; - private Checkbox lastCheckbox; - private boolean enabled; - private final float alpha; - - GridCheckboxCell(Component text, boolean checked, float alpha, double width, GridValueType widthType, double height) { - this(text, checked, alpha, width, widthType, height, null); - } - - GridCheckboxCell(Component text, boolean checked, float alpha, double width, GridValueType widthType, double height, Consumer onChange) { - super(width, height, widthType, null, null); - lastCheckbox = null; - enabled = true; - this.alpha = alpha; - this.componentPlacer = (transform) -> { - Checkbox cb = new SignalingCheckBox(transform.left, transform.top, transform.width, transform.height, - text, - checked, - (state)-> { - this.checked = state; - if (onChange!=null) onChange.accept(state); - } - ); - cb.setAlpha(alpha); - lastCheckbox = cb; - setEnabled(enabled); - return cb; - }; - - } - - public boolean isChecked(){ - return checked; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - if (lastCheckbox!=null){ - lastCheckbox.active = enabled; - lastCheckbox.setAlpha(enabled?alpha:(alpha *0.5f)); - } - this.enabled = enabled; - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridColumn.java b/src/main/java/ru/bclib/gui/gridlayout/GridColumn.java deleted file mode 100644 index 65511063..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridColumn.java +++ /dev/null @@ -1,72 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; -import ru.bclib.gui.gridlayout.GridLayout.VerticalAlignment; - -import java.util.List; - -@Environment(EnvType.CLIENT) -public class GridColumn extends GridContainer { - GridColumn(double width) { - super(width); - } - - GridColumn(double width, GridLayout.GridValueType widthType) { - super(width, widthType); - } - - public GridRow addRow() { - return addRow(VerticalAlignment.TOP); - } - - public GridRow addRow(VerticalAlignment align) { - GridRow row = new GridRow(1.0, widthType==GridValueType.INHERIT?GridValueType.INHERIT:GridLayout.GridValueType.PERCENTAGE, align); - this.cells.add(row); - return row; - } - - - public void addSpacerRow() { - this.addSpacerRow(4); - } - - public void addSpacerRow(int height) { - GridCell cell = new GridCell(1.0, height, GridValueType.PERCENTAGE, null, null); - this.cells.add(cell); - } - - @Override - public int calculateWidth(final int parentWidth){ - if (widthType == GridValueType.INHERIT) { - return cells.stream() - .filter(row->row.widthType == GridValueType.INHERIT) - .map(row -> row.buildElement(0, 0, 1, 0, 0, null).width) - .reduce(0, (p, c) -> Math.max(p, c)); - - } else { - return super.calculateWidth(parentWidth); - } - } - - - - @Override - protected GridElement buildElementAt(int left, int inTop, int width, final List collector) { - int height = 0; - int top = inTop; - - if (widthType == GridValueType.INHERIT) { - width = calculateWidth(width); - } - - for (GridCellDefinition row : cells) { - GridElement element = row.buildElement(width, 0, 1, left, top, collector); - top += element.height; - height += element.height; - } - - return new GridElement(left, inTop, width, height); - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridCustomRenderCell.java b/src/main/java/ru/bclib/gui/gridlayout/GridCustomRenderCell.java deleted file mode 100644 index d79229ea..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridCustomRenderCell.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; - - -@Environment(EnvType.CLIENT) -public abstract class GridCustomRenderCell extends GridCell{ - protected GridCustomRenderCell(double width, GridValueType widthType, double height) { - super(width, height, widthType, null, null); - this.customRender = this::onRender; - } - - public abstract void onRender(PoseStack poseStack, GridTransform transform, Object context); -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridImageCell.java b/src/main/java/ru/bclib/gui/gridlayout/GridImageCell.java deleted file mode 100644 index 51db3049..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridImageCell.java +++ /dev/null @@ -1,24 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import com.mojang.blaze3d.platform.GlStateManager; -import com.mojang.blaze3d.systems.RenderSystem; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.GuiComponent; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.resources.ResourceLocation; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; - -@Environment(EnvType.CLIENT) -public class GridImageCell extends GridCell{ - GridImageCell(ResourceLocation location, double width, GridValueType widthType, double height, float alpha, int uvLeft, int uvTop, int uvWidth, int uvHeight, int resourceWidth, int resourceHeight) { - super(width, height, widthType, null, (poseStack, transform, context) -> { - RenderSystem.setShader(GameRenderer::getPositionTexShader); - RenderSystem.setShaderTexture(0, location); - RenderSystem.enableBlend(); - RenderSystem.blendFunc(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA); - RenderSystem.setShaderColor(1.0F, 1.0F, 1.0F, alpha); - GuiComponent.blit(poseStack, transform.left, transform.top, transform.width, transform.height, uvLeft, uvTop, uvWidth, uvHeight, resourceWidth, resourceHeight); - }); - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java b/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java deleted file mode 100644 index cacee79d..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridLayout.java +++ /dev/null @@ -1,204 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import com.mojang.blaze3d.vertex.PoseStack; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.components.AbstractWidget; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; -import ru.bclib.util.Pair; -import ru.bclib.interfaces.TriConsumer; - -import java.util.LinkedList; -import java.util.List; -import java.util.function.Function; - - -@Environment(EnvType.CLIENT) -abstract class GridCellDefinition { - public final float width; - public final GridLayout.GridValueType widthType; - - public GridCellDefinition(double width, GridLayout.GridValueType widthType) { - this.width = (float)width; - this.widthType = widthType; - } - - public - int calculateWidth(final int parentWidth){ - if (widthType == GridLayout.GridValueType.CONSTANT) { - return (int) this.width; - } else if (widthType == GridValueType.PERCENTAGE) { - return (int) (this.width * parentWidth); - } else { - return 0; - } - } - - final GridElement buildElement(final int parentWidth, final int autoWidth, final float autoWidthSum, int left, final int top, final List collector) { - final int width = widthType == GridValueType.FILL ?(int)((this.width/autoWidthSum)*autoWidth):calculateWidth(parentWidth); - - final GridElement el = buildElementAt(left, top, width, collector); - if (collector!=null) { - collector.add(el); - } - return el; - } - - abstract protected GridElement buildElementAt(int left, int top, int width, final List collector); -} - -@Environment(EnvType.CLIENT) -class GridElement extends GridTransform{ - final Function componentPlacer; - final TriConsumer customRender; - Object renderContext; - - GridElement(int left, int top, int width, int height, Function componentPlacer, TriConsumer customRender) { - super(left, top, width, height); - this.componentPlacer = componentPlacer; - this.customRender = customRender; - } - - GridElement(int left, int top, int width, int height) { - this(left, top, width, height, null, null); - } - - GridTransform transformWithPadding(int leftPadding, int topPadding){ - return new GridTransform(left + leftPadding, top + topPadding, width, height); - } -} - -@Environment(EnvType.CLIENT) -abstract class GridContainer extends GridCellDefinition{ - protected List cells; - - public GridContainer(double width) { - this(width, GridLayout.GridValueType.CONSTANT); - } - - GridContainer(double width, GridLayout.GridValueType widthType) { - super(width, widthType); - cells = new LinkedList<>(); - } -} - -@Environment(EnvType.CLIENT) -public class GridLayout extends GridColumn { - public static final int COLOR_WHITE = 0xFFFFFFFF; - public static final int COLOR_RED = 0xFFDB1F48; - public static final int COLOR_CYAN = 0xFF01949A; - public static final int COLOR_GREEN = 0xFF00FF00; - public static final int COLOR_DARK_GREEN = 0xFF007F00; - public static final int COLOR_YELLOW = 0xFFFAD02C; - public static final int COLOR_BLUE = 0xFF0000FF; - public static final int COLOR_GRAY = 0xFF7F7F7F; - - public final GridScreen screen; - public final int screenHeight; - public final int sidePadding; - public final int initialTopPadding; - public final boolean centerVertically; - private int height; - private int topPadding; - - private List elements; - - public GridLayout(GridScreen screen) { - this(screen, 0, true); - } - - public GridLayout(GridScreen screen, int topPadding, boolean centerVertically) { - this(screen, topPadding, 20, centerVertically); - } - - public GridLayout(GridScreen screen, int topPadding, int sidePadding, boolean centerVertically) { - super(screen.width-2*sidePadding, GridValueType.CONSTANT); - this.screen = screen; - this.screenHeight = screen.height; - height = 0; - this.topPadding = topPadding; - this.sidePadding = sidePadding; - this.initialTopPadding = topPadding; - this.centerVertically = centerVertically; - } - - public int getHeight(){ - return height; - } - - public int getTopPadding() { - return topPadding; - } - - void buildLayout(){ - elements = new LinkedList<>(); - GridElement el = this.buildElement((int)this.width, 0, 1, 0,0, elements); - this.height = el.height; - if (centerVertically && el.height + initialTopPadding < screenHeight) { - topPadding = (screenHeight - el.height) >> 1; - } else { - topPadding = initialTopPadding; - } - - } - - public List> movableWidgets = new LinkedList<>(); - public void finalizeLayout(){ - buildLayout(); - - elements - .stream() - .filter(element -> element.componentPlacer!=null) - .forEach(element -> { - final GridTransform transform = element.transformWithPadding(sidePadding, topPadding); - final Object context = element.componentPlacer.apply(transform); - if (element.customRender != null){ - element.renderContext = context; - } else if (context instanceof AbstractWidget) { - final AbstractWidget widget = (AbstractWidget)context; - movableWidgets.add(new Pair(widget, widget.y)); - screen.addRenderableWidget(widget); - } - }); - } - - public void render(PoseStack poseStack){ - if (elements == null) return; - elements - .stream() - .filter(element -> element.customRender!=null) - .forEach(element -> element.customRender.accept(poseStack, element.transformWithPadding(sidePadding, topPadding), element.renderContext)); - } - - - public static enum VerticalAlignment { - TOP, CENTER, BOTTOM - } - - public static enum Alignment { - LEFT, CENTER, RIGHT - } - - /** - * Determines how a measurement value is interpreted - */ - public static enum GridValueType { - /** - * The value is a constant pixel size - */ - CONSTANT, - /** - * The Value is relative to the parent size - */ - PERCENTAGE, - /** - * The value will be set to fill up the remaining space (i.e. when this is applied to a width of a row element, - * a {@link #FILL}-type may be used to right align (FILL - CONSTANT) or center (FILL - CONSTANT - FILL) elements. - */ - FILL, - /** - * Calculate size based on child-elements - */ - INHERIT; - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridMessageCell.java b/src/main/java/ru/bclib/gui/gridlayout/GridMessageCell.java deleted file mode 100644 index 8c3c053c..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridMessageCell.java +++ /dev/null @@ -1,63 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.components.MultiLineLabel; -import net.minecraft.network.chat.Component; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; - -import java.util.List; - -@Environment(EnvType.CLIENT) -public class GridMessageCell extends GridCell { - private final Font font; - private Component text; - private MultiLineLabel lastLabel; - private GridTransform lastTransform; - - GridMessageCell(double width, GridValueType widthType, Alignment contentAlignment, Font font, Component text) { - this(width, widthType, contentAlignment, font, text, GridLayout.COLOR_WHITE); - } - GridMessageCell(double width, GridValueType widthType, Alignment contentAlignment, Font font, Component text, int color) { - super(width, -1, widthType, null, null); - this.font = font; - this.text = text; - - customRender = (poseStack, transform, context) -> { - //MultiLineLabel label = (MultiLineLabel) context; - if (contentAlignment == Alignment.CENTER) { - lastLabel.renderCentered(poseStack, transform.width / 2 + transform.left, transform.top, font.lineHeight, color); - } - else if (contentAlignment == Alignment.LEFT) { - lastLabel.renderLeftAligned(poseStack, transform.left, transform.top, font.lineHeight, color); - } - }; - } - - public void setText(Component text){ - this.text = text; - if (lastTransform!=null) { - create(lastTransform); - } - } - - private MultiLineLabel getLabel(GridTransform transform) { - return lastLabel; - } - - protected void create(GridTransform transform) { - this.lastTransform = transform; - this.lastLabel = MultiLineLabel.create(font, text, transform.width); - } - - @Override - protected GridElement buildElementAt(int left, int top, int width, List collector) { - create(new GridTransform(left, top, width, 0)); - int promptLines = this.lastLabel.getLineCount() + 1; - int height = promptLines * 9; - - return new GridElement(left, top, width, height, this::getLabel, customRender); - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridRow.java b/src/main/java/ru/bclib/gui/gridlayout/GridRow.java deleted file mode 100644 index 650a49d2..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridRow.java +++ /dev/null @@ -1,275 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.Font; -import net.minecraft.client.gui.components.Button; -import net.minecraft.client.gui.components.Button.OnPress; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; -import ru.bclib.gui.gridlayout.GridLayout.VerticalAlignment; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Function; - -@Environment(EnvType.CLIENT) -public class GridRow extends GridContainer { - public final GridLayout.VerticalAlignment alignment; - - GridRow(double width) { - this(width, VerticalAlignment.TOP); - } - - GridRow(double width, GridLayout.GridValueType widthType) { - this(width, widthType, VerticalAlignment.CENTER); - } - - GridRow(double width, GridLayout.VerticalAlignment alignment) { - super(width); - this.alignment = alignment; - } - - GridRow(double width, GridLayout.GridValueType widthType, GridLayout.VerticalAlignment alignment) { - super(width, widthType); - this.alignment = alignment; - } - - public GridColumn addColumn(double width, GridLayout.GridValueType widthType) { - GridColumn cell = new GridColumn(width, widthType); - this.cells.add(cell); - return cell; - } - - public GridCell addComponent(double height, Function componentPlacer) { - return addComponent(1.0, GridLayout.GridValueType.PERCENTAGE, height, componentPlacer); - } - - public GridCell addComponent(double width, GridLayout.GridValueType widthType, double height, Function componentPlacer) { - GridCell cell = new GridCell(width, height, widthType, componentPlacer, null); - this.cells.add(cell); - return cell; - } - - - public GridCell addButton(Component text, double height, OnPress onPress) { - return addButton(text, 1.0, GridValueType.PERCENTAGE, height, onPress); - } - - public GridCell addButton(Component text, float alpha, double height, OnPress onPress) { - return addButton(text, alpha, 1.0, GridValueType.PERCENTAGE, height, onPress); - } - - public GridCell addButton(Component text, double height, Font font, OnPress onPress) { - return addButton(text, 1.0f, height, font, onPress); - } - - public GridCell addButton(Component text, float alpha, double height, Font font, OnPress onPress) { - final int width = font.width(text.getVisualOrderText()) + 24; - return addButton(text, alpha, width, GridValueType.CONSTANT, height, onPress); - } - - public GridCell addButton(Component text, double width, GridValueType widthType, double height, OnPress onPress) { - return addButton(text, 1.0f, width, widthType, height, onPress); - } - - public GridCell addButton(Component text, float alpha, double width, GridValueType widthType, double height, OnPress onPress) { - GridCell cell = new GridCell(width, height, widthType, (transform) -> { - Button customButton = new Button(transform.left, transform.top, transform.width, transform.height, text, onPress); - customButton.setAlpha(alpha); - return customButton; - }, null); - this.cells.add(cell); - return cell; - } - - public GridCheckboxCell addCheckbox(Component text, boolean checked, Font font, Consumer onChange){ - final int width = font.width(text.getVisualOrderText()) + 24 + 2 * 12; - - GridCheckboxCell cell = new GridCheckboxCell(text, checked, 1.0f, width, widthType, 20, onChange); - this.cells.add(cell); - return cell; - } - - public GridCheckboxCell addCheckbox(Component text, boolean checked, int height) { - return addCheckbox(text, checked, 1.0f, height); - } - - public GridCheckboxCell addCheckbox(Component text, boolean checked, float alpha, int height) { - return addCheckbox(text, checked, alpha, 1.0, GridValueType.PERCENTAGE, height); - } - - public GridCheckboxCell addCheckbox(Component text, boolean checked, int height, Font font) { - return addCheckbox(text, checked, 1.0f, height, font); - } - - public GridCheckboxCell addCheckbox(Component text, boolean checked, float alpha, int height, Font font) { - final int width = font.width(text.getVisualOrderText()) + 24 + 2 * 12; - return addCheckbox(text, checked, alpha, width, GridValueType.CONSTANT, height); - } - - public GridCheckboxCell addCheckbox(Component text, boolean checked, double width, GridValueType widthType, int height) { - return addCheckbox(text, checked, 1.0f, width, widthType, height); - } - - public GridCheckboxCell addCheckbox(Component text, boolean checked, float alpha, double width, GridValueType widthType, int height) { - GridCheckboxCell cell = new GridCheckboxCell(text, checked, alpha, width, widthType, height); - this.cells.add(cell); - return cell; - } - - public GridCustomRenderCell addCustomRender(GridCustomRenderCell cell) { - this.cells.add(cell); - return cell; - } - - public GridCell addImage(ResourceLocation location, int width, int height) { - return addImage(location, 1.0f, width, height); - } - - public GridCell addImage(ResourceLocation location, float alpha, int width, int height) { - return addImage(location, alpha, width, GridValueType.CONSTANT, height, 0, 0, width, height, width, height); - } - - public GridCell addImage(ResourceLocation location, double width, GridValueType widthType, int height, int resourceWidth, int resourceHeight) { - return addImage(location, 1.0f, width, widthType, height, resourceWidth, resourceHeight); - } - - public GridCell addImage(ResourceLocation location, float alpha, double width, GridValueType widthType, int height, int resourceWidth, int resourceHeight) { - return addImage(location, alpha, width, widthType, height, 0, 0, resourceWidth, resourceWidth, resourceWidth, resourceHeight); - } - - public GridCell addImage(ResourceLocation location, double width, GridValueType widthType, int height, int uvLeft, int uvTop, int uvWidth, int uvHeight, int resourceWidth, int resourceHeight) { - return addImage(location, 1.0f, width, widthType, height, uvLeft, uvTop, uvWidth, uvHeight, resourceWidth, resourceHeight); - } - - public GridCell addImage(ResourceLocation location, float alpha, double width, GridValueType widthType, int height, int uvLeft, int uvTop, int uvWidth, int uvHeight, int resourceWidth, int resourceHeight) { - GridCell cell = new GridImageCell(location, width, widthType, height, alpha, uvLeft, uvTop, uvWidth, uvHeight, resourceWidth, resourceHeight); - this.cells.add(cell); - return cell; - } - - - public GridColumn addFiller() { - return addFiller(1); - } - - public GridColumn addFiller(float portion) { - GridColumn cell = new GridColumn(portion, GridValueType.FILL); - this.cells.add(cell); - return cell; - } - - public void addSpacer() { - addSpacer(12); - } - - public void addSpacer(int width) { - GridCell cell = new GridCell(width, 0, GridValueType.CONSTANT, null, null); - this.cells.add(cell); - } - - - public GridMessageCell addMessage(Component text, Font font, Alignment contentAlignment) { - return addMessage(text, font, GridLayout.COLOR_WHITE, contentAlignment); - } - - public GridMessageCell addMessage(Component text, Font font, int color, Alignment contentAlignment) { - return addMessage(text, 1.0, GridLayout.GridValueType.PERCENTAGE, font, color, contentAlignment); - } - - public GridMessageCell addMessage(Component text, double width, GridValueType widthType, Font font, Alignment contentAlignment) { - return addMessage(text, width, widthType, font, GridLayout.COLOR_WHITE, contentAlignment); - } - - public GridMessageCell addMessage(Component text, double width, GridValueType widthType, Font font, int color, Alignment contentAlignment) { - GridMessageCell cell = new GridMessageCell(width, widthType, contentAlignment, font, text, color); - this.cells.add(cell); - return cell; - } - - public GridStringCell addString(Component text, GridScreen parent) { - return this.addString(text, GridLayout.COLOR_WHITE, parent); - } - - - public GridStringCell addString(Component text, int color, GridScreen parent) { - final int width = parent.getWidth(text); - return this.addString(text, width, GridValueType.CONSTANT, color, Alignment.CENTER, parent); - } - - public GridStringCell addString(Component text, Alignment contentAlignment, GridScreen parent) { - return this.addString(text, GridLayout.COLOR_WHITE, contentAlignment, parent); - } - - public GridStringCell addString(Component text, int color, Alignment contentAlignment, GridScreen parent) { - return this.addString(text, 1.0, GridLayout.GridValueType.PERCENTAGE, color, contentAlignment, parent); - } - - public GridStringCell addString(Component text, double width, GridValueType widthType, Alignment contentAlignment, GridScreen parent) { - return addString(text, width, widthType, GridLayout.COLOR_WHITE, contentAlignment, parent); - } - - public GridStringCell addString(Component text, double width, GridValueType widthType, int color, Alignment contentAlignment, GridScreen parent) { - GridStringCell cell = new GridStringCell(width, widthType, parent.getFont().lineHeight, contentAlignment, parent, text, color); - this.cells.add(cell); - return cell; - } - - @Override - protected GridElement buildElementAt(int inLeft, int top, int width, final List collector) { - int height = 0; - int left = inLeft; - if (widthType == GridValueType.INHERIT) { - final int originalWidth = width; - width = cells.stream() - .filter(row -> row.widthType == GridValueType.CONSTANT || row.widthType == GridValueType.INHERIT) - .map(row -> row.buildElement(0, 0, 1, 0, 0, null).width) - .reduce(0, (p, c) -> p+c); - } - - final int inheritedWidth = width; - final int fixedWidth = cells.stream() - .filter(col -> col.widthType != GridValueType.FILL) - .map(col -> col.calculateWidth(inheritedWidth)) - .reduce(0, (p, c) -> p + c); - final float autoWidthSum = cells.stream() - .filter(col -> col.widthType == GridValueType.FILL) - .map(col -> col.width) - .reduce(0.0f, (p, c) -> p + c); - final int autoWidth = width - fixedWidth; - - if (alignment == VerticalAlignment.TOP) { - for (GridCellDefinition col : cells) { - GridElement element = col.buildElement(width, autoWidth, autoWidthSum, left, top, collector); - left += element.width; - height = Math.max(height, element.height); - } - } - else { - //first iteration will collect heights, second one will transform top position for alignment - Map cache = new HashMap<>(); - for (GridCellDefinition col : cells) { - GridElement element = col.buildElement(width, autoWidth, autoWidthSum, left, top, null); - left += element.width; - height = Math.max(height, element.height); - cache.put(col, element); - } - - left = inLeft; - for (GridCellDefinition col : cells) { - GridElement element = cache.get(col); - final int topOffset = (alignment == VerticalAlignment.BOTTOM) ? (height - element.height) : (height - element.height) >> 1; - element = col.buildElement(width, autoWidth, autoWidthSum, left, top + topOffset, collector); - left += element.width; - } - } - - - return new GridElement(inLeft, top, width, height); - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridScreen.java b/src/main/java/ru/bclib/gui/gridlayout/GridScreen.java deleted file mode 100644 index 663ca0dd..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridScreen.java +++ /dev/null @@ -1,257 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import com.mojang.blaze3d.systems.RenderSystem; -import com.mojang.blaze3d.vertex.BufferBuilder; -import com.mojang.blaze3d.vertex.DefaultVertexFormat; -import com.mojang.blaze3d.vertex.PoseStack; -import com.mojang.blaze3d.vertex.Tesselator; -import com.mojang.blaze3d.vertex.VertexFormat; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.Font; -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.screens.Screen; -import net.minecraft.client.renderer.GameRenderer; -import net.minecraft.network.chat.Component; -import net.minecraft.util.Mth; -import org.jetbrains.annotations.Nullable; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; - - -@Environment(EnvType.CLIENT) -public abstract class GridScreen extends Screen { - protected GridLayout grid = null; - public final int topPadding; - public final int sidePadding; - public final boolean centerVertically; - @Nullable - public final Screen parent; - - protected int scrollPos = 0; - - public GridScreen(Component title) { - this(null, title); - } - - public GridScreen(@Nullable Screen parent, Component title){ - this(parent, title, 0, true); - } - - public GridScreen(Component title, int topPadding, boolean centerVertically) { - this(null, title, topPadding, 20, centerVertically); - } - - public GridScreen(@Nullable Screen parent, Component title, int topPadding, boolean centerVertically) { - this(parent, title, topPadding, 20, centerVertically); - } - - public GridScreen(Component title, int topPadding, int sidePadding, boolean centerVertically) { - this(null, title, topPadding, sidePadding, centerVertically); - } - - public GridScreen(@Nullable Screen parent, Component title, int topPadding, int sidePadding, boolean centerVertically) { - super(title); - - this.parent = parent; - this.topPadding = topPadding; - this.sidePadding = sidePadding; - this.centerVertically = centerVertically; - } - - @Override - public void onClose() { - this.minecraft.setScreen(parent); - } - - public Font getFont(){ - return this.font; - } - - @Override - public boolean isPauseScreen() { - return true; - } - - @Override - public T addRenderableWidget(T guiEventListener) { - return super.addRenderableWidget(guiEventListener); - } - - protected void addTitle(){ - grid.addRow().addString(this.title, Alignment.CENTER, this); - grid.addSpacerRow(15); - } - - final protected void init() { - super.init(); - this.grid = new GridLayout(this, this.topPadding, this.sidePadding, this.centerVertically); - - addTitle(); - - initLayout(); - grid.finalizeLayout(); - } - - protected abstract void initLayout(); - - protected void renderScreen(PoseStack poseStack, int i, int j, float f) { - super.render(poseStack, i, j, f); - } - - public void render(PoseStack poseStack, int i, int j, float f) { - this.renderDirtBackground(i); - renderGrid(poseStack); - super.render(poseStack, i, j, f); - } - - protected void renderGrid(PoseStack poseStack) { - if (grid!=null) { - if (isScrollable()) { - for (var item : grid.movableWidgets) { - item.first.y = item.second + scrollPos; - } - - renderScroll(poseStack); - - poseStack.pushPose(); - poseStack.translate(0, scrollPos, 0); - grid.render(poseStack); - poseStack.popPose(); - } else { - grid.render(poseStack); - } - } - } - - public static int getWidth(Component text, Font font) { - return font.width(text.getVisualOrderText()); - } - - public int getWidth(Component text) { - return getWidth(text, getFont()); - } - - public void setScrollPos(int sp) { - scrollPos = Math.max(getMaxScrollPos(), Math.min(0, sp)); - } - - public int getScrollPos() { - return scrollPos; - } - - public int getScrollHeight() { - if (grid!=null) return grid.getHeight() + topPadding; - return height; - } - - public int getMaxScrollPos() { - return height - (getScrollHeight() + topPadding); - } - - public boolean isScrollable() { - return height= 0 && y <= height && x >= width-SCROLLER_WIDTH && x <= width; - } - - private boolean scrolling = false; - protected void updateScrollingState(double x, double y, int i) { - this.scrolling = i == 0 && x >= width-SCROLLER_WIDTH && x < width; - } - - private static final int SCROLLER_WIDTH = 6; - private void renderScroll(PoseStack poseStack){ - final int y1 = height; - final int y0 = 0; - final int yd = y1 - y0; - final int maxPosition = getScrollHeight() + topPadding; - - final int x0 = width-SCROLLER_WIDTH; - final int x1 = width; - - Tesselator tesselator = Tesselator.getInstance(); - BufferBuilder bufferBuilder = tesselator.getBuilder(); - RenderSystem.disableTexture(); - RenderSystem.setShader(GameRenderer::getPositionColorShader); - int widgetHeight = (int)((float)(yd*yd) / (float)maxPosition); - widgetHeight = Mth.clamp(widgetHeight, 32, yd - 8); - float relPos = (float)this.getScrollPos() / this.getMaxScrollPos(); - int top = (int)(relPos * (yd - widgetHeight)) + y0; - if (top < y0) { - top = y0; - } - - bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR); - - //scroller background - bufferBuilder.vertex((double)x0, (double)y1, 0.0D).color(0, 0, 0, 255).endVertex(); - bufferBuilder.vertex((double)x1, (double)y1, 0.0D).color(0, 0, 0, 255).endVertex(); - bufferBuilder.vertex((double)x1, (double)y0, 0.0D).color(0, 0, 0, 255).endVertex(); - bufferBuilder.vertex((double)x0, (double)y0, 0.0D).color(0, 0, 0, 255).endVertex(); - - //scroll widget shadow - bufferBuilder.vertex((double)x0, (double)(top + widgetHeight), 0.0D).color(128, 128, 128, 255).endVertex(); - bufferBuilder.vertex((double)x1, (double)(top + widgetHeight), 0.0D).color(128, 128, 128, 255).endVertex(); - bufferBuilder.vertex((double)x1, (double)top, 0.0D).color(128, 128, 128, 255).endVertex(); - bufferBuilder.vertex((double)x0, (double)top, 0.0D).color(128, 128, 128, 255).endVertex(); - - //scroll widget - bufferBuilder.vertex((double)x0, (double)(top + widgetHeight - 1), 0.0D).color(192, 192, 192, 255).endVertex(); - bufferBuilder.vertex((double)(x1 - 1), (double)(top + widgetHeight - 1), 0.0D).color(192, 192, 192, 255).endVertex(); - bufferBuilder.vertex((double)(x1 - 1), (double)top, 0.0D).color(192, 192, 192, 255).endVertex(); - bufferBuilder.vertex((double)x0, (double)top, 0.0D).color(192, 192, 192, 255).endVertex(); - tesselator.end(); - } - - public boolean mouseClicked(double x, double y, int i) { - this.updateScrollingState(x, y, i); - if (this.scrolling) { - return true; - } else { - return super.mouseClicked(x, y, i); - } - } - - public boolean mouseDragged(double xAbs, double yAbs, int i, double dX, double dY) { - if (super.mouseDragged(xAbs, yAbs, i, dX, dY)) { - return true; - } else if (i == 0 && this.scrolling) { - if (yAbs < 0) { - this.setScrollPos(0); - } else if (yAbs > height) { - this.setScrollPos(this.getMaxScrollPos()); - } else { - this.setScrollPos((int)(this.getScrollPos() - dY * 2)); - } - - return true; - } else { - return false; - } - } - - public boolean mouseScrolled(double d, double e, double f) { - if (isScrollable()) { - setScrollPos((int) (scrollPos + f * 10)); - } - return true; - } - - public boolean keyPressed(int keyCode, int j, int k) { - if (super.keyPressed(keyCode, j, k)) { - return true; - } else if (keyCode == 264) { - this.mouseScrolled(0, -1.0f, 0); - return true; - } else if (keyCode == 265) { - this.mouseScrolled(0, 1.0, 0); - return true; - } else { - return false; - } - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridStringCell.java b/src/main/java/ru/bclib/gui/gridlayout/GridStringCell.java deleted file mode 100644 index 3d4a4fe6..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridStringCell.java +++ /dev/null @@ -1,32 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.network.chat.Component; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; - -@Environment(EnvType.CLIENT) -public class GridStringCell extends GridCell { - private Component text; - GridStringCell(double width, GridValueType widthType, int height, Alignment contentAlignment, GridScreen parent, Component text) { - this(width, widthType, height, contentAlignment, parent, text, GridLayout.COLOR_WHITE); - - } - GridStringCell(double width, GridValueType widthType, int height, Alignment contentAlignment, GridScreen parent, Component text, int color) { - super(width, height, widthType, null, null); - this.text = text; - this.customRender = (poseStack, transform, context) -> { - if (contentAlignment == Alignment.CENTER) { - parent.drawCenteredString(poseStack, parent.getFont(), this.text, transform.width / 2 + transform.left, transform.top, color); - } - else if (contentAlignment == Alignment.LEFT) { - parent.drawString(poseStack, parent.getFont(), this.text, transform.left, transform.top, color); - } - }; - } - - public void setText(Component newText){ - this.text = newText; - } -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridTransform.java b/src/main/java/ru/bclib/gui/gridlayout/GridTransform.java deleted file mode 100644 index 4d392b41..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridTransform.java +++ /dev/null @@ -1,25 +0,0 @@ -package ru.bclib.gui.gridlayout; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; - -@Environment(EnvType.CLIENT) -public class GridTransform { - public final int left; - public final int top; - public final int width; - public final int height; - - GridTransform(int left, int top, int width, int height) { - this.left = left; - this.top = top; - this.width = width; - this.height = height; - } - - @Override - public String toString() { - return "{" + "left=" + left + ", top=" + top + ", width=" + width + ", height=" + height + '}'; - } - -} diff --git a/src/main/java/ru/bclib/gui/gridlayout/GridWidgetWithEnabledState.java b/src/main/java/ru/bclib/gui/gridlayout/GridWidgetWithEnabledState.java deleted file mode 100644 index caa9f150..00000000 --- a/src/main/java/ru/bclib/gui/gridlayout/GridWidgetWithEnabledState.java +++ /dev/null @@ -1,6 +0,0 @@ -package ru.bclib.gui.gridlayout; - -public interface GridWidgetWithEnabledState { - public boolean isEnabled(); - public void setEnabled(boolean enabled); -} diff --git a/src/main/java/ru/bclib/gui/modmenu/EntryPoint.java b/src/main/java/ru/bclib/gui/modmenu/EntryPoint.java deleted file mode 100644 index 18f3e4d5..00000000 --- a/src/main/java/ru/bclib/gui/modmenu/EntryPoint.java +++ /dev/null @@ -1,12 +0,0 @@ -package ru.bclib.gui.modmenu; - -import com.terraformersmc.modmenu.util.ModMenuApiMarker; -import ru.bclib.integration.ModMenuIntegration; - -public class EntryPoint extends ModMenuIntegration { - public static final ModMenuApiMarker entrypointObject = createEntrypoint(new EntryPoint()); - - public EntryPoint() { - super(MainScreen::new); - } -} diff --git a/src/main/java/ru/bclib/gui/modmenu/MainScreen.java b/src/main/java/ru/bclib/gui/modmenu/MainScreen.java deleted file mode 100644 index 3a649207..00000000 --- a/src/main/java/ru/bclib/gui/modmenu/MainScreen.java +++ /dev/null @@ -1,85 +0,0 @@ -package ru.bclib.gui.modmenu; - -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.TranslatableComponent; -import org.jetbrains.annotations.Nullable; -import ru.bclib.config.ConfigKeeper.BooleanEntry; -import ru.bclib.config.Configs; -import ru.bclib.config.NamedPathConfig; -import ru.bclib.config.NamedPathConfig.ConfigTokenDescription; -import ru.bclib.config.NamedPathConfig.DependendConfigToken; -import ru.bclib.gui.gridlayout.GridCheckboxCell; -import ru.bclib.gui.gridlayout.GridColumn; -import ru.bclib.gui.gridlayout.GridRow; -import ru.bclib.gui.gridlayout.GridScreen; -import ru.bclib.gui.gridlayout.GridWidgetWithEnabledState; - -import java.util.HashMap; -import java.util.Map; -import java.util.function.Supplier; - -public class MainScreen extends GridScreen{ - - public MainScreen(@Nullable Screen parent) { - super(parent, new TranslatableComponent("title.bclib.modmenu.main")); - } - - protected TranslatableComponent getComponent(NamedPathConfig config, ConfigTokenDescription option, String type){ - return new TranslatableComponent(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(GridColumn grid, NamedPathConfig config, ConfigTokenDescription option){ - if (BooleanEntry.class.isAssignableFrom(option.token.type)) { - addCheckbox(grid, config, (ConfigTokenDescription)option); - } - - grid.addSpacerRow(2); - } - - - protected void addCheckbox(GridColumn grid, NamedPathConfig config, ConfigTokenDescription option){ - if (option.topPadding>0){ - grid.addSpacerRow(option.topPadding); - } - GridRow row = grid.addRow(); - if (option.leftPadding>0){ - row.addSpacer(option.leftPadding); - } - GridCheckboxCell cb = row.addCheckbox(getComponent(config, option, "title"), config.getRaw(option.token), font, (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 void initLayout() { - final int BUTTON_HEIGHT = 20; - - Configs.CLIENT_CONFIG.getAllOptions().stream().filter(o -> !o.hidden).forEach(o -> addRow(grid, Configs.CLIENT_CONFIG, o)); - - grid.addSpacerRow(15); - GridRow row = grid.addRow(); - row.addFiller(); - row.addButton(CommonComponents.GUI_DONE, BUTTON_HEIGHT, font, (button)->{ - Configs.CLIENT_CONFIG.saveChanges(); - onClose(); - }); - } -} diff --git a/src/main/java/ru/bclib/gui/screens/AtomicProgressListener.java b/src/main/java/ru/bclib/gui/screens/AtomicProgressListener.java deleted file mode 100644 index c1b1c7e1..00000000 --- a/src/main/java/ru/bclib/gui/screens/AtomicProgressListener.java +++ /dev/null @@ -1,10 +0,0 @@ -package ru.bclib.gui.screens; - -import net.minecraft.network.chat.Component; - -public interface AtomicProgressListener { - public void incAtomic(int maxProgress); - public void resetAtomic(); - public void stop(); - public void progressStage(Component component); -} diff --git a/src/main/java/ru/bclib/gui/screens/BCLibScreen.java b/src/main/java/ru/bclib/gui/screens/BCLibScreen.java deleted file mode 100644 index bf95d7c4..00000000 --- a/src/main/java/ru/bclib/gui/screens/BCLibScreen.java +++ /dev/null @@ -1,53 +0,0 @@ -package ru.bclib.gui.screens; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.Component; -import net.minecraft.resources.ResourceLocation; -import org.jetbrains.annotations.Nullable; -import ru.bclib.BCLib; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; -import ru.bclib.gui.gridlayout.GridLayout.VerticalAlignment; -import ru.bclib.gui.gridlayout.GridRow; -import ru.bclib.gui.gridlayout.GridScreen; - -@Environment(EnvType.CLIENT) -abstract class BCLibScreen extends GridScreen { - static final ResourceLocation BCLIB_LOGO_LOCATION = new ResourceLocation(BCLib.MOD_ID, "icon.png"); - - public BCLibScreen(Component title) { - super(title); - } - - public BCLibScreen(@Nullable Screen parent, Component title){ - super(parent, title); - } - - public BCLibScreen(Component title, int topPadding, boolean centerVertically) { - super(title, topPadding, 20, centerVertically); - } - - public BCLibScreen(@Nullable Screen parent, Component title, int topPadding, boolean centerVertically) { - super(parent, title, topPadding, centerVertically); - } - - public BCLibScreen(Component title, int topPadding, int sidePadding, boolean centerVertically) { - super(title, topPadding, sidePadding, centerVertically); - } - - public BCLibScreen(@Nullable Screen parent, Component title, int topPadding, int sidePadding, boolean centerVertically) { - super(parent, title, topPadding, sidePadding, centerVertically); - } - - - protected void addTitle(){ - GridRow row = grid.addRow(VerticalAlignment.CENTER); - row.addFiller(); - row.addImage(BCLIB_LOGO_LOCATION, 24, GridValueType.CONSTANT, 24, 512, 512); - row.addSpacer(4); - row.addString(this.title, this); - row.addFiller(); - grid.addSpacerRow(15); - } -} diff --git a/src/main/java/ru/bclib/gui/screens/ConfirmFixScreen.java b/src/main/java/ru/bclib/gui/screens/ConfirmFixScreen.java deleted file mode 100644 index 20f983eb..00000000 --- a/src/main/java/ru/bclib/gui/screens/ConfirmFixScreen.java +++ /dev/null @@ -1,64 +0,0 @@ -package ru.bclib.gui.screens; - - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TranslatableComponent; -import org.jetbrains.annotations.Nullable; -import ru.bclib.gui.gridlayout.GridCheckboxCell; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridRow; - -@Environment(EnvType.CLIENT) -public class ConfirmFixScreen extends BCLibScreen { - protected final ConfirmFixScreen.Listener listener; - private final Component description; - protected int id; - - public ConfirmFixScreen(@Nullable Screen parent, ConfirmFixScreen.Listener listener) { - super(parent, new TranslatableComponent("bclib.datafixer.backupWarning.title")); - this.listener = listener; - - this.description = new TranslatableComponent("bclib.datafixer.backupWarning.message"); - } - - protected void initLayout() { - final int BUTTON_HEIGHT = 20; - - grid.addRow().addMessage(this.description, this.font, Alignment.CENTER); - grid.addSpacerRow(); - - GridRow row = grid.addRow(); - GridCheckboxCell backup = row.addCheckbox(new TranslatableComponent("bclib.datafixer.backupWarning.backup"), true, BUTTON_HEIGHT, this.font); - - grid.addSpacerRow(10); - - row = grid.addRow(); - GridCheckboxCell fix = row.addCheckbox(new TranslatableComponent("bclib.datafixer.backupWarning.fix"), true, BUTTON_HEIGHT, this.font); - - grid.addSpacerRow(20); - - row = grid.addRow(); - row.addFiller(); - row.addButton(CommonComponents.GUI_CANCEL, BUTTON_HEIGHT, this.font, (button) -> { - onClose(); - }); - row.addSpacer(); - row.addButton(CommonComponents.GUI_PROCEED, BUTTON_HEIGHT, this.font, (button) -> { - this.listener.proceed(backup.isChecked(), fix.isChecked()); - }); - row.addFiller(); - } - - public boolean shouldCloseOnEsc() { - return true; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(boolean createBackup, boolean applyPatches); - } -} diff --git a/src/main/java/ru/bclib/gui/screens/ConfirmRestartScreen.java b/src/main/java/ru/bclib/gui/screens/ConfirmRestartScreen.java deleted file mode 100644 index f4138f50..00000000 --- a/src/main/java/ru/bclib/gui/screens/ConfirmRestartScreen.java +++ /dev/null @@ -1,51 +0,0 @@ -package ru.bclib.gui.screens; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TranslatableComponent; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridRow; - - -@Environment(EnvType.CLIENT) -public class ConfirmRestartScreen extends BCLibScreen { - 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(new TranslatableComponent("title.bclib.confirmrestart")); - - this.description = message==null?new TranslatableComponent("message.bclib.confirmrestart"):message; - this.listener = listener; - } - - protected void initLayout() { - final int BUTTON_HEIGHT = 20; - - grid.addRow().addMessage(this.description, this.font, Alignment.CENTER); - - grid.addSpacerRow(); - - GridRow row = grid.addRow(); - row.addFiller(); - row.addButton(CommonComponents.GUI_PROCEED, BUTTON_HEIGHT, font, (button) -> { - listener.proceed(); - }); - row.addFiller(); - } - - public boolean shouldCloseOnEsc() { - return false; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(); - } -} diff --git a/src/main/java/ru/bclib/gui/screens/LevelFixErrorScreen.java b/src/main/java/ru/bclib/gui/screens/LevelFixErrorScreen.java deleted file mode 100644 index 1615c0f2..00000000 --- a/src/main/java/ru/bclib/gui/screens/LevelFixErrorScreen.java +++ /dev/null @@ -1,60 +0,0 @@ -package ru.bclib.gui.screens; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.TextComponent; -import net.minecraft.network.chat.TranslatableComponent; -import ru.bclib.gui.gridlayout.GridColumn; -import ru.bclib.gui.gridlayout.GridLayout; -import ru.bclib.gui.gridlayout.GridRow; - -@Environment(EnvType.CLIENT) -public class LevelFixErrorScreen extends BCLibScreen { - private final String[] errors; - final Listener onContinue; - - public LevelFixErrorScreen(Screen parent, String[] errors, Listener onContinue) { - super(parent, new TranslatableComponent("title.bclib.datafixer.error"), 10, true); - this.errors = errors; - this.onContinue = onContinue; - } - - @Override - protected void initLayout() { - grid.addSpacerRow(); - grid.addRow().addMessage(new TranslatableComponent("message.bclib.datafixer.error"), font, GridLayout.Alignment.CENTER); - grid.addSpacerRow(8); - - GridRow row = grid.addRow(); - row.addSpacer(10); - GridColumn col = row.addColumn(300, GridLayout.GridValueType.CONSTANT); - for (String error : errors){ - TextComponent dash = new TextComponent("-"); - row = col.addRow(); - row.addString(dash, this); - - row.addSpacer(4); - row.addString(new TextComponent(error), this); - } - - grid.addSpacerRow(8); - row = grid.addRow(); - row.addFiller(); - row.addButton(new TranslatableComponent("title.bclib.datafixer.error.continue"), 0.5f, 20, font, (n)-> { - onClose(); - onContinue.doContinue(true); - }); - row.addSpacer(); - row.addButton(CommonComponents.GUI_CANCEL, 20, font, (n)-> { - this.minecraft.setScreen(null); - }); - row.addFiller(); - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void doContinue(boolean markFixed); - } -} diff --git a/src/main/java/ru/bclib/gui/screens/ModListScreen.java b/src/main/java/ru/bclib/gui/screens/ModListScreen.java deleted file mode 100644 index f2af5008..00000000 --- a/src/main/java/ru/bclib/gui/screens/ModListScreen.java +++ /dev/null @@ -1,218 +0,0 @@ -package ru.bclib.gui.screens; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.fabricmc.loader.api.metadata.ModEnvironment; -import net.minecraft.client.gui.screens.Screen; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TextComponent; -import ru.bclib.api.dataexchange.handler.autosync.HelloClient; -import ru.bclib.gui.gridlayout.GridColumn; -import ru.bclib.gui.gridlayout.GridLayout; -import ru.bclib.gui.gridlayout.GridRow; -import ru.bclib.gui.gridlayout.GridScreen; -import ru.bclib.util.ModUtil; -import ru.bclib.util.PathUtil; -import ru.bclib.util.Triple; - -import java.util.Comparator; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Collectors; - -@Environment(EnvType.CLIENT) -public class ModListScreen extends BCLibScreen { - - 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, 10, true); - 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(GridColumn grid, java.util.List mods, HelloClient.IServerModMap serverInfo, GridScreen parent) { - final int STATE_OK = 6; - final int STATE_SERVER_MISSING_CLIENT_MOD = 5; - final int STATE_MISSING_NOT_OFFERED = 4; - 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())) { - 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() - .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 = GridLayout.COLOR_RED; - final String typeText; - if (state==STATE_VERSION || state==STATE_VERSION_NOT_OFFERED) { - typeText = "[VERSION]"; - if (state == STATE_VERSION_NOT_OFFERED) { - color = GridLayout.COLOR_YELLOW; - } - } else if (state==STATE_MISSING || state==STATE_MISSING_NOT_OFFERED) { - typeText = "[MISSING]"; - if (state == STATE_MISSING_NOT_OFFERED) { - color = GridLayout.COLOR_YELLOW; - } - } else if (state==STATE_SERVER_MISSING || state == STATE_SERVER_MISSING_CLIENT_MOD) { - if (state == STATE_SERVER_MISSING_CLIENT_MOD) { - color = GridLayout.COLOR_CYAN; - typeText = "[OK]"; - } else { - typeText = "[NOT ON SERVER]"; - } - } else { - color = GridLayout.COLOR_DARK_GREEN; - typeText = "[OK]"; - } - TextComponent dash = new TextComponent("-"); - TextComponent typeTextComponent = new TextComponent(typeText); - GridRow row = grid.addRow(); - - row.addString(dash, parent); - - row.addSpacer(4); - row.addString(new TextComponent(name), parent); - - row.addSpacer(4); - row.addString(typeTextComponent, color, parent); - - if (!stateString.isEmpty()) { - row = grid.addRow(); - row.addSpacer(4 + parent.getWidth(dash)); - row.addString(new TextComponent(stateString), GridLayout.COLOR_GRAY, parent); - } - - grid.addSpacerRow(); - }); - } - - @Override - protected void initLayout() { - if (description != null) { - grid.addSpacerRow(); - grid.addRow().addMessage(description, font, GridLayout.Alignment.CENTER); - grid.addSpacerRow(8); - } - - GridRow row = grid.addRow(); - row.addSpacer(10); - GridColumn col = row.addColumn(200, GridLayout.GridValueType.CONSTANT); - addModDesc(col, mods, serverInfo, this); - - grid.addSpacerRow(8); - row = grid.addRow(); - row.addFiller(); - row.addButton(buttonTitle, 20, font, (n)-> { - onClose(); - }); - row.addFiller(); - } - -} diff --git a/src/main/java/ru/bclib/gui/screens/ProgressScreen.java b/src/main/java/ru/bclib/gui/screens/ProgressScreen.java deleted file mode 100644 index bb5995ec..00000000 --- a/src/main/java/ru/bclib/gui/screens/ProgressScreen.java +++ /dev/null @@ -1,197 +0,0 @@ -package ru.bclib.gui.screens; - -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.network.chat.TextComponent; -import net.minecraft.network.chat.TranslatableComponent; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.util.ProgressListener; -import org.jetbrains.annotations.Nullable; -import ru.bclib.BCLib; -import ru.bclib.gui.gridlayout.GridColumn; -import ru.bclib.gui.gridlayout.GridCustomRenderCell; -import ru.bclib.gui.gridlayout.GridLayout; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridLayout.GridValueType; -import ru.bclib.gui.gridlayout.GridLayout.VerticalAlignment; -import ru.bclib.gui.gridlayout.GridMessageCell; -import ru.bclib.gui.gridlayout.GridRow; -import ru.bclib.gui.gridlayout.GridScreen; -import ru.bclib.gui.gridlayout.GridStringCell; -import ru.bclib.gui.gridlayout.GridTransform; - -import java.util.concurrent.atomic.AtomicInteger; - -class ProgressLogoRender extends GridCustomRenderCell { - 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(SIZE, GridValueType.CONSTANT, SIZE); - } - - @Override - public void onRender(PoseStack poseStack, GridTransform transform, Object context) { - time += 0.03; - 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 = transform.top + 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, BCLibScreen.BCLIB_LOGO_LOCATION); - GuiComponent.blit(poseStack, - xOffset + transform.left, - yOffset + transform.top, - width, - yBarImage, - 0, 0, LOGO_SIZE, uvTopLogo, - LOGO_SIZE, LOGO_SIZE - ); - } - - if (yBarImage0 && percentage<1.0){ - GuiComponent.fill(poseStack, - transform.left, - yBar, - transform.left+transform.width, - yBar+1, - 0x3FFFFFFF - ); - } - } -} - -public class ProgressScreen extends GridScreen 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, 20, true); - this.description = description; - } - - - Component description; - private Component stageComponent; - private GridMessageCell stage; - private GridStringCell 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 new TranslatableComponent("title.bclib.progress").append(": " + pg + "%"); - } - @Override - protected void initLayout() { - grid.addSpacerRow(); - - GridRow row = grid.addRow(VerticalAlignment.CENTER); - row.addFiller(); - progressImage = new ProgressLogoRender(); - progressImage.percentage = currentProgress / 100.0f; - row.addCustomRender(progressImage); - row.addSpacer(); - - int textWidth = Math.max(getWidth(description), getWidth(getProgressComponent(100))); - GridColumn textCol = row.addColumn(0, GridValueType.INHERIT); - textCol.addRow().addString(description, this); - textCol.addSpacerRow(); - progress = textCol.addRow().addString(getProgressComponent(), GridLayout.COLOR_GRAY, Alignment.LEFT, this); - - row.addFiller(); - - grid.addSpacerRow(20); - row = grid.addRow(); - stage = row.addMessage(stageComponent!=null?stageComponent:new TextComponent(""), font, Alignment.CENTER); - } - - @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); - } - - @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() { - - } -} diff --git a/src/main/java/ru/bclib/gui/screens/SyncFilesScreen.java b/src/main/java/ru/bclib/gui/screens/SyncFilesScreen.java deleted file mode 100644 index acab7fc9..00000000 --- a/src/main/java/ru/bclib/gui/screens/SyncFilesScreen.java +++ /dev/null @@ -1,113 +0,0 @@ -package ru.bclib.gui.screens; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.client.Minecraft; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TranslatableComponent; -import ru.bclib.api.dataexchange.handler.autosync.HelloClient; -import ru.bclib.gui.gridlayout.GridCheckboxCell; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridRow; -import ru.bclib.util.ModUtil; - -@Environment(EnvType.CLIENT) -public class SyncFilesScreen extends BCLibScreen { - 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(new TranslatableComponent("title.bclib.syncfiles")); - - this.serverInfo = serverInfo; - this.description = new TranslatableComponent("message.bclib.syncfiles"); - this.listener = listener; - - this.hasConfigFiles = configFiles>0; - this.hasFiles = singleFiles+folderFiles>0; - this.hasMods = modFiles>0; - this.shouldDelete = deleteFiles>0; - } - - protected void initLayout() { - final int BUTTON_HEIGHT = 20; - - grid.addRow() - .addMessage(this.description, this.font, Alignment.CENTER); - - grid.addSpacerRow(10); - - GridRow row; - - - final GridCheckboxCell mods; - row = grid.addRow(); - mods = row.addCheckbox(new TranslatableComponent("message.bclib.syncfiles.mods"), hasMods, BUTTON_HEIGHT, this.font); - mods.setEnabled(hasMods); - - row.addSpacer(); - row.addButton(new TranslatableComponent("title.bclib.syncfiles.modInfo"), 20, font, (button)->{ - ModListScreen scr = new ModListScreen( - this, - new TranslatableComponent("title.bclib.syncfiles.modlist"), - new TranslatableComponent("message.bclib.syncfiles.modlist"), - ModUtil.getMods(), - serverInfo - ); - Minecraft.getInstance().setScreen(scr); - }); - - grid.addSpacerRow(); - - - final GridCheckboxCell configs; - row = grid.addRow(); - configs = row.addCheckbox(new TranslatableComponent("message.bclib.syncfiles.configs"), hasConfigFiles, BUTTON_HEIGHT, this.font); - configs.setEnabled(hasConfigFiles); - - grid.addSpacerRow(); - - row = grid.addRow(); - - final GridCheckboxCell folder; - folder = row.addCheckbox(new TranslatableComponent("message.bclib.syncfiles.folders"), hasFiles, BUTTON_HEIGHT, this.font); - folder.setEnabled(hasFiles); - row.addSpacer(); - - GridCheckboxCell delete; - delete = row.addCheckbox(new TranslatableComponent("message.bclib.syncfiles.delete"), shouldDelete, BUTTON_HEIGHT, this.font); - delete.setEnabled(shouldDelete); - - - grid.addSpacerRow(30); - row = grid.addRow(); - row.addFiller(); - row.addButton(CommonComponents.GUI_NO, BUTTON_HEIGHT, this.font, (button) -> { - listener.proceed(false, false, false, false); - }); - row.addSpacer(); - row.addButton(CommonComponents.GUI_YES, BUTTON_HEIGHT, this.font, (button) -> { - listener.proceed( - mods.isChecked(), - configs.isChecked(), - folder.isChecked(), - delete.isChecked() - ); - }); - row.addFiller(); - } - - public boolean shouldCloseOnEsc() { - return false; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(boolean downloadMods, boolean downloadConfigs, boolean downloadFiles, boolean removeFiles); - } -} diff --git a/src/main/java/ru/bclib/gui/screens/WarnBCLibVersionMismatch.java b/src/main/java/ru/bclib/gui/screens/WarnBCLibVersionMismatch.java deleted file mode 100644 index 37d3f1c6..00000000 --- a/src/main/java/ru/bclib/gui/screens/WarnBCLibVersionMismatch.java +++ /dev/null @@ -1,47 +0,0 @@ -package ru.bclib.gui.screens; - -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.network.chat.CommonComponents; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TranslatableComponent; -import ru.bclib.gui.gridlayout.GridLayout.Alignment; -import ru.bclib.gui.gridlayout.GridRow; - -@Environment(EnvType.CLIENT) -public class WarnBCLibVersionMismatch extends BCLibScreen { - private final Component description; - private final Listener listener; - public WarnBCLibVersionMismatch(Listener listener) { - super(new TranslatableComponent("title.bclib.bclibmissmatch")); - - this.description = new TranslatableComponent("message.bclib.bclibmissmatch"); - this.listener = listener; - } - - protected void initLayout() { - final int BUTTON_HEIGHT = 20; - - grid.addRow().addMessage(this.description, this.font, Alignment.CENTER); - grid.addSpacerRow(20); - GridRow row = grid.addRow(); - row.addFiller(); - row.addButton(CommonComponents.GUI_NO, BUTTON_HEIGHT, this.font, (button) -> { - listener.proceed(false); - }); - row.addSpacer(); - row.addButton(CommonComponents.GUI_YES, BUTTON_HEIGHT, this.font, (button) -> { - listener.proceed(true); - }); - row.addFiller(); - } - - public boolean shouldCloseOnEsc() { - return false; - } - - @Environment(EnvType.CLIENT) - public interface Listener { - void proceed(boolean download); - } -} diff --git a/src/main/java/ru/bclib/integration/ModIntegration.java b/src/main/java/ru/bclib/integration/ModIntegration.java index 869edc61..69859df4 100644 --- a/src/main/java/ru/bclib/integration/ModIntegration.java +++ b/src/main/java/ru/bclib/integration/ModIntegration.java @@ -1,5 +1,10 @@ package ru.bclib.integration; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + import net.fabricmc.fabric.api.tag.TagRegistry; import net.fabricmc.loader.api.FabricLoader; import net.minecraft.core.Registry; @@ -20,11 +25,6 @@ import net.minecraft.world.level.levelgen.feature.Feature; import ru.bclib.BCLib; import ru.bclib.world.features.BCLFeature; -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; @@ -45,7 +45,7 @@ public abstract class ModIntegration { public Item getItem(String name) { return Registry.ITEM.get(getID(name)); } - + public BlockState getDefaultState(String name) { return getBlock(name).defaultBlockState(); } @@ -178,7 +178,7 @@ public abstract class ModIntegration { public Object newInstance(Class cl, Object... args) { if (cl != null) { - for (Constructor constructor : cl.getConstructors()) { + for (Constructor constructor: cl.getConstructors()) { if (constructor.getParameterCount() == args.length) { try { return constructor.newInstance(args); diff --git a/src/main/java/ru/bclib/integration/ModMenuIntegration.java b/src/main/java/ru/bclib/integration/ModMenuIntegration.java deleted file mode 100644 index ac26946e..00000000 --- a/src/main/java/ru/bclib/integration/ModMenuIntegration.java +++ /dev/null @@ -1,176 +0,0 @@ -package ru.bclib.integration; - -import com.google.common.collect.ImmutableMap; -import com.terraformersmc.modmenu.util.ModMenuApiMarker; -import net.minecraft.client.gui.screens.Screen; -import ru.bclib.integration.ModMenuIntegration.ModMenuScreenFactory; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.util.Map; - -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; - } -} - -/** - * 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 ModMenuApiMarker} 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 ModMenuApiMarker 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 (ModMenuApiMarker)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 { - Screen create(Screen parent); - } - - 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/ru/bclib/interfaces/AnvilScreenHandlerExtended.java b/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java deleted file mode 100644 index c7d3637e..00000000 --- a/src/main/java/ru/bclib/interfaces/AnvilScreenHandlerExtended.java +++ /dev/null @@ -1,36 +0,0 @@ -package ru.bclib.interfaces; - - -import ru.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/ru/bclib/interfaces/BiomeSetter.java b/src/main/java/ru/bclib/interfaces/BiomeSetter.java deleted file mode 100644 index 09a8e447..00000000 --- a/src/main/java/ru/bclib/interfaces/BiomeSetter.java +++ /dev/null @@ -1,8 +0,0 @@ -package ru.bclib.interfaces; - -import net.minecraft.core.BlockPos; -import net.minecraft.world.level.biome.Biome; - -public interface BiomeSetter { - public void bclib_setBiome(Biome biome, BlockPos pos); -} diff --git a/src/main/java/ru/bclib/interfaces/CustomItemProvider.java b/src/main/java/ru/bclib/interfaces/CustomItemProvider.java deleted file mode 100644 index eb1154c3..00000000 --- a/src/main/java/ru/bclib/interfaces/CustomItemProvider.java +++ /dev/null @@ -1,14 +0,0 @@ -package ru.bclib.interfaces; - -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.item.BlockItem; - -public interface CustomItemProvider { - /** - * Used to replace default Block Item when block is registered. - * - * @return {@link BlockItem} - */ - BlockItem getCustomItem(ResourceLocation blockID, FabricItemSettings settings); -} diff --git a/src/main/java/ru/bclib/interfaces/CustomColorProvider.java b/src/main/java/ru/bclib/interfaces/IColorProvider.java similarity index 82% rename from src/main/java/ru/bclib/interfaces/CustomColorProvider.java rename to src/main/java/ru/bclib/interfaces/IColorProvider.java index 608df477..c9f2f8b6 100644 --- a/src/main/java/ru/bclib/interfaces/CustomColorProvider.java +++ b/src/main/java/ru/bclib/interfaces/IColorProvider.java @@ -3,8 +3,8 @@ package ru.bclib.interfaces; import net.minecraft.client.color.block.BlockColor; import net.minecraft.client.color.item.ItemColor; -public interface CustomColorProvider { +public interface IColorProvider { BlockColor getProvider(); - + ItemColor getItemProvider(); } diff --git a/src/main/java/ru/bclib/interfaces/RenderLayerProvider.java b/src/main/java/ru/bclib/interfaces/IRenderTyped.java similarity index 74% rename from src/main/java/ru/bclib/interfaces/RenderLayerProvider.java rename to src/main/java/ru/bclib/interfaces/IRenderTyped.java index 2da7485a..445f9e6b 100644 --- a/src/main/java/ru/bclib/interfaces/RenderLayerProvider.java +++ b/src/main/java/ru/bclib/interfaces/IRenderTyped.java @@ -2,6 +2,6 @@ package ru.bclib.interfaces; import ru.bclib.client.render.BCLRenderLayer; -public interface RenderLayerProvider { +public interface IRenderTyped { BCLRenderLayer getRenderLayer(); } diff --git a/src/main/java/ru/bclib/interfaces/ISpetialItem.java b/src/main/java/ru/bclib/interfaces/ISpetialItem.java new file mode 100644 index 00000000..33112bf7 --- /dev/null +++ b/src/main/java/ru/bclib/interfaces/ISpetialItem.java @@ -0,0 +1,6 @@ +package ru.bclib.interfaces; + +public interface ISpetialItem { + boolean canPlaceOnWater(); + int getStackSize(); +} diff --git a/src/main/java/ru/bclib/interfaces/PostInitable.java b/src/main/java/ru/bclib/interfaces/PostInitable.java deleted file mode 100644 index 23073c9c..00000000 --- a/src/main/java/ru/bclib/interfaces/PostInitable.java +++ /dev/null @@ -1,5 +0,0 @@ -package ru.bclib.interfaces; - -public interface PostInitable { - void postInit(); -} diff --git a/src/main/java/ru/bclib/interfaces/TileEntityRenderProvider.java b/src/main/java/ru/bclib/interfaces/TileEntityRenderProvider.java deleted file mode 100644 index 5d59f113..00000000 --- a/src/main/java/ru/bclib/interfaces/TileEntityRenderProvider.java +++ /dev/null @@ -1,5 +0,0 @@ -package ru.bclib.interfaces; - -public interface TileEntityRenderProvider { - -} diff --git a/src/main/java/ru/bclib/interfaces/TriConsumer.java b/src/main/java/ru/bclib/interfaces/TriConsumer.java deleted file mode 100644 index dab5678f..00000000 --- a/src/main/java/ru/bclib/interfaces/TriConsumer.java +++ /dev/null @@ -1,6 +0,0 @@ -package ru.bclib.interfaces; - -@FunctionalInterface -public interface TriConsumer { - void accept(A a, B b, C c); -} diff --git a/src/main/java/ru/bclib/interfaces/UnknownReceipBookCategory.java b/src/main/java/ru/bclib/interfaces/UnknownReceipBookCategory.java deleted file mode 100644 index e4a9300a..00000000 --- a/src/main/java/ru/bclib/interfaces/UnknownReceipBookCategory.java +++ /dev/null @@ -1,4 +0,0 @@ -package ru.bclib.interfaces; - -public interface UnknownReceipBookCategory { -} diff --git a/src/main/java/ru/bclib/items/BaseAnvilItem.java b/src/main/java/ru/bclib/items/BaseAnvilItem.java index 465b82ad..c1b36914 100644 --- a/src/main/java/ru/bclib/items/BaseAnvilItem.java +++ b/src/main/java/ru/bclib/items/BaseAnvilItem.java @@ -1,5 +1,9 @@ package ru.bclib.items; +import java.util.List; + +import org.jetbrains.annotations.Nullable; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -14,60 +18,43 @@ 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 org.jetbrains.annotations.Nullable; import ru.bclib.blocks.BaseAnvilBlock; -import ru.bclib.interfaces.BlockModelProvider; -import ru.bclib.interfaces.ItemModelProvider; - -import java.util.List; -import java.util.Locale; +import ru.bclib.client.models.ItemModelProvider; 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); - } + blockState = blockState.setValue(BaseAnvilBlock.DESTRUCTION, destruction); } 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(new TranslatableComponent("message.bclib.anvil_damage").append(": " + percents)); + super.appendHoverText(itemStack, level, list, tooltipFlag); + int l = itemStack.getOrCreateTag().getInt(DESTRUCTION); + if (l > 0) { + list.add(new TranslatableComponent("message.bclib.anvil_damage").append(": " + l)); } } - + @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()); + return ((ItemModelProvider) anvilBlock).getItemModel(blockId); } } diff --git a/src/main/java/ru/bclib/items/BaseArmorItem.java b/src/main/java/ru/bclib/items/BaseArmorItem.java index 8523d30f..805c2128 100644 --- a/src/main/java/ru/bclib/items/BaseArmorItem.java +++ b/src/main/java/ru/bclib/items/BaseArmorItem.java @@ -1,57 +1,45 @@ package ru.bclib.items; +import java.util.UUID; + import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; + 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 ru.bclib.interfaces.ItemModelProvider; - -import java.util.UUID; +import ru.bclib.client.models.ItemModelProvider; 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") + 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) - ); + 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 - ) - ); + 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); diff --git a/src/main/java/ru/bclib/items/BaseBucketItem.java b/src/main/java/ru/bclib/items/BaseBucketItem.java index 9a4e8789..fae47053 100644 --- a/src/main/java/ru/bclib/items/BaseBucketItem.java +++ b/src/main/java/ru/bclib/items/BaseBucketItem.java @@ -5,7 +5,7 @@ import net.minecraft.sounds.SoundEvents; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.MobBucketItem; import net.minecraft.world.level.material.Fluids; -import ru.bclib.interfaces.ItemModelProvider; +import ru.bclib.client.models.ItemModelProvider; public class BaseBucketItem extends MobBucketItem implements ItemModelProvider { public BaseBucketItem(EntityType type, FabricItemSettings settings) { diff --git a/src/main/java/ru/bclib/items/BaseDiscItem.java b/src/main/java/ru/bclib/items/BaseDiscItem.java index 17157487..3b6a8e46 100644 --- a/src/main/java/ru/bclib/items/BaseDiscItem.java +++ b/src/main/java/ru/bclib/items/BaseDiscItem.java @@ -2,7 +2,7 @@ package ru.bclib.items; import net.minecraft.sounds.SoundEvent; import net.minecraft.world.item.RecordItem; -import ru.bclib.interfaces.ItemModelProvider; +import ru.bclib.client.models.ItemModelProvider; public class BaseDiscItem extends RecordItem implements ItemModelProvider { public BaseDiscItem(int comparatorOutput, SoundEvent sound, Properties settings) { diff --git a/src/main/java/ru/bclib/items/BaseDrinkItem.java b/src/main/java/ru/bclib/items/BaseDrinkItem.java index e50818bd..bb2216f2 100644 --- a/src/main/java/ru/bclib/items/BaseDrinkItem.java +++ b/src/main/java/ru/bclib/items/BaseDrinkItem.java @@ -17,22 +17,22 @@ 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()) { @@ -45,15 +45,15 @@ public class BaseDrinkItem extends ModelProviderItem { 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/ru/bclib/items/BaseSpawnEggItem.java b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java index b06834e8..7badc6f9 100644 --- a/src/main/java/ru/bclib/items/BaseSpawnEggItem.java +++ b/src/main/java/ru/bclib/items/BaseSpawnEggItem.java @@ -1,5 +1,7 @@ package ru.bclib.items; +import java.util.Optional; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; @@ -8,11 +10,9 @@ import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.Mob; import net.minecraft.world.item.SpawnEggItem; import ru.bclib.client.models.BasePatterns; +import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; import ru.bclib.client.models.PatternsHelper; -import ru.bclib.interfaces.ItemModelProvider; - -import java.util.Optional; public class BaseSpawnEggItem extends SpawnEggItem implements ItemModelProvider { public BaseSpawnEggItem(EntityType type, int primaryColor, int secondaryColor, Properties settings) { diff --git a/src/main/java/ru/bclib/items/ModelProviderItem.java b/src/main/java/ru/bclib/items/ModelProviderItem.java index 03b3d1ce..4fbd6a00 100644 --- a/src/main/java/ru/bclib/items/ModelProviderItem.java +++ b/src/main/java/ru/bclib/items/ModelProviderItem.java @@ -5,8 +5,8 @@ import net.fabricmc.api.Environment; import net.minecraft.client.renderer.block.model.BlockModel; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; +import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelProvider; public class ModelProviderItem extends Item implements ItemModelProvider { public ModelProviderItem(Properties settings) { diff --git a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java index f0543c0f..3836f161 100644 --- a/src/main/java/ru/bclib/items/tool/BaseAxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseAxeItem.java @@ -13,14 +13,14 @@ import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; +import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelProvider; public class BaseAxeItem extends AxeItem implements DynamicAttributeTool, ItemModelProvider { public BaseAxeItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { super(material, attackDamage, attackSpeed, settings); } - + @Override public int getMiningLevel(Tag tag, BlockState state, ItemStack stack, LivingEntity user) { if (tag.equals(FabricToolTags.AXES)) { diff --git a/src/main/java/ru/bclib/items/tool/BaseHoeItem.java b/src/main/java/ru/bclib/items/tool/BaseHoeItem.java index 786ed794..6e1aeab4 100644 --- a/src/main/java/ru/bclib/items/tool/BaseHoeItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseHoeItem.java @@ -6,8 +6,8 @@ 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 ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelProvider; public class BaseHoeItem extends HoeItem implements ItemModelProvider { public BaseHoeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { diff --git a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java index 53be6e2d..213c530b 100644 --- a/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java +++ b/src/main/java/ru/bclib/items/tool/BasePickaxeItem.java @@ -15,8 +15,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.PickaxeItem; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; +import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelProvider; public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool, ItemModelProvider { public BasePickaxeItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { @@ -34,10 +34,7 @@ public class BasePickaxeItem extends PickaxeItem implements DynamicAttributeTool @Override public float getDestroySpeed(ItemStack stack, BlockState state) { Entry entry = ToolManagerImpl.entryNullable(state.getBlock()); - return (entry != null && entry.getMiningLevel(FabricToolTags.PICKAXES) >= 0) ? speed : super.getDestroySpeed( - stack, - state - ); + return (entry != null && entry.getMiningLevel(FabricToolTags.PICKAXES) >= 0) ? speed : super.getDestroySpeed(stack, state); } @Override diff --git a/src/main/java/ru/bclib/items/tool/BaseShearsItem.java b/src/main/java/ru/bclib/items/tool/BaseShearsItem.java deleted file mode 100644 index 90af703f..00000000 --- a/src/main/java/ru/bclib/items/tool/BaseShearsItem.java +++ /dev/null @@ -1,21 +0,0 @@ -package ru.bclib.items.tool; - -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 ru.bclib.api.TagAPI; - -public class BaseShearsItem extends ShearsItem { - public BaseShearsItem(Properties properties) { - super(properties); - } - - public static boolean isShear(ItemStack itemStack, Item item){ - if (item == Items.SHEARS){ - return itemStack.is(item) | itemStack.is(TagAPI.ITEM_COMMON_SHEARS) || itemStack.is(TagAPI.ITEM_SHEARS); - } else { - return itemStack.is(item); - } - } -} diff --git a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java index a987b68b..1a84ee98 100644 --- a/src/main/java/ru/bclib/items/tool/BaseShovelItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseShovelItem.java @@ -15,8 +15,8 @@ import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.ShovelItem; import net.minecraft.world.item.Tier; import net.minecraft.world.level.block.state.BlockState; +import ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelProvider; public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, ItemModelProvider { public BaseShovelItem(Tier material, float attackDamage, float attackSpeed, Properties settings) { @@ -34,10 +34,7 @@ public class BaseShovelItem extends ShovelItem implements DynamicAttributeTool, @Override public float getDestroySpeed(ItemStack stack, BlockState state) { Entry entry = ToolManagerImpl.entryNullable(state.getBlock()); - return (entry != null && entry.getMiningLevel(FabricToolTags.SHOVELS) >= 0) ? speed : super.getDestroySpeed( - stack, - state - ); + return (entry != null && entry.getMiningLevel(FabricToolTags.SHOVELS) >= 0) ? speed : super.getDestroySpeed(stack, state); } @Override diff --git a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java index c32addac..f78098a3 100644 --- a/src/main/java/ru/bclib/items/tool/BaseSwordItem.java +++ b/src/main/java/ru/bclib/items/tool/BaseSwordItem.java @@ -7,8 +7,8 @@ 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 ru.bclib.client.models.ItemModelProvider; import ru.bclib.client.models.ModelsHelper; -import ru.bclib.interfaces.ItemModelProvider; public class BaseSwordItem extends SwordItem implements DynamicAttributeTool, ItemModelProvider { public BaseSwordItem(Tier material, int attackDamage, float attackSpeed, Properties settings) { diff --git a/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java b/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java deleted file mode 100644 index b60df8b4..00000000 --- a/src/main/java/ru/bclib/mixin/client/AnvilScreenMixin.java +++ /dev/null @@ -1,95 +0,0 @@ -package ru.bclib.mixin.client; - -import com.google.common.collect.Lists; -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.screens.inventory.AnvilScreen; -import net.minecraft.client.gui.screens.inventory.ItemCombinerScreen; -import net.minecraft.network.chat.Component; -import net.minecraft.network.chat.TextComponent; -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 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 ru.bclib.interfaces.AnvilScreenHandlerExtended; - -import java.util.List; - -@Mixin(AnvilScreen.class) -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, new TextComponent("<"), b -> be_previousRecipe())); - be_buttons.add(new Button(x + 154, y + 45, 15, 20, new TextComponent(">"), b -> be_nextRecipe())); - } - - @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(); - } - - @Override - public boolean 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/ru/bclib/mixin/client/BackgroundRendererMixin.java b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java index d6f109ce..10495c5a 100644 --- a/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java +++ b/src/main/java/ru/bclib/mixin/client/BackgroundRendererMixin.java @@ -1,29 +1,37 @@ package ru.bclib.mixin.client; -import net.minecraft.client.Camera; -import net.minecraft.client.multiplayer.ClientLevel; -import net.minecraft.client.renderer.FogRenderer; -import net.minecraft.core.BlockPos.MutableBlockPos; -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; -import ru.bclib.client.render.CustomBackgroundRenderer; + +import com.mojang.blaze3d.platform.GlStateManager; +import com.mojang.blaze3d.systems.RenderSystem; + +import net.minecraft.client.Camera; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.renderer.FogRenderer; +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.FluidState; +import ru.bclib.api.BiomeAPI; import ru.bclib.util.BackgroundInfo; +import ru.bclib.util.MHelper; +import ru.bclib.world.biomes.BCLBiome; @Mixin(FogRenderer.class) public class BackgroundRendererMixin { - private static final MutableBlockPos BCLIB_LAST_POS = new MutableBlockPos(0, -100, 0); - private static final MutableBlockPos BCLIB_MUT_POS = new MutableBlockPos(); - private static final float[] BCLIB_FOG_DENSITY = new float[8]; - //private static boolean isEnd; + private static final MutableBlockPos BCL_LAST_POS = new MutableBlockPos(0, -100, 0); + private static final MutableBlockPos BCL_MUT_POS = new MutableBlockPos(); + private static final float[] BCL_FOG_DENSITY = new float[8]; @Shadow private static float fogRed; @@ -33,7 +41,7 @@ public class BackgroundRendererMixin { 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) { + private static void bcl_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(); @@ -55,9 +63,80 @@ public class BackgroundRendererMixin { } @Inject(method = "setupFog", at = @At("HEAD"), cancellable = true) - private static void bclib_fogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog, CallbackInfo info) { - if (CustomBackgroundRenderer.applyFogDensity(camera, fogMode, viewDistance, thickFog)) { + private static void bcl_fogDensity(Camera camera, FogRenderer.FogMode fogMode, float viewDistance, boolean thickFog, CallbackInfo info) { + Entity entity = camera.getEntity(); + FogType fogType = camera.getFluidInCamera(); + if (fogType != FogType.WATER) { + float fog = bcl_getFogDensity(entity.level, entity.getX(), entity.getEyeY(), entity.getZ()); + BackgroundInfo.fogDensity = fog; + float start = viewDistance * 0.75F / fog; + float end = viewDistance / fog; + + if (entity instanceof LivingEntity) { + LivingEntity le = (LivingEntity) entity; + MobEffectInstance effect = le.getEffect(MobEffects.BLINDNESS); + if (effect != null) { + int duration = effect.getDuration(); + if (duration > 20) { + start = 0; + end *= 0.03F; + BackgroundInfo.blindness = 1; + } + else { + float delta = (float) duration / 20F; + BackgroundInfo.blindness = delta; + start = Mth.lerp(delta, start, 0); + end = Mth.lerp(delta, end, end * 0.03F); + } + } + else { + BackgroundInfo.blindness = 0; + } + } + + RenderSystem.setShaderFogStart(start); + RenderSystem.setShaderFogEnd(end); info.cancel(); } } + + private static float bcl_getFogDensityI(Level level, int x, int y, int z) { + Biome biome = level.getBiome(BCL_MUT_POS.set(x, y, z)); + BCLBiome renderBiome = BiomeAPI.getRenderBiome(biome); + return renderBiome.getFogDensity(); + } + + private static float bcl_getFogDensity(Level level, double x, double y, double z) { + int x1 = (MHelper.floor(x) >> 3) << 3; + int y1 = (MHelper.floor(y) >> 3) << 3; + int z1 = (MHelper.floor(z) >> 3) << 3; + float dx = (float) (x - x1) / 8F; + float dy = (float) (y - y1) / 8F; + float dz = (float) (z - z1) / 8F; + + if (BCL_LAST_POS.getX() != x1 || BCL_LAST_POS.getY() != y1 || BCL_LAST_POS.getZ() != z1) { + int x2 = x1 + 8; + int y2 = y1 + 8; + int z2 = z1 + 8; + BCL_LAST_POS.set(x1, y1, z1); + BCL_FOG_DENSITY[0] = bcl_getFogDensityI(level, x1, y1, z1); + BCL_FOG_DENSITY[1] = bcl_getFogDensityI(level, x2, y1, z1); + BCL_FOG_DENSITY[2] = bcl_getFogDensityI(level, x1, y2, z1); + BCL_FOG_DENSITY[3] = bcl_getFogDensityI(level, x2, y2, z1); + BCL_FOG_DENSITY[4] = bcl_getFogDensityI(level, x1, y1, z2); + BCL_FOG_DENSITY[5] = bcl_getFogDensityI(level, x2, y1, z2); + BCL_FOG_DENSITY[6] = bcl_getFogDensityI(level, x1, y2, z2); + BCL_FOG_DENSITY[7] = bcl_getFogDensityI(level, x2, y2, z2); + } + + float a = Mth.lerp(dx, BCL_FOG_DENSITY[0], BCL_FOG_DENSITY[1]); + float b = Mth.lerp(dx, BCL_FOG_DENSITY[2], BCL_FOG_DENSITY[3]); + float c = Mth.lerp(dx, BCL_FOG_DENSITY[4], BCL_FOG_DENSITY[5]); + float d = Mth.lerp(dx, BCL_FOG_DENSITY[6], BCL_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/ru/bclib/mixin/client/ClientRecipeBookMixin.java b/src/main/java/ru/bclib/mixin/client/ClientRecipeBookMixin.java deleted file mode 100644 index 329573e3..00000000 --- a/src/main/java/ru/bclib/mixin/client/ClientRecipeBookMixin.java +++ /dev/null @@ -1,20 +0,0 @@ -package ru.bclib.mixin.client; - -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; -import ru.bclib.interfaces.UnknownReceipBookCategory; - -@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/ru/bclib/mixin/client/EnchantingTableBlockMixin.java b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java index c6d91a25..a78291c5 100644 --- a/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java +++ b/src/main/java/ru/bclib/mixin/client/EnchantingTableBlockMixin.java @@ -1,25 +1,26 @@ package ru.bclib.mixin.client; +import java.util.Random; + +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 net.minecraft.core.BlockPos; import net.minecraft.core.particles.ParticleTypes; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.EnchantmentTableBlock; 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; import ru.bclib.api.TagAPI; -import java.util.Random; - @Mixin(EnchantmentTableBlock.class) public abstract class EnchantingTableBlockMixin extends Block { public EnchantingTableBlockMixin(Properties settings) { super(settings); } - + @Inject(method = "animateTick", at = @At(value = "TAIL")) private void be_onRandomDisplayTick(BlockState state, Level world, BlockPos pos, Random random, CallbackInfo info) { for (int px = -2; px <= 2; ++px) { @@ -30,24 +31,16 @@ public abstract class EnchantingTableBlockMixin extends Block { if (random.nextInt(16) == 0) { for (int py = 0; py <= 1; ++py) { BlockPos blockPos = pos.offset(px, py, pz); - if (world.getBlockState(blockPos).is(TagAPI.BLOCK_BOOKSHELVES)) { + if (world.getBlockState(blockPos).is(TagAPI.BOOKSHELVES)) { if (!world.isEmptyBlock(pos.offset(px / 2, 0, pz / 2))) { break; } - world.addParticle( - ParticleTypes.ENCHANT, - pos.getX() + 0.5, - pos.getY() + 2.0, - pos.getZ() + 0.5, - px + random.nextFloat() - 0.5, - py - random.nextFloat() - 1.0, - pz + random.nextFloat() - 0.5 - ); + world.addParticle(ParticleTypes.ENCHANT, pos.getX() + 0.5, pos.getY() + 2.0, pos.getZ() + 0.5, px + random.nextFloat() - 0.5, py - random.nextFloat() - 1.0, pz + random.nextFloat() - 0.5); } } } } } - + } } diff --git a/src/main/java/ru/bclib/mixin/client/GameMixin.java b/src/main/java/ru/bclib/mixin/client/GameMixin.java deleted file mode 100644 index 941557c1..00000000 --- a/src/main/java/ru/bclib/mixin/client/GameMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.client; - -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; -import ru.bclib.api.dataexchange.DataExchangeAPI; - -@Mixin(Game.class) -public class GameMixin { - - @Inject(method="onStartGameSession", at=@At("TAIL")) - public void bcliv_onStart(CallbackInfo ci){ - DataExchangeAPI.sendOnEnter(); - } -} diff --git a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java b/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java deleted file mode 100644 index f1cb2523..00000000 --- a/src/main/java/ru/bclib/mixin/client/MinecraftMixin.java +++ /dev/null @@ -1,74 +0,0 @@ -package ru.bclib.mixin.client; - -import com.mojang.datafixers.util.Function4; -import net.minecraft.client.Minecraft; -import net.minecraft.client.Minecraft.ExperimentalDialogType; -import net.minecraft.client.color.block.BlockColors; -import net.minecraft.client.color.item.ItemColors; -import net.minecraft.client.main.GameConfig; -import net.minecraft.core.Registry; -import net.minecraft.core.RegistryAccess; -import net.minecraft.core.RegistryAccess.RegistryHolder; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.world.level.DataPackConfig; -import net.minecraft.world.level.LevelSettings; -import net.minecraft.world.level.levelgen.WorldGenSettings; -import net.minecraft.world.level.storage.LevelStorageSource; -import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; -import net.minecraft.world.level.storage.WorldData; -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 ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.api.datafixer.DataFixerAPI; -import ru.bclib.interfaces.CustomColorProvider; - -import java.util.function.Function; - -@Mixin(Minecraft.class) -public abstract class MinecraftMixin { - @Final - @Shadow - private BlockColors blockColors; - - @Final - @Shadow - private ItemColors itemColors; - - @Inject(method = "*", at = @At("TAIL")) - private void bclib_onMCInit(GameConfig args, CallbackInfo info) { - Registry.BLOCK.forEach(block -> { - if (block instanceof CustomColorProvider) { - CustomColorProvider provider = (CustomColorProvider) block; - blockColors.register(provider.getProvider(), block); - itemColors.register(provider.getItemProvider(), block.asItem()); - } - }); - } - - @Shadow - protected abstract void doLoadLevel(String string, RegistryHolder registryHolder, Function function, Function4 function4, boolean bl, ExperimentalDialogType experimentalDialogType); - - @Shadow - @Final - private LevelStorageSource levelSource; - - @Inject(method = "loadLevel", cancellable = true, at = @At("HEAD")) - private void bclib_callFixerOnLoad(String levelID, CallbackInfo ci) { - DataExchangeAPI.prepareServerside(); - - if (DataFixerAPI.fixData(this.levelSource, levelID, true, (appliedFixes) -> { - this.doLoadLevel(levelID, RegistryAccess.builtin(), Minecraft::loadDataPacks, Minecraft::loadWorldData, false, appliedFixes?ExperimentalDialogType.NONE:ExperimentalDialogType.BACKUP); - })) { - ci.cancel(); - } - } - - @Inject(method = "createLevel", at = @At("HEAD")) - private void bclib_initPatchData(String levelID, LevelSettings levelSettings, RegistryHolder registryHolder, WorldGenSettings worldGenSettings, CallbackInfo ci) { - DataFixerAPI.initializeWorldData(this.levelSource, levelID, true); - } -} diff --git a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java index 0c78fd30..bcad7100 100644 --- a/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java +++ b/src/main/java/ru/bclib/mixin/client/ModelBakeryMixin.java @@ -1,33 +1,106 @@ package ru.bclib.mixin.client; -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 java.util.List; +import java.util.Map; +import java.util.Optional; + 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 ru.bclib.api.ModIntegrationAPI; -import ru.bclib.client.models.CustomModelBakery; -import java.util.Map; +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.ModelBakery; +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.item.BlockItem; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.state.BlockState; +import ru.bclib.BCLib; +import ru.bclib.client.models.BlockModelProvider; +import ru.bclib.client.models.ItemModelProvider; @Mixin(ModelBakery.class) public abstract class ModelBakeryMixin { + @Final + @Shadow + private ResourceManager resourceManager; @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); + + @Shadow + protected abstract void cacheAndQueueDependencies(ResourceLocation resourceLocation, UnbakedModel unbakedModel); + + @Inject(method = "loadModel", at = @At("HEAD"), cancellable = true) + private void bclib_loadModels(ResourceLocation resourceLocation, CallbackInfo info) { + if (resourceLocation instanceof ModelResourceLocation) { + String modId = resourceLocation.getNamespace(); + String path = resourceLocation.getPath(); + ResourceLocation clearLoc = new ResourceLocation(modId, path); + ModelResourceLocation modelId = (ModelResourceLocation) resourceLocation; + if ("inventory".equals(modelId.getVariant())) { + ResourceLocation itemLoc = new ResourceLocation(modId, "item/" + path); + ResourceLocation itemModelLoc = new ResourceLocation(modId, "models/" + itemLoc.getPath() + ".json"); + if (!resourceManager.hasResource(itemModelLoc)) { + Item item = Registry.ITEM.get(clearLoc); + ItemModelProvider modelProvider = null; + if (item instanceof ItemModelProvider) { + modelProvider = (ItemModelProvider) item; + } else if (item instanceof BlockItem) { + Block block = Registry.BLOCK.get(clearLoc); + if (block instanceof ItemModelProvider) { + modelProvider = (ItemModelProvider) block; + } + } + if (modelProvider != null) { + BlockModel model = modelProvider.getItemModel(clearLoc); + if (model != null) { + model.name = itemLoc.toString(); + cacheAndQueueDependencies(modelId, model); + unbakedCache.put(itemLoc, model); + } else { + BCLib.LOGGER.warning("Error loading model: {}", itemLoc); + } + info.cancel(); + } + } + } else { + ResourceLocation stateLoc = new ResourceLocation(modId, "blockstates/" + path + ".json"); + if (!resourceManager.hasResource(stateLoc)) { + Block block = Registry.BLOCK.get(clearLoc); + if (block instanceof BlockModelProvider) { + List possibleStates = block.getStateDefinition().getPossibleStates(); + Optional possibleState = possibleStates.stream() + .filter(state -> modelId.equals(BlockModelShaper.stateToModelLocation(clearLoc, state))) + .findFirst(); + if (possibleState.isPresent()) { + UnbakedModel modelVariant = ((BlockModelProvider) block).getModelVariant(modelId, possibleState.get(), unbakedCache); + if (modelVariant != null) { + if (modelVariant instanceof MultiPart) { + possibleStates.forEach(state -> { + ResourceLocation stateId = BlockModelShaper.stateToModelLocation(clearLoc, state); + cacheAndQueueDependencies(stateId, modelVariant); + }); + } else { + cacheAndQueueDependencies(modelId, modelVariant); + } + } else { + BCLib.LOGGER.warning("Error loading variant: {}", modelId); + } + info.cancel(); + } + } + } + } } } } diff --git a/src/main/java/ru/bclib/mixin/client/ModelManagerMixin.java b/src/main/java/ru/bclib/mixin/client/ModelManagerMixin.java deleted file mode 100644 index c7b28d17..00000000 --- a/src/main/java/ru/bclib/mixin/client/ModelManagerMixin.java +++ /dev/null @@ -1,19 +0,0 @@ -package ru.bclib.mixin.client; - -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; -import ru.bclib.client.BCLibClient; - -@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/ru/bclib/mixin/client/SimpleReloadableResourceManagerMixin.java b/src/main/java/ru/bclib/mixin/client/SimpleReloadableResourceManagerMixin.java deleted file mode 100644 index ed209646..00000000 --- a/src/main/java/ru/bclib/mixin/client/SimpleReloadableResourceManagerMixin.java +++ /dev/null @@ -1,53 +0,0 @@ -package ru.bclib.mixin.client; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.FallbackResourceManager; -import net.minecraft.server.packs.resources.Resource; -import net.minecraft.server.packs.resources.ResourceManager; -import net.minecraft.server.packs.resources.SimpleReloadableResourceManager; -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 ru.bclib.BCLib; -import ru.bclib.api.ModIntegrationAPI; -import ru.bclib.client.render.EmissiveTextureInfo; - -import java.io.IOException; -import java.util.Map; - -@Mixin(SimpleReloadableResourceManager.class) -public class SimpleReloadableResourceManagerMixin { - @Final - @Shadow - private Map namespacedPacks; - - private 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.namespacedPacks.get(resourceLocation.getNamespace()); - if (resourceManager != null && !resourceManager.hasResource(resourceLocation)) { - info.setReturnValue(resourceManager.getResource(bclib_alphaEmissionMaterial)); - } - } -} diff --git a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java b/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java deleted file mode 100644 index 2b2bbff2..00000000 --- a/src/main/java/ru/bclib/mixin/client/TextureAtlasMixin.java +++ /dev/null @@ -1,103 +0,0 @@ -package ru.bclib.mixin.client; - -import com.mojang.blaze3d.platform.NativeImage; -import net.fabricmc.fabric.impl.client.texture.FabricSprite; -import net.fabricmc.loader.api.FabricLoader; -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 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 ru.bclib.BCLib; -import ru.bclib.client.render.EmissiveTextureInfo; - -import java.io.IOException; - -@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" - ); - if (resourceManager.hasResource(emissiveLocation)) { - NativeImage sprite = null; - NativeImage emission = null; - try { - ResourceLocation spriteLocation = new ResourceLocation( - location.getNamespace(), - "textures/" + location.getPath() + ".png" - ); - Resource resource = resourceManager.getResource(spriteLocation); - sprite = NativeImage.read(resource.getInputStream()); - resource.close(); - - resource = resourceManager.getResource(emissiveLocation); - emission = NativeImage.read(resource.getInputStream()); - resource.close(); - } - 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/ru/bclib/mixin/common/AnvilBlockMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilBlockMixin.java deleted file mode 100644 index 0c296df3..00000000 --- a/src/main/java/ru/bclib/mixin/common/AnvilBlockMixin.java +++ /dev/null @@ -1,20 +0,0 @@ -package ru.bclib.mixin.common; - -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; -import ru.bclib.blocks.BaseAnvilBlock; - -@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/ru/bclib/mixin/common/AnvilMenuMixin.java b/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java deleted file mode 100644 index 5d5d9218..00000000 --- a/src/main/java/ru/bclib/mixin/common/AnvilMenuMixin.java +++ /dev/null @@ -1,212 +0,0 @@ -package ru.bclib.mixin.common; - -import net.minecraft.tags.BlockTags; -import net.minecraft.world.entity.player.Inventory; -import net.minecraft.world.entity.player.Player; -import net.minecraft.world.inventory.AnvilMenu; -import net.minecraft.world.inventory.ContainerLevelAccess; -import net.minecraft.world.inventory.DataSlot; -import net.minecraft.world.inventory.ItemCombinerMenu; -import net.minecraft.world.inventory.MenuType; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.crafting.RecipeManager; -import net.minecraft.world.level.block.Block; -import net.minecraft.world.level.block.state.BlockState; -import org.jetbrains.annotations.Nullable; -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 ru.bclib.blocks.BaseAnvilBlock; -import ru.bclib.blocks.LeveledAnvilBlock; -import ru.bclib.interfaces.AnvilScreenHandlerExtended; -import ru.bclib.recipes.AnvilRecipe; - -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -@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(); - if (anvilBlock instanceof LeveledAnvilBlock) { - return ((LeveledAnvilBlock) anvilBlock).getCraftingLevel(); - } - return 1; - }, 1); - anvilLevel.set(level); - } - else { - anvilLevel.set(1); - } - } - - @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 = "onTake", at = @At("HEAD"), cancellable = true) - protected void bclib_onTakeAnvilOutput(Player player, ItemStack stack, CallbackInfo info) { - if (be_currentRecipe != null) { - inputSlots.getItem(0).shrink(be_currentRecipe.getInputCount()); - stack = be_currentRecipe.craft(inputSlots, player); - slotsChanged(inputSlots); - access.execute((world, blockPos) -> { - BlockState anvilState = world.getBlockState(blockPos); - BaseAnvilBlock anvil = (BaseAnvilBlock) anvilState.getBlock(); - if (!player.getAbilities().instabuild && anvilState.is(BlockTags.ANVIL) && player.getRandom().nextDouble() < 0.1) { - BlockState damagedState = anvil.damageAnvilUse(anvilState, player.getRandom()); - if (damagedState == null) { - world.removeBlock(blockPos, false); - world.levelEvent(1029, blockPos, 0); - } - else { - world.setBlock(blockPos, damagedState, 2); - world.levelEvent(1030, blockPos, 0); - } - } - else { - world.levelEvent(1030, blockPos, 0); - } - }); - info.cancel(); - return; - } - - this.access.execute((level, blockPos) -> { - BlockState blockState = level.getBlockState(blockPos); - if (blockState.getBlock() instanceof BaseAnvilBlock) { - info.cancel(); - if (!player.getAbilities().instabuild) { - player.giveExperienceLevels(-this.cost.get()); - } - - this.inputSlots.setItem(0, ItemStack.EMPTY); - if (this.repairItemCountCost > 0) { - ItemStack itemStack2 = this.inputSlots.getItem(1); - if (!itemStack2.isEmpty() && itemStack2.getCount() > this.repairItemCountCost) { - itemStack2.shrink(this.repairItemCountCost); - this.inputSlots.setItem(1, itemStack2); - } - else { - this.inputSlots.setItem(1, ItemStack.EMPTY); - } - } - else { - this.inputSlots.setItem(1, ItemStack.EMPTY); - } - - this.cost.set(0); - - if (!player.getAbilities().instabuild && blockState.is(BlockTags.ANVIL) && player.getRandom().nextFloat() < 0.12F) { - BaseAnvilBlock anvil = (BaseAnvilBlock) blockState.getBlock(); - BlockState damaged = anvil.damageAnvilUse(blockState, player.getRandom()); - if (damaged == null) { - level.removeBlock(blockPos, false); - level.levelEvent(1029, blockPos, 0); - } - else { - level.setBlock(blockPos, damaged, 2); - level.levelEvent(1030, blockPos, 0); - } - } - else { - level.levelEvent(1030, blockPos, 0); - } - } - }); - } - - @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/ru/bclib/mixin/common/BiomeMixin.java b/src/main/java/ru/bclib/mixin/common/BiomeMixin.java deleted file mode 100644 index 26f16bcb..00000000 --- a/src/main/java/ru/bclib/mixin/common/BiomeMixin.java +++ /dev/null @@ -1,28 +0,0 @@ -package ru.bclib.mixin.common; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.WorldGenRegion; -import net.minecraft.world.level.StructureFeatureManager; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.WorldgenRandom; -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.ModifyArg; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; - -@Mixin(Biome.class) -public class BiomeMixin { - private int bclib_featureIteratorSeed; - - @ModifyArg(method = "generate", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/levelgen/WorldgenRandom;setFeatureSeed(JII)J")) - private long bclib_updateFeatureSeed(long seed) { - return Long.rotateRight(seed, bclib_featureIteratorSeed++); - } - - @Inject(method = "generate", at = @At("HEAD")) - private void bclib_obBiomeGenerate(StructureFeatureManager structureFeatureManager, ChunkGenerator chunkGenerator, WorldGenRegion worldGenRegion, long l, WorldgenRandom worldgenRandom, BlockPos blockPos, CallbackInfo info) { - bclib_featureIteratorSeed = 0; - } -} diff --git a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java index 52357c1a..30ca8ef0 100644 --- a/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java +++ b/src/main/java/ru/bclib/mixin/common/BoneMealItemMixin.java @@ -1,5 +1,10 @@ package ru.bclib.mixin.common; +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 net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Vec3i; @@ -7,46 +12,44 @@ 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.biome.Biome.BiomeCategory; 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.injection.At; -import org.spongepowered.asm.mixin.injection.Inject; -import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import ru.bclib.api.BiomeAPI; import ru.bclib.api.BonemealAPI; +import ru.bclib.api.TagAPI; import ru.bclib.util.BlocksHelper; import ru.bclib.util.MHelper; @Mixin(BoneMealItem.class) public class BoneMealItemMixin { 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) { BlockPos offseted = blockPos.relative(context.getClickedFace()); - if (BonemealAPI.isTerrain(world.getBlockState(blockPos).getBlock())) { + boolean endBiome = world.getBiome(offseted).getBiomeCategory() == BiomeCategory.THEEND; + + if (world.getBlockState(blockPos).is(TagAPI.END_GROUND)) { boolean consume = false; - if (BonemealAPI.isSpreadableTerrain(world.getBlockState(blockPos).getBlock())) { - BlockState terrain = bclib_getSpreadable(world, blockPos); - if (terrain != null) { - BlocksHelper.setWithoutUpdate(world, blockPos, terrain); + if (world.getBlockState(blockPos).is(Blocks.END_STONE)) { + BlockState nylium = bclib_getNylium(world, blockPos); + if (nylium != null) { + BlocksHelper.setWithoutUpdate(world, blockPos, nylium); consume = true; } } else { - BlockState stateAbove = world.getBlockState(blockPos.above()); - if (!stateAbove.getFluidState().isEmpty()) { - if (stateAbove.is(Blocks.WATER)) { + if (!world.getFluidState(offseted).isEmpty() && endBiome) { + if (world.getBlockState(offseted).getBlock().equals(Blocks.WATER)) { consume = bclib_growWaterGrass(world, blockPos); } } - else if (stateAbove.isAir()) { + else { consume = bclib_growLandGrass(world, blockPos); } } @@ -59,6 +62,12 @@ public class BoneMealItemMixin { info.cancel(); } } + else if (!world.getFluidState(offseted).isEmpty() && endBiome) { + if (world.getBlockState(offseted).getBlock().equals(Blocks.WATER)) { + info.setReturnValue(InteractionResult.FAIL); + info.cancel(); + } + } } } @@ -99,8 +108,7 @@ public class BoneMealItemMixin { for (int y = y1; y >= y2; y--) { bclib_BLOCK_POS.setY(y); BlockPos down = bclib_BLOCK_POS.below(); - if (BlocksHelper.isFluid(world.getBlockState(bclib_BLOCK_POS)) && !BlocksHelper.isFluid(world.getBlockState( - down))) { + if (BlocksHelper.isFluid(world.getBlockState(bclib_BLOCK_POS)) && !BlocksHelper.isFluid(world.getBlockState(down))) { BlockState grass = bclib_getWaterGrassState(world, down); if (grass != null) { BlocksHelper.setWithoutUpdate(world, bclib_BLOCK_POS, grass); @@ -123,42 +131,19 @@ public class BoneMealItemMixin { private BlockState bclib_getWaterGrassState(Level world, BlockPos pos) { BlockState state = world.getBlockState(pos); Block block = state.getBlock(); - block = BonemealAPI.getWaterGrass(BiomeAPI.getBiomeID(world.getBiome(pos)), block, world.getRandom()); + block = BonemealAPI.getLandGrass(BiomeAPI.getBiomeID(world.getBiome(pos)), block, world.getRandom()); return block == null ? null : block.defaultBlockState(); } - - private BlockState bclib_getSpreadable(Level world, BlockPos pos) { + + private BlockState bclib_getNylium(Level world, BlockPos pos) { Vec3i[] offsets = MHelper.getOffsets(world.getRandom()); - BlockState center = world.getBlockState(pos); for (Vec3i dir : offsets) { BlockPos p = pos.offset(dir); BlockState state = world.getBlockState(p); - Block terrain = BonemealAPI.getSpreadable(state.getBlock()); - if (center.is(terrain)) { - if (haveSameProperties(state, center)) { - for (Property property : center.getProperties()) { - state = state.setValue(property, center.getValue(property)); - } - } + if (BonemealAPI.isSpreadable(state.getBlock())) { return state; } } return null; } - - private boolean 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/ru/bclib/mixin/common/ChunkBiomeContainerMixin.java b/src/main/java/ru/bclib/mixin/common/ChunkBiomeContainerMixin.java deleted file mode 100644 index 3ad2c2a8..00000000 --- a/src/main/java/ru/bclib/mixin/common/ChunkBiomeContainerMixin.java +++ /dev/null @@ -1,134 +0,0 @@ -package ru.bclib.mixin.common; - -import net.fabricmc.loader.api.FabricLoader; -import net.minecraft.core.BlockPos; -import net.minecraft.util.BitStorage; -import net.minecraft.util.Mth; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.chunk.ChunkBiomeContainer; -import org.spongepowered.asm.mixin.Final; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.Shadow; -import ru.bclib.BCLib; -import ru.bclib.interfaces.BiomeSetter; - -import java.lang.reflect.Field; - -@Mixin(ChunkBiomeContainer.class) -public class ChunkBiomeContainerMixin implements BiomeSetter { - private static boolean bclib_hasHydrogen = FabricLoader.getInstance().isModLoaded("hydrogen"); - - @Final - @Shadow - private Biome[] biomes; - - @Final - @Shadow - private static int WIDTH_BITS; - - @Final - @Shadow - private static int HORIZONTAL_MASK; - - @Override - public void bclib_setBiome(Biome biome, BlockPos pos) { - int biomeX = pos.getX() >> 2; - int biomeY = pos.getY() >> 2; - int biomeZ = pos.getZ() >> 2; - int index = be_getArrayIndex(biomeX, biomeY, biomeZ); - - if (bclib_hasHydrogen && be_shouldWriteToHydrogen()) { - try { - ChunkBiomeContainer self = (ChunkBiomeContainer) (Object) this; - BitStorage storage = be_getHydrogenStorage(self); - Biome[] palette = be_getHydrogenPalette(self); - int paletteIndex = be_getHydrogenPaletteIndex(biome, palette); - if (paletteIndex == -1) { - Biome[] newPalette = new Biome[palette.length + 1]; - System.arraycopy(palette, 0, newPalette, 0, palette.length); - paletteIndex = palette.length; - palette = newPalette; - palette[paletteIndex] = biome; - be_setHydrogenPalette(self, palette); - } - try { - storage.set(index, paletteIndex); - } - catch (Exception e) { - int size = storage.getSize(); - int bits = Mth.ceillog2(palette.length); - BitStorage newStorage = new BitStorage(bits, size); - for (int i = 0; i < size; i++) { - newStorage.set(i, storage.get(i)); - } - storage = newStorage; - storage.set(index, paletteIndex); - be_setHydrogenStorage(self, storage); - } - } - catch (Exception e) { - BCLib.LOGGER.warning(e.getLocalizedMessage()); - } - return; - } - - biomes[index] = biome; - } - - @Shadow - @Final - private int quartMinY; - @Shadow - @Final - private int quartHeight; - - private boolean be_shouldWriteToHydrogen() { - try { - Field field = ChunkBiomeContainer.class.getDeclaredField("intArray"); - return field != null; - } - catch (NoSuchFieldException e) { - return false; - } - } - - private int be_getArrayIndex(int biomeX, int biomeY, int biomeZ) { - int i = biomeX & HORIZONTAL_MASK; - int j = Mth.clamp(biomeY - this.quartMinY, 0, this.quartHeight); - int k = biomeZ & HORIZONTAL_MASK; - return j << WIDTH_BITS + WIDTH_BITS | k << WIDTH_BITS | i; - } - - private Field be_getField(String name) throws Exception { - Field field = ChunkBiomeContainer.class.getDeclaredField(name); - field.setAccessible(true); - return field; - } - - private BitStorage be_getHydrogenStorage(ChunkBiomeContainer container) throws Exception { - return (BitStorage) be_getField("intArray").get(container); - } - - private Biome[] be_getHydrogenPalette(ChunkBiomeContainer container) throws Exception { - return (Biome[]) be_getField("palette").get(container); - } - - private int be_getHydrogenPaletteIndex(Biome biome, Biome[] palette) { - int index = -1; - for (int i = 0; i < palette.length; i++) { - if (palette[i] == biome) { - index = i; - break; - } - } - return index; - } - - private void be_setHydrogenPalette(ChunkBiomeContainer container, Biome[] palette) throws Exception { - be_getField("palette").set(container, palette); - } - - private void be_setHydrogenStorage(ChunkBiomeContainer container, BitStorage storage) throws Exception { - be_getField("intArray").set(container, storage); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java b/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java index 9aad31dc..81a2ba6c 100644 --- a/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/ComposterBlockAccessor.java @@ -1,9 +1,10 @@ package ru.bclib.mixin.common; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.ComposterBlock; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(ComposterBlock.class) public interface ComposterBlockAccessor { diff --git a/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java b/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java deleted file mode 100644 index a925d152..00000000 --- a/src/main/java/ru/bclib/mixin/common/DimensionTypeMixin.java +++ /dev/null @@ -1,35 +0,0 @@ -package ru.bclib.mixin.common; - -import net.minecraft.core.Registry; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.dimension.DimensionType; -import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; -import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; -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 ru.bclib.world.generator.BCLibEndBiomeSource; -import ru.bclib.world.generator.BCLibNetherBiomeSource; - -@Mixin(value = DimensionType.class, priority = 100) -public class DimensionTypeMixin { - @Inject(method = "defaultNetherGenerator", at = @At("HEAD"), cancellable = true) - private static void be_replaceNetherBiomeSource(Registry biomeRegistry, Registry chunkGeneratorSettingsRegistry, long seed, CallbackInfoReturnable info) { - info.setReturnValue(new NoiseBasedChunkGenerator( - new BCLibNetherBiomeSource(biomeRegistry, seed), - seed, - () -> chunkGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.NETHER) - )); - } - - @Inject(method = "defaultEndGenerator", at = @At("HEAD"), cancellable = true) - private static void be_replaceEndBiomeSource(Registry biomeRegistry, Registry chunkGeneratorSettingsRegistry, long seed, CallbackInfoReturnable info) { - info.setReturnValue(new NoiseBasedChunkGenerator( - new BCLibEndBiomeSource(biomeRegistry, seed), - seed, - () -> chunkGeneratorSettingsRegistry.getOrThrow(NoiseGeneratorSettings.END) - )); - } -} \ No newline at end of file diff --git a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java index 2f73d643..d0af1dd8 100644 --- a/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java +++ b/src/main/java/ru/bclib/mixin/common/EnchantmentMenuMixin.java @@ -1,5 +1,15 @@ package ru.bclib.mixin.common; +import java.util.List; +import java.util.Random; + +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 net.minecraft.core.Registry; import net.minecraft.world.Container; import net.minecraft.world.inventory.AbstractContainerMenu; @@ -10,51 +20,42 @@ import net.minecraft.world.inventory.MenuType; import net.minecraft.world.item.ItemStack; import net.minecraft.world.item.enchantment.EnchantmentHelper; import net.minecraft.world.item.enchantment.EnchantmentInstance; -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 ru.bclib.api.TagAPI; -import java.util.List; -import java.util.Random; - @Mixin(EnchantmentMenu.class) public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { @Final @Shadow private Container enchantSlots; - + @Final @Shadow private ContainerLevelAccess access; - + @Final @Shadow private Random random; - + @Final @Shadow private DataSlot enchantmentSeed; - + @Shadow @Final public int[] costs; - + @Shadow @Final public int[] enchantClue; - + @Shadow @Final public int[] levelClue; - + protected EnchantmentMenuMixin(MenuType type, int syncId) { super(type, syncId); } - + @Inject(method = "slotsChanged", at = @At("HEAD"), cancellable = true) private void be_slotsChanged(Container inventory, CallbackInfo info) { if (inventory == this.enchantSlots) { @@ -62,46 +63,42 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { if (!itemStack.isEmpty() && itemStack.isEnchantable()) { this.access.execute((world, blockPos) -> { int i = 0; - + int j; for (j = -1; j <= 1; ++j) { for (int k = -1; k <= 1; ++k) { - if ((j != 0 || k != 0) && world.isEmptyBlock(blockPos.offset( - k, - 0, - j - )) && world.isEmptyBlock(blockPos.offset(k, 1, j))) { - if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { + if ((j != 0 || k != 0) && world.isEmptyBlock(blockPos.offset(k, 0, j)) && world.isEmptyBlock(blockPos.offset(k, 1, j))) { + if (world.getBlockState(blockPos.offset(k * 2, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } - - if (world.getBlockState(blockPos.offset(k * 2, 1, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { + + if (world.getBlockState(blockPos.offset(k * 2, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } - + if (k != 0 && j != 0) { - if (world.getBlockState(blockPos.offset(k * 2, 0, j)).is(TagAPI.BLOCK_BOOKSHELVES)) { + if (world.getBlockState(blockPos.offset(k * 2, 0, j)).is(TagAPI.BOOKSHELVES)) { ++i; } - - if (world.getBlockState(blockPos.offset(k * 2, 1, j)).is(TagAPI.BLOCK_BOOKSHELVES)) { + + if (world.getBlockState(blockPos.offset(k * 2, 1, j)).is(TagAPI.BOOKSHELVES)) { ++i; } - - if (world.getBlockState(blockPos.offset(k, 0, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { + + if (world.getBlockState(blockPos.offset(k, 0, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } - - if (world.getBlockState(blockPos.offset(k, 1, j * 2)).is(TagAPI.BLOCK_BOOKSHELVES)) { + + if (world.getBlockState(blockPos.offset(k, 1, j * 2)).is(TagAPI.BOOKSHELVES)) { ++i; } } } } } - + random.setSeed(enchantmentSeed.get()); - + for (j = 0; j < 3; ++j) { costs[j] = EnchantmentHelper.getEnchantmentCost(this.random, j, i, itemStack); enchantClue[j] = -1; @@ -110,19 +107,18 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { costs[j] = 0; } } - + for (j = 0; j < 3; ++j) { if (this.costs[j] > 0) { List list = this.getEnchantmentList(itemStack, j, this.costs[j]); if (list != null && !list.isEmpty()) { - EnchantmentInstance enchantmentLevelEntry = (EnchantmentInstance) list.get(this.random.nextInt( - list.size())); + EnchantmentInstance enchantmentLevelEntry = (EnchantmentInstance) list.get(this.random.nextInt(list.size())); enchantClue[j] = Registry.ENCHANTMENT.getId(enchantmentLevelEntry.enchantment); levelClue[j] = enchantmentLevelEntry.level; } } } - + broadcastChanges(); }); } @@ -136,7 +132,7 @@ public abstract class EnchantmentMenuMixin extends AbstractContainerMenu { info.cancel(); } } - + @Shadow private List getEnchantmentList(ItemStack stack, int slot, int level) { return null; diff --git a/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java index 5e6ed7ad..d54b39cc 100644 --- a/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/FeatureDecoratorsAccessor.java @@ -1,11 +1,18 @@ package ru.bclib.mixin.common; +import net.minecraft.data.worldgen.Features; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.crafting.Recipe; +import net.minecraft.world.item.crafting.RecipeType; +import net.minecraft.world.level.block.ComposterBlock; import net.minecraft.world.level.levelgen.placement.ConfiguredDecorator; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.gen.Accessor; +import java.util.Map; + @Mixin(targets = "net.minecraft.data.worldgen.Features$Decorators") public interface FeatureDecoratorsAccessor { @Accessor("HEIGHTMAP_SQUARE") - ConfiguredDecorator bclib_getHeightmapSquare(); + ConfiguredDecorator bcl_getHeightmapSquare(); } diff --git a/src/main/java/ru/bclib/mixin/common/InternalBiomeDataMixin.java b/src/main/java/ru/bclib/mixin/common/InternalBiomeDataMixin.java deleted file mode 100644 index 3f0e7c37..00000000 --- a/src/main/java/ru/bclib/mixin/common/InternalBiomeDataMixin.java +++ /dev/null @@ -1,40 +0,0 @@ -package ru.bclib.mixin.common; - -import net.fabricmc.fabric.impl.biome.InternalBiomeData; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.Biomes; -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 ru.bclib.world.biomes.FabricBiomesData; - -@Mixin(value = InternalBiomeData.class, remap = false) -public class InternalBiomeDataMixin { - @Inject(method = "addEndBiomeReplacement", at = @At(value = "HEAD")) - private static void bclib_addEndBiomeReplacement(ResourceKey replaced, ResourceKey variant, double weight, CallbackInfo info) { - if (replaced == Biomes.END_BARRENS || replaced == Biomes.SMALL_END_ISLANDS) { - FabricBiomesData.END_VOID_BIOMES.put(variant, (float) weight); - } - else { - FabricBiomesData.END_LAND_BIOMES.put(variant, (float) weight); - } - } - - @Inject(method = "addEndMidlandsReplacement", at = @At(value = "HEAD")) - private static void bclib_addEndMidlandsReplacement(ResourceKey highlands, ResourceKey midlands, double weight, CallbackInfo info) { - FabricBiomesData.END_LAND_BIOMES.put(midlands, (float) weight); - } - - @Inject(method = "addEndBarrensReplacement", at = @At(value = "HEAD")) - private static void bclib_addEndBarrensReplacement(ResourceKey highlands, ResourceKey barrens, double weight, CallbackInfo info) { - FabricBiomesData.END_LAND_BIOMES.put(barrens, (float) weight); - FabricBiomesData.END_VOID_BIOMES.put(barrens, (float) weight); - } - - @Inject(method = "addNetherBiome", at = @At(value = "HEAD")) - private static void bclib_addNetherBiome(ResourceKey biome, Biome.ClimateParameters spawnNoisePoint, CallbackInfo info) { - FabricBiomesData.NETHER_BIOMES.add(biome); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/MainMixin.java b/src/main/java/ru/bclib/mixin/common/MainMixin.java deleted file mode 100644 index 142aada1..00000000 --- a/src/main/java/ru/bclib/mixin/common/MainMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common; - -import net.minecraft.server.Main; -import net.minecraft.world.level.storage.LevelStorageSource; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.ModifyArg; -import ru.bclib.api.datafixer.DataFixerAPI; - -@Mixin(Main.class) -abstract public class MainMixin { - @ModifyArg(method="main", at=@At(value="INVOKE", target="Lnet/minecraft/server/MinecraftServer;convertFromRegionFormatIfNeeded(Lnet/minecraft/world/level/storage/LevelStorageSource$LevelStorageAccess;)V")) - private static LevelStorageSource.LevelStorageAccess bclib_callServerFix(LevelStorageSource.LevelStorageAccess session){ - DataFixerAPI.fixData(session, false, (didFix)->{/* not called when showUI==false */}); - return session; - } -} diff --git a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java index e494a05f..1cf79d29 100644 --- a/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/MinecraftServerMixin.java @@ -1,20 +1,9 @@ package ru.bclib.mixin.common; -import com.mojang.authlib.GameProfileRepository; -import com.mojang.authlib.minecraft.MinecraftSessionService; -import com.mojang.datafixers.DataFixer; -import net.minecraft.core.RegistryAccess.RegistryHolder; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.ServerResources; -import net.minecraft.server.level.ServerLevel; -import net.minecraft.server.level.progress.ChunkProgressListenerFactory; -import net.minecraft.server.packs.repository.PackRepository; -import net.minecraft.server.players.GameProfileCache; -import net.minecraft.world.level.Level; -import net.minecraft.world.level.storage.LevelStorageSource; -import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess; -import net.minecraft.world.level.storage.WorldData; +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.CompletableFuture; + import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @@ -22,55 +11,45 @@ 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 ru.bclib.api.BiomeAPI; -import ru.bclib.api.dataexchange.DataExchangeAPI; -import ru.bclib.recipes.BCLRecipeManager; -import java.net.Proxy; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.CompletableFuture; +import net.fabricmc.loader.api.FabricLoader; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.MinecraftServer; +import net.minecraft.server.ServerResources; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.storage.WorldData; +import ru.bclib.api.BiomeAPI; +import ru.bclib.recipes.BCLRecipeManager; @Mixin(MinecraftServer.class) public class MinecraftServerMixin { - @Shadow - private ServerResources resources; + @Shadow + private ServerResources resources; + + @Final + @Shadow + private Map, ServerLevel> levels; + + @Final + @Shadow + protected WorldData worldData; - @Final - @Shadow - private Map, ServerLevel> levels; + @Inject(method = "reloadResources", at = @At(value = "RETURN"), cancellable = true) + private void bcl_reloadResources(Collection collection, CallbackInfoReturnable> info) { + bcl_injectRecipes(); + } - @Final - @Shadow - protected WorldData worldData; + @Inject(method = "loadLevel", at = @At(value = "RETURN"), cancellable = true) + private void bcl_loadLevel(CallbackInfo info) { + bcl_injectRecipes(); + BiomeAPI.initRegistry(MinecraftServer.class.cast(this)); + } - @Inject(method = "*", at = @At("TAIL")) - private void bclib_onServerInit(Thread thread, RegistryHolder registryHolder, LevelStorageAccess levelStorageAccess, WorldData worldData, PackRepository packRepository, Proxy proxy, DataFixer dataFixer, ServerResources serverResources, MinecraftSessionService minecraftSessionService, GameProfileRepository gameProfileRepository, GameProfileCache gameProfileCache, ChunkProgressListenerFactory chunkProgressListenerFactory, CallbackInfo ci) { - DataExchangeAPI.prepareServerside(); - } - - @Inject(method = "convertFromRegionFormatIfNeeded", at = @At("HEAD")) - private static void bclib_applyPatches(LevelStorageSource.LevelStorageAccess session, CallbackInfo ci) { - - /*File levelPath = session.getLevelPath(LevelResource.ROOT).toFile(); - WorldDataAPI.load(new File(levelPath, "data")); - DataFixerAPI.fixData(levelPath, session.getLevelId());*/ - } - - - @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(); - BiomeAPI.initRegistry(MinecraftServer.class.cast(this)); - } - - private void bclib_injectRecipes() { - RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.getRecipeManager(); - accessor.bclib_setRecipes(BCLRecipeManager.getMap(accessor.bclib_getRecipes())); - } + private void bcl_injectRecipes() { + if (FabricLoader.getInstance().isModLoaded("kubejs")) { + RecipeManagerAccessor accessor = (RecipeManagerAccessor) resources.getRecipeManager(); + accessor.bcl_setRecipes(BCLRecipeManager.getMap(accessor.bcl_getRecipes())); + } + } } diff --git a/src/main/java/ru/bclib/mixin/common/PistonBaseBlockMixin.java b/src/main/java/ru/bclib/mixin/common/PistonBaseBlockMixin.java deleted file mode 100644 index ae2d3a02..00000000 --- a/src/main/java/ru/bclib/mixin/common/PistonBaseBlockMixin.java +++ /dev/null @@ -1,23 +0,0 @@ -package ru.bclib.mixin.common; - -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; -import ru.bclib.api.TagAPI; - -@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(TagAPI.BLOCK_IMMOBILE)){ - cir.setReturnValue(false); - cir.cancel(); - } - } -} diff --git a/src/main/java/ru/bclib/mixin/common/PortalShapeMixin.java b/src/main/java/ru/bclib/mixin/common/PortalShapeMixin.java deleted file mode 100644 index b4cd38e7..00000000 --- a/src/main/java/ru/bclib/mixin/common/PortalShapeMixin.java +++ /dev/null @@ -1,33 +0,0 @@ -package ru.bclib.mixin.common; - -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; -import ru.bclib.api.TagAPI; - -@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(TagAPI.BLOCK_NETHER_PORTAL_FRAME) || FRAME.test(state, getter, pos); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java b/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java index ac5f7d11..b0c8e3f4 100644 --- a/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/PotionBrewingAccessor.java @@ -1,10 +1,11 @@ package ru.bclib.mixin.common; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Invoker; + import net.minecraft.world.item.Item; import net.minecraft.world.item.alchemy.Potion; import net.minecraft.world.item.alchemy.PotionBrewing; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.gen.Invoker; @Mixin(PotionBrewing.class) public interface PotionBrewingAccessor { diff --git a/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java b/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java index 3920b687..e3dece33 100644 --- a/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java +++ b/src/main/java/ru/bclib/mixin/common/RecipeManagerAccessor.java @@ -1,19 +1,20 @@ package ru.bclib.mixin.common; +import java.util.Map; + +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.gen.Accessor; + import net.minecraft.resources.ResourceLocation; 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(); - + Map, Map>> bcl_getRecipes(); + @Accessor("recipes") - void bclib_setRecipes(Map, Map>> recipes); + void bcl_setRecipes(Map, Map>> recipes); } \ No newline at end of file diff --git a/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java b/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java index f398ef64..5c2092f6 100644 --- a/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java +++ b/src/main/java/ru/bclib/mixin/common/RecipeManagerMixin.java @@ -1,32 +1,46 @@ package ru.bclib.mixin.common; -import net.minecraft.Util; -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.Overwrite; -import org.spongepowered.asm.mixin.Shadow; - import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; +import org.spongepowered.asm.mixin.Mixin; +import org.spongepowered.asm.mixin.Overwrite; +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 com.google.gson.JsonElement; + +import net.minecraft.Util; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.server.packs.resources.ResourceManager; +import net.minecraft.util.profiling.ProfilerFiller; +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 ru.bclib.recipes.BCLRecipeManager; + @Mixin(RecipeManager.class) public abstract class RecipeManagerMixin { @Shadow private Map, Map>> recipes; - + + @Inject(method = "apply", at = @At(value = "RETURN")) + private void be_apply(Map map, ResourceManager resourceManager, ProfilerFiller profiler, CallbackInfo info) { + recipes = BCLRecipeManager.getMap(recipes); + } + @Shadow private > Map> byType(RecipeType type) { return null; } - + /** * @author paulevs * @reason Remove conflicts with vanilla tags @@ -42,7 +56,7 @@ public abstract class RecipeManagerMixin { boolean b2 = v2.getId().getNamespace().equals("minecraft"); return b1 ^ b2 ? (b1 ? 1 : -1) : 0; }); - + return list.stream().flatMap((recipe) -> { return Util.toStream(type.tryMatch(recipe, world, inventory)); }).findFirst(); diff --git a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java index 1717d4f7..ef881e4d 100644 --- a/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java +++ b/src/main/java/ru/bclib/mixin/common/ServerLevelMixin.java @@ -1,5 +1,15 @@ package ru.bclib.mixin.common; +import java.io.File; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.function.Supplier; + +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 net.minecraft.resources.ResourceKey; import net.minecraft.server.MinecraftServer; import net.minecraft.server.level.ServerLevel; @@ -12,32 +22,35 @@ import net.minecraft.world.level.dimension.DimensionType; import net.minecraft.world.level.storage.LevelStorageSource; 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 ru.bclib.api.BiomeAPI; - -import java.util.List; -import java.util.concurrent.Executor; -import java.util.function.Supplier; +import ru.bclib.api.DataFixerAPI; +import ru.bclib.api.WorldDataAPI; @Mixin(ServerLevel.class) public abstract class ServerLevelMixin extends Level { - private static String bclib_lastWorld = null; + private static String bcl_lastWorld = null; protected ServerLevelMixin(WritableLevelData writableLevelData, ResourceKey resourceKey, DimensionType dimensionType, Supplier supplier, boolean bl, boolean bl2, long l) { super(writableLevelData, resourceKey, dimensionType, supplier, bl, bl2, l); } - + @Inject(method = "*", at = @At("TAIL")) - private void bclib_onServerWorldInit(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { + private void bcl_onServerWorldInit(MinecraftServer server, Executor workerExecutor, LevelStorageSource.LevelStorageAccess session, ServerLevelData properties, ResourceKey registryKey, DimensionType dimensionType, ChunkProgressListener worldGenerationProgressListener, ChunkGenerator chunkGenerator, boolean debugWorld, long l, List list, boolean bl, CallbackInfo info) { BiomeAPI.initRegistry(server); - if (bclib_lastWorld != null && bclib_lastWorld.equals(session.getLevelId())) { + if (bcl_lastWorld != null && bcl_lastWorld.equals(session.getLevelId())) { return; } - bclib_lastWorld = session.getLevelId(); + bcl_lastWorld = session.getLevelId(); + + ServerLevel world = ServerLevel.class.cast(this); + File dir = session.getDimensionPath(world.dimension()); + if (!new File(dir, "level.dat").exists()) { + dir = dir.getParentFile(); + } + + DataFixerAPI.fixData(dir); + WorldDataAPI.load(new File(dir, "data")); } } diff --git a/src/main/java/ru/bclib/mixin/common/SimpleReloadableResourceManagerMixin.java b/src/main/java/ru/bclib/mixin/common/SimpleReloadableResourceManagerMixin.java deleted file mode 100644 index 94f5ea2d..00000000 --- a/src/main/java/ru/bclib/mixin/common/SimpleReloadableResourceManagerMixin.java +++ /dev/null @@ -1,39 +0,0 @@ -package ru.bclib.mixin.common; - -import net.minecraft.resources.ResourceLocation; -import net.minecraft.server.packs.resources.FallbackResourceManager; -import net.minecraft.server.packs.resources.SimpleReloadableResourceManager; -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.Map; - -@Mixin(SimpleReloadableResourceManager.class) -public class SimpleReloadableResourceManagerMixin { - @Final - @Shadow - private Map namespacedPacks; - - 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 = "hasResource", at = @At("HEAD"), cancellable = true) - private void hasResource(ResourceLocation resourceLocation, CallbackInfoReturnable info) { - if (resourceLocation.getNamespace().equals("minecraft")) { - for (String key: BCLIB_MISSING_RESOURCES) { - if (resourceLocation.getPath().equals(key)) { - info.setReturnValue(false); - return; - } - } - } - } -} diff --git a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java index 4d89c067..e01df428 100644 --- a/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java +++ b/src/main/java/ru/bclib/mixin/common/TagLoaderMixin.java @@ -7,7 +7,7 @@ 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 ru.bclib.api.TagAPI; +import ru.bclib.util.TagHelper; import java.util.Map; @@ -15,9 +15,9 @@ import java.util.Map; public class TagLoaderMixin { @Shadow private String directory; - + @ModifyArg(method = "loadAndBuild", at = @At(value = "INVOKE", target = "Lnet/minecraft/tags/TagLoader;build(Ljava/util/Map;)Lnet/minecraft/tags/TagCollection;")) public Map be_modifyTags(Map tagsMap) { - return TagAPI.apply(directory, tagsMap); + return TagHelper.apply(directory, tagsMap); } } diff --git a/src/main/java/ru/bclib/mixin/common/WorldGenRegionMixin.java b/src/main/java/ru/bclib/mixin/common/WorldGenRegionMixin.java deleted file mode 100644 index a8866f3e..00000000 --- a/src/main/java/ru/bclib/mixin/common/WorldGenRegionMixin.java +++ /dev/null @@ -1,26 +0,0 @@ -package ru.bclib.mixin.common; - -import net.minecraft.core.BlockPos; -import net.minecraft.server.level.WorldGenRegion; -import net.minecraft.world.level.ChunkPos; -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 ChunkPos center; - - @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.x) < 2 && Math.abs(z - center.z) < 2); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/shears/BeehiveBlockMixin.java b/src/main/java/ru/bclib/mixin/common/shears/BeehiveBlockMixin.java deleted file mode 100644 index 9dc7ed3f..00000000 --- a/src/main/java/ru/bclib/mixin/common/shears/BeehiveBlockMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common.shears; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.BeehiveBlock; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; -import ru.bclib.items.tool.BaseShearsItem; - -@Mixin(BeehiveBlock.class) -public class BeehiveBlockMixin { - @Redirect(method="use", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) - public boolean bn_useProxy(ItemStack itemStack, Item item){ - return BaseShearsItem.isShear(itemStack, item); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/shears/DiggingEnchantmentMixin.java b/src/main/java/ru/bclib/mixin/common/shears/DiggingEnchantmentMixin.java deleted file mode 100644 index 47354537..00000000 --- a/src/main/java/ru/bclib/mixin/common/shears/DiggingEnchantmentMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common.shears; - -import net.minecraft.world.item.Item; -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.Redirect; -import ru.bclib.items.tool.BaseShearsItem; - -@Mixin(DiggingEnchantment.class) -public class DiggingEnchantmentMixin { - @Redirect(method="canEnchant", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) - public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ - return BaseShearsItem.isShear(itemStack, item); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/shears/MushroomCowMixin.java b/src/main/java/ru/bclib/mixin/common/shears/MushroomCowMixin.java deleted file mode 100644 index d58d93c1..00000000 --- a/src/main/java/ru/bclib/mixin/common/shears/MushroomCowMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common.shears; - -import net.minecraft.world.entity.animal.MushroomCow; -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.Redirect; -import ru.bclib.items.tool.BaseShearsItem; - -@Mixin(MushroomCow.class) -public class MushroomCowMixin { - @Redirect(method="mobInteract", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) - public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ - return BaseShearsItem.isShear(itemStack, item); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/shears/PumpkinBlockMixin.java b/src/main/java/ru/bclib/mixin/common/shears/PumpkinBlockMixin.java deleted file mode 100644 index deb7fc08..00000000 --- a/src/main/java/ru/bclib/mixin/common/shears/PumpkinBlockMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common.shears; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.PumpkinBlock; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; -import ru.bclib.items.tool.BaseShearsItem; - -@Mixin(PumpkinBlock.class) -public abstract class PumpkinBlockMixin { - @Redirect(method="use", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) - public boolean bn_useProxy(ItemStack itemStack, Item item){ - return BaseShearsItem.isShear(itemStack, item); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/shears/SheepMixin.java b/src/main/java/ru/bclib/mixin/common/shears/SheepMixin.java deleted file mode 100644 index 77e42736..00000000 --- a/src/main/java/ru/bclib/mixin/common/shears/SheepMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common.shears; - -import net.minecraft.world.entity.animal.Sheep; -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.Redirect; -import ru.bclib.items.tool.BaseShearsItem; - -@Mixin(Sheep.class) -public class SheepMixin { - @Redirect(method="mobInteract", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) - public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ - return BaseShearsItem.isShear(itemStack, item); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/shears/SnowGolemMixin.java b/src/main/java/ru/bclib/mixin/common/shears/SnowGolemMixin.java deleted file mode 100644 index f6fc2f6a..00000000 --- a/src/main/java/ru/bclib/mixin/common/shears/SnowGolemMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common.shears; - -import net.minecraft.world.entity.animal.SnowGolem; -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.Redirect; -import ru.bclib.items.tool.BaseShearsItem; - -@Mixin(SnowGolem.class) -public class SnowGolemMixin { - @Redirect(method="mobInteract", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) - public boolean bn_mobInteractProxy(ItemStack itemStack, Item item){ - return BaseShearsItem.isShear(itemStack, item); - } -} diff --git a/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java b/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java deleted file mode 100644 index acc98049..00000000 --- a/src/main/java/ru/bclib/mixin/common/shears/TripWireBlockMixin.java +++ /dev/null @@ -1,17 +0,0 @@ -package ru.bclib.mixin.common.shears; - -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.level.block.TripWireBlock; -import org.spongepowered.asm.mixin.Mixin; -import org.spongepowered.asm.mixin.injection.At; -import org.spongepowered.asm.mixin.injection.Redirect; -import ru.bclib.items.tool.BaseShearsItem; - -@Mixin(TripWireBlock.class) -public class TripWireBlockMixin { - @Redirect(method="playerWillDestroy", at=@At(value="INVOKE", target="Lnet/minecraft/world/item/ItemStack;is(Lnet/minecraft/world/item/Item;)Z")) - public boolean bn_useProxy(ItemStack itemStack, Item item){ - return BaseShearsItem.isShear(itemStack, item); - } -} diff --git a/src/main/java/ru/bclib/noise/OpenSimplexNoise.java b/src/main/java/ru/bclib/noise/OpenSimplexNoise.java index 9a59f424..d002334f 100644 --- a/src/main/java/ru/bclib/noise/OpenSimplexNoise.java +++ b/src/main/java/ru/bclib/noise/OpenSimplexNoise.java @@ -3,7 +3,7 @@ package ru.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 @@ -23,31 +23,31 @@ public class OpenSimplexNoise { 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 short[] perm; private 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 @@ -57,60 +57,60 @@ public class OpenSimplexNoise { perm = new short[256]; permGradIndex3D = new short[256]; short[] source = new short[256]; - for (short i = 0; i < 256; i++) { + 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); + 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; @@ -119,7 +119,7 @@ public class OpenSimplexNoise { 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; @@ -128,49 +128,44 @@ public class OpenSimplexNoise { 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 + // triangular vertices if (xins > yins) { xsv_ext = xsb + 1; ysv_ext = ysb - 1; dx_ext = dx0 - 1; dy_ext = dy0 + 1; - } - else { + } 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. + } 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) + } 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 + // 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 { + } 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. + } else { // (1,0) and (0,1) are the closest two vertices. dx_ext = dx0; dy_ext = dy0; xsv_ext = xsb; @@ -181,71 +176,71 @@ public class OpenSimplexNoise { 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; @@ -254,115 +249,106 @@ public class OpenSimplexNoise { if (aScore >= bScore && zins > bScore) { bScore = zins; bPoint = 0x04; - } - else if (aScore < bScore && zins > aScore) { + } 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. + // closest two tetrahedral + // vertices. byte c = (bScore > aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - + // 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 { + } 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 { + } else { ysv_ext0 -= 1; dy_ext0 += 1; } - } - else { + } 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 { + } 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. + } 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. - + // 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 { + } 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 { + } 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 { + } 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; @@ -372,7 +358,7 @@ public class OpenSimplexNoise { 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; @@ -382,7 +368,7 @@ public class OpenSimplexNoise { 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; @@ -392,10 +378,9 @@ public class OpenSimplexNoise { 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) - + } 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; @@ -405,108 +390,99 @@ public class OpenSimplexNoise { if (aScore <= bScore && zins < bScore) { bScore = zins; bPoint = 0x03; - } - else if (aScore > bScore && zins < aScore) { + } 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. + // closest two tetrahedral + // vertices. byte c = (bScore < aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - + // 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 { + } 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 { + } else { ysv_ext0 += 1; dy_ext0 -= 1; } - } - else { + } 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 { + } 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. + } 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. - + // 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 { + } 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 { + } 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 { + } 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; @@ -516,7 +492,7 @@ public class OpenSimplexNoise { 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; @@ -526,7 +502,7 @@ public class OpenSimplexNoise { 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; @@ -536,7 +512,7 @@ public class OpenSimplexNoise { 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; @@ -546,42 +522,39 @@ public class OpenSimplexNoise { 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. + } 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 { + } 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 { + } 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; @@ -591,32 +564,29 @@ public class OpenSimplexNoise { aScore = score; aPoint = 0x06; aIsFurtherSide = true; - } - else if (aScore > bScore && bScore < score) { + } else if (aScore > bScore && bScore < score) { bScore = score; bPoint = 0x06; bIsFurtherSide = true; } - } - else { + } else { double score = 1 - p3; if (aScore <= bScore && aScore < score) { aScore = score; aPoint = 0x01; aIsFurtherSide = false; - } - else if (aScore > bScore && bScore < score) { + } 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; @@ -624,7 +594,7 @@ public class OpenSimplexNoise { 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) { @@ -634,16 +604,14 @@ public class OpenSimplexNoise { xsv_ext1 = xsb + 2; ysv_ext1 = ysb; zsv_ext1 = zsb; - } - else if ((c & 0x02) != 0) { + } 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 { + } else { dx_ext1 = dx0 - 2 * SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 2 * SQUISH_CONSTANT_3D; dz_ext1 = dz0 - 2 - 2 * SQUISH_CONSTANT_3D; @@ -651,9 +619,8 @@ public class OpenSimplexNoise { ysv_ext1 = ysb; zsv_ext1 = zsb + 2; } - } - else {// Both closest points on (0,0,0) side - + } 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; @@ -661,7 +628,7 @@ public class OpenSimplexNoise { 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) { @@ -671,16 +638,14 @@ public class OpenSimplexNoise { xsv_ext1 = xsb - 1; ysv_ext1 = ysb + 1; zsv_ext1 = zsb + 1; - } - else if ((c & 0x02) == 0) { + } 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 { + } else { dx_ext1 = dx0 - 1 - SQUISH_CONSTANT_3D; dy_ext1 = dy0 - 1 - SQUISH_CONSTANT_3D; dz_ext1 = dz0 + 1 - SQUISH_CONSTANT_3D; @@ -689,18 +654,16 @@ public class OpenSimplexNoise { zsv_ext1 = zsb - 1; } } - } - else { // One point on (0,0,0) side, one point on (1,1,1) side + } 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 { + } 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; @@ -709,16 +672,14 @@ public class OpenSimplexNoise { xsv_ext0 = xsb - 1; ysv_ext0 = ysb + 1; zsv_ext0 = zsb + 1; - } - else if ((c1 & 0x02) == 0) { + } 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 { + } else { dx_ext0 = dx0 - 1 - SQUISH_CONSTANT_3D; dy_ext0 = dy0 - 1 - SQUISH_CONSTANT_3D; dz_ext0 = dz0 + 1 - SQUISH_CONSTANT_3D; @@ -726,7 +687,7 @@ public class OpenSimplexNoise { 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; @@ -737,17 +698,15 @@ public class OpenSimplexNoise { if ((c2 & 0x01) != 0) { dx_ext1 -= 2; xsv_ext1 += 2; - } - else if ((c2 & 0x02) != 0) { + } else if ((c2 & 0x02) != 0) { dy_ext1 -= 2; ysv_ext1 += 2; - } - else { + } 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; @@ -757,7 +716,7 @@ public class OpenSimplexNoise { 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; @@ -767,7 +726,7 @@ public class OpenSimplexNoise { 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; @@ -777,7 +736,7 @@ public class OpenSimplexNoise { 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; @@ -787,7 +746,7 @@ public class OpenSimplexNoise { 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; @@ -797,7 +756,7 @@ public class OpenSimplexNoise { 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; @@ -808,41 +767,41 @@ public class OpenSimplexNoise { 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; @@ -850,24 +809,24 @@ public class OpenSimplexNoise { 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; @@ -876,11 +835,11 @@ public class OpenSimplexNoise { 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) - + // (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; @@ -890,61 +849,56 @@ public class OpenSimplexNoise { if (aScore >= bScore && zins > bScore) { bScore = zins; bPoint = 0x04; - } - else if (aScore < bScore && zins > aScore) { + } 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) { + } 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. + // closest two pentachoron + // vertices. byte c = (bScore > aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. + // 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 { + } 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 { + } else { ysv_ext1 -= 1; dy_ext1 += 1; } - } - else { + } 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; @@ -952,52 +906,46 @@ public class OpenSimplexNoise { if ((c & 0x03) == 0x03) { zsv_ext0 -= 1; dz_ext0 += 1; - } - else { + } else { zsv_ext1 -= 1; dz_ext1 += 1; } - } - else { + } else { zsv_ext2 -= 1; dz_ext2 += 1; } - } - else { + } 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 { + } 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. + } 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. - + // 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 { + } 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; @@ -1005,18 +953,16 @@ public class OpenSimplexNoise { if ((c & 0x01) == 0x01) { ysv_ext1 -= 1; dy_ext1 += 1; - } - else { + } else { ysv_ext2 -= 1; dy_ext2 += 1; } - } - else { + } 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; @@ -1024,39 +970,36 @@ public class OpenSimplexNoise { if ((c & 0x03) == 0x03) { zsv_ext1 -= 1; dz_ext1 += 1; - } - else { + } else { zsv_ext2 -= 1; dz_ext2 += 1; } - } - else { + } 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 { + } 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; @@ -1067,7 +1010,7 @@ public class OpenSimplexNoise { 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; @@ -1078,7 +1021,7 @@ public class OpenSimplexNoise { 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; @@ -1089,7 +1032,7 @@ public class OpenSimplexNoise { 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; @@ -1100,12 +1043,11 @@ public class OpenSimplexNoise { 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. + } 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; @@ -1113,62 +1055,57 @@ public class OpenSimplexNoise { if (aScore <= bScore && zins < bScore) { bScore = zins; bPoint = 0x0B; - } - else if (aScore > bScore && zins < aScore) { + } 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) { + } 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. + // closest two pentachoron + // vertices. byte c = (bScore < aScore ? bPoint : aPoint); // Our other - // closest - // vertex is the - // closest out - // of a and b. - + // 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 { + } 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 { + } else { ysv_ext0 += 1; dy_ext0 -= 1; } - } - else { + } 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; @@ -1176,52 +1113,46 @@ public class OpenSimplexNoise { if ((c & 0x03) == 0) { zsv_ext0 += 1; dz_ext0 -= 1; - } - else { + } else { zsv_ext1 += 1; dz_ext1 -= 1; } - } - else { + } else { zsv_ext2 += 1; dz_ext2 -= 1; } - } - else { + } 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 { + } 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. + } 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. - + // 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 { + } 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; @@ -1229,18 +1160,16 @@ public class OpenSimplexNoise { if ((c & 0x01) != 0) { ysv_ext2 += 1; dy_ext2 -= 1; - } - else { + } else { ysv_ext1 += 1; dy_ext1 -= 1; } - } - else { + } 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; @@ -1248,32 +1177,29 @@ public class OpenSimplexNoise { if ((c & 0x03) != 0) { zsv_ext2 += 1; dz_ext2 -= 1; - } - else { + } else { zsv_ext1 += 1; dz_ext1 -= 1; } - } - else { + } 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 { + } 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; @@ -1284,7 +1210,7 @@ public class OpenSimplexNoise { 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; @@ -1295,7 +1221,7 @@ public class OpenSimplexNoise { 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; @@ -1306,7 +1232,7 @@ public class OpenSimplexNoise { 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; @@ -1317,7 +1243,7 @@ public class OpenSimplexNoise { 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; @@ -1328,36 +1254,33 @@ public class OpenSimplexNoise { 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) + } 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 { + } 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 { + } 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) { @@ -1365,76 +1288,69 @@ public class OpenSimplexNoise { if (aScore >= bScore && score > bScore) { bScore = score; bPoint = 0x09; - } - else if (aScore < bScore && score > aScore) { + } else if (aScore < bScore && score > aScore) { aScore = score; aPoint = 0x09; } - } - else { + } else { double score = yins + zins; if (aScore >= bScore && score > bScore) { bScore = score; bPoint = 0x06; - } - else if (aScore < bScore && score > aScore) { + } 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) { + } 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) { + } 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) { + } 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) { + } 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) { @@ -1446,49 +1362,45 @@ public class OpenSimplexNoise { xsv_ext1 = xsb - 1; dx_ext0 = dx0 - 3 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 + 1 - 2 * SQUISH_CONSTANT_4D; - } - else { + } 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 { + } 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 { + } 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 { + } 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; @@ -1501,23 +1413,19 @@ public class OpenSimplexNoise { if ((c2 & 0x01) != 0) { xsv_ext2 += 2; dx_ext2 -= 2; - } - else if ((c2 & 0x02) != 0) { + } else if ((c2 & 0x02) != 0) { ysv_ext2 += 2; dy_ext2 -= 2; - } - else if ((c2 & 0x04) != 0) { + } else if ((c2 & 0x04) != 0) { zsv_ext2 += 2; dz_ext2 -= 2; - } - else { + } 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) + + } 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; @@ -1526,79 +1434,71 @@ public class OpenSimplexNoise { 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 { + } 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 { + } else { ysv_ext1 -= 1; dy_ext1 += 1; } - } - else { + } 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 { + } else { zsv_ext1 -= 1; dz_ext1 += 1; } - } - else { + } 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 { + } else { wsv_ext0 = wsv_ext1 = wsb + 1; dw_ext0 = dw_ext1 = dw0 - 1 - SQUISH_CONSTANT_4D; } - + } - } - else { // One point on each "side" + } else { // One point on each "side" byte c1, c2; if (aIsBiggerSide) { c1 = aPoint; c2 = bPoint; - } - else { + } else { c1 = bPoint; c2 = aPoint; } - + // Two contributions are the bigger-sided point with each 0 // replaced with -1. if ((c1 & 0x01) == 0) { @@ -1606,57 +1506,51 @@ public class OpenSimplexNoise { xsv_ext1 = xsb; dx_ext0 = dx0 + 1 - SQUISH_CONSTANT_4D; dx_ext1 = dx0 - SQUISH_CONSTANT_4D; - } - else { + } 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 { + } else { ysv_ext1 -= 1; dy_ext1 += 1; } - } - else { + } 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 { + } else { zsv_ext1 -= 1; dz_ext1 += 1; } - } - else { + } 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 { + } 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; @@ -1670,21 +1564,18 @@ public class OpenSimplexNoise { if ((c2 & 0x01) != 0) { xsv_ext2 += 2; dx_ext2 -= 2; - } - else if ((c2 & 0x02) != 0) { + } else if ((c2 & 0x02) != 0) { ysv_ext2 += 2; dy_ext2 -= 2; - } - else if ((c2 & 0x04) != 0) { + } else if ((c2 & 0x04) != 0) { zsv_ext2 += 2; dz_ext2 -= 2; - } - else { + } 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; @@ -1695,7 +1586,7 @@ public class OpenSimplexNoise { 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; @@ -1706,7 +1597,7 @@ public class OpenSimplexNoise { 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; @@ -1717,7 +1608,7 @@ public class OpenSimplexNoise { 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; @@ -1728,7 +1619,7 @@ public class OpenSimplexNoise { 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; @@ -1739,7 +1630,7 @@ public class OpenSimplexNoise { 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; @@ -1750,7 +1641,7 @@ public class OpenSimplexNoise { 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; @@ -1761,7 +1652,7 @@ public class OpenSimplexNoise { 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; @@ -1772,7 +1663,7 @@ public class OpenSimplexNoise { 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; @@ -1783,7 +1674,7 @@ public class OpenSimplexNoise { 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; @@ -1794,35 +1685,32 @@ public class OpenSimplexNoise { 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) + } 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 { + } 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 { + } 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) { @@ -1830,83 +1718,76 @@ public class OpenSimplexNoise { if (aScore <= bScore && score < bScore) { bScore = score; bPoint = 0x06; - } - else if (aScore > bScore && score < aScore) { + } else if (aScore > bScore && score < aScore) { aScore = score; aPoint = 0x06; } - } - else { + } else { double score = yins + zins; if (aScore <= bScore && score < bScore) { bScore = score; bPoint = 0x09; - } - else if (aScore > bScore && score < aScore) { + } 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) { + } 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) { + } 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) { + } 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) { + } 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; @@ -1926,26 +1807,23 @@ public class OpenSimplexNoise { dx_ext0 -= 1; xsv_ext1 += 2; dx_ext1 -= 2; - } - else if ((c1 & 0x02) != 0) { + } else if ((c1 & 0x02) != 0) { ysv_ext0 += 1; dy_ext0 -= 1; ysv_ext1 += 2; dy_ext1 -= 2; - } - else if ((c1 & 0x04) != 0) { + } else if ((c1 & 0x04) != 0) { zsv_ext0 += 1; dz_ext0 -= 1; zsv_ext1 += 2; dz_ext1 -= 2; - } - else { + } 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; @@ -1959,22 +1837,18 @@ public class OpenSimplexNoise { if ((c2 & 0x01) == 0) { xsv_ext2 -= 2; dx_ext2 += 2; - } - else if ((c2 & 0x02) == 0) { + } else if ((c2 & 0x02) == 0) { ysv_ext2 -= 2; dy_ext2 += 2; - } - else if ((c2 & 0x04) == 0) { + } else if ((c2 & 0x04) == 0) { zsv_ext2 -= 2; dz_ext2 += 2; - } - else { + } 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) + } 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; @@ -1983,78 +1857,70 @@ public class OpenSimplexNoise { 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 { + } 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 { + } else { ysv_ext1 += 1; dy_ext1 -= 1; } - } - else { + } 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 { + } else { zsv_ext1 += 1; dz_ext1 -= 1; } - } - else { + } 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 { + } else { wsv_ext0 = wsv_ext1 = wsb; dw_ext0 = dw_ext1 = dw0 - 3 * SQUISH_CONSTANT_4D; } } - } - else { // One point on each "side" + } else { // One point on each "side" byte c1, c2; if (aIsBiggerSide) { c1 = aPoint; c2 = bPoint; - } - else { + } else { c1 = bPoint; c2 = aPoint; } - + // Two contributions are the bigger-sided point with each 1 // replaced with 2. if ((c1 & 0x01) != 0) { @@ -2062,57 +1928,51 @@ public class OpenSimplexNoise { xsv_ext1 = xsb + 1; dx_ext0 = dx0 - 2 - 3 * SQUISH_CONSTANT_4D; dx_ext1 = dx0 - 1 - 3 * SQUISH_CONSTANT_4D; - } - else { + } 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 { + } else { ysv_ext1 += 1; dy_ext1 -= 1; } - } - else { + } 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 { + } else { zsv_ext1 += 1; dz_ext1 -= 1; } - } - else { + } 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 { + } 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; @@ -2126,21 +1986,18 @@ public class OpenSimplexNoise { if ((c2 & 0x01) == 0) { xsv_ext2 -= 2; dx_ext2 += 2; - } - else if ((c2 & 0x02) == 0) { + } else if ((c2 & 0x02) == 0) { ysv_ext2 -= 2; dy_ext2 += 2; - } - else if ((c2 & 0x04) == 0) { + } else if ((c2 & 0x04) == 0) { zsv_ext2 -= 2; dz_ext2 += 2; - } - else { + } 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; @@ -2151,7 +2008,7 @@ public class OpenSimplexNoise { 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; @@ -2162,7 +2019,7 @@ public class OpenSimplexNoise { 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; @@ -2173,7 +2030,7 @@ public class OpenSimplexNoise { 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; @@ -2184,7 +2041,7 @@ public class OpenSimplexNoise { 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; @@ -2195,7 +2052,7 @@ public class OpenSimplexNoise { 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; @@ -2206,7 +2063,7 @@ public class OpenSimplexNoise { 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; @@ -2217,7 +2074,7 @@ public class OpenSimplexNoise { 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; @@ -2228,7 +2085,7 @@ public class OpenSimplexNoise { 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; @@ -2239,7 +2096,7 @@ public class OpenSimplexNoise { 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; @@ -2251,421 +2108,78 @@ public class OpenSimplexNoise { 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 - ); + 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 - ); + 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 - ); + 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; + 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 byte[] gradients2D = new byte[] {5, 2, 2, 5, -5, 2, -2, 5, 5, -2, 2, -5, -5, -2, -2, -5,}; - + private static 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 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, - }; - + private static 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 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, - }; + private static 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/ru/bclib/noise/VoronoiNoise.java b/src/main/java/ru/bclib/noise/VoronoiNoise.java index 5575b203..07bea100 100644 --- a/src/main/java/ru/bclib/noise/VoronoiNoise.java +++ b/src/main/java/ru/bclib/noise/VoronoiNoise.java @@ -1,10 +1,10 @@ package ru.bclib.noise; +import java.util.Random; + import net.minecraft.core.BlockPos; import ru.bclib.util.MHelper; -import java.util.Random; - public class VoronoiNoise { private static final Random RANDOM = new Random(); final int seed; @@ -12,7 +12,7 @@ public class VoronoiNoise { public VoronoiNoise() { this(0); } - + public VoronoiNoise(int seed) { this.seed = seed; } @@ -22,7 +22,7 @@ public class VoronoiNoise { 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); @@ -133,16 +133,8 @@ public class VoronoiNoise { } } - 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 - ); + 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/ru/bclib/recipes/AnvilRecipe.java b/src/main/java/ru/bclib/recipes/AnvilRecipe.java deleted file mode 100644 index 378a7fd9..00000000 --- a/src/main/java/ru/bclib/recipes/AnvilRecipe.java +++ /dev/null @@ -1,334 +0,0 @@ -package ru.bclib.recipes; - -import com.google.gson.JsonObject; -import com.mojang.brigadier.exceptions.CommandSyntaxException; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -import net.minecraft.core.NonNullList; -import net.minecraft.nbt.CompoundTag; -import net.minecraft.nbt.TagParser; -import net.minecraft.network.FriendlyByteBuf; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.tags.Tag; -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 ru.bclib.BCLib; -import ru.bclib.api.TagAPI; -import ru.bclib.config.PathConfig; -import ru.bclib.interfaces.UnknownReceipBookCategory; -import ru.bclib.util.ItemUtil; -import ru.bclib.util.RecipeHelper; - -import java.util.Objects; - -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); - - 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; - } - - public static Builder create(String id) { - return create(BCLib.makeID(id)); - } - - public static Builder create(ResourceLocation id) { - Builder.INSTANCE.id = id; - Builder.INSTANCE.input = null; - Builder.INSTANCE.output = null; - Builder.INSTANCE.inputCount = 1; - Builder.INSTANCE.toolLevel = 1; - Builder.INSTANCE.anvilLevel = 1; - Builder.INSTANCE.damage = 1; - Builder.INSTANCE.alright = true; - Builder.INSTANCE.exist = true; - - return Builder.INSTANCE; - } - - @Override - public RecipeSerializer getSerializer() { - return SERIALIZER; - } - - @Override - public ItemStack getResultItem() { - return this.output; - } - - @Override - public boolean matches(Container craftingInventory, Level world) { - return this.matches(craftingInventory); - } - - @Override - public ItemStack assemble(Container craftingInventory) { - return this.output.copy(); - } - - public ItemStack craft(Container craftingInventory, Player player) { - if (!player.isCreative()) { - if (!checkHammerDurability(craftingInventory, player)) return ItemStack.EMPTY; - ItemStack hammer = craftingInventory.getItem(1); - hammer.hurtAndBreak(this.damage, player, entity -> entity.broadcastBreakEvent((InteractionHand) null)); - } - return this.assemble(craftingInventory); - } - - public boolean checkHammerDurability(Container craftingInventory, Player player) { - if (player.isCreative()) return true; - ItemStack hammer = craftingInventory.getItem(1); - int damage = hammer.getDamageValue() + this.damage; - return damage < hammer.getMaxDamage(); - } - - public boolean matches(Container craftingInventory) { - ItemStack hammer = craftingInventory.getItem(1); - if (hammer.isEmpty() || !TagAPI.ITEM_HAMMERS.contains(hammer.getItem())) { - return false; - } - ItemStack material = craftingInventory.getItem(0); - int materialCount = material.getCount(); - int level = ((TieredItem) hammer.getItem()).getTier().getLevel(); - return this.input.test(craftingInventory.getItem(0)) && materialCount >= this.inputCount && level >= this.toolLevel; - } - - public int getDamage() { - return this.damage; - } - - public int getInputCount() { - return this.inputCount; - } - - public int getAnvilLevel() { - return this.anvilLevel; - } - - @Override - public NonNullList getIngredients() { - NonNullList defaultedList = NonNullList.create(); - defaultedList.add(Ingredient.of(TagAPI.ITEM_HAMMERS.getValues() - .stream() - .filter(hammer -> ((TieredItem) hammer).getTier() - .getLevel() >= toolLevel) - .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 ItemStack output; - private int inputCount = 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(Tag 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 setOutput(ItemLike output) { - return this.setOutput(output, 1); - } - - public Builder setOutput(ItemLike output, int amount) { - this.alright &= RecipeHelper.exists(output); - this.output = new ItemStack(output, amount); - 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) { - 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, output, 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/ru/bclib/recipes/BCLRecipeManager.java b/src/main/java/ru/bclib/recipes/BCLRecipeManager.java index 0ecacc23..8e2f6e71 100644 --- a/src/main/java/ru/bclib/recipes/BCLRecipeManager.java +++ b/src/main/java/ru/bclib/recipes/BCLRecipeManager.java @@ -1,6 +1,10 @@ package ru.bclib.recipes; +import java.util.Map; +import java.util.Map.Entry; + import com.google.common.collect.Maps; + import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.crafting.Recipe; @@ -9,12 +13,9 @@ import net.minecraft.world.item.crafting.RecipeType; import net.minecraft.world.level.ItemLike; import net.minecraft.world.level.block.Block; -import java.util.Map; -import java.util.Map.Entry; - public class BCLRecipeManager { private static final Map, Map>> RECIPES = Maps.newHashMap(); - + public static void addRecipe(RecipeType type, Recipe recipe) { Map> list = RECIPES.get(type); if (list == null) { @@ -31,16 +32,16 @@ public class BCLRecipeManager { } return 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); } - + for (RecipeType type : RECIPES.keySet()) { Map> list = RECIPES.get(type); if (list != null) { @@ -51,32 +52,32 @@ public class BCLRecipeManager { } for (Entry> entry : list.entrySet()) { ResourceLocation id = entry.getKey(); - if (!typeList.containsKey(id)) typeList.put(id, entry.getValue()); + if (!typeList.containsKey(id)) + typeList.put(id, entry.getValue()); } } } - + 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 { + } else { return Registry.ITEM.getKey(item.asItem()) != Registry.ITEM.getDefaultKey(); } } diff --git a/src/main/java/ru/bclib/recipes/CraftingRecipes.java b/src/main/java/ru/bclib/recipes/CraftingRecipes.java index 539305bf..d28b5b97 100644 --- a/src/main/java/ru/bclib/recipes/CraftingRecipes.java +++ b/src/main/java/ru/bclib/recipes/CraftingRecipes.java @@ -9,79 +9,29 @@ import ru.bclib.config.Configs; public class CraftingRecipes { public static void init() { - GridRecipe.make(BCLib.MOD_ID, "tag_smith_table", Blocks.SMITHING_TABLE) - .setShape("II", "##", "##") - .addMaterial('#', ItemTags.PLANKS) - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_cauldron", Blocks.CAULDRON) - .setShape("I I", "I I", "III") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER) - .setShape("I I", "ICI", " I ") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .addMaterial('C', TagAPI.ITEM_CHEST) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_piston", Blocks.PISTON) - .setShape("WWW", "CIC", "CDC") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .addMaterial('D', Items.REDSTONE) - .addMaterial('C', Items.COBBLESTONE) - .addMaterial('W', ItemTags.PLANKS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_rail", Blocks.RAIL) - .setOutputCount(16) - .setShape("I I", "ISI", "I I") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .addMaterial('S', Items.STICK) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_stonecutter", Blocks.STONECUTTER) - .setShape(" I ", "SSS") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .addMaterial('S', Items.STONE) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_bucket", Items.BUCKET) - .setShape("I I", " I ") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_compass", Items.COMPASS) - .setShape(" I ", "IDI", " I ") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .addMaterial('D', Items.REDSTONE) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_minecart", Items.MINECART) - .setShape("I I", "III") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - GridRecipe.make(BCLib.MOD_ID, "tag_shield", Items.SHIELD) - .setShape("WIW", "WWW", " W ") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .addMaterial('W', ItemTags.PLANKS) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_smith_table", Blocks.SMITHING_TABLE).setShape("II", "##", "##").addMaterial('#', ItemTags.PLANKS).addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_cauldron", Blocks.CAULDRON).setShape("I I", "I I", "III").addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER).setShape("I I", "ICI", " I ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('C', TagAPI.ITEM_CHEST).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_piston", Blocks.PISTON).setShape("WWW", "CIC", "CDC").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('D', Items.REDSTONE).addMaterial('C', Items.COBBLESTONE).addMaterial('W', ItemTags.PLANKS).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_rail", Blocks.RAIL).setOutputCount(16).setShape("I I", "ISI", "I I").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('S', Items.STICK).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_stonecutter", Blocks.STONECUTTER).setShape(" I ", "SSS").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('S', Items.STONE).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_bucket", Items.BUCKET).setShape("I I", " I ").addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_compass", Items.COMPASS).setShape(" I ", "IDI", " I ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('D', Items.REDSTONE).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_minecart", Items.MINECART).setShape("I I", "III").addMaterial('I', TagAPI.IRON_INGOTS).checkConfig(Configs.RECIPE_CONFIG).build(); + GridRecipe.make(BCLib.MOD_ID, "tag_shield", Items.SHIELD).setShape("WIW", "WWW", " W ").addMaterial('I', TagAPI.IRON_INGOTS).addMaterial('W', ItemTags.PLANKS).checkConfig(Configs.RECIPE_CONFIG).build(); GridRecipe.make(BCLib.MOD_ID, "tag_hopper", Blocks.HOPPER) - .setShape("I I", "ICI", " I ") - .addMaterial('I', TagAPI.ITEM_IRON_INGOTS) - .addMaterial('C', TagAPI.ITEM_CHEST) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); - + .setShape("I I", "ICI", " I ") + .addMaterial('I', TagAPI.IRON_INGOTS) + .addMaterial('C', TagAPI.ITEM_CHEST) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); + GridRecipe.make(BCLib.MOD_ID, "tag_shulker_box", Blocks.SHULKER_BOX) - .setShape("S", "C", "S") - .addMaterial('S', Items.SHULKER_SHELL) - .addMaterial('C', TagAPI.ITEM_CHEST) - .checkConfig(Configs.RECIPE_CONFIG) - .build(); + .setShape("S", "C", "S") + .addMaterial('S', Items.SHULKER_SHELL) + .addMaterial('C', TagAPI.ITEM_CHEST) + .checkConfig(Configs.RECIPE_CONFIG) + .build(); } } diff --git a/src/main/java/ru/bclib/recipes/FurnaceRecipe.java b/src/main/java/ru/bclib/recipes/FurnaceRecipe.java index fbdd57ea..38d20a4b 100644 --- a/src/main/java/ru/bclib/recipes/FurnaceRecipe.java +++ b/src/main/java/ru/bclib/recipes/FurnaceRecipe.java @@ -77,49 +77,21 @@ public class FurnaceRecipe { public void build(boolean blasting, boolean campfire, boolean smoker) { if (exist) { - SmeltingRecipe recipe = new SmeltingRecipe( - id, - group, - Ingredient.of(input), - new ItemStack(output, count), - xp, - time - ); + SmeltingRecipe recipe = new SmeltingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time); BCLRecipeManager.addRecipe(RecipeType.SMELTING, recipe); if (blasting) { - BlastingRecipe recipe2 = new BlastingRecipe( - id, - group, - Ingredient.of(input), - new ItemStack(output, count), - xp, - time / 2 - ); + BlastingRecipe recipe2 = new BlastingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time / 2); BCLRecipeManager.addRecipe(RecipeType.BLASTING, recipe2); } if (campfire) { - CampfireCookingRecipe recipe2 = new CampfireCookingRecipe( - id, - group, - Ingredient.of(input), - new ItemStack(output, count), - xp, - time * 3 - ); + CampfireCookingRecipe recipe2 = new CampfireCookingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time * 3); BCLRecipeManager.addRecipe(RecipeType.CAMPFIRE_COOKING, recipe2); } if (smoker) { - SmokingRecipe recipe2 = new SmokingRecipe( - id, - group, - Ingredient.of(input), - new ItemStack(output, count), - xp, - time / 2 - ); + SmokingRecipe recipe2 = new SmokingRecipe(id, group, Ingredient.of(input), new ItemStack(output, count), xp, time / 2); BCLRecipeManager.addRecipe(RecipeType.SMOKING, recipe2); } } diff --git a/src/main/java/ru/bclib/recipes/GridRecipe.java b/src/main/java/ru/bclib/recipes/GridRecipe.java index 71a6bbc9..bfb9abe7 100644 --- a/src/main/java/ru/bclib/recipes/GridRecipe.java +++ b/src/main/java/ru/bclib/recipes/GridRecipe.java @@ -1,6 +1,10 @@ package ru.bclib.recipes; +import java.util.Arrays; +import java.util.Map; + import com.google.common.collect.Maps; + import net.minecraft.core.NonNullList; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.Tag; @@ -15,9 +19,6 @@ import net.minecraft.world.level.ItemLike; import ru.bclib.BCLib; import ru.bclib.config.PathConfig; -import java.util.Arrays; -import java.util.Map; - public class GridRecipe { private static final GridRecipe INSTANCE = new GridRecipe(); @@ -33,13 +34,9 @@ public class GridRecipe { private boolean exist = true; private GridRecipe() {} - + public static GridRecipe make(String modID, String name, ItemLike output) { - return make(new ResourceLocation(modID, name), output); - } - - public static GridRecipe make(ResourceLocation id, ItemLike output) { - INSTANCE.id = id; + INSTANCE.id = new ResourceLocation(modID, name); INSTANCE.output = output; INSTANCE.group = ""; @@ -49,7 +46,7 @@ public class GridRecipe { INSTANCE.materialKeys.clear(); INSTANCE.count = 1; - INSTANCE.exist = output != null && BCLRecipeManager.exists(output); + INSTANCE.exist = BCLRecipeManager.exists(output); return INSTANCE; } @@ -58,7 +55,7 @@ public class GridRecipe { exist |= config.getBoolean("grid", id.getPath(), true); return this; } - + public GridRecipe setGroup(String group) { this.group = group; return this; @@ -70,7 +67,7 @@ public class GridRecipe { } public GridRecipe setList(String shape) { - this.shape = new String[] {shape}; + this.shape = new String[] { shape }; this.shaped = false; return this; } @@ -84,7 +81,7 @@ public class GridRecipe { } public GridRecipe addMaterial(char key, ItemLike... values) { - for (ItemLike item : values) { + for (ItemLike item: values) { exist &= BCLRecipeManager.exists(item); } return addMaterial(key, Ingredient.of(values)); @@ -103,11 +100,11 @@ public class GridRecipe { private NonNullList getMaterials(int width, int height) { NonNullList materials = NonNullList.withSize(width * height, Ingredient.EMPTY); int pos = 0; - for (String line : shape) { + for (String line: shape) { for (int i = 0; i < width; i++) { char c = line.charAt(i); Ingredient material = materialKeys.get(c); - materials.set(pos++, material == null ? Ingredient.EMPTY : material); + materials.set(pos ++, material == null ? Ingredient.EMPTY : material); } } return materials; @@ -120,17 +117,9 @@ public class GridRecipe { ItemStack result = new ItemStack(output, count); NonNullList materials = this.getMaterials(width, height); - CraftingRecipe recipe = shaped ? new ShapedRecipe( - id, - group, - width, - height, - materials, - result - ) : new ShapelessRecipe(id, group, result, materials); + CraftingRecipe recipe = shaped ? new ShapedRecipe(id, group, width, height, materials, result) : new ShapelessRecipe(id, group, result, materials); BCLRecipeManager.addRecipe(type, recipe); - } - else { + } else { BCLib.LOGGER.debug("Recipe {} couldn't be added", id); } } diff --git a/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java b/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java index a74c6184..bc6aa702 100644 --- a/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java +++ b/src/main/java/ru/bclib/recipes/SmithingTableRecipe.java @@ -89,7 +89,7 @@ public class SmithingTableRecipe { BCLib.LOGGER.warning("Addition input for Smithing recipe can't be 'null', recipe {} will be ignored!", id); return; } - if (result == null) { + if(result == null) { BCLib.LOGGER.warning("Result for Smithing recipe can't be 'null', recipe {} will be ignored!", id); return; } diff --git a/src/main/java/ru/bclib/registry/BaseBlockEntities.java b/src/main/java/ru/bclib/registry/BaseBlockEntities.java index 4c90e226..7da1352b 100644 --- a/src/main/java/ru/bclib/registry/BaseBlockEntities.java +++ b/src/main/java/ru/bclib/registry/BaseBlockEntities.java @@ -1,7 +1,10 @@ package ru.bclib.registry; +import java.util.function.Supplier; + import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.BlockItem; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.entity.BlockEntity; import ru.bclib.BCLib; @@ -21,38 +24,34 @@ public class BaseBlockEntities { 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); + return BaseRegistry.getRegisteredBlocks().values().stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseChestBlock) + .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } - + public static Block[] getBarrels() { - return Registry.BLOCK - .stream() - .filter(block -> block instanceof BaseBarrelBlock) - .toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks().values().stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseBarrelBlock) + .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } - + public static Block[] getSigns() { - return Registry.BLOCK - .stream() - .filter(block -> block instanceof BaseSignBlock) - .toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks().values().stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseSignBlock) + .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } - + public static Block[] getFurnaces() { - return Registry.BLOCK - .stream() - .filter(block -> block instanceof BaseFurnaceBlock) - .toArray(Block[]::new); + return BaseRegistry.getRegisteredBlocks().values().stream() + .filter(item -> item instanceof BlockItem && ((BlockItem) item).getBlock() instanceof BaseFurnaceBlock) + .map(item -> ((BlockItem) item).getBlock()).toArray(Block[]::new); } } diff --git a/src/main/java/ru/bclib/registry/BaseRegistry.java b/src/main/java/ru/bclib/registry/BaseRegistry.java index ea5a4fd7..cf9796b5 100644 --- a/src/main/java/ru/bclib/registry/BaseRegistry.java +++ b/src/main/java/ru/bclib/registry/BaseRegistry.java @@ -1,60 +1,42 @@ package ru.bclib.registry; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import net.fabricmc.fabric.api.item.v1.FabricItemSettings; -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 ru.bclib.config.PathConfig; - import java.util.List; import java.util.Map; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import net.fabricmc.fabric.api.item.v1.FabricItemSettings; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Items; +import ru.bclib.BCLib; + 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_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 FabricItemSettings makeItemSettings() { - FabricItemSettings properties = new FabricItemSettings(); - return (FabricItemSettings) properties.tab(creativeTab); - } - - private void registerInternal() {} - + public static Map> getRegisteredBlocks() { - return MOD_BLOCK_ITEMS; + return MOD_BLOCKS; } - + 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); + + public static List getModBlocks(String modId) { + if (MOD_BLOCKS.containsKey(modId)) { + return MOD_BLOCKS.get(modId); } List modBlocks = Lists.newArrayList(); - MOD_BLOCK_ITEMS.put(modId, modBlocks); + MOD_BLOCKS.put(modId, modBlocks); return modBlocks; } - + public static List getModItems(String modId) { if (MOD_ITEMS.containsKey(modId)) { return MOD_ITEMS.get(modId); @@ -63,17 +45,39 @@ public abstract class BaseRegistry { 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); } + + protected final CreativeModeTab creativeTab; + + protected BaseRegistry(CreativeModeTab creativeTab) { + this.creativeTab = creativeTab; + REGISTRIES.add(this); + } + + public T register(String name, T obj) { + return register(createModId(name), obj); + } + + public abstract T register(ResourceLocation objId, T obj); + + public ResourceLocation createModId(String name) { + return BCLib.makeID(name); + } + + public void registerItem(ResourceLocation id, Item item, List registry) { + if (item != Items.AIR) { + Registry.register(Registry.ITEM, id, item); + registry.add(item); + } + } + + public FabricItemSettings makeItemSettings() { + FabricItemSettings properties = new FabricItemSettings(); + return (FabricItemSettings) properties.tab(creativeTab); + } + + private void registerInternal() {} } diff --git a/src/main/java/ru/bclib/registry/BlockRegistry.java b/src/main/java/ru/bclib/registry/BlockRegistry.java deleted file mode 100644 index 608e9ca7..00000000 --- a/src/main/java/ru/bclib/registry/BlockRegistry.java +++ /dev/null @@ -1,78 +0,0 @@ -package ru.bclib.registry; - -import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; -import net.minecraft.core.Registry; -import net.minecraft.resources.ResourceLocation; -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 ru.bclib.api.TagAPI; -import ru.bclib.blocks.BaseLeavesBlock; -import ru.bclib.blocks.FeatureSaplingBlock; -import ru.bclib.config.PathConfig; -import ru.bclib.interfaces.CustomItemProvider; - -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)) { - 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){ - TagAPI.addTags(block, TagAPI.BLOCK_LEAVES); - if (item != null){ - TagAPI.addTags(item, TagAPI.ITEM_LEAVES); - } - } else if (block instanceof FeatureSaplingBlock){ - TagAPI.addTags(block, TagAPI.BLOCK_SAPLINGS); - if (item != null){ - TagAPI.addTags(item, TagAPI.ITEM_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, Item 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/ru/bclib/registry/BlocksRegistry.java b/src/main/java/ru/bclib/registry/BlocksRegistry.java new file mode 100644 index 00000000..bd663f50 --- /dev/null +++ b/src/main/java/ru/bclib/registry/BlocksRegistry.java @@ -0,0 +1,49 @@ +package ru.bclib.registry; + +import net.fabricmc.fabric.api.registry.FlammableBlockRegistry; +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.world.item.BlockItem; +import net.minecraft.world.item.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.Item.Properties; +import net.minecraft.world.item.WaterLilyBlockItem; +import net.minecraft.world.level.block.Block; +import ru.bclib.interfaces.ISpetialItem; + +public abstract class BlocksRegistry extends BaseRegistry { + + protected BlocksRegistry(CreativeModeTab creativeTab) { + super(creativeTab); + } + + @Override + public Block register(ResourceLocation id, Block block) { + int maxCount = 64; + boolean placeOnWater = false; + if (block instanceof ISpetialItem) { + ISpetialItem item = (ISpetialItem) block; + maxCount = item.getStackSize(); + placeOnWater = item.canPlaceOnWater(); + } + Properties item = makeItemSettings().stacksTo(maxCount); + if (placeOnWater) { + registerBlockItem(id, new WaterLilyBlockItem(block, item)); + } else { + registerBlockItem(id, new BlockItem(block, item)); + } + if (block.defaultBlockState().getMaterial().isFlammable() && FlammableBlockRegistry.getDefaultInstance().get(block).getBurnChance() == 0) { + FlammableBlockRegistry.getDefaultInstance().add(block, 5, 5); + } + return Registry.register(Registry.BLOCK, id, block); + } + + public Block registerBlockOnly(String name, Block block) { + return Registry.register(Registry.BLOCK, createModId(name), block); + } + + public Item registerBlockItem(ResourceLocation id, Item item) { + registerItem(id, item, BaseRegistry.getModBlocks(id.getNamespace())); + return item; + } +} diff --git a/src/main/java/ru/bclib/registry/ItemRegistry.java b/src/main/java/ru/bclib/registry/ItemRegistry.java deleted file mode 100644 index fddeacb4..00000000 --- a/src/main/java/ru/bclib/registry/ItemRegistry.java +++ /dev/null @@ -1,159 +0,0 @@ -package ru.bclib.registry; - -import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; -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.tags.Tag; -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.CreativeModeTab; -import net.minecraft.world.item.Item; -import net.minecraft.world.item.ItemStack; -import net.minecraft.world.item.Items; -import net.minecraft.world.item.ShovelItem; -import net.minecraft.world.item.SpawnEggItem; -import net.minecraft.world.item.SwordItem; -import net.minecraft.world.level.block.DispenserBlock; -import ru.bclib.api.TagAPI; -import ru.bclib.config.PathConfig; -import ru.bclib.items.BaseDiscItem; -import ru.bclib.items.BaseDrinkItem; -import ru.bclib.items.BaseSpawnEggItem; -import ru.bclib.items.ModelProviderItem; -import ru.bclib.items.tool.BaseAxeItem; -import ru.bclib.items.tool.BaseHoeItem; -import ru.bclib.items.tool.BasePickaxeItem; -import ru.bclib.items.tool.BaseShearsItem; - -public class ItemRegistry extends BaseRegistry { - public ItemRegistry(CreativeModeTab creativeTab, PathConfig config) { - super(creativeTab, config); - } - - public Item registerDisc(ResourceLocation itemId, int power, SoundEvent sound) { - BaseDiscItem item = new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1)); - - if (!config.getBoolean("musicDiscs", itemId.getPath(), true)) { - return item; - } - - return register(itemId, new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1))); - } - - 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) { - TagAPI.addTag((Tag.Named) FabricToolTags.SHOVELS, item); - } - else if (item instanceof SwordItem) { - TagAPI.addTag((Tag.Named) FabricToolTags.SWORDS, item); - } - else if (item instanceof BasePickaxeItem) { - TagAPI.addTag((Tag.Named) FabricToolTags.PICKAXES, item); - } - else if (item instanceof BaseAxeItem) { - TagAPI.addTag((Tag.Named) FabricToolTags.AXES, item); - } - else if (item instanceof BaseHoeItem) { - TagAPI.addTag((Tag.Named) FabricToolTags.HOES, item); - } - else if (item instanceof BaseShearsItem) { - TagAPI.addTags(item, (Tag.Named) FabricToolTags.SHEARS, TagAPI.ITEM_SHEARS, TagAPI.ITEM_COMMON_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/ru/bclib/registry/ItemsRegistry.java b/src/main/java/ru/bclib/registry/ItemsRegistry.java new file mode 100644 index 00000000..7dcc9744 --- /dev/null +++ b/src/main/java/ru/bclib/registry/ItemsRegistry.java @@ -0,0 +1,110 @@ +package ru.bclib.registry; + +import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags; +import net.minecraft.core.BlockSource; +import net.minecraft.core.Direction; +import net.minecraft.core.dispenser.DefaultDispenseItemBehavior; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.sounds.SoundEvent; +import net.minecraft.tags.Tag; +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.CreativeModeTab; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.ShovelItem; +import net.minecraft.world.item.SpawnEggItem; +import net.minecraft.world.item.SwordItem; +import net.minecraft.world.item.TieredItem; +import net.minecraft.world.level.block.DispenserBlock; +import ru.bclib.items.BaseDiscItem; +import ru.bclib.items.BaseDrinkItem; +import ru.bclib.items.BaseSpawnEggItem; +import ru.bclib.items.ModelProviderItem; +import ru.bclib.items.tool.BaseAxeItem; +import ru.bclib.items.tool.BaseHoeItem; +import ru.bclib.items.tool.BasePickaxeItem; +import ru.bclib.util.TagHelper; + +public abstract class ItemsRegistry extends BaseRegistry { + + protected ItemsRegistry(CreativeModeTab creativeTab) { + super(creativeTab); + } + + public Item registerDisc(String name, int power, SoundEvent sound) { + return register(name, new BaseDiscItem(power, sound, makeItemSettings().stacksTo(1))); + } + + public Item registerItem(String name) { + return register(name, new ModelProviderItem(makeItemSettings())); + } + + @Override + public Item register(ResourceLocation itemId, Item item) { + registerItem(itemId, item, BaseRegistry.getModItems(itemId.getNamespace())); + return item; + } + + public TieredItem registerTool(String name, TieredItem item) { + ResourceLocation id = createModId(name); + registerItem(id, item, BaseRegistry.getModItems(id.getNamespace())); + + if (item instanceof ShovelItem) { + TagHelper.addTag((Tag.Named) FabricToolTags.SHOVELS, item); + } else if (item instanceof SwordItem) { + TagHelper.addTag((Tag.Named) FabricToolTags.SWORDS, item); + } else if (item instanceof BasePickaxeItem) { + TagHelper.addTag((Tag.Named) FabricToolTags.PICKAXES, item); + } else if (item instanceof BaseAxeItem) { + TagHelper.addTag((Tag.Named) FabricToolTags.AXES, item); + } else if (item instanceof BaseHoeItem) { + TagHelper.addTag((Tag.Named) FabricToolTags.HOES, item); + } + + return item; + } + + public Item registerEgg(String name, EntityType type, int background, int dots) { + SpawnEggItem item = new BaseSpawnEggItem(type, background, dots, makeItemSettings()); + 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(name, item); + } + + public Item registerFood(String name, 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(name, builder.build()); + } + + public Item registerFood(String name, FoodProperties foodComponent) { + return register(name, new ModelProviderItem(makeItemSettings().food(foodComponent))); + } + + public Item registerDrink(String name) { + return register(name, new BaseDrinkItem(makeItemSettings().stacksTo(1))); + } + + public Item registerDrink(String name, FoodProperties foodComponent) { + return register(name, new BaseDrinkItem(makeItemSettings().stacksTo(1).food(foodComponent))); + } + + public Item registerDrink(String name, int hunger, float saturation) { + FoodProperties.Builder builder = new FoodProperties.Builder().nutrition(hunger).saturationMod(saturation); + return registerDrink(name, builder.build()); + } +} diff --git a/src/main/java/ru/bclib/sdf/PosInfo.java b/src/main/java/ru/bclib/sdf/PosInfo.java index d7e7e0ed..b8a64c4d 100644 --- a/src/main/java/ru/bclib/sdf/PosInfo.java +++ b/src/main/java/ru/bclib/sdf/PosInfo.java @@ -1,12 +1,12 @@ package ru.bclib.sdf; +import java.util.Map; + 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; @@ -86,12 +86,12 @@ public class PosInfo implements Comparable { } return pos.equals(((PosInfo) obj).pos); } - + @Override public int compareTo(PosInfo info) { return this.pos.getY() - info.pos.getY(); } - + public BlockPos getPos() { return pos; } diff --git a/src/main/java/ru/bclib/sdf/SDF.java b/src/main/java/ru/bclib/sdf/SDF.java index 57d7ab31..396850de 100644 --- a/src/main/java/ru/bclib/sdf/SDF.java +++ b/src/main/java/ru/bclib/sdf/SDF.java @@ -1,8 +1,16 @@ package ru.bclib.sdf; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; + import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -12,19 +20,12 @@ import net.minecraft.world.phys.AABB; import ru.bclib.util.BlocksHelper; import ru.bclib.world.structures.StructureWorld; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; - public abstract class SDF { private 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); @@ -51,8 +52,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { + for (BlockPos center: ends) { + for (Direction dir: Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); @@ -85,7 +86,7 @@ public abstract class SDF { infos.forEach((info) -> { BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); }); - + infos.clear(); infos.addAll(addInfo.values()); Collections.sort(infos); @@ -134,7 +135,7 @@ public abstract class SDF { infos.forEach((info) -> { BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); }); - + infos.clear(); infos.addAll(addInfo.values()); Collections.sort(infos); @@ -163,8 +164,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { + for (BlockPos center: ends) { + for (Direction dir: Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); BlockState state = world.getBlockState(wpos); @@ -197,7 +198,7 @@ public abstract class SDF { infos.forEach((info) -> { BlocksHelper.setWithoutUpdate(world, info.getPos(), info.getState()); }); - + infos.clear(); infos.addAll(addInfo.values()); Collections.sort(infos); @@ -226,8 +227,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { + for (BlockPos center: ends) { + for (Direction dir: Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); @@ -283,8 +284,8 @@ public abstract class SDF { MutableBlockPos bPos = new MutableBlockPos(); while (run) { - for (BlockPos center : ends) { - for (Direction dir : Direction.values()) { + for (BlockPos center: ends) { + for (Direction dir: Direction.values()) { bPos.set(center).move(dir); BlockPos wpos = bPos.offset(start); BlockState state = world.getBlockState(wpos); diff --git a/src/main/java/ru/bclib/sdf/operator/SDFBinary.java b/src/main/java/ru/bclib/sdf/operator/SDFBinary.java index 056aba3f..0e223e54 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFBinary.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFBinary.java @@ -27,8 +27,7 @@ public abstract class SDFBinary extends SDF { public BlockState getBlockState(BlockPos pos) { if (firstValue) { return sourceA.getBlockState(pos); - } - else { + } else { return sourceB.getBlockState(pos); } } diff --git a/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java b/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java index d0c01c3e..1b096f5e 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFCoordModify.java @@ -1,9 +1,9 @@ package ru.bclib.sdf.operator; -import com.mojang.math.Vector3f; - import java.util.function.Consumer; +import com.mojang.math.Vector3f; + public class SDFCoordModify extends SDFUnary { private static final Vector3f POS = new Vector3f(); private Consumer function; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java b/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java index c25bbae2..5ca88dee 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFDisplacement.java @@ -1,9 +1,9 @@ package ru.bclib.sdf.operator; -import com.mojang.math.Vector3f; - import java.util.function.Function; +import com.mojang.math.Vector3f; + public class SDFDisplacement extends SDFUnary { private static final Vector3f POS = new Vector3f(); private Function displace; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java b/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java index b5233d51..5629607a 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFHeightmap.java @@ -1,6 +1,7 @@ package ru.bclib.sdf.operator; import com.mojang.blaze3d.platform.NativeImage; + import net.minecraft.util.Mth; public class SDFHeightmap extends SDFDisplacement { diff --git a/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java b/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java index 3e3be641..921768db 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFRadialNoiseMap.java @@ -34,10 +34,7 @@ public class SDFRadialNoiseMap extends SDFDisplacement { } 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; + 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) { diff --git a/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java b/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java index 5770d25b..393d66d2 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFSmoothIntersection.java @@ -4,7 +4,7 @@ import net.minecraft.util.Mth; public class SDFSmoothIntersection extends SDFBinary { private float radius; - + public SDFSmoothIntersection setRadius(float radius) { this.radius = radius; return this; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java b/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java index c7ac6e73..020b8590 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFSmoothSubtraction.java @@ -4,7 +4,7 @@ import net.minecraft.util.Mth; public class SDFSmoothSubtraction extends SDFBinary { private float radius; - + public SDFSmoothSubtraction setRadius(float radius) { this.radius = radius; return this; diff --git a/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java b/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java index e7034e75..493c1c9b 100644 --- a/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java +++ b/src/main/java/ru/bclib/sdf/operator/SDFSmoothUnion.java @@ -4,12 +4,12 @@ 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); diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java b/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java index bd3230ba..891253da 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFCappedCone.java @@ -22,7 +22,7 @@ public class SDFCappedCone extends SDFPrimitive { this.height = height; return this; } - + @Override public float getDistance(float x, float y, float z) { float qx = MHelper.length(x, z); @@ -30,11 +30,7 @@ public class SDFCappedCone extends SDFPrimitive { 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 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; diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java b/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java index 586aaf73..1f06cbf5 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFFlatland.java @@ -3,6 +3,6 @@ package ru.bclib.sdf.primitive; public class SDFFlatland extends SDFPrimitive { @Override public float getDistance(float x, float y, float z) { - return y; + return y; } } diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java b/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java index a2e28a83..23a5b55c 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFHexPrism.java @@ -15,7 +15,7 @@ public class SDFHexPrism extends SDFPrimitive { this.height = height; return this; } - + @Override public float getDistance(float x, float y, float z) { float px = Math.abs(x); diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFLine.java b/src/main/java/ru/bclib/sdf/primitive/SDFLine.java index 0c166a91..9fd316d7 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFLine.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFLine.java @@ -30,17 +30,17 @@ public class SDFLine extends SDFPrimitive { 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); diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFPie.java b/src/main/java/ru/bclib/sdf/primitive/SDFPie.java index 6bff34ea..0ad180f4 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFPie.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFPie.java @@ -22,10 +22,10 @@ public class SDFPie extends SDFPrimitive { @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); + 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 * (float) Math.signum(cos * px - sin * z)); + return MHelper.max(l, m * (float) Math.signum(cos * px - sin * z)); } } diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java b/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java index 4e3b527f..e40b61ab 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFPrimitive.java @@ -1,12 +1,12 @@ package ru.bclib.sdf.primitive; +import java.util.function.Function; + import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.state.BlockState; import ru.bclib.sdf.SDF; -import java.util.function.Function; - public abstract class SDFPrimitive extends SDF { protected Function placerFunction; diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java b/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java index edeb8ea2..c8ff092b 100644 --- a/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java +++ b/src/main/java/ru/bclib/sdf/primitive/SDFSphere.java @@ -6,7 +6,7 @@ public class SDFSphere extends SDFPrimitive { private float radius; public SDFSphere setRadius(float radius) { - this.radius = radius; + this.radius = radius; return this; } diff --git a/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java b/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java deleted file mode 100644 index e7540c93..00000000 --- a/src/main/java/ru/bclib/sdf/primitive/SDFTorus.java +++ /dev/null @@ -1,24 +0,0 @@ -package ru.bclib.sdf.primitive; - -import ru.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/ru/bclib/server/BCLibServer.java b/src/main/java/ru/bclib/server/BCLibServer.java index e76b1147..2fbc8c0b 100644 --- a/src/main/java/ru/bclib/server/BCLibServer.java +++ b/src/main/java/ru/bclib/server/BCLibServer.java @@ -2,15 +2,10 @@ package ru.bclib.server; import net.fabricmc.api.DedicatedServerModInitializer; import ru.bclib.api.ModIntegrationAPI; -import ru.bclib.api.PostInitAPI; -import ru.bclib.api.dataexchange.DataExchangeAPI; public class BCLibServer implements DedicatedServerModInitializer { @Override public void onInitializeServer() { ModIntegrationAPI.registerAll(); - DataExchangeAPI.prepareServerside(); - - PostInitAPI.postInit(false); } } diff --git a/src/main/java/ru/bclib/util/BlocksHelper.java b/src/main/java/ru/bclib/util/BlocksHelper.java index 1ba8952a..21b974f9 100644 --- a/src/main/java/ru/bclib/util/BlocksHelper.java +++ b/src/main/java/ru/bclib/util/BlocksHelper.java @@ -1,6 +1,10 @@ package ru.bclib.util; +import java.util.Map; +import java.util.Random; + import com.google.common.collect.Maps; + import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -14,51 +18,48 @@ 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 java.util.Map; -import java.util.Random; - 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_UPDATE_BLOCK | 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 MutableBlockPos POS = 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++) { @@ -66,7 +67,7 @@ public class BlocksHelper { } 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++) { @@ -74,7 +75,7 @@ public class BlocksHelper { } return length; } - + public static int downRayRep(LevelAccessor world, BlockPos pos, int maxDist) { POS.set(pos); for (int j = 1; j < maxDist && (world.getBlockState(POS)).getMaterial().isReplaceable(); j++) { @@ -82,7 +83,7 @@ public class BlocksHelper { } return pos.getY() - POS.getY(); } - + public static int raycastSqr(LevelAccessor world, BlockPos pos, int dx, int dy, int dz, int maxDist) { POS.set(pos); for (int j = 1; j < maxDist && (world.getBlockState(POS)).getMaterial().isReplaceable(); j++) { @@ -90,23 +91,21 @@ public class BlocksHelper { } 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 state - {@link BlockState} to mirror; * @param rotation - {@link Rotation}; - * @param facing - Block {@link Direction} {@link Property}. + * @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 state - {@link BlockState} to mirror; * @param mirror - {@link Mirror}; * @param facing - Block {@link Direction} {@link Property}. * @return Mirrored {@link BlockState}. @@ -114,12 +113,11 @@ public class BlocksHelper { 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 pos - {@link BlockPos} start position; * @param block - {@link Block} to count. * @return Integer amount of blocks. */ @@ -130,40 +128,36 @@ public class BlocksHelper { } 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}; + 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(Random 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(Random random) { return DIRECTIONS[random.nextInt(6)]; } - + /** * Check if block is {@link Fluid} or not. - * * @param state - {@link BlockState} to check. * @return {@code true} if block is fluid and {@code false} if not. */ @@ -173,10 +167,9 @@ public class BlocksHelper { /** * 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. + * @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) { @@ -185,7 +178,6 @@ public class BlocksHelper { /** * 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. */ diff --git a/src/main/java/ru/bclib/util/ColorExtractor.java b/src/main/java/ru/bclib/util/ColorExtractor.java index e383a5d3..9614345d 100644 --- a/src/main/java/ru/bclib/util/ColorExtractor.java +++ b/src/main/java/ru/bclib/util/ColorExtractor.java @@ -9,7 +9,7 @@ public class ColorExtractor { private List

centers = new ArrayList<>(); private List colors; private Integer result; - + public ColorExtractor(List colors) { this.colors = colors; Random rnd = new Random(); @@ -19,7 +19,7 @@ public class ColorExtractor { this.centers.add(new Center(color)); } } - + public int analize() { boolean moved = true; while (moved) { @@ -41,10 +41,10 @@ public class ColorExtractor { toClear.forEach(clear -> centers.remove(clear)); } this.centers.sort(Center.COMPARATOR); - + return this.getResult(); } - + public int getResult() { if (result == null) { double weights = 0; @@ -59,20 +59,19 @@ public class ColorExtractor { 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 -> { @@ -90,7 +89,7 @@ public class ColorExtractor { this.centers.get(id).colors.add(color); }); } - + private static class Center { static final Comparator
COMPARATOR = new Comparator
() { @Override @@ -98,24 +97,24 @@ public class ColorExtractor { 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); @@ -123,7 +122,7 @@ public class ColorExtractor { int b = (int) Math.round(this.b); return a << 24 | r << 16 | g << 8 | b; } - + public boolean move() { double or = r; double og = g; @@ -140,9 +139,9 @@ public class ColorExtractor { 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/ru/bclib/util/ColorUtil.java b/src/main/java/ru/bclib/util/ColorUtil.java index d091e83d..179dff9e 100644 --- a/src/main/java/ru/bclib/util/ColorUtil.java +++ b/src/main/java/ru/bclib/util/ColorUtil.java @@ -1,7 +1,13 @@ package ru.bclib.util; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + import com.google.common.collect.Maps; import com.mojang.blaze3d.platform.NativeImage; + import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.fabricmc.fabric.impl.client.indigo.renderer.helper.ColorHelper; @@ -15,39 +21,39 @@ import net.minecraft.world.item.BlockItem; import net.minecraft.world.item.Item; import ru.bclib.BCLib; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - public class ColorUtil { 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}; + 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) { @@ -57,27 +63,34 @@ public class ColorUtil { 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; + 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; + 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; + 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) { @@ -124,13 +137,13 @@ public class ColorUtil { } return 0xFF000000 | (r << 16) | (g << 8) | (b << 0); } - + public static int parseHex(String hexColor) { int len = hexColor.length(); if (len < 6 || len > 8 || len % 2 > 0) { return -1; } - + int color, shift; if (len == 6) { color = 0xFF000000; @@ -140,7 +153,7 @@ public class ColorUtil { color = 0; shift = 24; } - + try { String[] splited = hexColor.split("(?<=\\G.{2})"); for (String digit : splited) { @@ -152,17 +165,17 @@ public class ColorUtil { 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; @@ -170,18 +183,18 @@ public class ColorUtil { 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 applyTint(int color, int tint) { return colorBrigtness(ColorHelper.multiplyColor(color, tint), 1.5F); } - + public static int colorDistance(int color1, int color2) { int r1 = (color1 >> 16) & 255; int g1 = (color1 >> 8) & 255; @@ -191,9 +204,9 @@ public class ColorUtil { int b2 = color2 & 255; return MHelper.sqr(r1 - r2) + MHelper.sqr(g1 - g2) + MHelper.sqr(b1 - b2); } - + private static Map colorPalette = Maps.newHashMap(); - + @Environment(EnvType.CLIENT) public static int extractColor(Item item) { ResourceLocation id = Registry.ITEM.getKey(item); @@ -219,16 +232,16 @@ public class ColorUtil { } } 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(); diff --git a/src/main/java/ru/bclib/util/ItemUtil.java b/src/main/java/ru/bclib/util/ItemUtil.java deleted file mode 100644 index fd639a3b..00000000 --- a/src/main/java/ru/bclib/util/ItemUtil.java +++ /dev/null @@ -1,74 +0,0 @@ -package ru.bclib.util; - -import com.google.gson.JsonObject; -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 org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import ru.bclib.BCLib; - -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/ru/bclib/util/JsonFactory.java b/src/main/java/ru/bclib/util/JsonFactory.java index 185c0b24..9397f32c 100644 --- a/src/main/java/ru/bclib/util/JsonFactory.java +++ b/src/main/java/ru/bclib/util/JsonFactory.java @@ -1,32 +1,23 @@ package ru.bclib.util; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import net.fabricmc.api.EnvType; -import net.fabricmc.api.Environment; -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 org.jetbrains.annotations.Nullable; -import ru.bclib.BCLib; - import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; import java.io.Reader; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import ru.bclib.BCLib; + public class JsonFactory { - public final static Gson GSON = new GsonBuilder().setPrettyPrinting() - .create(); - + public final static Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + public static JsonObject getJsonObject(InputStream stream) { try { Reader reader = new InputStreamReader(stream); @@ -41,7 +32,7 @@ public class JsonFactory { } return new JsonObject(); } - + public static JsonObject getJsonObject(File jsonFile) { if (jsonFile.exists()) { JsonElement json = loadJson(jsonFile); @@ -52,34 +43,7 @@ public class JsonFactory { } 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); - if (resource != null) { - InputStream stream = resource.getInputStream(); - InputStreamReader reader = new InputStreamReader(stream); - 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)) { @@ -91,11 +55,11 @@ public class JsonFactory { } 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)) { String json = GSON.toJson(jsonObject); @@ -106,34 +70,22 @@ public class JsonFactory { BCLib.LOGGER.catching(ex); } } - - public static void storeJson(OutputStream outStream, JsonElement jsonObject) { - OutputStreamWriter writer = new OutputStreamWriter(outStream); - 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/ru/bclib/util/Logger.java b/src/main/java/ru/bclib/util/Logger.java index 68cce157..52721bac 100644 --- a/src/main/java/ru/bclib/util/Logger.java +++ b/src/main/java/ru/bclib/util/Logger.java @@ -6,56 +6,56 @@ import org.apache.logging.log4j.LogManager; public final class Logger { private static final org.apache.logging.log4j.Logger LOGGER = LogManager.getLogger(); private final String modPref; - + public Logger(String modID) { this.modPref = "[" + modID + "] "; } - + public void log(Level level, String message) { LOGGER.log(level, modPref + message); } - + public void log(Level level, String message, Object... params) { LOGGER.log(level, modPref + message, params); } - + public void debug(Object message) { this.log(Level.DEBUG, message.toString()); } - + public void debug(Object message, Object... params) { this.log(Level.DEBUG, message.toString(), params); } - + public void catching(Throwable ex) { this.error(ex.getLocalizedMessage()); LOGGER.catching(ex); } - + public void info(String message) { this.log(Level.INFO, message); } - + public void info(String message, Object... params) { this.log(Level.INFO, message, params); } - + public void warning(String message, Object... params) { this.log(Level.WARN, message, params); } - + public void warning(String message, Object obj, Exception ex) { LOGGER.warn(modPref + message, obj, ex); } - + public void error(String message) { this.log(Level.ERROR, message); } - + public void error(String message, Object obj, Exception ex) { LOGGER.error(modPref + message, obj, ex); } - + public void error(String message, Exception ex) { LOGGER.error(modPref + message, ex); } diff --git a/src/main/java/ru/bclib/util/MHelper.java b/src/main/java/ru/bclib/util/MHelper.java index 95bb8853..b7d53913 100644 --- a/src/main/java/ru/bclib/util/MHelper.java +++ b/src/main/java/ru/bclib/util/MHelper.java @@ -1,17 +1,18 @@ package ru.bclib.util; -import com.mojang.math.Vector3f; -import net.minecraft.core.Vec3i; - import java.util.Random; +import com.mojang.math.Vector3f; + +import net.minecraft.core.Vec3i; + public class MHelper { 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 int randRange(int min, int max, Random random) { return min + random.nextInt(max - min + 1); } @@ -19,37 +20,37 @@ public class MHelper { public static double randRange(double min, double max, Random random) { return min + random.nextDouble() * (max - min); } - + public static float randRange(float min, float max, Random 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; } @@ -133,7 +134,7 @@ public class MHelper { 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; @@ -148,7 +149,7 @@ public class MHelper { array[i2] = element; } } - + public static int sqr(int i) { return i * i; } @@ -169,7 +170,8 @@ public class MHelper { return value / RAD_TO_DEG; } - public static Vector3f cross(Vector3f vec1, Vector3f vec2) { + 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(); diff --git a/src/main/java/ru/bclib/util/ModUtil.java b/src/main/java/ru/bclib/util/ModUtil.java deleted file mode 100644 index 8f4b973a..00000000 --- a/src/main/java/ru/bclib/util/ModUtil.java +++ /dev/null @@ -1,423 +0,0 @@ -package ru.bclib.util; - -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; -import com.google.gson.stream.JsonReader; -import net.fabricmc.loader.api.FabricLoader; -import net.fabricmc.loader.api.ModContainer; -import net.fabricmc.loader.api.SemanticVersion; -import net.fabricmc.loader.api.Version; -import net.fabricmc.loader.api.VersionParsingException; -import net.fabricmc.loader.api.metadata.ContactInformation; -import net.fabricmc.loader.api.metadata.CustomValue; -import net.fabricmc.loader.api.metadata.ModDependency; -import net.fabricmc.loader.api.metadata.ModEnvironment; -import net.fabricmc.loader.api.metadata.ModMetadata; -import net.fabricmc.loader.api.metadata.Person; -import net.fabricmc.loader.util.version.SemanticVersionImpl; -import org.apache.logging.log4j.LogManager; -import ru.bclib.BCLib; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.nio.file.FileSystem; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class ModUtil { - private static Map mods; - - /** - * Unloads the cache of available mods created from {@link #getMods()} - */ - public static void invalidateCachedMods() { - mods = null; - } - - /** - * return a map of all mods that were found in the 'mods'-folder. - *

- * The method will cache the results. You can clear that cache (and free the memory) by - * calling {@link #invalidateCachedMods()} - *

- * An error message is printed if a mod fails to load, but the parsing will continue. - * - * @return A map of all found mods. (key=ModID, value={@link ModInfo}) - */ - public static Map getMods() { - if (mods != null) return mods; - - mods = new HashMap<>(); - org.apache.logging.log4j.Logger logger = LogManager.getFormatterLogger("BCLib|ModLoader"); - PathUtil.fileWalker(PathUtil.MOD_FOLDER.toFile(), false, (file -> { - try { - URI uri = URI.create("jar:" + file.toUri()); - FileSystem fs = FileSystems.getFileSystem(uri); - if (fs!=null) { - try { - Path modMetaFile = fs.getPath("fabric.mod.json"); - if (modMetaFile != null) { - try (InputStream is = Files.newInputStream(modMetaFile)) { - //ModMetadata mc = ModMetadataParser.parseMetadata(is, uri.toString(), new LinkedList()); - ModMetadata mc = readJSON(is, uri.toString()); - if (mc!=null){ - mods.put(mc.getId(), new ModInfo(mc, file)); - } - } - } - } catch (Exception e) { - BCLib.LOGGER.error(e.getMessage()); - } - } - } - catch (Exception e) { - BCLib.LOGGER.error(e.getMessage()); - } - })); - - return mods; - } - - private static ModMetadata readJSON(InputStream is, String sourceFile) throws IOException { - try (com.google.gson.stream.JsonReader reader = new JsonReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { - JsonObject data = new JsonParser().parse(reader).getAsJsonObject(); - Version ver; - try { - ver = new SemanticVersionImpl(data.get("version").getAsString(), false); - } - catch (VersionParsingException e) { - BCLib.LOGGER.error("Unable to parse Version in " + sourceFile); - return null; - } - - if (data.get("id") == null){ - BCLib.LOGGER.error("Unable to read ID in " + sourceFile); - return null; - } - - if (data.get("name") == null){ - BCLib.LOGGER.error("Unable to read name in " + sourceFile); - return null; - } - - return new ModMetadata() { - @Override - public Version getVersion() { - return ver; - } - @Override - public String getType() { - return "fabric"; - } - - @Override - public String getId() { - return data.get("id").getAsString(); - } - - @Override - public Collection getProvides() { - return new ArrayList<>(); - } - - @Override - public ModEnvironment getEnvironment() { - JsonElement env = data.get("environment"); - if (env==null) { - BCLib.LOGGER.error("No environment specified in " + sourceFile); - return ModEnvironment.UNIVERSAL; - } - final String environment = env.getAsString().toLowerCase(Locale.ROOT); - - if (environment.isEmpty() || environment.equals("*") || environment.equals("common")) { - JsonElement entrypoints = data.get("entrypoints"); - boolean hasClient = true; - - //check if there is an actual client entrypoint - if (entrypoints!=null && entrypoints.isJsonObject()){ - JsonElement client = entrypoints.getAsJsonObject().get("client"); - if (client!=null && client.isJsonArray()){ - hasClient = client.getAsJsonArray().size() > 0; - } else if (client==null || !client.isJsonPrimitive()){ - hasClient = false; - } else if (!client.getAsJsonPrimitive().isString()){ - hasClient = false; - } - } - - if (hasClient == false) return ModEnvironment.SERVER; - return ModEnvironment.UNIVERSAL; - } else if (environment.equals("client")) { - return ModEnvironment.CLIENT; - } else if (environment.equals("server")) { - return ModEnvironment.SERVER; - } else { - BCLib.LOGGER.error("Unable to read environment in " + sourceFile); - return ModEnvironment.UNIVERSAL; - } - } - - @Override - public Collection getDepends() { - return new ArrayList<>(); - } - - @Override - public Collection getRecommends() { - return new ArrayList<>(); - } - - @Override - public Collection getSuggests() { - return new ArrayList<>(); - } - - @Override - public Collection getConflicts() { - return new ArrayList<>(); - } - - @Override - public Collection getBreaks() { - return new ArrayList<>(); - } - - public Collection getDependencies() { - return new ArrayList<>(); - } - - @Override - public String getName() { - return data.get("name").getAsString(); - } - - @Override - public String getDescription() { - return ""; - } - - @Override - public Collection getAuthors() { - return new ArrayList<>(); - } - - @Override - public Collection getContributors() { - return new ArrayList<>(); - } - - @Override - public ContactInformation getContact() { - return null; - } - - @Override - public Collection getLicense() { - return new ArrayList<>(); - } - - @Override - public Optional getIconPath(int size) { - return Optional.empty(); - } - - @Override - public boolean containsCustomValue(String key) { - return false; - } - - @Override - public CustomValue getCustomValue(String key) { - return null; - } - - @Override - public Map getCustomValues() { - return new HashMap<>(); - } - - @Override - public boolean containsCustomElement(String key) { - return false; - } - - public JsonElement getCustomElement(String key) { - return null; - } - }; - } - } - - /** - * Returns the {@link ModInfo} or {@code null} if the mod was not found. - *

- * The call will also return null if the mode-Version in the jar-File is not the same - * as the version of the loaded Mod. - * - * @param modID The mod ID to query - * @return A {@link ModInfo}-Object for the querried Mod. - */ - public static ModInfo getModInfo(String modID) { - return getModInfo(modID, true); - } - - public static ModInfo getModInfo(String modID, boolean matchVersion) { - getMods(); - final ModInfo mi = mods.get(modID); - if (mi == null || (matchVersion && !getModVersion(modID).equals(mi.getVersion()))) return null; - return mi; - } - - /** - * Local Mod Version for the queried Mod - * - * @param modID The mod ID to query - * @return The version of the locally installed Mod - */ - public static String getModVersion(String modID) { - Optional optional = FabricLoader.getInstance() - .getModContainer(modID); - if (optional.isPresent()) { - ModContainer modContainer = optional.get(); - return ModInfo.versionToString(modContainer.getMetadata() - .getVersion()); - - } - - return getModVersionFromJar(modID); - } - - /** - * Local Mod Version for the queried Mod from the Jar-File in the games mod-directory - * - * @param modID The mod ID to query - * @return The version of the locally installed Mod - */ - public static String getModVersionFromJar(String modID) { - final ModInfo mi = getModInfo(modID, false); - if (mi != null) return mi.getVersion(); - - return "0.0.0"; - } - - /** - * Get mod version from string. String should be in format: %d.%d.%d - * - * @param version - {@link String} mod version. - * @return int mod version. - */ - public static int convertModVersion(String version) { - if (version.isEmpty()) { - return 0; - } - try { - int res = 0; - final String semanticVersionPattern = "(\\d+)\\.(\\d+)\\.(\\d+)\\D*"; - final Matcher matcher = Pattern.compile(semanticVersionPattern) - .matcher(version); - if (matcher.find()) { - if (matcher.groupCount() > 0) res = (Integer.parseInt(matcher.group(1)) & 0xFF) << 22; - if (matcher.groupCount() > 1) res |= (Integer.parseInt(matcher.group(2)) & 0xFF) << 14; - if (matcher.groupCount() > 2) res |= Integer.parseInt(matcher.group(3)) & 0x3FFF; - } - - return res; - } - catch (Exception e) { - return 0; - } - } - - /** - * Get mod version from integer. String will be in format %d.%d.%d - * - * @param version - mod version in integer form. - * @return {@link String} mod version. - */ - public static String convertModVersion(int version) { - int a = (version >> 22) & 0xFF; - int b = (version >> 14) & 0xFF; - int c = version & 0x3FFF; - return String.format(Locale.ROOT, "%d.%d.%d", a, b, c); - } - - /** - * {@code true} if the version v1 is larger than v2 - * - * @param v1 A Version string - * @param v2 Another Version string - * @return v1 > v2 - */ - public static boolean isLargerVersion(String v1, String v2) { - return convertModVersion(v1) > convertModVersion(v2); - } - - /** - * {@code true} if the version v1 is larger or equal v2 - * - * @param v1 A Version string - * @param v2 Another Version string - * @return v1 ≥ v2 - */ - public static boolean isLargerOrEqualVersion(String v1, String v2) { - return convertModVersion(v1) >= convertModVersion(v2); - } - - public static class ModInfo { - public final ModMetadata metadata; - public final Path jarPath; - - ModInfo(ModMetadata metadata, Path jarPath) { - this.metadata = metadata; - this.jarPath = jarPath; - } - - public static String versionToString(Version v) { - if (v instanceof SemanticVersion) { - return versionToString((SemanticVersion) v); - } - return convertModVersion(convertModVersion(v.toString())); - } - - public static String versionToString(SemanticVersion v) { - StringBuilder stringBuilder = new StringBuilder(); - boolean first = true; - final int cCount = Math.min(v.getVersionComponentCount(), 3); - for (int i = 0; i < cCount; i++) { - if (first) { - first = false; - } - else { - stringBuilder.append('.'); - } - - stringBuilder.append(v.getVersionComponent(i)); - } - - return stringBuilder.toString(); - } - - @Override - public String toString() { - return "ModInfo{" + "id=" + metadata.getId() + ", version=" + metadata.getVersion() + ", jarPath=" + jarPath + '}'; - } - - public String getVersion() { - if (metadata == null) return "0.0.0"; - return versionToString(metadata.getVersion()); - } - } -} diff --git a/src/main/java/ru/bclib/util/Pair.java b/src/main/java/ru/bclib/util/Pair.java deleted file mode 100644 index c542ac09..00000000 --- a/src/main/java/ru/bclib/util/Pair.java +++ /dev/null @@ -1,31 +0,0 @@ -package ru.bclib.util; - -import java.util.Objects; - -public class Pair { - 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/ru/bclib/util/PathUtil.java b/src/main/java/ru/bclib/util/PathUtil.java deleted file mode 100644 index ddd0c8f1..00000000 --- a/src/main/java/ru/bclib/util/PathUtil.java +++ /dev/null @@ -1,101 +0,0 @@ -package ru.bclib.util; - -import net.fabricmc.loader.api.FabricLoader; - -import java.io.File; -import java.nio.file.Path; -import java.util.function.Consumer; - -public class PathUtil { - public final static Path GAME_FOLDER = FabricLoader.getInstance() - .getGameDir() - .normalize(); - - public final static Path MOD_FOLDER = FabricLoader.getInstance() - .getGameDir() - .resolve("mods") - .normalize(); - - public final static Path MOD_BAK_FOLDER = MOD_FOLDER.resolve("_bclib_deactivated") - .normalize(); - - /** - * Tests if a path is a child-path. - *

- * A path is a child of another if it is located in the parent or any of the parents subdirectories - * - * @param parent The folder we search for the {@code child} - * @param child The folder you want to test - * @return {@code true} if {@code child} is in {@code parent} or any of its sub directories - */ - public static boolean isChildOf(Path parent, Path child) { - if (child == null || parent == null) return false; - parent = parent.toAbsolutePath().normalize(); - child = child.toAbsolutePath().normalize(); - - final int pCount = parent.getNameCount(); - final int cCount = child.getNameCount(); - - if (cCount > pCount) return isChildOf(parent, child.getParent()); - if (cCount < pCount) return false; - - return child.equals(parent); - } - - /** - * A simple directory walker that ignores dot-files - * - * @param path The path where you want to start - * @param pathConsumer The consumer called for each valid file. The consumer will get an absolute {@link Path}-Object - * for each visited file - */ - public static void fileWalker(File path, Consumer pathConsumer) { - fileWalker(path, true, pathConsumer); - } - - /** - * A simple directory walker that ignores dot-files - * - * @param path The path where you want to start - * @param recursive if {@code false}, only the {@code path} is traversed - * @param pathConsumer The consumer called for each valid file. The consumer will get an absolute {@link Path}-Object - * for each visited file - */ - public static void fileWalker(File path, boolean recursive, Consumer pathConsumer) { - if (!path.exists()) return; - for (final File f : path.listFiles()) { - if (f.getName() - .startsWith(".")) continue; - if (f.isDirectory()) { - if (recursive) fileWalker(f, pathConsumer); - } - else if (f.isFile()) { - pathConsumer.accept(f.toPath()); - } - } - } - - /** - * Creates a human readable File-Size - * - * @param size Filesize in bytes - * @return A Human readable String - */ - public static String humanReadableFileSize(long size) { - final int threshold = 2; - final int factor = 1024; - if (size < 0) return "? Byte"; - if (size < factor * threshold) { - return size + " Byte"; - } - char[] units = {'K', 'M', 'G', 'T', 'P'}; - int unitIndex = 0; - double fSize = size; - do { - unitIndex++; - fSize /= 1024; - } while (fSize > factor * threshold && unitIndex < units.length); - - return String.format("%.1f %ciB", fSize, units[unitIndex - 1]); - } -} diff --git a/src/main/java/ru/bclib/util/RecipeHelper.java b/src/main/java/ru/bclib/util/RecipeHelper.java deleted file mode 100644 index 82527011..00000000 --- a/src/main/java/ru/bclib/util/RecipeHelper.java +++ /dev/null @@ -1,25 +0,0 @@ -package ru.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/ru/bclib/util/SplineHelper.java b/src/main/java/ru/bclib/util/SplineHelper.java index de5b9a0a..0b1e8a75 100644 --- a/src/main/java/ru/bclib/util/SplineHelper.java +++ b/src/main/java/ru/bclib/util/SplineHelper.java @@ -1,7 +1,13 @@ package ru.bclib.util; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.function.Function; + import com.google.common.collect.Lists; import com.mojang.math.Vector3f; + import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.util.Mth; @@ -11,11 +17,6 @@ import ru.bclib.sdf.SDF; import ru.bclib.sdf.operator.SDFUnion; import ru.bclib.sdf.primitive.SDFLine; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -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(); @@ -85,10 +86,11 @@ public class SplineHelper { 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); + 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; } @@ -103,10 +105,11 @@ public class SplineHelper { 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); + 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; } @@ -306,7 +309,7 @@ public class SplineHelper { } public static void rotateSpline(List spline, float angle) { - for (Vector3f v : spline) { + for (Vector3f v: spline) { float sin = (float) Math.sin(angle); float cos = (float) Math.cos(angle); float x = v.x() * cos + v.z() * sin; @@ -317,7 +320,7 @@ public class SplineHelper { public static List copySpline(List spline) { List result = new ArrayList(spline.size()); - for (Vector3f v : spline) { + for (Vector3f v: spline) { result.add(new Vector3f(v.x(), v.y(), v.z())); } return result; @@ -328,13 +331,13 @@ public class SplineHelper { } public static void scale(List spline, float x, float y, float z) { - for (Vector3f v : spline) { + 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) { + for (Vector3f v: spline) { v.set(offset.x() + v.x(), offset.y() + v.y(), offset.z() + v.z()); } } diff --git a/src/main/java/ru/bclib/util/StructureHelper.java b/src/main/java/ru/bclib/util/StructureHelper.java index 28494f48..9d724ac8 100644 --- a/src/main/java/ru/bclib/util/StructureHelper.java +++ b/src/main/java/ru/bclib/util/StructureHelper.java @@ -1,6 +1,16 @@ package ru.bclib.util; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Enumeration; +import java.util.Random; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + import com.google.common.collect.Sets; + import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -21,15 +31,6 @@ import net.minecraft.world.level.material.Material; import net.minecraft.world.phys.Vec3; import ru.bclib.api.TagAPI; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.Random; -import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - public class StructureHelper { private static final Direction[] DIR = BlocksHelper.makeHorizontal(); @@ -53,7 +54,7 @@ public class StructureHelper { 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); } @@ -79,20 +80,15 @@ public class StructureHelper { 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 - ); + Vec3 offset = StructureTemplate.transform(Vec3.atCenterOf(structure.getSize()), mirror, rotation, BlockPos.ZERO); return pos.offset(-offset.x * 0.5, 0, -offset.z * 0.5); } @@ -102,9 +98,7 @@ public class StructureHelper { public static void placeCenteredBottom(WorldGenLevel world, BlockPos pos, StructureTemplate structure, Rotation rotation, Mirror mirror, BoundingBox bounds, Random random) { BlockPos offset = offsetPos(pos, structure, rotation, mirror); - StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation) - .setMirror(mirror) - .setBoundingBox(bounds); + StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); structure.placeInWorld(world, offset, offset, placementData, random, 4); } @@ -147,11 +141,7 @@ public class StructureHelper { 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))) { + 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(); @@ -174,11 +164,7 @@ public class StructureHelper { int dz = pz - cz; dz *= dz; mut.setZ(pz); - if (dx + dy + dz <= r && BlocksHelper.isInvulnerable( - world.getBlockState(mut), - world, - mut - )) { + if (dx + dy + dz <= r && BlocksHelper.isInvulnerable(world.getBlockState(mut), world, mut)) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); } } @@ -195,9 +181,8 @@ public class StructureHelper { } 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))) { + 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--) { @@ -212,11 +197,7 @@ public class StructureHelper { } break; } - else if (random.nextInt(8) == 0 && !BlocksHelper.isInvulnerable( - world.getBlockState(mut.above()), - world, - mut - )) { + else if (random.nextInt(8) == 0 && !BlocksHelper.isInvulnerable(world.getBlockState(mut.above()), world, mut)) { BlocksHelper.setWithoutUpdate(world, mut, Blocks.AIR); } } @@ -245,7 +226,7 @@ public class StructureHelper { } } } - + public static void erodeIntense(WorldGenLevel world, BoundingBox bounds, Random random) { MutableBlockPos mut = new MutableBlockPos(); MutableBlockPos mut2 = new MutableBlockPos(); @@ -280,13 +261,13 @@ public class StructureHelper { } } } - + drop(world, bounds); } private static boolean isTerrainNear(WorldGenLevel world, BlockPos pos) { - for (Direction dir : BlocksHelper.DIRECTIONS) { - if (world.getBlockState(pos.relative(dir)).is(TagAPI.BLOCK_GEN_TERRAIN)) { + for (Direction dir: BlocksHelper.DIRECTIONS) { + if (world.getBlockState(pos.relative(dir)).is(TagAPI.GEN_TERRAIN)) { return true; } } @@ -319,8 +300,8 @@ public class StructureHelper { } while (!edge.isEmpty()) { - for (BlockPos center : edge) { - for (Direction dir : BlocksHelper.DIRECTIONS) { + for (BlockPos center: edge) { + for (Direction dir: BlocksHelper.DIRECTIONS) { BlockState state = world.getBlockState(center); if (state.isCollisionShapeFullBlock(world, center)) { mut.set(center).move(dir); @@ -362,14 +343,16 @@ public class StructureHelper { } } } - + private static boolean ignore(BlockState state, WorldGenLevel world, BlockPos pos) { - return state.getMaterial().isReplaceable() || !state.getFluidState() - .isEmpty() || state.is(TagAPI.BLOCK_END_GROUND) || state.is( - BlockTags.LOGS) || state.is(BlockTags.LEAVES) || state.getMaterial() - .equals(Material.PLANT) || state.getMaterial() - .equals(Material.LEAVES) || BlocksHelper - .isInvulnerable(state, world, pos); + return state.getMaterial().isReplaceable() || + !state.getFluidState().isEmpty() || + state.is(TagAPI.END_GROUND) || + state.is(BlockTags.LOGS) || + state.is(BlockTags.LEAVES) || + state.getMaterial().equals(Material.PLANT) || + state.getMaterial().equals(Material.LEAVES) || + BlocksHelper.isInvulnerable(state, world, pos); } public static void cover(WorldGenLevel world, BoundingBox bounds, Random random) { @@ -382,9 +365,7 @@ public class StructureHelper { for (int y = bounds.maxY(); y >= bounds.minY(); y--) { mut.setY(y); BlockState state = world.getBlockState(mut); - if (state.is(TagAPI.BLOCK_END_GROUND) && !world.getBlockState(mut.above()) - .getMaterial() - .isSolidBlocking()) { + if (state.is(TagAPI.END_GROUND) && !world.getBlockState(mut.above()).getMaterial().isSolidBlocking()) { BlocksHelper.setWithoutUpdate(world, mut, top); } } diff --git a/src/main/java/ru/bclib/util/TagHelper.java b/src/main/java/ru/bclib/util/TagHelper.java new file mode 100644 index 00000000..dae193d0 --- /dev/null +++ b/src/main/java/ru/bclib/util/TagHelper.java @@ -0,0 +1,73 @@ +package ru.bclib.util; + +import java.util.Map; +import java.util.Set; + +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + +import net.minecraft.core.Registry; +import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.Tag; +import net.minecraft.world.item.Item; +import net.minecraft.world.level.ItemLike; +import net.minecraft.world.level.block.Block; + +public class TagHelper { + private static final Map> TAGS_BLOCK = Maps.newConcurrentMap(); + private static final Map> TAGS_ITEM = Maps.newConcurrentMap(); + + public static void addTag(Tag.Named tag, Block... blocks) { + ResourceLocation tagID = tag.getName(); + Set set = TAGS_BLOCK.computeIfAbsent(tagID, k -> Sets.newHashSet()); + for (Block block: blocks) { + ResourceLocation id = Registry.BLOCK.getKey(block); + if (id != Registry.BLOCK.getDefaultKey()) { + set.add(id); + } + } + } + + public static void addTag(Tag.Named tag, ItemLike... items) { + ResourceLocation tagID = tag.getName(); + Set set = TAGS_ITEM.computeIfAbsent(tagID, k -> Sets.newHashSet()); + for (ItemLike item: items) { + ResourceLocation id = Registry.ITEM.getKey(item.asItem()); + if (id != Registry.ITEM.getDefaultKey()) { + set.add(id); + } + } + } + + @SafeVarargs + public static void addTags(ItemLike item, Tag.Named... tags) { + for (Tag.Named tag: tags) { + addTag(tag, item); + } + } + + @SafeVarargs + public static void addTags(Block block, Tag.Named... tags) { + for (Tag.Named tag: tags) { + addTag(tag, block); + } + } + + public static Tag.Builder apply(Tag.Builder builder, Set ids) { + ids.forEach(value -> builder.addElement(value, "Better End Code")); + return builder; + } + + public static Map apply(String directory, Map tagsMap) { + Map> endTags = null; + if ("tags/blocks".equals(directory)) { + endTags = TAGS_BLOCK; + } else if ("tags/items".equals(directory)) { + endTags = TAGS_ITEM; + } + if (endTags != null) { + endTags.forEach((id, ids) -> apply(tagsMap.computeIfAbsent(id, key -> Tag.Builder.tag()), ids)); + } + return tagsMap; + } +} diff --git a/src/main/java/ru/bclib/util/TranslationHelper.java b/src/main/java/ru/bclib/util/TranslationHelper.java index d85a07ba..68ad5412 100644 --- a/src/main/java/ru/bclib/util/TranslationHelper.java +++ b/src/main/java/ru/bclib/util/TranslationHelper.java @@ -1,42 +1,37 @@ package ru.bclib.util; -import com.google.common.collect.Sets; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.Collections; +import java.util.List; + +import com.google.common.collect.Lists; import com.google.gson.Gson; import com.google.gson.JsonObject; + import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceLocation; -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(); + public static void printMissingNames(String modID) { + List missingNamesEn = Lists.newArrayList(); + List missingNamesRu = Lists.newArrayList(); 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); + InputStream streamEn = TranslationHelper.class.getResourceAsStream("/assets/" + modID + "/lang/en_us.json"); + InputStream streamRu = TranslationHelper.class.getResourceAsStream("/assets/" + modID + "/lang/ru_ru.json"); + JsonObject translationEn = gson.fromJson(new InputStreamReader(streamEn), JsonObject.class); + JsonObject translationRu = gson.fromJson(new InputStreamReader(streamRu), 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); + if (!translationEn.has(name)) { + missingNamesEn.add(name); + } + if (!translationRu.has(name)) { + missingNamesRu.add(name); } } }); @@ -44,8 +39,11 @@ public class TranslationHelper { Registry.ITEM.forEach(item -> { if (Registry.ITEM.getKey(item).getNamespace().equals(modID)) { String name = item.getDescription().getString(); - if (!translation.has(name)) { - missingNames.add(name); + if (!translationEn.has(name)) { + missingNamesEn.add(name); + } + if (!translationRu.has(name)) { + missingNamesRu.add(name); } } }); @@ -54,8 +52,11 @@ public class TranslationHelper { ResourceLocation id = BuiltinRegistries.BIOME.getKey(biome); if (id.getNamespace().equals(modID)) { String name = "biome." + modID + "." + id.getPath(); - if (!translation.has(name)) { - missingNames.add(name); + if (!translationEn.has(name)) { + missingNamesEn.add(name); + } + if (!translationRu.has(name)) { + missingNamesRu.add(name); } } }); @@ -64,45 +65,44 @@ public class TranslationHelper { 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 (!translationEn.has(name)) { + missingNamesEn.add(name); + } + if (!translationRu.has(name)) { + missingNamesRu.add(name); } } }); - if (!missingNames.isEmpty()) { + if (!missingNamesEn.isEmpty() || !missingNamesRu.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 + "\": \"\","); - }); - } + if (!missingNamesEn.isEmpty()) { + Collections.sort(missingNamesEn); + System.out.println("========================================"); + System.out.println(" ENGLISH"); + System.out.println("========================================"); + missingNamesEn.forEach((name) -> { + System.out.println(" \"" + name + "\": \"" + fastTranslateEn(name) + "\","); + }); + } + + if (!missingNamesRu.isEmpty()) { + Collections.sort(missingNamesRu); + System.out.println("========================================"); + System.out.println(" RUSSIAN"); + System.out.println("========================================"); + missingNamesRu.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(); diff --git a/src/main/java/ru/bclib/util/Triple.java b/src/main/java/ru/bclib/util/Triple.java deleted file mode 100644 index a40f1a90..00000000 --- a/src/main/java/ru/bclib/util/Triple.java +++ /dev/null @@ -1,31 +0,0 @@ -package ru.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/ru/bclib/util/WeighTree.java b/src/main/java/ru/bclib/util/WeighTree.java index 8aca4f5f..096747c4 100644 --- a/src/main/java/ru/bclib/util/WeighTree.java +++ b/src/main/java/ru/bclib/util/WeighTree.java @@ -14,7 +14,6 @@ public class WeighTree { /** * Get eandom value from tree. - * * @param random - {@link Random}. * @return {@link T} value. */ @@ -54,7 +53,7 @@ public class WeighTree { this.min = min; this.max = max; } - + @Override T get(float value) { return value < separator ? min.get(value) : max.get(value); @@ -72,7 +71,7 @@ public class WeighTree { Leaf(T value) { this.biome = value; } - + @Override T get(float value) { return biome; diff --git a/src/main/java/ru/bclib/util/WeightedList.java b/src/main/java/ru/bclib/util/WeightedList.java index 3a7f3680..5455dd39 100644 --- a/src/main/java/ru/bclib/util/WeightedList.java +++ b/src/main/java/ru/bclib/util/WeightedList.java @@ -12,7 +12,6 @@ public class WeightedList { /** * Adds value with specified weight to the list - * * @param value * @param weight */ @@ -24,7 +23,6 @@ public class WeightedList { /** * Get random value. - * * @param random - {@link Random}. * @return {@link T} value. */ @@ -43,7 +41,6 @@ public class WeightedList { /** * Get value by index. - * * @param index - {@code int} index. * @return {@link T} value. */ @@ -53,37 +50,33 @@ public class WeightedList { /** * 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). + * @param end - {@code int} end index (exclusive). * @return {@link WeightedList}. */ protected WeightedList subList(int start, int end) { @@ -94,29 +87,26 @@ public class WeightedList { } 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() { diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiome.java b/src/main/java/ru/bclib/world/biomes/BCLBiome.java index 0cf21cbb..d6326ebe 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiome.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiome.java @@ -1,9 +1,15 @@ package ru.bclib.world.biomes; +import java.io.InputStream; +import java.util.List; +import java.util.Map; +import java.util.Random; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gson.JsonArray; import com.google.gson.JsonObject; + import net.minecraft.core.Registry; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.biome.Biome; @@ -15,28 +21,23 @@ import ru.bclib.world.features.ListFeature; import ru.bclib.world.features.ListFeature.StructureInfo; import ru.bclib.world.features.NBTStructureFeature.TerrainMerge; -import java.io.InputStream; -import java.util.List; -import java.util.Map; -import java.util.Random; - public class BCLBiome { protected WeightedList subbiomes = new WeightedList(); - + protected final Biome biome; protected final ResourceLocation mcID; protected BCLBiome edge; protected int edgeSize; - + protected BCLBiome biomeParent; protected float maxSubBiomeChance = 1; protected final float genChance; - + private final Map customData; private final float fogDensity; private BCLFeature structuresFeature; private Biome actualBiome; - + public BCLBiome(BCLBiomeDef definition) { this.mcID = definition.getID(); this.readStructureList(); @@ -47,9 +48,8 @@ public class BCLBiome { this.genChance = definition.getGenChance(); this.fogDensity = definition.getFodDensity(); this.customData = definition.getCustomData(); - subbiomes.add(this, 1); } - + public BCLBiome(ResourceLocation id, Biome biome, float fogDensity, float genChance) { this.mcID = id; this.biome = biome; @@ -57,26 +57,25 @@ public class BCLBiome { this.fogDensity = fogDensity; this.readStructureList(); this.customData = Maps.newHashMap(); - subbiomes.add(this, 1); } - + public BCLBiome getEdge() { return edge == null ? this : edge; } - + public void setEdge(BCLBiome edge) { this.edge = edge; edge.biomeParent = this; } - + public int getEdgeSize() { return edgeSize; } - + public void setEdgeSize(int size) { edgeSize = size; } - + public void addSubBiome(BCLBiome biome) { biome.biomeParent = this; subbiomes.add(biome, biome.getGenChance()); @@ -85,40 +84,41 @@ public class BCLBiome { public boolean containsSubBiome(BCLBiome biome) { return subbiomes.contains(biome); } - + public BCLBiome getSubBiome(Random random) { - return subbiomes.get(random); + BCLBiome biome = subbiomes.get(random); + return biome == null ? this : biome; } - + public BCLBiome getParentBiome() { return this.biomeParent; } - + public boolean hasEdge() { return edge != null; } - + public boolean hasParentBiome() { return biomeParent != null; } - + public boolean isSame(BCLBiome biome) { return biome == this || (biome.hasParentBiome() && biome.getParentBiome() == this); } - + public Biome getBiome() { return biome; } - + @Override public String toString() { return mcID.toString(); } - + public ResourceLocation getID() { return mcID; } - + public float getFogDensity() { return fogDensity; } @@ -126,7 +126,7 @@ public class BCLBiome { protected void readStructureList() { String ns = mcID.getNamespace(); String nm = mcID.getPath(); - + String path = "/data/" + ns + "/structures/biome/" + nm + "/"; InputStream inputstream = StructureHelper.class.getResourceAsStream(path + "structures.json"); if (inputstream != null) { @@ -142,11 +142,7 @@ public class BCLBiome { list.add(new StructureInfo(structure, offsetY, terrainMerge)); }); if (!list.isEmpty()) { - structuresFeature = BCLFeature.makeChansedFeature( - new ResourceLocation(ns, nm + "_structures"), - new ListFeature(list), - 10 - ); + structuresFeature = BCLFeature.makeChansedFeature(new ResourceLocation(ns, nm + "_structures"), new ListFeature(list), 10); } } } @@ -159,7 +155,7 @@ public class BCLBiome { public Biome getActualBiome() { return this.actualBiome; } - + public float getGenChance() { return this.genChance; } diff --git a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java index 60ced512..1d77c26d 100644 --- a/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java +++ b/src/main/java/ru/bclib/world/biomes/BCLBiomeDef.java @@ -1,7 +1,11 @@ package ru.bclib.world.biomes; +import java.util.List; +import java.util.Map; + import com.google.common.collect.Lists; import com.google.common.collect.Maps; + import net.minecraft.core.Registry; import net.minecraft.core.particles.ParticleOptions; import net.minecraft.resources.ResourceLocation; @@ -28,6 +32,7 @@ import net.minecraft.world.level.levelgen.carver.CarverConfiguration; import net.minecraft.world.level.levelgen.carver.ConfiguredWorldCarver; import net.minecraft.world.level.levelgen.feature.ConfiguredFeature; import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; +import net.minecraft.world.level.levelgen.feature.configurations.ProbabilityFeatureConfiguration; import net.minecraft.world.level.levelgen.surfacebuilders.ConfiguredSurfaceBuilder; import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilder; import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilderBaseConfiguration; @@ -37,9 +42,6 @@ import ru.bclib.world.features.BCLFeature; import ru.bclib.world.structures.BCLStructureFeature; import ru.bclib.world.surface.DoubleBlockSurfaceBuilder; -import java.util.List; -import java.util.Map; - public class BCLBiomeDef { public static final int DEF_FOLIAGE_OVERWORLD = ColorUtil.color(110, 143, 64); public static final int DEF_FOLIAGE_NETHER = ColorUtil.color(117, 10, 10); @@ -53,19 +55,18 @@ public class BCLBiomeDef { private final Map customData = Maps.newHashMap(); private final ResourceLocation id; - + private AmbientParticleSettings particleConfig; private AmbientAdditionsSettings additions; private AmbientMoodSettings mood; private SoundEvent music; private SoundEvent loop; - + private int foliageColor = DEF_FOLIAGE_OVERWORLD; private int grassColor = DEF_FOLIAGE_OVERWORLD; private int waterFogColor = 329011; private int waterColor = 4159204; private int fogColor = 10518688; - private int skyColor = 0; private float fogDensity = 1F; private float depth = 0.1F; @@ -77,19 +78,17 @@ public class BCLBiomeDef { private int edgeSize = 32; private ConfiguredSurfaceBuilder surface; - + /** * Custom biome definition. Can be extended with new parameters. - * * @param id - Biome {@link ResourceLocation} (identifier). */ public BCLBiomeDef(ResourceLocation id) { this.id = id; } - /** + /** * Create default definition for The Nether biome. - * * @return {@link BCLBiomeDef}. */ public BCLBiomeDef netherBiome() { @@ -99,9 +98,8 @@ public class BCLBiomeDef { return this; } - /** + /** * Create default definition for The End biome. - * * @return {@link BCLBiomeDef}. */ public BCLBiomeDef endBiome() { @@ -113,7 +111,6 @@ public class BCLBiomeDef { /** * Used to load biome settings from config. - * * @param config - {@link IdConfig}. * @return this {@link BCLBiomeDef}. */ @@ -126,7 +123,6 @@ public class BCLBiomeDef { /** * Set category of the biome. - * * @param category - {@link BiomeCategory}. * @return this {@link BCLBiomeDef}. */ @@ -142,18 +138,15 @@ public class BCLBiomeDef { public BCLBiomeDef setSurface(Block block) { setSurface(SurfaceBuilder.DEFAULT.configured(new SurfaceBuilderBaseConfiguration( - block.defaultBlockState(), - Blocks.END_STONE.defaultBlockState(), - Blocks.END_STONE.defaultBlockState() + block.defaultBlockState(), + Blocks.END_STONE.defaultBlockState(), + Blocks.END_STONE.defaultBlockState() ))); return this; } public BCLBiomeDef setSurface(Block block1, Block block2) { - setSurface(DoubleBlockSurfaceBuilder.register("bclib_" + id.getPath() + "_surface") - .setBlock1(block1) - .setBlock2(block2) - .configured()); + setSurface(DoubleBlockSurfaceBuilder.register("bclib_" + id.getPath() + "_surface").setBlock1(block1).setBlock2(block2).configured()); return this; } @@ -161,7 +154,7 @@ public class BCLBiomeDef { this.surface = builder; return this; } - + public BCLBiomeDef setParticles(ParticleOptions particle, float probability) { this.particleConfig = new AmbientParticleSettings(particle, probability); return this; @@ -191,7 +184,7 @@ public class BCLBiomeDef { this.edgeSize = edgeSize; return this; } - + public BCLBiomeDef addMobSpawn(EntityType type, int weight, int minGroupSize, int maxGroupSize) { ResourceLocation eID = Registry.ENTITY_TYPE.getKey(type); if (eID != Registry.ENTITY_TYPE.getDefaultKey()) { @@ -209,7 +202,7 @@ public class BCLBiomeDef { spawns.add(entry); return this; } - + public BCLBiomeDef addStructureFeature(ConfiguredStructureFeature feature) { structures.add(feature); return this; @@ -227,7 +220,7 @@ public class BCLBiomeDef { features.add(info); return this; } - + public BCLBiomeDef addFeature(Decoration featureStep, ConfiguredFeature feature) { FeatureInfo info = new FeatureInfo(); info.featureStep = featureStep; @@ -242,35 +235,22 @@ public class BCLBiomeDef { b = Mth.clamp(b, 0, 255); return ColorUtil.color(r, g, b); } - - public BCLBiomeDef setSkyColor(int rgb) { - this.skyColor = rgb; - return this; - } - - public BCLBiomeDef setSkyColor(int r, int g, int b) { - return setSkyColor(getColor(r, g, b)); - } - - public BCLBiomeDef setFogColor(int rgb) { - this.fogColor = rgb; - return this; - } - + public BCLBiomeDef setFogColor(int r, int g, int b) { - return setFogColor(getColor(r, g, b)); + this.fogColor = getColor(r, g, b); + return this; } - + public BCLBiomeDef setFogDensity(float density) { this.fogDensity = density; return this; } - + public BCLBiomeDef setWaterColor(int r, int g, int b) { this.waterColor = getColor(r, g, b); return this; } - + public BCLBiomeDef setWaterFogColor(int r, int g, int b) { this.waterFogColor = getColor(r, g, b); return this; @@ -293,41 +273,34 @@ public class BCLBiomeDef { public BCLBiomeDef setPlantsColor(int r, int g, int b) { return this.setFoliageColor(r, g, b).setGrassColor(r, g, b); } - + public BCLBiomeDef setLoop(SoundEvent loop) { this.loop = loop; return this; } - + public BCLBiomeDef setMood(SoundEvent mood) { this.mood = new AmbientMoodSettings(mood, 6000, 8, 2.0D); return this; } - + public BCLBiomeDef setAdditions(SoundEvent additions) { this.additions = new AmbientAdditionsSettings(additions, 0.0111); return this; } - + public BCLBiomeDef setMusic(SoundEvent music) { this.music = music; return this; } - - protected void addCustomToBuild(BiomeGenerationSettings.Builder generationSettings){ - - } - + public Biome build() { MobSpawnSettings.Builder spawnSettings = new MobSpawnSettings.Builder(); BiomeGenerationSettings.Builder generationSettings = new BiomeGenerationSettings.Builder(); Builder effects = new Builder(); - + mobs.forEach((spawn) -> { - spawnSettings.addSpawn( - spawn.type.getCategory(), - new MobSpawnSettings.SpawnerData(spawn.type, spawn.weight, spawn.minGroupSize, spawn.maxGroupSize) - ); + spawnSettings.addSpawn(spawn.type.getCategory(), new MobSpawnSettings.SpawnerData(spawn.type, spawn.weight, spawn.minGroupSize, spawn.maxGroupSize)); }); spawns.forEach((entry) -> { @@ -338,21 +311,14 @@ public class BCLBiomeDef { structures.forEach((structure) -> generationSettings.addStructureStart(structure)); features.forEach((info) -> generationSettings.addFeature(info.featureStep, info.feature)); carvers.forEach((info) -> generationSettings.addCarver(info.carverStep, info.carver)); - - addCustomToBuild(generationSettings); - - effects.skyColor(skyColor) - .waterColor(waterColor) - .waterFogColor(waterFogColor) - .fogColor(fogColor) - .foliageColorOverride(foliageColor) - .grassColorOverride(grassColor); + + effects.skyColor(0).waterColor(waterColor).waterFogColor(waterFogColor).fogColor(fogColor).foliageColorOverride(foliageColor).grassColorOverride(grassColor); if (loop != null) effects.ambientLoopSound(loop); if (mood != null) effects.ambientMoodSound(mood); if (additions != null) effects.ambientAdditionsSound(additions); if (particleConfig != null) effects.ambientParticle(particleConfig); effects.backgroundMusic(music != null ? new Music(music, 600, 2400, true) : Musics.END); - + return new Biome.BiomeBuilder() .precipitation(precipitation) .biomeCategory(category) @@ -365,24 +331,24 @@ public class BCLBiomeDef { .generationSettings(generationSettings.build()) .build(); } - + private static final class SpawnInfo { EntityType type; int weight; int minGroupSize; int maxGroupSize; } - + private static final class FeatureInfo { Decoration featureStep; ConfiguredFeature feature; } - private static final class CarverInfo { + private static final class CarverInfo { Carving carverStep; - ConfiguredWorldCarver carver; + ConfiguredWorldCarver carver; } - + public ResourceLocation getID() { return id; } @@ -390,7 +356,7 @@ public class BCLBiomeDef { public float getFodDensity() { return fogDensity; } - + public float getGenChance() { return genChance; } @@ -398,8 +364,8 @@ public class BCLBiomeDef { public int getEdgeSize() { return edgeSize; } - - public BCLBiomeDef addCarver(Carving carverStep, ConfiguredWorldCarver carver) { + + public BCLBiomeDef addCarver(Carving carverStep, ConfiguredWorldCarver carver) { CarverInfo info = new CarverInfo(); info.carverStep = carverStep; info.carver = carver; diff --git a/src/main/java/ru/bclib/world/biomes/FabricBiomesData.java b/src/main/java/ru/bclib/world/biomes/FabricBiomesData.java deleted file mode 100644 index 01d71897..00000000 --- a/src/main/java/ru/bclib/world/biomes/FabricBiomesData.java +++ /dev/null @@ -1,15 +0,0 @@ -package ru.bclib.world.biomes; - -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import net.minecraft.resources.ResourceKey; -import net.minecraft.world.level.biome.Biome; - -import java.util.Map; -import java.util.Set; - -public class FabricBiomesData { - public static final Map, Float> END_LAND_BIOMES = Maps.newHashMap(); - public static final Map, Float> END_VOID_BIOMES = Maps.newHashMap(); - public static final Set> NETHER_BIOMES = Sets.newHashSet(); -} diff --git a/src/main/java/ru/bclib/world/features/BCLDecorators.java b/src/main/java/ru/bclib/world/features/BCLDecorators.java index ee5b60b2..d037c5f6 100644 --- a/src/main/java/ru/bclib/world/features/BCLDecorators.java +++ b/src/main/java/ru/bclib/world/features/BCLDecorators.java @@ -8,7 +8,7 @@ import java.lang.reflect.Field; public class BCLDecorators { public static final ConfiguredDecorator HEIGHTMAP_SQUARE; - + private static final ConfiguredDecorator getDecorator(Field[] fields, int index) { try { return (ConfiguredDecorator) fields[index].get(null); @@ -18,7 +18,7 @@ public class BCLDecorators { return null; } } - + static { Class[] classes = Features.class.getDeclaredClasses(); Field[] fields = classes[1].getDeclaredFields(); // Decorators class diff --git a/src/main/java/ru/bclib/world/features/BCLFeature.java b/src/main/java/ru/bclib/world/features/BCLFeature.java index b7b898d0..2227cddd 100644 --- a/src/main/java/ru/bclib/world/features/BCLFeature.java +++ b/src/main/java/ru/bclib/world/features/BCLFeature.java @@ -2,7 +2,9 @@ package ru.bclib.world.features; import net.minecraft.core.Registry; import net.minecraft.data.BuiltinRegistries; +import net.minecraft.data.worldgen.Features; import net.minecraft.resources.ResourceLocation; +import net.minecraft.tags.BlockTags; import net.minecraft.world.level.block.Block; import net.minecraft.world.level.block.Blocks; import net.minecraft.world.level.levelgen.GenerationStep; @@ -13,6 +15,7 @@ import net.minecraft.world.level.levelgen.feature.configurations.CountConfigurat 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.OreConfiguration; +import net.minecraft.world.level.levelgen.feature.configurations.RangeDecoratorConfiguration; import net.minecraft.world.level.levelgen.placement.ChanceDecoratorConfiguration; import net.minecraft.world.level.levelgen.placement.FeatureDecorator; import net.minecraft.world.level.levelgen.structure.templatesystem.BlockMatchTest; @@ -21,11 +24,11 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.TagMatchTest; import ru.bclib.api.TagAPI; public class BCLFeature { - private static final RuleTest ANY_TERRAIN = new TagMatchTest(TagAPI.BLOCK_GEN_TERRAIN); + private static final RuleTest ANY_TERRAIN = new TagMatchTest(TagAPI.GEN_TERRAIN); private ConfiguredFeature featureConfigured; private GenerationStep.Decoration featureStep; private Feature feature; - + public BCLFeature(Feature feature, ConfiguredFeature configuredFeature, GenerationStep.Decoration featureStep) { this.featureConfigured = configuredFeature; this.featureStep = featureStep; @@ -39,67 +42,42 @@ public class BCLFeature { } public static BCLFeature makeVegetationFeature(ResourceLocation id, Feature feature, int density) { - ConfiguredFeature configured = feature - .configured(FeatureConfiguration.NONE) - .decorated(BCLDecorators.HEIGHTMAP_SQUARE) - .countRandom(density); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(BCLDecorators.HEIGHTMAP_SQUARE).countRandom(density); return new BCLFeature(id, feature, GenerationStep.Decoration.VEGETAL_DECORATION, configured); } public static BCLFeature makeRawGenFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature - .configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.RAW_GENERATION, configured); } - @Deprecated public static BCLFeature makeLakeFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature - .configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.LAVA_LAKE.configured(new ChanceDecoratorConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.LAVA_LAKE.configured(new ChanceDecoratorConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.LAKES, configured); } public static BCLFeature makeOreFeature(ResourceLocation id, Block blockOre, int veins, int veinSize, int offset, int minY, int maxY) { - OreConfiguration featureConfig = new OreConfiguration( - new BlockMatchTest(Blocks.END_STONE), - blockOre.defaultBlockState(), - veinSize - ); + OreConfiguration featureConfig = new OreConfiguration(new BlockMatchTest(Blocks.END_STONE), blockOre.defaultBlockState(), veinSize); OreConfiguration config = new OreConfiguration(ANY_TERRAIN, blockOre.defaultBlockState(), 33); - ConfiguredFeature oreFeature = Feature.ORE - .configured(featureConfig) - .rangeUniform( - VerticalAnchor.absolute(minY), - VerticalAnchor.absolute(maxY) - ) + ConfiguredFeature oreFeature = Feature.ORE.configured(featureConfig) + .rangeUniform(VerticalAnchor.absolute(minY), VerticalAnchor.absolute(maxY)) .squared() .count(veins); - return new BCLFeature( - Feature.ORE, - Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, id, oreFeature), - GenerationStep.Decoration.UNDERGROUND_ORES - ); + return new BCLFeature(Feature.ORE, Registry.register(BuiltinRegistries.CONFIGURED_FEATURE, id, oreFeature), GenerationStep.Decoration.UNDERGROUND_ORES); } public static BCLFeature makeChunkFeature(ResourceLocation id, Feature feature) { - ConfiguredFeature configured = feature - .configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(1))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(1))); return new BCLFeature(id, feature, GenerationStep.Decoration.LOCAL_MODIFICATIONS, configured); } public static BCLFeature makeChansedFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature - .configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.CHANCE.configured(new ChanceDecoratorConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.SURFACE_STRUCTURES, configured); } public static BCLFeature makeCountRawFeature(ResourceLocation id, Feature feature, int chance) { - ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE) - .decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(chance))); + ConfiguredFeature configured = feature.configured(FeatureConfiguration.NONE).decorated(FeatureDecorator.COUNT.configured(new CountConfiguration(chance))); return new BCLFeature(id, feature, GenerationStep.Decoration.RAW_GENERATION, configured); } @@ -111,11 +89,11 @@ public class BCLFeature { public Feature getFeature() { return feature; } - + public ConfiguredFeature getFeatureConfigured() { return featureConfigured; } - + public GenerationStep.Decoration getFeatureStep() { return featureStep; } diff --git a/src/main/java/ru/bclib/world/features/ListFeature.java b/src/main/java/ru/bclib/world/features/ListFeature.java index a6990896..8f00c087 100644 --- a/src/main/java/ru/bclib/world/features/ListFeature.java +++ b/src/main/java/ru/bclib/world/features/ListFeature.java @@ -1,5 +1,8 @@ package ru.bclib.world.features; +import java.util.List; +import java.util.Random; + import net.minecraft.core.BlockPos; import net.minecraft.world.level.WorldGenLevel; import net.minecraft.world.level.block.Mirror; @@ -8,9 +11,6 @@ import net.minecraft.world.level.levelgen.structure.templatesystem.StructurePlac import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplate; import ru.bclib.util.StructureHelper; -import java.util.List; -import java.util.Random; - public class ListFeature extends NBTStructureFeature { private final List list; private StructureInfo selected; @@ -24,29 +24,29 @@ public class ListFeature extends NBTStructureFeature { selected = list.get(random.nextInt(list.size())); return selected.getStructure(); } - + @Override protected boolean canSpawn(WorldGenLevel world, BlockPos pos, Random random) { int cx = pos.getX() >> 4; int cz = pos.getZ() >> 4; return ((cx + cz) & 1) == 0 && pos.getY() > 58;// && world.getBlockState(pos.below()).is(EndTags.GEN_TERRAIN); } - + @Override protected Rotation getRotation(WorldGenLevel world, BlockPos pos, Random random) { return Rotation.getRandom(random); } - + @Override protected Mirror getMirror(WorldGenLevel world, BlockPos pos, Random random) { return Mirror.values()[random.nextInt(3)]; } - + @Override protected int getYOffset(StructureTemplate structure, WorldGenLevel world, BlockPos pos, Random random) { return selected.offsetY; } - + @Override protected TerrainMerge getTerrainMerge(WorldGenLevel world, BlockPos pos, Random random) { return selected.terrainMerge; diff --git a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java index 37aa0050..e48bfb5a 100644 --- a/src/main/java/ru/bclib/world/features/NBTStructureFeature.java +++ b/src/main/java/ru/bclib/world/features/NBTStructureFeature.java @@ -1,5 +1,9 @@ package ru.bclib.world.features; +import java.io.IOException; +import java.io.InputStream; +import java.util.Random; + import net.minecraft.core.BlockPos; import net.minecraft.core.BlockPos.MutableBlockPos; import net.minecraft.core.Direction; @@ -13,38 +17,36 @@ import net.minecraft.world.level.biome.Biome; 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.feature.FeaturePlaceContext; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; 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.level.levelgen.surfacebuilders.SurfaceBuilderConfiguration; +import net.minecraft.world.phys.Vec3; import ru.bclib.api.BiomeAPI; import ru.bclib.api.TagAPI; import ru.bclib.util.BlocksHelper; import ru.bclib.world.processors.DestructionStructureProcessor; -import java.io.IOException; -import java.io.InputStream; -import java.util.Random; - public abstract class NBTStructureFeature extends DefaultFeature { protected static final DestructionStructureProcessor DESTRUCTION = new DestructionStructureProcessor(); - + protected abstract StructureTemplate getStructure(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract boolean canSpawn(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract Rotation getRotation(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract Mirror getMirror(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract int getYOffset(StructureTemplate structure, WorldGenLevel world, BlockPos pos, Random random); - + protected abstract TerrainMerge getTerrainMerge(WorldGenLevel world, BlockPos pos, Random random); - + protected abstract void addStructureData(StructurePlaceSettings data); - + protected BlockPos getGround(WorldGenLevel world, BlockPos center) { Biome biome = world.getBiome(center); ResourceLocation id = BiomeAPI.getBiomeID(biome); @@ -57,7 +59,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { return new BlockPos(center.getX(), y, center.getZ()); } } - + protected int getAverageY(WorldGenLevel world, BlockPos center) { int y = getYOnSurface(world, center.getX(), center.getZ()); y += getYOnSurface(world, center.getX() - 2, center.getZ() - 2); @@ -66,7 +68,7 @@ public abstract class NBTStructureFeature extends DefaultFeature { y += getYOnSurface(world, center.getX() + 2, center.getZ() + 2); return y / 5; } - + protected int getAverageYWG(WorldGenLevel world, BlockPos center) { int y = getYOnSurfaceWG(world, center.getX(), center.getZ()); y += getYOnSurfaceWG(world, center.getX() - 2, center.getZ() - 2); @@ -75,40 +77,33 @@ public abstract class NBTStructureFeature extends DefaultFeature { y += getYOnSurfaceWG(world, center.getX() + 2, center.getZ() + 2); return y / 5; } - + @Override public boolean place(FeaturePlaceContext context) { WorldGenLevel world = context.level(); Random random = context.random(); BlockPos center = context.origin(); - + center = new BlockPos(((center.getX() >> 4) << 4) | 8, 128, ((center.getZ() >> 4) << 4) | 8); center = getGround(world, center); - + if (!canSpawn(world, center, random)) { return false; } - + int posY = center.getY() + 1; StructureTemplate structure = getStructure(world, center, random); Rotation rotation = getRotation(world, center, random); Mirror mirror = getMirror(world, center, random); - BlockPos offset = StructureTemplate.transform( - new BlockPos(structure.getSize()), - mirror, - rotation, - BlockPos.ZERO - ); + BlockPos offset = StructureTemplate.transform(new BlockPos(structure.getSize()), mirror, rotation, BlockPos.ZERO); center = center.offset(0, getYOffset(structure, world, center, random) + 0.5, 0); - + BoundingBox bounds = makeBox(center); - StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation) - .setMirror(mirror) - .setBoundingBox(bounds); + StructurePlaceSettings placementData = new StructurePlaceSettings().setRotation(rotation).setMirror(mirror).setBoundingBox(bounds); addStructureData(placementData); center = center.offset(-offset.getX() * 0.5, 0, -offset.getZ() * 0.5); structure.placeInWorld(world, center, center, placementData, random, 4); - + TerrainMerge merge = getTerrainMerge(world, center, random); int x1 = center.getX(); int z1 = center.getZ(); @@ -116,19 +111,19 @@ public abstract class NBTStructureFeature extends DefaultFeature { int z2 = z1 + offset.getZ(); if (merge != TerrainMerge.NONE) { MutableBlockPos mut = new MutableBlockPos(); - + if (x2 < x1) { int a = x1; x1 = x2; x2 = a; } - + if (z2 < z1) { int a = z1; z1 = z2; z2 = a; } - + int surfMax = posY - 1; for (int x = x1; x <= x2; x++) { mut.setX(x); @@ -136,15 +131,13 @@ public abstract class NBTStructureFeature extends DefaultFeature { mut.setZ(z); mut.setY(surfMax); BlockState state = world.getBlockState(mut); - if (!state.is(TagAPI.BLOCK_GEN_TERRAIN) && state.isFaceSturdy(world, mut, Direction.DOWN)) { + if (!state.is(TagAPI.GEN_TERRAIN) && state.isFaceSturdy(world, mut, Direction.DOWN)) { for (int i = 0; i < 10; i++) { mut.setY(mut.getY() - 1); BlockState stateSt = world.getBlockState(mut); - if (!stateSt.is(TagAPI.BLOCK_GEN_TERRAIN)) { + if (!stateSt.is(TagAPI.GEN_TERRAIN)) { if (merge == TerrainMerge.SURFACE) { - SurfaceBuilderConfiguration config = world.getBiome(mut) - .getGenerationSettings() - .getSurfaceBuilderConfig(); + SurfaceBuilderConfiguration config = world.getBiome(mut).getGenerationSettings().getSurfaceBuilderConfig(); boolean isTop = mut.getY() == surfMax && state.getMaterial().isSolidBlocking(); BlockState top = isTop ? config.getTopMaterial() : config.getUnderMaterial(); BlocksHelper.setWithoutUpdate(world, mut, top); @@ -154,11 +147,10 @@ public abstract class NBTStructureFeature extends DefaultFeature { } } else { - if (stateSt.is(TagAPI.BLOCK_END_GROUND) && state.getMaterial().isSolidBlocking()) { + if (stateSt.is(TagAPI.END_GROUND) && state.getMaterial().isSolidBlocking()) { if (merge == TerrainMerge.SURFACE) { - SurfaceBuilderConfiguration config = world.getBiome(mut) - .getGenerationSettings() - .getSurfaceBuilderConfig(); + SurfaceBuilderConfiguration config = world.getBiome(mut).getGenerationSettings() + .getSurfaceBuilderConfig(); BlocksHelper.setWithoutUpdate(world, mut, config.getUnderMaterial()); } else { @@ -173,10 +165,10 @@ public abstract class NBTStructureFeature extends DefaultFeature { } } //BlocksHelper.fixBlocks(world, new BlockPos(x1, center.getY(), z1), new BlockPos(x2, center.getY() + offset.getY(), z2)); - + return true; } - + protected BoundingBox makeBox(BlockPos pos) { int sx = ((pos.getX() >> 4) << 4) - 16; int sz = ((pos.getZ() >> 4) << 4) - 16; @@ -184,34 +176,35 @@ public abstract class NBTStructureFeature extends DefaultFeature { int ez = sz + 47; return BoundingBox.fromCorners(new Vec3i(sx, 0, sz), new Vec3i(ex, 255, ez)); } - + protected static StructureTemplate readStructure(ResourceLocation resource) { String ns = resource.getNamespace(); String nm = resource.getPath(); - + try { - InputStream inputstream = MinecraftServer.class.getResourceAsStream("/data/" + ns + "/structures/" + nm + ".nbt"); + 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 static enum TerrainMerge { NONE, SURFACE, OBJECT; - + public static TerrainMerge getFromString(String type) { if (type.equals("surface")) { return SURFACE; diff --git a/src/main/java/ru/bclib/world/generator/BCLibEndBiomeSource.java b/src/main/java/ru/bclib/world/generator/BCLibEndBiomeSource.java deleted file mode 100644 index d5dd9827..00000000 --- a/src/main/java/ru/bclib/world/generator/BCLibEndBiomeSource.java +++ /dev/null @@ -1,155 +0,0 @@ -package ru.bclib.world.generator; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Registry; -import net.minecraft.resources.RegistryLookupCodec; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.Biome.BiomeCategory; -import net.minecraft.world.level.biome.BiomeSource; -import net.minecraft.world.level.biome.Biomes; -import net.minecraft.world.level.biome.TheEndBiomeSource; -import net.minecraft.world.level.levelgen.WorldgenRandom; -import net.minecraft.world.level.levelgen.synth.SimplexNoise; -import ru.bclib.BCLib; -import ru.bclib.api.BiomeAPI; -import ru.bclib.noise.OpenSimplexNoise; -import ru.bclib.world.biomes.BCLBiome; - -import java.awt.Point; -import java.util.List; -import java.util.function.Function; - -public class BCLibEndBiomeSource extends BiomeSource { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { - return instance.group(RegistryLookupCodec.create(Registry.BIOME_REGISTRY).forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.biomeRegistry; - }), Codec.LONG.fieldOf("seed").stable().forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.seed; - })).apply(instance, instance.stable(BCLibEndBiomeSource::new)); - }); - private static final OpenSimplexNoise SMALL_NOISE = new OpenSimplexNoise(8324); - private Function endLandFunction; - private final Registry biomeRegistry; - private final SimplexNoise noise; - private final Biome centerBiome; - private final Biome barrens; - private BiomeMap mapLand; - private BiomeMap mapVoid; - private final long seed; - private final Point pos; - - public BCLibEndBiomeSource(Registry biomeRegistry, long seed) { - super(getBiomes(biomeRegistry)); - - BiomeAPI.END_LAND_BIOME_PICKER.clearMutables(); - BiomeAPI.END_VOID_BIOME_PICKER.clearMutables(); - - this.possibleBiomes.forEach(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); - if (!BiomeAPI.hasBiome(key)) { - BCLBiome bclBiome = new BCLBiome(key, biome, 1, 1); - BiomeAPI.END_LAND_BIOME_PICKER.addBiomeMutable(bclBiome); - } - else { - BCLBiome bclBiome = BiomeAPI.getBiome(key); - if (bclBiome != BiomeAPI.EMPTY_BIOME && !bclBiome.hasParentBiome()) { - if (!BiomeAPI.END_LAND_BIOME_PICKER.containsImmutable(key) && !BiomeAPI.END_VOID_BIOME_PICKER.containsImmutable(key)) { - BiomeAPI.END_LAND_BIOME_PICKER.addBiomeMutable(bclBiome); - } - } - } - }); - - BiomeAPI.END_LAND_BIOME_PICKER.getBiomes().forEach(biome -> biome.updateActualBiomes(biomeRegistry)); - BiomeAPI.END_VOID_BIOME_PICKER.getBiomes().forEach(biome -> biome.updateActualBiomes(biomeRegistry)); - - BiomeAPI.END_LAND_BIOME_PICKER.rebuild(); - BiomeAPI.END_VOID_BIOME_PICKER.rebuild(); - - this.mapLand = new BiomeMap(seed, GeneratorOptions.getBiomeSizeEndLand(), BiomeAPI.END_LAND_BIOME_PICKER); - this.mapVoid = new BiomeMap(seed, GeneratorOptions.getBiomeSizeEndVoid(), BiomeAPI.END_VOID_BIOME_PICKER); - this.centerBiome = biomeRegistry.getOrThrow(Biomes.THE_END); - this.barrens = biomeRegistry.getOrThrow(Biomes.END_BARRENS); - this.biomeRegistry = biomeRegistry; - this.seed = seed; - - WorldgenRandom chunkRandom = new WorldgenRandom(seed); - chunkRandom.consumeCount(17292); - this.noise = new SimplexNoise(chunkRandom); - - this.endLandFunction = GeneratorOptions.getEndLandFunction(); - this.pos = new Point(); - } - - private static List getBiomes(Registry biomeRegistry) { - return biomeRegistry.stream().filter(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); - BCLBiome bclBiome = BiomeAPI.getBiome(key); - if (bclBiome != BiomeAPI.EMPTY_BIOME) { - if (bclBiome.hasParentBiome()) { - bclBiome = bclBiome.getParentBiome(); - } - key = bclBiome.getID(); - } - return BiomeAPI.END_LAND_BIOME_PICKER.containsImmutable(key) || BiomeAPI.END_VOID_BIOME_PICKER.containsImmutable(key) || (biome.getBiomeCategory() == BiomeCategory.THEEND && BiomeAPI.isDatapackBiome(key)); - }).toList(); - } - - @Override - public Biome getNoiseBiome(int biomeX, int biomeY, int biomeZ) { - long i = (long) biomeX * (long) biomeX; - long j = (long) biomeZ * (long) biomeZ; - long check = GeneratorOptions.isFarEndBiomes() ? 65536L : 625L; - long dist = i + j; - - if ((biomeX & 63) == 0 && (biomeZ & 63) == 0) { - mapLand.clearCache(); - mapVoid.clearCache(); - } - - if (endLandFunction == null) { - if (dist <= check) return centerBiome; - float height = TheEndBiomeSource.getHeightValue( - noise, - (biomeX >> 1) + 1, - (biomeZ >> 1) + 1 - ) + (float) SMALL_NOISE.eval(biomeX, biomeZ) * 5; - - if (height > -20F && height < -5F) { - return barrens; - } - - if (height < -10F) { - return mapVoid.getBiome(biomeX << 2, biomeZ << 2).getActualBiome(); - } - else { - return mapLand.getBiome(biomeX << 2, biomeZ << 2).getActualBiome(); - } - } - else { - pos.setLocation(biomeX, biomeZ); - if (endLandFunction.apply(pos)) { - return dist <= check ? centerBiome : mapLand.getBiome(biomeX << 2, biomeZ << 2).getActualBiome(); - } - else { - return dist <= check ? barrens : mapVoid.getBiome(biomeX << 2, biomeZ << 2).getActualBiome(); - } - } - } - - @Override - public BiomeSource withSeed(long seed) { - return new BCLibEndBiomeSource(biomeRegistry, seed); - } - - @Override - protected Codec codec() { - return CODEC; - } - - public static void register() { - Registry.register(Registry.BIOME_SOURCE, BCLib.makeID("end_biome_source"), CODEC); - } -} diff --git a/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java b/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java deleted file mode 100644 index 9fdbfbe5..00000000 --- a/src/main/java/ru/bclib/world/generator/BCLibNetherBiomeSource.java +++ /dev/null @@ -1,99 +0,0 @@ -package ru.bclib.world.generator; - -import com.mojang.serialization.Codec; -import com.mojang.serialization.codecs.RecordCodecBuilder; -import net.minecraft.core.Registry; -import net.minecraft.resources.RegistryLookupCodec; -import net.minecraft.resources.ResourceLocation; -import net.minecraft.world.level.biome.Biome; -import net.minecraft.world.level.biome.Biome.BiomeCategory; -import net.minecraft.world.level.biome.BiomeSource; -import ru.bclib.BCLib; -import ru.bclib.api.BiomeAPI; -import ru.bclib.world.biomes.BCLBiome; - -import java.util.LinkedList; -import java.util.List; -import java.util.function.Consumer; - -public class BCLibNetherBiomeSource extends BiomeSource { - public static final Codec CODEC = RecordCodecBuilder.create((instance) -> { - return instance.group(RegistryLookupCodec.create(Registry.BIOME_REGISTRY).forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.biomeRegistry; - }), Codec.LONG.fieldOf("seed").stable().forGetter((theEndBiomeSource) -> { - return theEndBiomeSource.seed; - })).apply(instance, instance.stable(BCLibNetherBiomeSource::new)); - }); - private final Registry biomeRegistry; - private BiomeMap biomeMap; - private final long seed; - - public static final List> onInit = new LinkedList<>(); - - public BCLibNetherBiomeSource(Registry biomeRegistry, long seed) { - super(getBiomes(biomeRegistry)); - - BiomeAPI.NETHER_BIOME_PICKER.clearMutables(); - - this.possibleBiomes.forEach(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); - if (!BiomeAPI.hasBiome(key)) { - BCLBiome bclBiome = new BCLBiome(key, biome, 1, 1); - BiomeAPI.NETHER_BIOME_PICKER.addBiomeMutable(bclBiome); - } - else { - BCLBiome bclBiome = BiomeAPI.getBiome(key); - if (bclBiome != BiomeAPI.EMPTY_BIOME && !bclBiome.hasParentBiome()) { - if (!BiomeAPI.NETHER_BIOME_PICKER.containsImmutable(key)) { - BiomeAPI.NETHER_BIOME_PICKER.addBiomeMutable(bclBiome); - } - } - } - }); - - BiomeAPI.NETHER_BIOME_PICKER.getBiomes().forEach(biome -> biome.updateActualBiomes(biomeRegistry)); - BiomeAPI.NETHER_BIOME_PICKER.rebuild(); - - this.biomeMap = new BiomeMap(seed, GeneratorOptions.getBiomeSizeNether(), BiomeAPI.NETHER_BIOME_PICKER); - this.biomeRegistry = biomeRegistry; - this.seed = seed; - - onInit.forEach(consumer->consumer.accept(this)); - } - - private static List getBiomes(Registry biomeRegistry) { - return biomeRegistry.stream().filter(biome -> { - ResourceLocation key = biomeRegistry.getKey(biome); - BCLBiome bclBiome = BiomeAPI.getBiome(key); - if (bclBiome != BiomeAPI.EMPTY_BIOME) { - if (bclBiome.hasParentBiome()) { - bclBiome = bclBiome.getParentBiome(); - } - key = bclBiome.getID(); - } - return BiomeAPI.NETHER_BIOME_PICKER.containsImmutable(key) || (biome.getBiomeCategory() == BiomeCategory.NETHER && BiomeAPI.isDatapackBiome(key)); - }).toList(); - } - - @Override - public Biome getNoiseBiome(int biomeX, int biomeY, int biomeZ) { - if ((biomeX & 63) == 0 && (biomeZ & 63) == 0) { - biomeMap.clearCache(); - } - return biomeMap.getBiome(biomeX << 2, biomeZ << 2).getActualBiome(); - } - - @Override - public BiomeSource withSeed(long seed) { - return new BCLibNetherBiomeSource(biomeRegistry, seed); - } - - @Override - protected Codec codec() { - return CODEC; - } - - public static void register() { - Registry.register(Registry.BIOME_SOURCE, BCLib.makeID("nether_biome_source"), CODEC); - } -} diff --git a/src/main/java/ru/bclib/world/generator/BiomeChunk.java b/src/main/java/ru/bclib/world/generator/BiomeChunk.java index d424462e..3fdb6358 100644 --- a/src/main/java/ru/bclib/world/generator/BiomeChunk.java +++ b/src/main/java/ru/bclib/world/generator/BiomeChunk.java @@ -1,54 +1,35 @@ package ru.bclib.world.generator; -import ru.bclib.world.biomes.BCLBiome; - import java.util.Random; +import ru.bclib.world.biomes.BCLBiome; + public class BiomeChunk { - private static final int BIT_OFFSET = 4; - protected static final int WIDTH = 1 << BIT_OFFSET; + protected static final int WIDTH = 16; 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 BCLBiome[] biomes; - + + private final BCLBiome[][] biomes; + public BiomeChunk(BiomeMap map, Random random, BiomePicker picker) { - BCLBiome[] PreBio = new BCLBiome[SM_CAPACITY]; - biomes = new BCLBiome[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); - } - } + BCLBiome[][] PreBio = new BCLBiome[SM_WIDTH][SM_WIDTH]; + biomes = new BCLBiome[WIDTH][WIDTH]; + + for (int x = 0; x < SM_WIDTH; x++) + for (int z = 0; z < SM_WIDTH; z++) + PreBio[x][z] = picker.getBiome(random); + + for (int x = 0; x < WIDTH; x++) + for (int z = 0; z < WIDTH; z++) + biomes[x][z] = PreBio[offsetXZ(x, random)][offsetXZ(z, random)].getSubBiome(random); } - + public BCLBiome getBiome(int x, int z) { - return biomes[getIndex(x & MASK_WIDTH, z & MASK_WIDTH)]; + return biomes[x & MASK_WIDTH][z & MASK_WIDTH]; } - + private int offsetXZ(int x, Random 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/ru/bclib/world/generator/BiomeMap.java b/src/main/java/ru/bclib/world/generator/BiomeMap.java index 9de76325..088fda63 100644 --- a/src/main/java/ru/bclib/world/generator/BiomeMap.java +++ b/src/main/java/ru/bclib/world/generator/BiomeMap.java @@ -1,14 +1,15 @@ package ru.bclib.world.generator; +import java.util.Map; + import com.google.common.collect.Maps; + import net.minecraft.world.level.ChunkPos; import net.minecraft.world.level.levelgen.WorldgenRandom; import ru.bclib.noise.OpenSimplexNoise; import ru.bclib.util.MHelper; import ru.bclib.world.biomes.BCLBiome; -import java.util.Map; - public class BiomeMap { private static final WorldgenRandom RANDOM = new WorldgenRandom(); diff --git a/src/main/java/ru/bclib/world/generator/BiomePicker.java b/src/main/java/ru/bclib/world/generator/BiomePicker.java index 99eae8df..57eb36dd 100644 --- a/src/main/java/ru/bclib/world/generator/BiomePicker.java +++ b/src/main/java/ru/bclib/world/generator/BiomePicker.java @@ -1,35 +1,30 @@ package ru.bclib.world.generator; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import net.minecraft.resources.ResourceLocation; -import ru.bclib.util.WeighTree; -import ru.bclib.util.WeightedList; -import ru.bclib.world.biomes.BCLBiome; - import java.util.List; import java.util.Random; import java.util.Set; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + +import net.minecraft.resources.ResourceLocation; +import ru.bclib.util.WeighTree; +import ru.bclib.util.WeightedList; +import ru.bclib.world.biomes.BCLBiome; + public class BiomePicker { private final Set immutableIDs = Sets.newHashSet(); private final List biomes = Lists.newArrayList(); - private WeighTree tree; private int biomeCount = 0; + private WeighTree tree; public void addBiome(BCLBiome biome) { - if (immutableIDs.contains(biome.getID())) { - return; - } immutableIDs.add(biome.getID()); biomes.add(biome); - biomeCount++; + biomeCount ++; } public void addBiomeMutable(BCLBiome biome) { - if (immutableIDs.contains(biome.getID())) { - return; - } biomes.add(biome); } @@ -65,10 +60,10 @@ public class BiomePicker { if (biomes.isEmpty()) { return; } - WeightedList list = new WeightedList<>(); - biomes.forEach(biome -> { + WeightedList list = new WeightedList(); + biomes.forEach((biome) -> { list.add(biome, biome.getGenChance()); }); - tree = new WeighTree<>(list); + tree = new WeighTree(list); } } diff --git a/src/main/java/ru/bclib/world/generator/BiomeType.java b/src/main/java/ru/bclib/world/generator/BiomeType.java index 7556894d..6e40eb2c 100644 --- a/src/main/java/ru/bclib/world/generator/BiomeType.java +++ b/src/main/java/ru/bclib/world/generator/BiomeType.java @@ -1,5 +1,6 @@ package ru.bclib.world.generator; public enum BiomeType { - LAND, VOID; + LAND, + VOID; } diff --git a/src/main/java/ru/bclib/world/generator/GeneratorOptions.java b/src/main/java/ru/bclib/world/generator/GeneratorOptions.java deleted file mode 100644 index 7137ad2b..00000000 --- a/src/main/java/ru/bclib/world/generator/GeneratorOptions.java +++ /dev/null @@ -1,49 +0,0 @@ -package ru.bclib.world.generator; - -import net.minecraft.util.Mth; -import ru.bclib.config.Configs; - -import java.awt.Point; -import java.util.function.Function; - -public class GeneratorOptions { - private static int biomeSizeNether; - private static int biomeSizeEndLand; - private static int biomeSizeEndVoid; - private static Function endLandFunction; - private static boolean farEndBiomes = true; - - public static void init() { - biomeSizeNether = Configs.GENERATOR_CONFIG.getInt("nether.biomeMap", "biomeSize", 256); - biomeSizeEndLand = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeLand", 256); - biomeSizeEndVoid = Configs.GENERATOR_CONFIG.getInt("end.biomeMap", "biomeSizeVoid", 256); - } - - public static int getBiomeSizeNether() { - return Mth.clamp(biomeSizeNether, 1, 8192); - } - - public static int getBiomeSizeEndLand() { - return Mth.clamp(biomeSizeEndLand, 1, 8192); - } - - public static int getBiomeSizeEndVoid() { - return Mth.clamp(biomeSizeEndVoid, 1, 8192); - } - - public static void setEndLandFunction(Function endLandFunction) { - GeneratorOptions.endLandFunction = endLandFunction; - } - - public static Function getEndLandFunction() { - return endLandFunction; - } - - public static boolean isFarEndBiomes() { - return farEndBiomes; - } - - public static void setFarEndBiomes(boolean farEndBiomes) { - GeneratorOptions.farEndBiomes = farEndBiomes; - } -} diff --git a/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java b/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java index 381bd324..3d12057a 100644 --- a/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java +++ b/src/main/java/ru/bclib/world/processors/DestructionStructureProcessor.java @@ -18,16 +18,12 @@ public class DestructionStructureProcessor extends StructureProcessor { @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) { + 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/ru/bclib/world/processors/TerrainStructureProcessor.java b/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java index 1f758427..dceb0ee1 100644 --- a/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java +++ b/src/main/java/ru/bclib/world/processors/TerrainStructureProcessor.java @@ -14,15 +14,12 @@ public class TerrainStructureProcessor extends StructureProcessor { public StructureBlockInfo processBlock(LevelReader worldView, BlockPos pos, BlockPos blockPos, StructureBlockInfo structureBlockInfo, StructureBlockInfo structureBlockInfo2, StructurePlaceSettings structurePlacementData) { BlockPos bpos = structureBlockInfo2.pos; if (structureBlockInfo2.state.is(Blocks.END_STONE) && worldView.isEmptyBlock(bpos.above())) { - BlockState top = worldView.getBiome(structureBlockInfo2.pos) - .getGenerationSettings() - .getSurfaceBuilderConfig() - .getTopMaterial(); + BlockState top = worldView.getBiome(structureBlockInfo2.pos).getGenerationSettings().getSurfaceBuilderConfig().getTopMaterial(); return new StructureBlockInfo(bpos, top, structureBlockInfo2.nbt); } return structureBlockInfo2; } - + @Override protected StructureProcessorType getType() { return StructureProcessorType.RULE; diff --git a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java index 4497bfc7..581f0b60 100644 --- a/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java +++ b/src/main/java/ru/bclib/world/structures/BCLStructureFeature.java @@ -1,7 +1,8 @@ package ru.bclib.world.structures; +import java.util.Random; + import net.fabricmc.fabric.api.structure.v1.FabricStructureBuilder; -import net.fabricmc.fabric.mixin.structure.FlatChunkGeneratorConfigAccessor; import net.minecraft.data.BuiltinRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.level.levelgen.GenerationStep; @@ -9,8 +10,6 @@ import net.minecraft.world.level.levelgen.feature.ConfiguredStructureFeature; import net.minecraft.world.level.levelgen.feature.StructureFeature; import net.minecraft.world.level.levelgen.feature.configurations.NoneFeatureConfiguration; -import java.util.Random; - public class BCLStructureFeature { private static final Random RANDOM = new Random(354); private final StructureFeature structure; @@ -20,22 +19,23 @@ public class BCLStructureFeature { public BCLStructureFeature(ResourceLocation id, StructureFeature structure, GenerationStep.Decoration step, int spacing, int separation) { this.featureStep = step; this.structure = FabricStructureBuilder.create(id, structure) - .step(step) - .defaultConfig(spacing, separation, RANDOM.nextInt(8192)) - .register(); + .step(step) + .defaultConfig(spacing, separation, RANDOM.nextInt(8192)) + .register(); + this.featureConfigured = this.structure.configured(NoneFeatureConfiguration.NONE); + BuiltinRegistries.register(BuiltinRegistries.CONFIGURED_STRUCTURE_FEATURE, id, this.featureConfigured); - FlatChunkGeneratorConfigAccessor.getStructureToFeatures().put(this.structure, this.featureConfigured); } - + public StructureFeature getStructure() { return structure; } - + public ConfiguredStructureFeature getFeatureConfigured() { return featureConfigured; } - + public GenerationStep.Decoration getFeatureStep() { return featureStep; } diff --git a/src/main/java/ru/bclib/world/structures/StructureWorld.java b/src/main/java/ru/bclib/world/structures/StructureWorld.java index 48c2ea30..8f3c80d5 100644 --- a/src/main/java/ru/bclib/world/structures/StructureWorld.java +++ b/src/main/java/ru/bclib/world/structures/StructureWorld.java @@ -1,6 +1,9 @@ package ru.bclib.world.structures; +import java.util.Map; + import com.google.common.collect.Maps; + import net.minecraft.core.BlockPos; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.ListTag; @@ -12,8 +15,6 @@ import net.minecraft.world.level.block.state.BlockState; import net.minecraft.world.level.chunk.ChunkAccess; import net.minecraft.world.level.levelgen.structure.BoundingBox; -import java.util.Map; - public class StructureWorld { private Map parts = Maps.newHashMap(); private ChunkPos lastPos; @@ -152,7 +153,7 @@ public class StructureWorld { blocks.forEach((pos, state) -> { int stateID = states.getOrDefault(states, -1); if (stateID < 0) { - stateID = id[0]++; + stateID = id[0] ++; states.put(state, stateID); stateMap.add(NbtUtils.writeBlockState(state)); } diff --git a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java index 434b1a39..14e6bba4 100644 --- a/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java +++ b/src/main/java/ru/bclib/world/surface/DoubleBlockSurfaceBuilder.java @@ -1,5 +1,7 @@ package ru.bclib.world.surface; +import java.util.Random; + import net.minecraft.core.Registry; import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.block.Block; @@ -12,8 +14,6 @@ import net.minecraft.world.level.levelgen.surfacebuilders.SurfaceBuilderBaseConf import ru.bclib.noise.OpenSimplexNoise; import ru.bclib.util.MHelper; -import java.util.Random; - public class DoubleBlockSurfaceBuilder extends SurfaceBuilder { private static final OpenSimplexNoise NOISE = new OpenSimplexNoise(4141); private SurfaceBuilderBaseConfiguration config1; @@ -43,24 +43,10 @@ public class DoubleBlockSurfaceBuilder extends SurfaceBuilder 0 ? config1 : config2 - ); + SurfaceBuilder.DEFAULT.apply(random, chunkAccess, biome, x, z, height, noise, defaultBlock, defaultFluid, l, m, seed, noise > 0 ? config1 : config2); } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/icon.png b/src/main/resources/assets/bclib/icon.png index 368a2a60..95281739 100644 Binary files a/src/main/resources/assets/bclib/icon.png and b/src/main/resources/assets/bclib/icon.png differ diff --git a/src/main/resources/assets/bclib/iconpixelated.png b/src/main/resources/assets/bclib/iconpixelated.png deleted file mode 100644 index 056ed30a..00000000 Binary files a/src/main/resources/assets/bclib/iconpixelated.png and /dev/null differ diff --git a/src/main/resources/assets/bclib/lang/de_de.json b/src/main/resources/assets/bclib/lang/de_de.json deleted file mode 100644 index 7fcb0c99..00000000 --- a/src/main/resources/assets/bclib/lang/de_de.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "message.bclib.anvil_damage": "§cSchaden", - "bclib.datafixer.backupWarning.title": "Der Wächter hat eine inkompatible Welt entdeckt", - "bclib.datafixer.backupWarning.message": "Der Wächter hat festgestellt, dass einige Mod Änderungen an der Welt durchführen müssen.\n\nDiese Änderungen können automatische angewendet werden. Wenn Du fortfährst ohne die Änderungen anzuwenden, kann dies zu Fehlern oder Abstürzen führen. Bevor du fortfährst sollte auf jedenfall ein Backup angelegt werden.", - "bclib.datafixer.backupWarning.backup": "Backup erstellen bevor die Reperaturen angewendet werden", - "bclib.datafixer.backupWarning.nofixes": "Weiter ohne Reperaturen", - "bclib.datafixer.backupWarning.fix": "Reperaturen Anwenden", - "title.bclib.bclibmissmatch": "Versionsunterschied", - "message.bclib.bclibmissmatch": "Die Version von BCLib auf dem Server und dem Client sind unterschiedlich. Dies kann Probleme verursachen.\n\nSoll die passende Version von BCLib vom Server auf diese Maschine kopiert werden? \n\nDazu wird die aktuell installierte Version von BCLib im Mods-Verzeichnis in einen Unterordner verschoben und die Version vom Server installiert.", - "title.bclib.syncfiles": "Inkonsistente Daten", - "message.bclib.syncfiles": "Einige Daten (Konfigurationen, Mods, ...) sind unterschiedlich.\nSollen die unten ausgewählten Inhalte vom Server auf diese Maschine kopieren?", - "message.bclib.syncfiles.mods": "Mods synchronisieren", - "message.bclib.syncfiles.configs": "Einstellungen synchronisieren", - "message.bclib.syncfiles.folders": "Dateien und Ordner synchronisieren", - "message.bclib.syncfiles.delete": "Unnötige löschen", - "title.bclib.confirmrestart": "Neustart erforderlich", - "message.bclib.confirmrestart": "Die angeforderten Inhalte wurden erfolgreich übertragen. Minecraft muss nun neu gestartet werden.", - "title.link.bclib.discord": "Discord", - "title.bclib.modmenu.main": "BCLib Einstellungen", - "title.bclib.progress": "Fortschritt", - "title.bclib.filesync.progress": "Datenübertragung", - "message.bclib.filesync.progress": "Snychronisiere Dateien und Verzeichnise vom Server", - "message.bclib.filesync.progress.stage.empty": "", - - "title.config.bclib.client.auto_sync.enabled": "Auto-Sync Aktivieren", - "title.config.bclib.client.auto_sync.acceptConfigs": "Konfiguration von Server annehmen", - "title.config.bclib.client.auto_sync.acceptFiles": "Dateien von Server annehmen", - "title.config.bclib.client.auto_sync.acceptMods": "Mods von Server annehmen", - "title.config.bclib.client.auto_sync.displayModInfo": "Warnung anzeigen wen Mods auf Server/Client unterschiedlich", - "title.config.bclib.client.auto_sync.debugHashes": "Erweiterete Logausgabe für Auto-Sync", - - "title.bclib.syncfiles.modInfo": "Mod Info", - "title.bclib.syncfiles.modlist": "Mod Information", - "message.bclib.syncfiles.modlist": "Im Folgenden wird der Status deiner installierten Mods angezeigt.\n\nAlle Mods, die lokal nicht vorhanden sind oder eine andere Version auf dem Server haben, werden synchronisiert.", - "title.bclib.modmissmatch": "Mod-Konflikt", - "message.bclib.modmissmatch": "Einige Mods auf diesem Rechner stimmen nicht mit der Version auf dem Server überein.\n\nNicht übereinstimmende Mods können zu merkwürdigem Spielverhalten oder Abstürzen führen. Bitte stellen Sie sicher, dass Sie die gleichen Mods wie auf dem Server verwenden.", - - "message.bclib.datafixer.progress.waitbackup": "Ich warte auf das Ende der Sicherung. Dies kann eine Weile dauern!", - "message.bclib.datafixer.progress.reading": "Lese Daten", - "message.bclib.datafixer.progress.players": "Repariere Spieler", - "message.bclib.datafixer.progress.level": "Patches auf level.dat anwenden", - "message.bclib.datafixer.progress.worlddata": "Benutzerdefinierte Weltdaten patchen", - "message.bclib.datafixer.progress.regions": "Alle Regionen reparieren", - "message.bclib.datafixer.progress.saving": "Patch-Status speichern", - "title.bclib.datafixer.progress": "Welt in Ordnung bringen", - "message.bclib.datafixer.progress": "Anwenden aller Änderungen", - "title.bclib.datafixer.error": "Fehler beim Reparieren der Welt", - "message.bclib.datafixer.error": "Es gab Fehler beim Reparieren der Welt. Das bedeutet, dass dieser Level wahrscheinlich in einem inkonsistenten Zustand ist und Sie ihn nicht spielen sollten. Bitte stellen Sie Ihr Backup wieder her und beheben Sie die unten aufgeführten Fehler, bevor Sie es erneut versuchen.", - "title.bclib.datafixer.error.continue": "Continue and Mark as Fixed" -} \ No newline at end of file diff --git a/src/main/resources/assets/bclib/lang/en_us.json b/src/main/resources/assets/bclib/lang/en_us.json deleted file mode 100644 index 68aa85bc..00000000 --- a/src/main/resources/assets/bclib/lang/en_us.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "message.bclib.anvil_damage": "§cDamage", - "bclib.datafixer.backupWarning.title": "Guardian detected an incompatible World", - "bclib.datafixer.backupWarning.message": "The Guardian detected, that the internals some installed Mods did change since this world was last played.\n\nWe can automatically change the world for you. If you continue without applying the changes the world may not load correct. Before you continue, you should create a Backup.", - "bclib.datafixer.backupWarning.backup": "Create Backup before applying Fixes", - "bclib.datafixer.backupWarning.nofixes": "Continue Without Fixes", - "bclib.datafixer.backupWarning.fix": "Apply Fixes", - "title.bclib.bclibmissmatch": "Version Mismatch", - "message.bclib.bclibmissmatch": "The Version of BCLib on the server and this client do not match. This will cause problems when playing.\n\nDo you want to automatically download the BCLib-Version from the server? \n\nBCLib will move the old version into a subdirectory of your Mods-Folder and before installing the new one.", - "title.bclib.syncfiles": "Mismatching Data", - "message.bclib.syncfiles": "Some Content on the Server does not match the versions on the client.\nDo you want to replace the selected content with the data from the server?", - "message.bclib.syncfiles.mods": "Synchronize Mods", - "message.bclib.syncfiles.configs": "Synchronize Configs", - "message.bclib.syncfiles.folders": "Synchronize Folders and Files", - "message.bclib.syncfiles.delete": "Delete unneeded", - "title.bclib.confirmrestart": "Restart Required", - "message.bclib.confirmrestart": "The requested content was synchronized. You need to restart Minecraft now.", - "title.link.bclib.discord": "Discord", - "title.bclib.modmenu.main": "BCLib Settings", - "title.bclib.progress": "Progress", - "title.bclib.filesync.progress": "File Transfer", - "message.bclib.filesync.progress": "Syncing File-Content with Server", - "message.bclib.filesync.progress.stage.empty": "", - - "title.config.bclib.client.auto_sync.enabled": "Enable Auto-Sync", - "title.config.bclib.client.auto_sync.acceptConfigs": "Accept incoming Config Files", - "title.config.bclib.client.auto_sync.acceptFiles": "Accept incoming Files", - "title.config.bclib.client.auto_sync.acceptMods": "Accept incoming Mods", - "title.config.bclib.client.auto_sync.displayModInfo": "Display warning when Serverside Mods differ from Client", - "title.config.bclib.client.auto_sync.debugHashes": "Print Auto-Sync Debug-Hashes to Log", - - "title.bclib.syncfiles.modInfo": "Mod Info", - "title.bclib.syncfiles.modlist": "Mod Information", - "message.bclib.syncfiles.modlist": "The following shows the state of your installed installed Mods.\n\nAll Mods that do not exist locally, or have a different version on the Server will be synchronized.", - "title.bclib.modmissmatch": "Mod Version Conflict", - "message.bclib.modmissmatch": "Some Mods on this client do not match the version of Mods on the Server.\n\nMismatching Mods can result in odd game behavior or crashes. Please make sue that you use the same mods as the server.", - - "message.bclib.datafixer.progress.waitbackup": "Waiting for Backup to finish. This may take a while!", - "message.bclib.datafixer.progress.reading": "Reading Data", - "message.bclib.datafixer.progress.players": "Fixing Players", - "message.bclib.datafixer.progress.level": "Applying Patches to level.dat", - "message.bclib.datafixer.progress.worlddata": "Patching Custom World-Data", - "message.bclib.datafixer.progress.regions": "Repairing all Regions", - "message.bclib.datafixer.progress.saving": "Saving Patch State", - "title.bclib.datafixer.progress": "Fixing World", - "message.bclib.datafixer.progress": "Applying all Patches to your World.", - "title.bclib.datafixer.error": "Errors while fixing World", - "message.bclib.datafixer.error": "There were errors while repairing the world. This means that this level is probably in an inconsistent state and you should not play it. Please restore your backup and fix the errors below before trying again.", - "title.bclib.datafixer.error.continue": "Fortfahren und als behoben markieren" -} \ No newline at end of file diff --git a/src/main/resources/assets/bclib/lang/ru_ru.json b/src/main/resources/assets/bclib/lang/ru_ru.json deleted file mode 100644 index 092f7299..00000000 --- a/src/main/resources/assets/bclib/lang/ru_ru.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "message.bclib.anvil_damage": "§cПовреждение" -} \ No newline at end of file diff --git a/src/main/resources/assets/bclib/materialmaps/block/alpha_emission.json b/src/main/resources/assets/bclib/materialmaps/block/alpha_emission.json deleted file mode 100644 index ae85105c..00000000 --- a/src/main/resources/assets/bclib/materialmaps/block/alpha_emission.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "defaultMaterial": "bclib:alpha_emission" -} diff --git a/src/main/resources/assets/bclib/materials/alpha_emission.json b/src/main/resources/assets/bclib/materials/alpha_emission.json deleted file mode 100644 index 914848b1..00000000 --- a/src/main/resources/assets/bclib/materials/alpha_emission.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "layers": [ - { - "vertexSource": "canvas:shaders/material/default.vert", - "fragmentSource": "bclib:shaders/material/alpha_emission.frag" - } - ] -} diff --git a/src/main/resources/assets/bclib/models/block/chest_item.json b/src/main/resources/assets/bclib/models/block/chest_item.json index 4f96625e..c0a3265f 100644 --- a/src/main/resources/assets/bclib/models/block/chest_item.json +++ b/src/main/resources/assets/bclib/models/block/chest_item.json @@ -3,188 +3,188 @@ "parent": "block/block", "elements": [ { - "__comment": "Box1", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 3.5, - 4.75, - 7, - 8.25 - ] + "__comment": "Box1", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 3.5, + 4.75, + 7, + 8.25 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 3.5, + 10.75, + 7, + 8.25 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 10.5, + 10.75, + 14, + 8.25 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 0, + 10.75, + 3.5, + 8.25 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 7, + 10.75, + 10.5, + 8.25 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 3.5, - 10.75, - 7, - 8.25 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 10.5, - 10.75, - 14, - 8.25 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 0, - 10.75, - 3.5, - 8.25 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 7, - 10.75, - 10.5, - 8.25 - ] - } - }, - "from": [ - 1, - 0, - 1 - ], - "to": [ - 15, - 10, - 15 - ] + "from": [ + 1, + 0, + 1 + ], + "to": [ + 15, + 10, + 15 + ] }, { - "__comment": "Box1", - "faces": { - "east": { - "texture": "#texture", - "uv": [ - 3.5, - 4.75, - 7, - 3.75 - ] + "__comment": "Box1", + "faces": { + "east": { + "texture": "#texture", + "uv": [ + 3.5, + 4.75, + 7, + 3.75 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 10.5, + 4.75, + 14, + 3.75 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 0, + 4.75, + 3.5, + 3.75 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 7, + 0, + 10.5, + 3.5 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 7, + 4.75, + 10.5, + 3.75 + ] + } }, - "north": { - "texture": "#texture", - "uv": [ - 10.5, - 4.75, - 14, - 3.75 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 0, - 4.75, - 3.5, - 3.75 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 7, - 0, - 10.5, - 3.5 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 7, - 4.75, - 10.5, - 3.75 - ] - } - }, - "from": [ - 1, - 10, - 1 - ], - "to": [ - 15, - 14, - 15 - ] + "from": [ + 1, + 10, + 1 + ], + "to": [ + 15, + 14, + 15 + ] }, { - "__comment": "Box1", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 0.25, - 0, - 0.75, - 0.25 - ] + "__comment": "Box1", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 0.25, + 0, + 0.75, + 0.25 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 0, + 1.25, + 0.25, + 0.25 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 0.5, + 1.25, + 1, + 0.25 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 0.75, + 0, + 1.25, + 0.25 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 0, + 1.25, + 0.25, + 0.25 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 0, - 1.25, - 0.25, - 0.25 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 0.5, - 1.25, - 1, - 0.25 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 0.75, - 0, - 1.25, - 0.25 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 0, - 1.25, - 0.25, - 0.25 - ] - } - }, - "from": [ - 7, - 7, - 0 - ], - "to": [ - 9, - 11, - 1 - ] + "from": [ + 7, + 7, + 0 + ], + "to": [ + 9, + 11, + 1 + ] } ] } diff --git a/src/main/resources/assets/bclib/models/block/ladder.json b/src/main/resources/assets/bclib/models/block/ladder.json index 710f39cd..65ea537b 100644 --- a/src/main/resources/assets/bclib/models/block/ladder.json +++ b/src/main/resources/assets/bclib/models/block/ladder.json @@ -2,436 +2,436 @@ "__comment": "Designed by Paulevs with Cubik Studio - https://cubik.studio", "elements": [ { - "__comment": "Box1", - "faces": { - "down": { - "cullface": "down", - "rotation": 180, - "texture": "#texture", - "uv": [ - 2, - 15, - 4, - 16 - ] + "__comment": "Box1", + "faces": { + "down": { + "cullface": "down", + "rotation": 180, + "texture": "#texture", + "uv": [ + 2, + 15, + 4, + 16 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 2, + 0, + 3, + 16 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 2, + 0, + 4, + 16 + ] + }, + "south": { + "cullface": "north", + "texture": "#texture", + "uv": [ + 2, + 0, + 4, + 16 + ] + }, + "up": { + "cullface": "up", + "rotation": 180, + "texture": "#texture", + "uv": [ + 2, + 0, + 4, + 1 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 3, + 0, + 4, + 16 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 2, - 0, - 3, - 16 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 2, - 0, - 4, - 16 - ] - }, - "south": { - "cullface": "north", - "texture": "#texture", - "uv": [ - 2, - 0, - 4, - 16 - ] - }, - "up": { - "cullface": "up", - "rotation": 180, - "texture": "#texture", - "uv": [ - 2, - 0, - 4, - 1 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 3, - 0, - 4, - 16 - ] - } - }, - "from": [ - 12, - 0, - 15 - ], - "to": [ - 14, - 16, - 16 - ] + "from": [ + 12, + 0, + 15 + ], + "to": [ + 14, + 16, + 16 + ] }, { - "__comment": "Box1", - "faces": { - "down": { - "cullface": "down", - "rotation": 180, - "texture": "#texture", - "uv": [ - 12, - 15, - 14, - 16 - ] + "__comment": "Box1", + "faces": { + "down": { + "cullface": "down", + "rotation": 180, + "texture": "#texture", + "uv": [ + 12, + 15, + 14, + 16 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 2, + 0, + 3, + 16 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 12, + 0, + 14, + 16 + ] + }, + "south": { + "cullface": "north", + "texture": "#texture", + "uv": [ + 12, + 0, + 14, + 16 + ] + }, + "up": { + "cullface": "up", + "rotation": 180, + "texture": "#texture", + "uv": [ + 12, + 0, + 14, + 1 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 3, + 0, + 4, + 16 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 2, - 0, - 3, - 16 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 12, - 0, - 14, - 16 - ] - }, - "south": { - "cullface": "north", - "texture": "#texture", - "uv": [ - 12, - 0, - 14, - 16 - ] - }, - "up": { - "cullface": "up", - "rotation": 180, - "texture": "#texture", - "uv": [ - 12, - 0, - 14, - 1 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 3, - 0, - 4, - 16 - ] - } - }, - "from": [ - 2, - 0, - 15 - ], - "to": [ - 4, - 16, - 16 - ] + "from": [ + 2, + 0, + 15 + ], + "to": [ + 4, + 16, + 16 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 14, - 15, - 15 - ] + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 14, + 15, + 15 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 1, + 13, + 2, + 15 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 13, + 15, + 15 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 13, + 15, + 15 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 13, + 15, + 14 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 13, + 15, + 15 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 13, - 2, - 15 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 13, - 15, - 15 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 13, - 15, - 15 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 13, - 15, - 14 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 13, - 15, - 15 - ] - } - }, - "from": [ - 1, - 1, - 14.5 - ], - "to": [ - 15, - 3, - 15.5 - ] + "from": [ + 1, + 1, + 14.5 + ], + "to": [ + 15, + 3, + 15.5 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 10, - 15, - 11 - ] + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 10, + 15, + 11 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 1, + 9, + 2, + 11 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 9, + 15, + 11 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 9, + 15, + 11 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 9, + 15, + 10 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 9, + 15, + 11 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 9, - 2, - 11 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 9, - 15, - 11 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 9, - 15, - 11 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 9, - 15, - 10 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 9, - 15, - 11 - ] - } - }, - "from": [ - 1, - 5, - 14.5 - ], - "to": [ - 15, - 7, - 15.5 - ] + "from": [ + 1, + 5, + 14.5 + ], + "to": [ + 15, + 7, + 15.5 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 6, - 15, - 7 - ] + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 6, + 15, + 7 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 1, + 5, + 2, + 7 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 5, + 15, + 7 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 5, + 15, + 7 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 5, + 15, + 6 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 5, + 15, + 7 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 5, - 2, - 7 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 5, - 15, - 7 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 5, - 15, - 7 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 5, - 15, - 6 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 5, - 15, - 7 - ] - } - }, - "from": [ - 1, - 9, - 14.5 - ], - "to": [ - 15, - 11, - 15.5 - ] + "from": [ + 1, + 9, + 14.5 + ], + "to": [ + 15, + 11, + 15.5 + ] }, { - "__comment": "Box3", - "faces": { - "down": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 2, - 15, - 3 - ] + "__comment": "Box3", + "faces": { + "down": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 2, + 15, + 3 + ] + }, + "east": { + "texture": "#texture", + "uv": [ + 1, + 1, + 2, + 3 + ] + }, + "north": { + "texture": "#texture", + "uv": [ + 1, + 1, + 15, + 3 + ] + }, + "south": { + "texture": "#texture", + "uv": [ + 1, + 1, + 15, + 3 + ] + }, + "up": { + "rotation": 180, + "texture": "#texture", + "uv": [ + 1, + 1, + 15, + 2 + ] + }, + "west": { + "texture": "#texture", + "uv": [ + 14, + 1, + 15, + 3 + ] + } }, - "east": { - "texture": "#texture", - "uv": [ - 1, - 1, - 2, - 3 - ] - }, - "north": { - "texture": "#texture", - "uv": [ - 1, - 1, - 15, - 3 - ] - }, - "south": { - "texture": "#texture", - "uv": [ - 1, - 1, - 15, - 3 - ] - }, - "up": { - "rotation": 180, - "texture": "#texture", - "uv": [ - 1, - 1, - 15, - 2 - ] - }, - "west": { - "texture": "#texture", - "uv": [ - 14, - 1, - 15, - 3 - ] - } - }, - "from": [ - 1, - 13, - 14.5 - ], - "to": [ - 15, - 15, - 15.5 - ] + "from": [ + 1, + 13, + 14.5 + ], + "to": [ + 15, + 15, + 15.5 + ] } ], "parent": "block/ladder", diff --git a/src/main/resources/assets/bclib/models/block/path.json b/src/main/resources/assets/bclib/models/block/path.json index 696ef5f5..04fed330 100644 --- a/src/main/resources/assets/bclib/models/block/path.json +++ b/src/main/resources/assets/bclib/models/block/path.json @@ -1,81 +1,18 @@ -{ - "parent": "block/block", - "textures": { - "particle": "#bottom" - }, - "elements": [ - { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 16, - 15, - 16 - ], - "faces": { - "down": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#bottom", - "cullface": "down" - }, - "up": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#top" - }, - "north": { - "uv": [ - 0, - 1, - 16, - 16 - ], - "texture": "#side", - "cullface": "north" - }, - "south": { - "uv": [ - 0, - 1, - 16, - 16 - ], - "texture": "#side", - "cullface": "south" - }, - "west": { - "uv": [ - 0, - 1, - 16, - 16 - ], - "texture": "#side", - "cullface": "west" - }, - "east": { - "uv": [ - 0, - 1, - 16, - 16 - ], - "texture": "#side", - "cullface": "east" - } - } - } - ] +{ "parent": "block/block", + "textures": { + "particle": "#bottom" + }, + "elements": [ + { "from": [ 0, 0, 0 ], + "to": [ 16, 15, 16 ], + "faces": { + "down": { "uv": [ 0, 0, 16, 16 ], "texture": "#bottom", "cullface": "down" }, + "up": { "uv": [ 0, 0, 16, 16 ], "texture": "#top" }, + "north": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "north" }, + "south": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "south" }, + "west": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "west" }, + "east": { "uv": [ 0, 1, 16, 16 ], "texture": "#side", "cullface": "east" } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_bottom.json b/src/main/resources/assets/bclib/models/block/sided_door_bottom.json index debe45de..6fddf595 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_bottom.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_bottom.json @@ -1,71 +1,18 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 3, - 16, - 16 - ], - "faces": { - "down": { - "uv": [ - 13, - 0, - 16, - 16 - ], - "texture": "#side", - "cullface": "down" - }, - "north": { - "uv": [ - 3, - 0, - 0, - 16 - ], - "texture": "#side", - "cullface": "north" - }, - "south": { - "uv": [ - 0, - 0, - 3, - 16 - ], - "texture": "#side", - "cullface": "south" - }, - "west": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#facade", - "cullface": "west" - }, - "east": { - "uv": [ - 16, - 0, - 0, - 16 - ], - "texture": "#facade" - } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { "from": [ 0, 0, 0 ], + "to": [ 3, 16, 16 ], + "faces": { + "down": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "down" }, + "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, + "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, + "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade", "cullface": "west" }, + "east": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade" } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json b/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json index 112dcc5b..e6294d19 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_bottom_rh.json @@ -1,71 +1,18 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 3, - 16, - 16 - ], - "faces": { - "down": { - "uv": [ - 13, - 0, - 16, - 16 - ], - "texture": "#side", - "cullface": "down" - }, - "north": { - "uv": [ - 3, - 0, - 0, - 16 - ], - "texture": "#side", - "cullface": "north" - }, - "south": { - "uv": [ - 0, - 0, - 3, - 16 - ], - "texture": "#side", - "cullface": "south" - }, - "west": { - "uv": [ - 16, - 0, - 0, - 16 - ], - "texture": "#facade", - "cullface": "west" - }, - "east": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#facade" - } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { "from": [ 0, 0, 0 ], + "to": [ 3, 16, 16 ], + "faces": { + "down": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "down" }, + "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, + "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, + "west": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade", "cullface": "west" }, + "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade" } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_top.json b/src/main/resources/assets/bclib/models/block/sided_door_top.json index df8005ff..4a646108 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_top.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_top.json @@ -1,71 +1,18 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 3, - 16, - 16 - ], - "faces": { - "up": { - "uv": [ - 13, - 0, - 16, - 16 - ], - "texture": "#side", - "cullface": "up" - }, - "north": { - "uv": [ - 3, - 0, - 0, - 16 - ], - "texture": "#side", - "cullface": "north" - }, - "south": { - "uv": [ - 0, - 0, - 3, - 16 - ], - "texture": "#side", - "cullface": "south" - }, - "west": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#facade", - "cullface": "west" - }, - "east": { - "uv": [ - 16, - 0, - 0, - 16 - ], - "texture": "#facade" - } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { "from": [ 0, 0, 0 ], + "to": [ 3, 16, 16 ], + "faces": { + "up": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "up" }, + "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, + "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, + "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade", "cullface": "west" }, + "east": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade" } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json b/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json index 6e564e02..c706fe16 100644 --- a/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json +++ b/src/main/resources/assets/bclib/models/block/sided_door_top_rh.json @@ -1,71 +1,18 @@ { - "ambientocclusion": false, - "textures": { - "particle": "#facade" - }, - "elements": [ - { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 3, - 16, - 16 - ], - "faces": { - "up": { - "uv": [ - 13, - 0, - 16, - 16 - ], - "texture": "#side", - "cullface": "up" - }, - "north": { - "uv": [ - 3, - 0, - 0, - 16 - ], - "texture": "#side", - "cullface": "north" - }, - "south": { - "uv": [ - 0, - 0, - 3, - 16 - ], - "texture": "#side", - "cullface": "south" - }, - "west": { - "uv": [ - 16, - 0, - 0, - 16 - ], - "texture": "#facade", - "cullface": "west" - }, - "east": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#facade" - } - } - } - ] + "ambientocclusion": false, + "textures": { + "particle": "#facade" + }, + "elements": [ + { "from": [ 0, 0, 0 ], + "to": [ 3, 16, 16 ], + "faces": { + "up": { "uv": [ 13, 0, 16, 16 ], "texture": "#side", "cullface": "up" }, + "north": { "uv": [ 3, 0, 0, 16 ], "texture": "#side", "cullface": "north" }, + "south": { "uv": [ 0, 0, 3, 16 ], "texture": "#side", "cullface": "south" }, + "west": { "uv": [ 16, 0, 0, 16 ], "texture": "#facade", "cullface": "west" }, + "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#facade" } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/sided_trapdoor.json b/src/main/resources/assets/bclib/models/block/sided_trapdoor.json index c6b99a46..9f776427 100644 --- a/src/main/resources/assets/bclib/models/block/sided_trapdoor.json +++ b/src/main/resources/assets/bclib/models/block/sided_trapdoor.json @@ -1,85 +1,18 @@ -{ - "parent": "block/thin_block", - "textures": { - "particle": "#texture" - }, - "elements": [ - { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 16, - 3, - 16 - ], - "faces": { - "down": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture", - "cullface": "down" - }, - "up": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture" - }, - "north": { - "uv": [ - 16, - 0, - 13, - 16 - ], - "texture": "#side", - "cullface": "north", - "rotation": 90 - }, - "south": { - "uv": [ - 16, - 0, - 13, - 16 - ], - "texture": "#side", - "cullface": "south", - "rotation": 90 - }, - "west": { - "uv": [ - 16, - 0, - 13, - 16 - ], - "texture": "#side", - "cullface": "west", - "rotation": 90 - }, - "east": { - "uv": [ - 16, - 0, - 13, - 16 - ], - "texture": "#side", - "cullface": "east", - "rotation": 90 - } - } - } - ] +{ "parent": "block/thin_block", + "textures": { + "particle": "#texture" + }, + "elements": [ + { "from": [ 0, 0, 0 ], + "to": [ 16, 3, 16 ], + "faces": { + "down": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "down" }, + "up": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture" }, + "north": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "north", "rotation": 90 }, + "south": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "south", "rotation": 90 }, + "west": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "west", "rotation": 90 }, + "east": { "uv": [ 16, 0, 13, 16 ], "texture": "#side", "cullface": "east", "rotation": 90 } + } + } + ] } diff --git a/src/main/resources/assets/bclib/models/block/tint_cube.json b/src/main/resources/assets/bclib/models/block/tint_cube.json index a99494bf..f65b5c05 100644 --- a/src/main/resources/assets/bclib/models/block/tint_cube.json +++ b/src/main/resources/assets/bclib/models/block/tint_cube.json @@ -3,86 +3,18 @@ "textures": { "particle": "#texture" }, - "elements": [ + "elements": [ { "__comment": "Box1", - "from": [ - 0, - 0, - 0 - ], - "to": [ - 16, - 16, - 16 - ], + "from": [ 0, 0, 0 ], + "to": [ 16, 16, 16 ], "faces": { - "down": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture", - "cullface": "down", - "tintindex": 0 - }, - "up": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture", - "cullface": "up", - "tintindex": 0 - }, - "north": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture", - "cullface": "north", - "tintindex": 0 - }, - "south": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture", - "cullface": "south", - "tintindex": 0 - }, - "west": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture", - "cullface": "west", - "tintindex": 0 - }, - "east": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#texture", - "cullface": "east", - "tintindex": 0 - } + "down": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "down", "tintindex": 0 }, + "up": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "up", "tintindex": 0 }, + "north": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "north", "tintindex": 0 }, + "south": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "south", "tintindex": 0 }, + "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "west", "tintindex": 0 }, + "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#texture", "cullface": "east", "tintindex": 0 } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/anvil.json b/src/main/resources/assets/bclib/patterns/block/anvil.json index 94bc7a6c..7710c9a1 100644 --- a/src/main/resources/assets/bclib/patterns/block/anvil.json +++ b/src/main/resources/assets/bclib/patterns/block/anvil.json @@ -8,270 +8,61 @@ "panel": "%modid%:block/%anvil%_panel", "bottom": "%modid%:block/%anvil%_bottom" }, - "elements": [ + "elements": [ { "__comment": "Bottom", - "from": [ - 2, - 0, - 2 - ], - "to": [ - 14, - 4, - 14 - ], + "from": [ 2, 0, 2 ], + "to": [ 14, 4, 14 ], "faces": { - "down": { - "uv": [ - 2, - 2, - 14, - 14 - ], - "texture": "#bottom", - "cullface": "down" - }, - "up": { - "uv": [ - 2, - 2, - 14, - 14 - ], - "texture": "#panel" - }, - "north": { - "uv": [ - 2, - 12, - 14, - 16 - ], - "texture": "#back" - }, - "south": { - "uv": [ - 2, - 12, - 14, - 16 - ], - "texture": "#back" - }, - "west": { - "uv": [ - 2, - 12, - 14, - 16 - ], - "texture": "#front" - }, - "east": { - "uv": [ - 2, - 12, - 14, - 16 - ], - "texture": "#front" - } + "down": { "uv": [ 2, 2, 14, 14 ], "texture": "#bottom", "cullface": "down" }, + "up": { "uv": [ 2, 2, 14, 14 ], "texture": "#panel" }, + "north": { "uv": [ 2, 12, 14, 16 ], "texture": "#back" }, + "south": { "uv": [ 2, 12, 14, 16 ], "texture": "#back" }, + "west": { "uv": [ 2, 12, 14, 16 ], "texture": "#front" }, + "east": { "uv": [ 2, 12, 14, 16 ], "texture": "#front" } } }, { "__comment": "Plate", - "from": [ - 4, - 4, - 3 - ], - "to": [ - 12, - 5, - 13 - ], + "from": [ 4, 4, 3 ], + "to": [ 12, 5, 13 ], "faces": { - "up": { - "uv": [ - 4, - 3, - 12, - 13 - ], - "texture": "#panel" - }, - "north": { - "uv": [ - 4, - 11, - 12, - 12 - ], - "texture": "#back" - }, - "south": { - "uv": [ - 4, - 11, - 12, - 12 - ], - "texture": "#back" - }, - "west": { - "uv": [ - 3, - 11, - 13, - 12 - ], - "texture": "#front" - }, - "east": { - "uv": [ - 3, - 11, - 13, - 12 - ], - "texture": "#front" - } + "up": { "uv": [ 4, 3, 12, 13 ], "texture": "#panel" }, + "north": { "uv": [ 4, 11, 12, 12 ], "texture": "#back" }, + "south": { "uv": [ 4, 11, 12, 12 ], "texture": "#back" }, + "west": { "uv": [ 3, 11, 13, 12 ], "texture": "#front" }, + "east": { "uv": [ 3, 11, 13, 12 ], "texture": "#front" } } }, { "__comment": "Support", - "from": [ - 6, - 5, - 4 - ], - "to": [ - 10, - 10, - 12 - ], + "from": [ 6, 5, 4 ], + "to": [ 10, 10, 12 ], "faces": { - "north": { - "uv": [ - 6, - 6, - 10, - 11 - ], - "texture": "#back" - }, - "south": { - "uv": [ - 6, - 6, - 10, - 11 - ], - "texture": "#back" - }, - "west": { - "uv": [ - 4, - 6, - 12, - 11 - ], - "texture": "#front" - }, - "east": { - "uv": [ - 4, - 6, - 12, - 11 - ], - "texture": "#front" - } + "north": { "uv": [ 6, 6, 10, 11 ], "texture": "#back" }, + "south": { "uv": [ 6, 6, 10, 11 ], "texture": "#back" }, + "west": { "uv": [ 4, 6, 12, 11 ], "texture": "#front" }, + "east": { "uv": [ 4, 6, 12, 11 ], "texture": "#front" } } }, { "__comment": "Top", - "from": [ - 3, - 10, - 0 - ], - "to": [ - 13, - 16, - 16 - ], + "from": [ 3, 10, 0 ], + "to": [ 13, 16, 16 ], "faces": { - "down": { - "uv": [ - 3, - 0, - 13, - 16 - ], - "texture": "#top" - }, - "up": { - "uv": [ - 3, - 0, - 13, - 16 - ], - "texture": "#top" - }, - "north": { - "uv": [ - 3, - 0, - 13, - 6 - ], - "texture": "#back" - }, - "south": { - "uv": [ - 3, - 0, - 13, - 6 - ], - "texture": "#back" - }, - "west": { - "uv": [ - 0, - 0, - 16, - 6 - ], - "texture": "#front" - }, - "east": { - "uv": [ - 0, - 0, - 16, - 6 - ], - "texture": "#front" - } + "down": { "uv": [ 3, 0, 13, 16 ], "texture": "#top" }, + "up": { "uv": [ 3, 0, 13, 16 ], "texture": "#top" }, + "north": { "uv": [ 3, 0, 13, 6 ], "texture": "#back" }, + "south": { "uv": [ 3, 0, 13, 6 ], "texture": "#back" }, + "west": { "uv": [ 0, 0, 16, 6 ], "texture": "#front" }, + "east": { "uv": [ 0, 0, 16, 6 ], "texture": "#front" } } } ], "display": { "fixed": { - "rotation": [ - 0, - 90, - 0 - ], - "scale": [ - 0.5, - 0.5, - 0.5 - ] + "rotation": [ 0, 90, 0 ], + "scale": [ 0.5, 0.5, 0.5 ] } } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/bars_post.json b/src/main/resources/assets/bclib/patterns/block/bars_post.json index 8ef444bc..0dee124c 100644 --- a/src/main/resources/assets/bclib/patterns/block/bars_post.json +++ b/src/main/resources/assets/bclib/patterns/block/bars_post.json @@ -4,76 +4,18 @@ "top": "%modid%:block/%texture%_top", "particle": "#top" }, - "elements": [ + "elements": [ { "__comment": "Box1", - "from": [ - 7, - 0, - 7 - ], - "to": [ - 9, - 16, - 9 - ], + "from": [ 7, 0, 7 ], + "to": [ 9, 16, 9 ], "faces": { - "down": { - "uv": [ - 7, - 7, - 9, - 9 - ], - "texture": "#top", - "cullface": "down" - }, - "up": { - "uv": [ - 7, - 7, - 9, - 9 - ], - "texture": "#top", - "cullface": "up" - }, - "north": { - "uv": [ - 7, - 0, - 9, - 16 - ], - "texture": "#top" - }, - "south": { - "uv": [ - 7, - 0, - 9, - 16 - ], - "texture": "#top" - }, - "west": { - "uv": [ - 7, - 0, - 9, - 16 - ], - "texture": "#top" - }, - "east": { - "uv": [ - 7, - 0, - 9, - 16 - ], - "texture": "#top" - } + "down": { "uv": [ 7, 7, 9, 9 ], "texture": "#top", "cullface": "down" }, + "up": { "uv": [ 7, 7, 9, 9 ], "texture": "#top", "cullface": "up" }, + "north": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" }, + "south": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" }, + "west": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" }, + "east": { "uv": [ 7, 0, 9, 16 ], "texture": "#top" } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/bars_side.json b/src/main/resources/assets/bclib/patterns/block/bars_side.json index c22a18fa..44794f8e 100644 --- a/src/main/resources/assets/bclib/patterns/block/bars_side.json +++ b/src/main/resources/assets/bclib/patterns/block/bars_side.json @@ -5,77 +5,18 @@ "top": "%modid%:block/%texture%_top", "particle": "#side" }, - "elements": [ + "elements": [ { "__comment": "Box1", - "from": [ - 7, - 0, - 0 - ], - "to": [ - 9, - 16, - 9 - ], + "from": [ 7, 0, 0 ], + "to": [ 9, 16, 9 ], "faces": { - "down": { - "uv": [ - 7, - 7, - 9, - 16 - ], - "texture": "#top", - "cullface": "down" - }, - "up": { - "uv": [ - 7, - 0, - 9, - 9 - ], - "texture": "#top", - "cullface": "up" - }, - "north": { - "uv": [ - 7, - 0, - 9, - 16 - ], - "texture": "#side", - "cullface": "north" - }, - "south": { - "uv": [ - 7, - 0, - 9, - 16 - ], - "texture": "#side" - }, - "west": { - "uv": [ - 0, - 0, - 9, - 16 - ], - "texture": "#side" - }, - "east": { - "uv": [ - 7, - 0, - 16, - 16 - ], - "texture": "#side" - } + "down": { "uv": [ 7, 7, 9, 16 ], "texture": "#top", "cullface": "down" }, + "up": { "uv": [ 7, 0, 9, 9 ], "texture": "#top", "cullface": "up" }, + "north": { "uv": [ 7, 0, 9, 16 ], "texture": "#side", "cullface": "north" }, + "south": { "uv": [ 7, 0, 9, 16 ], "texture": "#side" }, + "west": { "uv": [ 0, 0, 9, 16 ], "texture": "#side" }, + "east": { "uv": [ 7, 0, 16, 16 ], "texture": "#side" } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/block.json b/src/main/resources/assets/bclib/patterns/block/block.json index b827a128..431bc5cf 100644 --- a/src/main/resources/assets/bclib/patterns/block/block.json +++ b/src/main/resources/assets/bclib/patterns/block/block.json @@ -1,6 +1,6 @@ { - "parent": "block/cube_all", - "textures": { - "all": "%modid%:block/%texture%" - } + "parent": "block/cube_all", + "textures": { + "all": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/button.json b/src/main/resources/assets/bclib/patterns/block/button.json index 14a6c8f2..e09625cd 100644 --- a/src/main/resources/assets/bclib/patterns/block/button.json +++ b/src/main/resources/assets/bclib/patterns/block/button.json @@ -1,6 +1,6 @@ { - "parent": "block/button", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/button", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/button_pressed.json b/src/main/resources/assets/bclib/patterns/block/button_pressed.json index 23c89dd8..dfe04d40 100644 --- a/src/main/resources/assets/bclib/patterns/block/button_pressed.json +++ b/src/main/resources/assets/bclib/patterns/block/button_pressed.json @@ -1,6 +1,6 @@ { - "parent": "block/button_pressed", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/button_pressed", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/composter.json b/src/main/resources/assets/bclib/patterns/block/composter.json index 82fb4e2a..cddf7792 100644 --- a/src/main/resources/assets/bclib/patterns/block/composter.json +++ b/src/main/resources/assets/bclib/patterns/block/composter.json @@ -9,145 +9,51 @@ }, "elements": [ { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 16, - 2, - 16 - ], + "from": [ 0, 0, 0 ], + "to": [ 16, 2, 16 ], "faces": { - "up": { - "texture": "#inside", - "cullface": "up" - }, - "down": { - "texture": "#bottom", - "cullface": "down" - } + "up": { "texture": "#inside", "cullface": "up" }, + "down": { "texture": "#bottom", "cullface": "down" } } }, { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 2, - 16, - 16 - ], + "from": [ 0, 0, 0 ], + "to": [ 2, 16, 16 ], "faces": { - "up": { - "texture": "#top", - "cullface": "up" - }, - "north": { - "texture": "#side", - "cullface": "north" - }, - "south": { - "texture": "#side", - "cullface": "south" - }, - "west": { - "texture": "#side", - "cullface": "west" - }, - "east": { - "texture": "#side", - "cullface": "up" - } + "up": { "texture": "#top", "cullface": "up" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side", "cullface": "up" } } }, { - "from": [ - 14, - 0, - 0 - ], - "to": [ - 16, - 16, - 16 - ], + "from": [ 14, 0, 0 ], + "to": [ 16, 16, 16 ], "faces": { - "up": { - "texture": "#top", - "cullface": "up" - }, - "north": { - "texture": "#side", - "cullface": "north" - }, - "south": { - "texture": "#side", - "cullface": "south" - }, - "west": { - "texture": "#side", - "cullface": "up" - }, - "east": { - "texture": "#side", - "cullface": "east" - } + "up": { "texture": "#top", "cullface": "up" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "up" }, + "east": { "texture": "#side", "cullface": "east" } } }, { - "from": [ - 2, - 0, - 0 - ], - "to": [ - 14, - 16, - 2 - ], + "from": [ 2, 0, 0 ], + "to": [ 14, 16, 2 ], "faces": { - "up": { - "texture": "#top", - "cullface": "up" - }, - "north": { - "texture": "#side", - "cullface": "north" - }, - "south": { - "texture": "#side", - "cullface": "up" - } + "up": { "texture": "#top", "cullface": "up" }, + "north": { "texture": "#side", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "up" } } }, { - "from": [ - 2, - 0, - 14 - ], - "to": [ - 14, - 16, - 16 - ], + "from": [ 2, 0, 14 ], + "to": [ 14, 16, 16 ], "faces": { - "up": { - "texture": "#top", - "cullface": "up" - }, - "north": { - "texture": "#side", - "cullface": "up" - }, - "south": { - "texture": "#side", - "cullface": "south" - } + "up": { "texture": "#top", "cullface": "up" }, + "north": { "texture": "#side", "cullface": "up" }, + "south": { "texture": "#side", "cullface": "south" } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/cross_shaded.json b/src/main/resources/assets/bclib/patterns/block/cross_shaded.json index 421f42bd..1db00d86 100644 --- a/src/main/resources/assets/bclib/patterns/block/cross_shaded.json +++ b/src/main/resources/assets/bclib/patterns/block/cross_shaded.json @@ -5,88 +5,20 @@ "particle": "#cross" }, "elements": [ - { - "from": [ - 0.8, - 0, - 8 - ], - "to": [ - 15.2, - 16, - 8 - ], - "rotation": { - "origin": [ - 8, - 8, - 8 - ], - "axis": "y", - "angle": 45, - "rescale": true - }, + { "from": [ 0.8, 0, 8 ], + "to": [ 15.2, 16, 8 ], + "rotation": { "origin": [ 8, 8, 8 ], "axis": "y", "angle": 45, "rescale": true }, "faces": { - "north": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#cross" - }, - "south": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#cross" - } + "north": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" }, + "south": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" } } }, - { - "from": [ - 8, - 0, - 0.8 - ], - "to": [ - 8, - 16, - 15.2 - ], - "rotation": { - "origin": [ - 8, - 8, - 8 - ], - "axis": "y", - "angle": 45, - "rescale": true - }, + { "from": [ 8, 0, 0.8 ], + "to": [ 8, 16, 15.2 ], + "rotation": { "origin": [ 8, 8, 8 ], "axis": "y", "angle": 45, "rescale": true }, "faces": { - "west": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#cross" - }, - "east": { - "uv": [ - 0, - 0, - 16, - 16 - ], - "texture": "#cross" - } + "west": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" }, + "east": { "uv": [ 0, 0, 16, 16 ], "texture": "#cross" } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/furnace_glow.json b/src/main/resources/assets/bclib/patterns/block/furnace_glow.json index 12b059a5..caa5ffdc 100644 --- a/src/main/resources/assets/bclib/patterns/block/furnace_glow.json +++ b/src/main/resources/assets/bclib/patterns/block/furnace_glow.json @@ -8,79 +8,30 @@ }, "display": { "firstperson_righthand": { - "rotation": [ - 0, - 135, - 0 - ], - "translation": [ - 0, - 0, - 0 - ], - "scale": [ - 0.40, - 0.40, - 0.40 - ] + "rotation": [ 0, 135, 0 ], + "translation": [ 0, 0, 0 ], + "scale": [ 0.40, 0.40, 0.40 ] } }, "elements": [ { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 16, - 16, - 16 - ], + "from": [ 0, 0, 0 ], + "to": [ 16, 16, 16 ], "faces": { - "down": { - "texture": "#top", - "cullface": "down" - }, - "up": { - "texture": "#top", - "cullface": "up" - }, - "north": { - "texture": "#front", - "cullface": "north" - }, - "south": { - "texture": "#side", - "cullface": "south" - }, - "west": { - "texture": "#side", - "cullface": "west" - }, - "east": { - "texture": "#side", - "cullface": "east" - } + "down": { "texture": "#top", "cullface": "down" }, + "up": { "texture": "#top", "cullface": "up" }, + "north": { "texture": "#front", "cullface": "north" }, + "south": { "texture": "#side", "cullface": "south" }, + "west": { "texture": "#side", "cullface": "west" }, + "east": { "texture": "#side", "cullface": "east" } } }, { - "from": [ - 0, - 0, - 0 - ], - "to": [ - 16, - 16, - 16 - ], + "from": [ 0, 0, 0 ], + "to": [ 16, 16, 16 ], "shade": false, "faces": { - "north": { - "texture": "#glow", - "cullface": "north" - } + "north": { "texture": "#glow", "cullface": "north" } } } ] diff --git a/src/main/resources/assets/bclib/patterns/block/path.json b/src/main/resources/assets/bclib/patterns/block/path.json index d73787a0..347121bb 100644 --- a/src/main/resources/assets/bclib/patterns/block/path.json +++ b/src/main/resources/assets/bclib/patterns/block/path.json @@ -1,8 +1,7 @@ -{ - "parent": "bclib:block/path", - "textures": { - "top": "%modid%:block/%top%", - "side": "%modid%:block/%side%", - "bottom": "%bottom%" - } +{ "parent": "bclib:block/path", + "textures": { + "top": "%modid%:block/%top%", + "side": "%modid%:block/%side%", + "bottom": "%bottom%" + } } diff --git a/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json b/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json index 7de574bb..60147e84 100644 --- a/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json +++ b/src/main/resources/assets/bclib/patterns/block/pressure_plate_down.json @@ -1,6 +1,6 @@ { - "parent": "block/pressure_plate_down", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/pressure_plate_down", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json b/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json index 274d36ba..66c028a3 100644 --- a/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json +++ b/src/main/resources/assets/bclib/patterns/block/pressure_plate_up.json @@ -1,6 +1,6 @@ { - "parent": "block/pressure_plate_up", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/pressure_plate_up", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/slab.json b/src/main/resources/assets/bclib/patterns/block/slab.json index 02fb5d29..7012e909 100644 --- a/src/main/resources/assets/bclib/patterns/block/slab.json +++ b/src/main/resources/assets/bclib/patterns/block/slab.json @@ -1,8 +1,8 @@ { - "parent": "block/slab", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/slab", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/stairs.json b/src/main/resources/assets/bclib/patterns/block/stairs.json index 6db6d51b..af694555 100644 --- a/src/main/resources/assets/bclib/patterns/block/stairs.json +++ b/src/main/resources/assets/bclib/patterns/block/stairs.json @@ -1,8 +1,8 @@ { - "parent": "block/stairs", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/stairs", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/stairs_inner.json b/src/main/resources/assets/bclib/patterns/block/stairs_inner.json index 4f9f2f9d..30b7d9bf 100644 --- a/src/main/resources/assets/bclib/patterns/block/stairs_inner.json +++ b/src/main/resources/assets/bclib/patterns/block/stairs_inner.json @@ -1,8 +1,8 @@ { - "parent": "block/inner_stairs", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/inner_stairs", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/stairs_outer.json b/src/main/resources/assets/bclib/patterns/block/stairs_outer.json index fa54a797..3544d10f 100644 --- a/src/main/resources/assets/bclib/patterns/block/stairs_outer.json +++ b/src/main/resources/assets/bclib/patterns/block/stairs_outer.json @@ -1,8 +1,8 @@ { - "parent": "block/outer_stairs", - "textures": { - "bottom": "%modid%:block/%texture%", - "side": "%modid%:block/%texture%", - "top": "%modid%:block/%texture%" - } + "parent": "block/outer_stairs", + "textures": { + "bottom": "%modid%:block/%texture%", + "side": "%modid%:block/%texture%", + "top": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_inventory.json b/src/main/resources/assets/bclib/patterns/block/wall_inventory.json index c6c852ad..85d64810 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_inventory.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_inventory.json @@ -1,6 +1,6 @@ { - "parent": "block/wall_inventory", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/wall_inventory", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_post.json b/src/main/resources/assets/bclib/patterns/block/wall_post.json index a4f1819d..466b91eb 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_post.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_post.json @@ -1,6 +1,6 @@ { - "parent": "block/template_wall_post", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/template_wall_post", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_side.json b/src/main/resources/assets/bclib/patterns/block/wall_side.json index e44d462a..e93fd118 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_side.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_side.json @@ -1,6 +1,6 @@ { - "parent": "block/template_wall_side", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/template_wall_side", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json b/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json index 69e4647d..86451081 100644 --- a/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json +++ b/src/main/resources/assets/bclib/patterns/block/wall_side_tall.json @@ -1,6 +1,6 @@ { - "parent": "block/template_wall_side_tall", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/template_wall_side_tall", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/item/pattern_button.json b/src/main/resources/assets/bclib/patterns/item/pattern_button.json index ceacffba..7cc6b6e0 100644 --- a/src/main/resources/assets/bclib/patterns/item/pattern_button.json +++ b/src/main/resources/assets/bclib/patterns/item/pattern_button.json @@ -1,6 +1,6 @@ { - "parent": "block/button_inventory", - "textures": { - "texture": "%modid%:block/%texture%" - } + "parent": "block/button_inventory", + "textures": { + "texture": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json b/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json index debcb565..765225c9 100644 --- a/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json +++ b/src/main/resources/assets/bclib/patterns/item/pattern_item_spawn_egg.json @@ -1,3 +1,3 @@ { - "parent": "item/template_spawn_egg" + "parent": "item/template_spawn_egg" } diff --git a/src/main/resources/assets/bclib/patterns/item/pattern_wall.json b/src/main/resources/assets/bclib/patterns/item/pattern_wall.json index c6c852ad..85d64810 100644 --- a/src/main/resources/assets/bclib/patterns/item/pattern_wall.json +++ b/src/main/resources/assets/bclib/patterns/item/pattern_wall.json @@ -1,6 +1,6 @@ { - "parent": "block/wall_inventory", - "textures": { - "wall": "%modid%:block/%texture%" - } + "parent": "block/wall_inventory", + "textures": { + "wall": "%modid%:block/%texture%" + } } \ No newline at end of file diff --git a/src/main/resources/assets/bclib/shaders/material/alpha_emission.frag b/src/main/resources/assets/bclib/shaders/material/alpha_emission.frag deleted file mode 100644 index 32ae9482..00000000 --- a/src/main/resources/assets/bclib/shaders/material/alpha_emission.frag +++ /dev/null @@ -1,14 +0,0 @@ -#include frex:shaders/api/fragment.glsl -#include frex:shaders/lib/math.glsl - -// Value near 254 -bool isEmissive(float alpha) { - return 0.9960 < alpha && alpha < 0.9962; -} - -void frx_startFragment(inout frx_FragmentData fragData) { - if (isEmissive(fragData.spriteColor.a)) { - fragData.emissivity = 1.0; - fragData.spriteColor.a = 1.0; - } -} diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh deleted file mode 100644 index c14819e8..00000000 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_cutout.fsh +++ /dev/null @@ -1,53 +0,0 @@ -#version 150 -#moj_import - -uniform sampler2D Sampler0; - -uniform vec4 ColorModulator; -uniform float FogStart; -uniform float FogEnd; -uniform vec4 FogColor; - -in float vertexDistance; -in vec4 vertexColor; -in vec2 texCoord0; -in vec4 normal; - -out vec4 fragColor; - -vec3 rgbToHSV(vec3 color) { - vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); - vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); -} - -vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); -} - -// Value near 254 -bool isEmissive(float alpha) { - return 0.9960 < alpha && alpha < 0.9962; -} - -void main() { - vec4 tex = texture(Sampler0, texCoord0); - if (tex.a < 0.1) { - discard; - } - vec4 color = tex * ColorModulator; - vec4 vertex = vertexColor; - if (isEmissive(tex.a)) { - vec3 hsv = rgbToHSV(vertex.rgb); - hsv.z = 1.0; - vertex.rgb = hsvToRGB(hsv); - } - color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); - color.a = 1.0; - fragColor = color; -} diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh deleted file mode 100644 index 3e3e352f..00000000 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_entity_cutout.fsh +++ /dev/null @@ -1,56 +0,0 @@ -#version 150 -#moj_import - -uniform sampler2D Sampler0; - -uniform vec4 ColorModulator; -uniform float FogStart; -uniform float FogEnd; -uniform vec4 FogColor; - -in float vertexDistance; -in vec4 vertexColor; -in vec4 lightMapColor; -in vec4 overlayColor; -in vec2 texCoord0; -in vec4 normal; - -out vec4 fragColor; - -vec3 rgbToHSV(vec3 color) { - vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); - vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); -} - -vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); -} - -// Value near 254 -bool isEmissive(float alpha) { - return 0.9960 < alpha && alpha < 0.9962; -} - -void main() { - vec4 tex = texture(Sampler0, texCoord0); - if (tex.a < 0.1) { - discard; - } - vec4 color = tex * ColorModulator; - color.rgb = mix(overlayColor.rgb, color.rgb, overlayColor.a); - vec4 vertex = vertexColor * lightMapColor; - if (isEmissive(tex.a)) { - vec3 hsv = rgbToHSV(vertex.rgb); - hsv.z = 1.0; - vertex.rgb = hsvToRGB(hsv); - } - color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); - color.a = 1.0; - fragColor = color; -} \ No newline at end of file diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh deleted file mode 100644 index 453e467f..00000000 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_item_entity_translucent_cull.fsh +++ /dev/null @@ -1,53 +0,0 @@ -#version 150 -#moj_import - -uniform sampler2D Sampler0; - -uniform vec4 ColorModulator; -uniform float FogStart; -uniform float FogEnd; -uniform vec4 FogColor; - -in float vertexDistance; -in vec4 vertexColor; -in vec2 texCoord0; -in vec2 texCoord1; -in vec4 normal; - -out vec4 fragColor; - -vec3 rgbToHSV(vec3 color) { - vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); - vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); -} - -vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); -} - -// Value near 254 -bool isEmissive(float alpha) { - return 0.9960 < alpha && alpha < 0.9962; -} - -void main() { - vec4 tex = texture(Sampler0, texCoord0); - if (tex.a < 0.1) { - discard; - } - vec4 color = tex * ColorModulator; - vec4 vertex = vertexColor; - if (isEmissive(tex.a)) { - vec3 hsv = rgbToHSV(vertex.rgb); - hsv.z = 1.0; - vertex.rgb = hsvToRGB(hsv); - } - color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); - fragColor = color; -} \ No newline at end of file diff --git a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh b/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh deleted file mode 100644 index 95c1a52f..00000000 --- a/src/main/resources/assets/minecraft/shaders/core/rendertype_solid.fsh +++ /dev/null @@ -1,50 +0,0 @@ -#version 150 -#moj_import - -uniform sampler2D Sampler0; - -uniform vec4 ColorModulator; -uniform float FogStart; -uniform float FogEnd; -uniform vec4 FogColor; - -in float vertexDistance; -in vec4 vertexColor; -in vec2 texCoord0; -in vec4 normal; - -out vec4 fragColor; - -vec3 rgbToHSV(vec3 color) { - vec4 k = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); - vec4 p = mix(vec4(color.bg, k.wz), vec4(color.gb, k.xy), step(color.b, color.g)); - vec4 q = mix(vec4(p.xyw, color.r), vec4(color.r, p.yzx), step(p.x, color.r)); - float d = q.x - min(q.w, q.y); - float e = 1.0e-10; - return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); -} - -vec3 hsvToRGB(vec3 color) { - vec4 k = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); - vec3 p = abs(fract(color.xxx + k.xyz) * 6.0 - k.www); - return color.z * mix(k.xxx, clamp(p - k.xxx, 0.0, 1.0), color.y); -} - -// Value near 254 -bool isEmissive(float alpha) { - return 0.9960 < alpha && alpha < 0.9962; -} - -void main() { - vec4 tex = texture(Sampler0, texCoord0); - vec4 color = tex * ColorModulator; - vec4 vertex = vertexColor; - if (isEmissive(tex.a)) { - vec3 hsv = rgbToHSV(vertex.rgb); - hsv.z = 1.0; - vertex.rgb = hsvToRGB(hsv); - } - color = linear_fog(color * vertex, vertexDistance, FogStart, FogEnd, FogColor); - color.a = 1.0; - fragColor = color; -} diff --git a/src/main/resources/bclib.accesswidener b/src/main/resources/bclib.accesswidener deleted file mode 100644 index 3efe4455..00000000 --- a/src/main/resources/bclib.accesswidener +++ /dev/null @@ -1,4 +0,0 @@ -accessWidener v1 named - -# Classes -accessible class net/minecraft/client/Minecraft$ExperimentalDialogType \ No newline at end of file diff --git a/src/main/resources/bclib.mixins.client.json b/src/main/resources/bclib.mixins.client.json index b3aebf4a..f36a59e9 100644 --- a/src/main/resources/bclib.mixins.client.json +++ b/src/main/resources/bclib.mixins.client.json @@ -2,18 +2,11 @@ "required": true, "minVersion": "0.8", "package": "ru.bclib.mixin.client", - "compatibilityLevel": "JAVA_16", + "compatibilityLevel": "JAVA_8", "client": [ - "SimpleReloadableResourceManagerMixin", "EnchantingTableBlockMixin", "BackgroundRendererMixin", - "ClientRecipeBookMixin", - "ModelManagerMixin", - "TextureAtlasMixin", - "AnvilScreenMixin", - "ModelBakeryMixin", - "MinecraftMixin", - "GameMixin" + "ModelBakeryMixin" ], "injectors": { "defaultRequire": 1 diff --git a/src/main/resources/bclib.mixins.common.json b/src/main/resources/bclib.mixins.common.json index 2ce54afa..20e03d8d 100644 --- a/src/main/resources/bclib.mixins.common.json +++ b/src/main/resources/bclib.mixins.common.json @@ -2,35 +2,17 @@ "required": true, "minVersion": "0.8", "package": "ru.bclib.mixin.common", - "compatibilityLevel": "JAVA_16", + "compatibilityLevel": "JAVA_8", "mixins": [ - "SimpleReloadableResourceManagerMixin", - "shears.DiggingEnchantmentMixin", - "shears.TripWireBlockMixin", - "ChunkBiomeContainerMixin", - "shears.BeehiveBlockMixin", - "shears.PumpkinBlockMixin", - "shears.MushroomCowMixin", - "shears.SnowGolemMixin", "ComposterBlockAccessor", - "InternalBiomeDataMixin", "PotionBrewingAccessor", "RecipeManagerAccessor", "EnchantmentMenuMixin", "MinecraftServerMixin", - "PistonBaseBlockMixin", - "WorldGenRegionMixin", - "DimensionTypeMixin", "RecipeManagerMixin", "BoneMealItemMixin", - "shears.SheepMixin", - "PortalShapeMixin", "ServerLevelMixin", - "AnvilBlockMixin", - "AnvilMenuMixin", - "TagLoaderMixin", - "BiomeMixin", - "MainMixin" + "TagLoaderMixin" ], "injectors": { "defaultRequire": 1 diff --git a/src/main/resources/fabric.mod.json b/src/main/resources/fabric.mod.json index d49eb0a9..d4c9f8f1 100644 --- a/src/main/resources/fabric.mod.json +++ b/src/main/resources/fabric.mod.json @@ -2,6 +2,7 @@ "schemaVersion": 1, "id": "bclib", "version": "${version}", + "name": "BCLib", "description": "A library for BetterX team mods", "authors": [ @@ -13,8 +14,10 @@ "issues": "https://github.com/paulevsGitch/bclib/issues", "sources": "https://github.com/paulevsGitch/bclib" }, + "license": "MIT", "icon": "assets/bclib/icon.png", + "environment": "*", "entrypoints": { "main": [ @@ -25,24 +28,16 @@ ], "server": [ "ru.bclib.server.BCLibServer" - ], - "modmenu": [ "ru.bclib.gui.modmenu.EntryPoint::entrypointObject" ] + ] }, - "accessWidener" : "bclib.accesswidener", "mixins": [ "bclib.mixins.common.json", "bclib.mixins.client.json" ], + "depends": { - "fabricloader": ">=0.11.6", - "fabric": ">=0.41.0", - "minecraft": ">=1.17.1" - }, - "custom":{ - "modmenu":{ - "links":{ - "title.link.bclib.discord":"https://discord.gg/kYuATbYbKW" - } - } - } + "fabricloader": ">=0.11.0", + "fabric": ">=0.32.0", + "minecraft": ">=1.16.4" + } }