Compare commits
20 Commits
1.16.5-For
...
1.16.5-Fab
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7065c9dd8c | ||
|
|
368b50a578 | ||
|
|
cd2d46f422 | ||
|
|
03367443b4 | ||
|
|
81d3a2eba4 | ||
|
|
79ef6cfaa9 | ||
|
|
40fd46b278 | ||
|
|
9dacdde761 | ||
|
|
6a31adcdd8 | ||
|
|
b46fdeaeef | ||
|
|
f1fa629c5c | ||
|
|
ad914ac03a | ||
|
|
d8ce8ecb06 | ||
|
|
8d9214c190 | ||
|
|
594db19bfb | ||
|
|
a89edd53a4 | ||
|
|
d741338d46 | ||
|
|
01f697d2d3 | ||
|
|
4c439dccd2 | ||
|
|
df50f61b0d |
@@ -1,47 +1,52 @@
|
||||
import net.fabricmc.loom.task.RemapJarTask
|
||||
import org.ajoberstar.grgit.Grgit
|
||||
|
||||
plugins {
|
||||
kotlin("jvm").version("1.3.61")
|
||||
id("net.minecraftforge.gradle").version("3.0.157")
|
||||
id("org.spongepowered.mixin").version("0.7-SNAPSHOT")
|
||||
id("fabric-loom").version("0.6-SNAPSHOT")
|
||||
kotlin("jvm").version("1.4.31")
|
||||
id("org.ajoberstar.grgit").version("3.1.1")
|
||||
}
|
||||
apply(plugin = "org.spongepowered.mixin")
|
||||
apply(plugin = "org.ajoberstar.grgit")
|
||||
|
||||
val gitHash = (project.ext.get("grgit") as Grgit).head().abbreviatedId
|
||||
val semVer = "${project.version}+$gitHash"
|
||||
val jarName = "BetterFoliage-$semVer-Fabric-${properties["mcVersion"]}"
|
||||
|
||||
repositories {
|
||||
maven("http://files.minecraftforge.net/maven")
|
||||
maven("https://repo.spongepowered.org/maven")
|
||||
maven("https://maven.fabricmc.net/")
|
||||
maven("https://minecraft.curseforge.com/api/maven")
|
||||
maven("https://maven.modmuss50.me/")
|
||||
maven("https://maven.shedaniel.me/")
|
||||
maven("https://grondag-repo.appspot.com").credentials { username = "guest"; password = "" }
|
||||
maven("https://jitpack.io")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
"minecraft"("net.minecraftforge:forge:${properties["mcVersion"]}-${properties["forgeVersion"]}")
|
||||
"minecraft"("com.mojang:minecraft:${properties["mcVersion"]}")
|
||||
"mappings"("net.fabricmc:yarn:${properties["yarnMappings"]}:v2")
|
||||
|
||||
"implementation"("kottle:Kottle:${properties["kottleVersion"]}")
|
||||
// basic Fabric stuff
|
||||
"modImplementation"("net.fabricmc:fabric-loader:${properties["loaderVersion"]}")
|
||||
"modImplementation"("net.fabricmc.fabric-api:fabric-api:${properties["fabricVersion"]}")
|
||||
"modImplementation"("net.fabricmc:fabric-language-kotlin:${properties["fabricKotlinVersion"]}")
|
||||
|
||||
"implementation"("org.spongepowered:mixin:0.8-SNAPSHOT")
|
||||
annotationProcessor("org.spongepowered:mixin:0.8-SNAPSHOT")
|
||||
// configuration handling
|
||||
"modImplementation"("io.github.prospector:modmenu:${properties["modMenuVersion"]}")
|
||||
listOf("modImplementation", "include").forEach { configuration ->
|
||||
configuration("me.shedaniel.cloth:cloth-config-fabric:${properties["clothConfigVersion"]}")
|
||||
configuration("me.zeroeightsix:fiber:${properties["fiberVersion"]}")
|
||||
}
|
||||
|
||||
// Canvas Renderer
|
||||
// "modImplementation"("grondag:canvas:0.7.+")
|
||||
|
||||
// Optifabric
|
||||
// "modImplementation"("com.github.modmuss50:OptiFabric:1.0.0")
|
||||
"implementation"("org.zeroturnaround:zt-zip:1.13")
|
||||
}
|
||||
|
||||
sourceSets {
|
||||
get("main").ext["refMap"] = "betterfoliage.refmap.json"
|
||||
get("main").resources.srcDir("src/forge/resources")
|
||||
get("main").java.srcDir("src/forge/java")
|
||||
}
|
||||
kotlin.sourceSets {
|
||||
get("main").kotlin.srcDir("src/forge/kotlin")
|
||||
}
|
||||
|
||||
|
||||
minecraft {
|
||||
mappings(properties["mappingsChannel"] as String, properties["mappingsVersion"] as String)
|
||||
accessTransformer(file("src/main/resources/META-INF/accesstransformer.cfg"))
|
||||
|
||||
runs.create("client") {
|
||||
workingDirectory(file("run"))
|
||||
properties["forge.logging.markers"] = "CORE"
|
||||
properties["forge.logging.console.level"] = "debug"
|
||||
mods.create("betterfoliage") {
|
||||
source(sourceSets["main"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
java {
|
||||
@@ -51,15 +56,15 @@ java {
|
||||
|
||||
kotlin {
|
||||
target.compilations.configureEach {
|
||||
kotlinOptions.jvmTarget = "1.8"
|
||||
kotlinOptions.freeCompilerArgs += listOf("-Xno-param-assertions", "-Xno-call-assertions")
|
||||
}
|
||||
}
|
||||
|
||||
tasks.getByName<Jar>("jar") {
|
||||
archiveName = "BetterFoliage-${project.version}-Forge-${properties["mcVersion"]}.jar"
|
||||
manifest {
|
||||
from(file("src/main/resources/META-INF/MANIFEST.MF"))
|
||||
attributes["Implementation-Version"] = project.version
|
||||
}
|
||||
exclude("net")
|
||||
tasks.getByName<ProcessResources>("processResources") {
|
||||
filesMatching("fabric.mod.json") { expand(mutableMapOf("version" to semVer)) }
|
||||
}
|
||||
|
||||
tasks.getByName<RemapJarTask>("remapJar") {
|
||||
archiveName = "$jarName.jar"
|
||||
}
|
||||
@@ -2,13 +2,19 @@ org.gradle.jvmargs=-Xmx2G
|
||||
org.gradle.daemon=false
|
||||
|
||||
group = com.github.octarine-noise
|
||||
name = betterfoliage
|
||||
jarName = BetterFoliage-Forge
|
||||
|
||||
version = 2.3.1
|
||||
version = 2.6.5
|
||||
|
||||
mcVersion = 1.14.4
|
||||
forgeVersion = 28.1.109
|
||||
mappingsChannel = snapshot
|
||||
mappingsVersion = 20190719-1.14.3
|
||||
mcVersion = 1.16.5
|
||||
yarnMappings=1.16.5+build.6
|
||||
loaderVersion=0.11.3
|
||||
fabricVersion=0.32.5+1.16
|
||||
|
||||
kottleVersion = 1.4.0
|
||||
kotlinVersion=1.3.60
|
||||
fabricKotlinVersion=1.5.0+kotlin.1.4.31
|
||||
|
||||
clothConfigVersion=4.11.24
|
||||
modMenuVersion=1.16.9
|
||||
fiberVersion=0.8.0-2
|
||||
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
BIN
gradle/wrapper/gradle-wrapper.jar
vendored
Binary file not shown.
51
gradlew
vendored
51
gradlew
vendored
@@ -1,5 +1,21 @@
|
||||
#!/usr/bin/env sh
|
||||
|
||||
#
|
||||
# Copyright 2015 the original author or authors.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# https://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
|
||||
##############################################################################
|
||||
##
|
||||
## Gradle start up script for UN*X
|
||||
@@ -28,7 +44,7 @@ APP_NAME="Gradle"
|
||||
APP_BASE_NAME=`basename "$0"`
|
||||
|
||||
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
DEFAULT_JVM_OPTS=""
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD="maximum"
|
||||
@@ -109,8 +125,8 @@ if $darwin; then
|
||||
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
|
||||
fi
|
||||
|
||||
# For Cygwin, switch paths to Windows format before running java
|
||||
if $cygwin ; then
|
||||
# For Cygwin or MSYS, switch paths to Windows format before running java
|
||||
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
|
||||
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
|
||||
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
|
||||
JAVACMD=`cygpath --unix "$JAVACMD"`
|
||||
@@ -138,19 +154,19 @@ if $cygwin ; then
|
||||
else
|
||||
eval `echo args$i`="\"$arg\""
|
||||
fi
|
||||
i=$((i+1))
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
case $i in
|
||||
(0) set -- ;;
|
||||
(1) set -- "$args0" ;;
|
||||
(2) set -- "$args0" "$args1" ;;
|
||||
(3) set -- "$args0" "$args1" "$args2" ;;
|
||||
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
0) set -- ;;
|
||||
1) set -- "$args0" ;;
|
||||
2) set -- "$args0" "$args1" ;;
|
||||
3) set -- "$args0" "$args1" "$args2" ;;
|
||||
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
|
||||
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
|
||||
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
|
||||
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
|
||||
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
|
||||
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
@@ -159,14 +175,9 @@ save () {
|
||||
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
|
||||
echo " "
|
||||
}
|
||||
APP_ARGS=$(save "$@")
|
||||
APP_ARGS=`save "$@"`
|
||||
|
||||
# Collect all arguments for the java command, following the shell quoting and substitution rules
|
||||
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
|
||||
|
||||
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
|
||||
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
|
||||
cd "$(dirname "$0")"
|
||||
fi
|
||||
|
||||
exec "$JAVACMD" "$@"
|
||||
|
||||
18
gradlew.bat
vendored
18
gradlew.bat
vendored
@@ -1,3 +1,19 @@
|
||||
@rem
|
||||
@rem Copyright 2015 the original author or authors.
|
||||
@rem
|
||||
@rem Licensed under the Apache License, Version 2.0 (the "License");
|
||||
@rem you may not use this file except in compliance with the License.
|
||||
@rem You may obtain a copy of the License at
|
||||
@rem
|
||||
@rem https://www.apache.org/licenses/LICENSE-2.0
|
||||
@rem
|
||||
@rem Unless required by applicable law or agreed to in writing, software
|
||||
@rem distributed under the License is distributed on an "AS IS" BASIS,
|
||||
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@rem See the License for the specific language governing permissions and
|
||||
@rem limitations under the License.
|
||||
@rem
|
||||
|
||||
@if "%DEBUG%" == "" @echo off
|
||||
@rem ##########################################################################
|
||||
@rem
|
||||
@@ -14,7 +30,7 @@ set APP_BASE_NAME=%~n0
|
||||
set APP_HOME=%DIRNAME%
|
||||
|
||||
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
|
||||
set DEFAULT_JVM_OPTS=
|
||||
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
|
||||
|
||||
@rem Find java.exe
|
||||
if defined JAVA_HOME goto findJavaFromJavaHome
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
maven("http://files.minecraftforge.net/maven")
|
||||
maven("https://repo.spongepowered.org/maven")
|
||||
jcenter()
|
||||
maven("https://maven.fabricmc.net/")
|
||||
gradlePluginPortal()
|
||||
}
|
||||
resolutionStrategy {
|
||||
eachPlugin {
|
||||
if (requested.id.let { it.namespace == "net.minecraftforge" && it.name == "gradle"} ) useModule("net.minecraftforge.gradle:ForgeGradle:${requested.version}")
|
||||
if (requested.id.let { it.namespace == "org.spongepowered" && it.name == "mixin"} ) useModule("org.spongepowered:mixingradle:${requested.version}")
|
||||
}
|
||||
}
|
||||
}
|
||||
rootProject.name = "betterfoliage"
|
||||
49
src/main/java/mods/betterfoliage/MixinConfigPlugin.java
Normal file
49
src/main/java/mods/betterfoliage/MixinConfigPlugin.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package mods.betterfoliage;
|
||||
|
||||
import net.fabricmc.loader.api.FabricLoader;
|
||||
import org.apache.logging.log4j.Level;
|
||||
import org.apache.logging.log4j.LogManager;
|
||||
import org.apache.logging.log4j.Logger;
|
||||
import org.objectweb.asm.tree.ClassNode;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
|
||||
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
public class MixinConfigPlugin implements IMixinConfigPlugin {
|
||||
|
||||
Logger logger = LogManager.getLogger(this);
|
||||
|
||||
Boolean hasOptifine = null;
|
||||
|
||||
@Override
|
||||
public boolean shouldApplyMixin(String targetClassName, String mixinClassName) {
|
||||
if (hasOptifine == null) {
|
||||
hasOptifine = FabricLoader.getInstance().isModLoaded("optifabric");
|
||||
if (hasOptifine) logger.log(Level.INFO, "[BetterFoliage] Optifabric detected, applying Optifine mixins");
|
||||
else logger.log(Level.INFO, "[BetterFoliage] Optifabric not detected, applying Vanilla mixins");
|
||||
}
|
||||
if (mixinClassName.endsWith("Vanilla") && hasOptifine) return false;
|
||||
if (mixinClassName.endsWith("Optifine") && !hasOptifine) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad(String mixinPackage) { }
|
||||
|
||||
@Override
|
||||
public String getRefMapperConfig() { return null; }
|
||||
|
||||
@Override
|
||||
public void acceptTargets(Set<String> myTargets, Set<String> otherTargets) { }
|
||||
|
||||
@Override
|
||||
public List<String> getMixins() { return null; }
|
||||
|
||||
@Override
|
||||
public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { }
|
||||
|
||||
@Override
|
||||
public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { }
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
package mods.betterfoliage;
|
||||
|
||||
import org.spongepowered.asm.mixin.Mixins;
|
||||
import org.spongepowered.asm.mixin.connect.IMixinConnector;
|
||||
|
||||
public class MixinConnector implements IMixinConnector {
|
||||
@Override
|
||||
public void connect() {
|
||||
Mixins.addConfiguration("betterfoliage.common.mixins.json");
|
||||
|
||||
try {
|
||||
Class.forName("optifine.OptiFineTransformationService");
|
||||
Mixins.addConfiguration("betterfoliage.optifine.mixins.json");
|
||||
} catch (ClassNotFoundException e) {
|
||||
Mixins.addConfiguration("betterfoliage.vanilla.mixins.json");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,44 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.Hooks;
|
||||
import mods.betterfoliage.Hooks;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.util.Direction;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.shapes.VoxelShape;
|
||||
import net.minecraft.world.IBlockReader;
|
||||
import net.minecraft.util.math.Direction;
|
||||
import net.minecraft.util.shape.VoxelShape;
|
||||
import net.minecraft.world.BlockView;
|
||||
import net.minecraft.world.World;
|
||||
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.Redirect;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
|
||||
/**
|
||||
* Mixin overriding the {@link VoxelShape} used for the neighbor block in {@link Block}.shouldSideBeRendered().
|
||||
*
|
||||
* This way log blocks can be made to not block rendering, without altering any {@link Block} or
|
||||
* {@link BlockState} properties with potential gameplay ramifications.
|
||||
*/
|
||||
@Mixin(Block.class)
|
||||
public class MixinBlock {
|
||||
private static final String shouldSideBeRendered = "Lnet/minecraft/block/Block;shouldSideBeRendered(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/IBlockReader;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/Direction;)Z";
|
||||
private static final String getVoxelShape = "Lnet/minecraft/block/BlockState;func_215702_a(Lnet/minecraft/world/IBlockReader;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/Direction;)Lnet/minecraft/util/math/shapes/VoxelShape;";
|
||||
private static final String shouldSideBeRendered = "Lnet/minecraft/block/Block;shouldDrawSide(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/Direction;)Z";
|
||||
private static final String getVoxelShape = "Lnet/minecraft/block/BlockState;getCullingFace(Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/math/Direction;)Lnet/minecraft/util/shape/VoxelShape;";
|
||||
private static final String randomDisplayTick = "randomDisplayTick(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Ljava/util/Random;)V";
|
||||
|
||||
/**
|
||||
* Override the {@link VoxelShape} used for the neighbor block in {@link Block}.shouldSideBeRendered().
|
||||
*
|
||||
* This way log blocks can be made to not block rendering, without altering any {@link Block} or
|
||||
* {@link BlockState} properties with potential gameplay ramifications.
|
||||
*/
|
||||
@Redirect(method = shouldSideBeRendered, at = @At(value = "INVOKE", target = getVoxelShape, ordinal = 1))
|
||||
private static VoxelShape getVoxelShapeOverride(BlockState state, IBlockReader reader, BlockPos pos, Direction dir) {
|
||||
private static VoxelShape getVoxelShapeOverride(BlockState state, BlockView reader, BlockPos pos, Direction dir) {
|
||||
return Hooks.getVoxelShapeOverride(state, reader, pos, dir);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject a callback to call for every random display tick. Used for adding custom particle effects to blocks.
|
||||
*/
|
||||
@Inject(method = randomDisplayTick, at = @At("HEAD"))
|
||||
void onRandomDisplayTick(BlockState state, World world, BlockPos pos, Random rnd, CallbackInfo ci) {
|
||||
// Hooks.onRandomDisplayTick(state.getBlock(), state, world, pos, rnd);
|
||||
}
|
||||
}
|
||||
|
||||
17
src/main/java/mods/betterfoliage/mixin/MixinBlockModels.java
Normal file
17
src/main/java/mods/betterfoliage/mixin/MixinBlockModels.java
Normal file
@@ -0,0 +1,17 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.BlockModelsReloadCallback;
|
||||
import net.minecraft.client.render.block.BlockModels;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
@Mixin(BlockModels.class)
|
||||
public class MixinBlockModels {
|
||||
|
||||
@Inject(method = "reload()V", at = @At("RETURN"))
|
||||
void onReload(CallbackInfo ci) {
|
||||
BlockModelsReloadCallback.EVENT.invoker().reloadBlockModels((BlockModels) (Object) this);
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,11 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.Hooks;
|
||||
import mods.betterfoliage.Hooks;
|
||||
import net.minecraft.block.AbstractBlock;
|
||||
import net.minecraft.block.Block;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.IBlockReader;
|
||||
import net.minecraft.world.BlockView;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
@@ -14,14 +15,15 @@ import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
*
|
||||
* Needed to avoid excessive darkening of Round Logs at the corners, now that they are not full blocks.
|
||||
*/
|
||||
@Mixin(BlockState.class)
|
||||
@SuppressWarnings({"UnnecessaryQualifiedMemberReference", "deprecation"})
|
||||
@Mixin(AbstractBlock.AbstractBlockState.class)
|
||||
@SuppressWarnings({"deprecation"})
|
||||
public class MixinBlockState {
|
||||
private static final String callFrom = "Lnet/minecraft/block/BlockState;func_215703_d(Lnet/minecraft/world/IBlockReader;Lnet/minecraft/util/math/BlockPos;)F";
|
||||
private static final String callTo = "Lnet/minecraft/block/Block;func_220080_a(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/IBlockReader;Lnet/minecraft/util/math/BlockPos;)F";
|
||||
private static final String callFrom = "Lnet/minecraft/block/AbstractBlock$AbstractBlockState;getAmbientOcclusionLightLevel(Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos;)F";
|
||||
// why is the INVOKEVIRTUAL target class Block in the bytecode, not AbstractBlock?
|
||||
private static final String callTo = "Lnet/minecraft/block/Block;getAmbientOcclusionLightLevel(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/BlockView;Lnet/minecraft/util/math/BlockPos;)F";
|
||||
|
||||
@Redirect(method = callFrom, at = @At(value = "INVOKE", target = callTo))
|
||||
float getAmbientOcclusionValue(Block block, BlockState state, IBlockReader reader, BlockPos pos) {
|
||||
return Hooks.getAmbientOcclusionLightValueOverride(block.func_220080_a(state, reader, pos), state);
|
||||
float getAmbientOcclusionValue(Block block, BlockState state, BlockView reader, BlockPos pos) {
|
||||
return Hooks.getAmbientOcclusionLightValueOverride(block.getAmbientOcclusionLightLevel(state, reader, pos), state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.Hooks;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.client.renderer.BlockRendererDispatcher;
|
||||
import net.minecraft.client.renderer.BufferBuilder;
|
||||
import net.minecraft.client.renderer.chunk.ChunkRender;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.IEnviromentBlockReader;
|
||||
import net.minecraftforge.client.MinecraftForgeClient;
|
||||
import net.minecraftforge.client.model.data.IModelData;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
import java.util.Random;
|
||||
|
||||
@Mixin(ChunkRender.class)
|
||||
public class MixinChunkRender {
|
||||
|
||||
private static final String rebuildChunk = "rebuildChunk(FFFLnet/minecraft/client/renderer/chunk/ChunkRenderTask;)V";
|
||||
private static final String renderBlock = "Lnet/minecraft/client/renderer/BlockRendererDispatcher;renderBlock(Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/IEnviromentBlockReader;Lnet/minecraft/client/renderer/BufferBuilder;Ljava/util/Random;Lnet/minecraftforge/client/model/data/IModelData;)Z";
|
||||
|
||||
@Redirect(method = rebuildChunk, at = @At(value = "INVOKE", target = renderBlock))
|
||||
public boolean renderBlock(BlockRendererDispatcher dispatcher, BlockState state, BlockPos pos, IEnviromentBlockReader reader, BufferBuilder buffer, Random random, IModelData modelData) {
|
||||
return Hooks.renderWorldBlock(dispatcher, state, pos, reader, buffer, random, modelData, MinecraftForgeClient.getRenderLayer());
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.Hooks;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.client.renderer.chunk.ChunkRender;
|
||||
import net.minecraft.util.BlockRenderLayer;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
@Mixin(ChunkRender.class)
|
||||
public class MixinChunkRenderVanilla {
|
||||
|
||||
private static final String rebuildChunk = "rebuildChunk(FFFLnet/minecraft/client/renderer/chunk/ChunkRenderTask;)V";
|
||||
private static final String canRenderInLayer = "Lnet/minecraft/block/BlockState;canRenderInLayer(Lnet/minecraft/util/BlockRenderLayer;)Z";
|
||||
|
||||
@Redirect(method = rebuildChunk, at = @At(value = "INVOKE", target = canRenderInLayer))
|
||||
boolean canRenderInLayer(BlockState state, BlockRenderLayer layer) {
|
||||
return Hooks.canRenderInLayerOverride(state, layer);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.ClientChunkLoadCallback;
|
||||
import net.minecraft.client.world.ClientChunkManager;
|
||||
import net.minecraft.nbt.CompoundTag;
|
||||
import net.minecraft.network.PacketByteBuf;
|
||||
import net.minecraft.world.biome.source.BiomeArray;
|
||||
import net.minecraft.world.chunk.WorldChunk;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(ClientChunkManager.class)
|
||||
public class MixinClientChunkManager {
|
||||
|
||||
private static final String onLoadChunkFromPacket = "Lnet/minecraft/client/world/ClientChunkManager;loadChunkFromPacket(IILnet/minecraft/world/biome/source/BiomeArray;Lnet/minecraft/network/PacketByteBuf;Lnet/minecraft/nbt/CompoundTag;IZ)Lnet/minecraft/world/chunk/WorldChunk;";
|
||||
|
||||
@Inject(method = onLoadChunkFromPacket, at = @At(value = "RETURN", ordinal = 2))
|
||||
void onLoadChunkFromPacket(int x, int z, @Nullable BiomeArray biomes, PacketByteBuf buf, CompoundTag tag, int verticalStripBitmask, boolean complete, CallbackInfoReturnable<WorldChunk> ci) {
|
||||
ClientChunkLoadCallback.EVENT.invoker().loadChunk(ci.getReturnValue());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.ClientChunkLoadCallback;
|
||||
import net.minecraft.world.chunk.WorldChunk;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
|
||||
|
||||
@Mixin(targets = {"net.minecraft.client.world.ClientChunkManager$ClientChunkMap"})
|
||||
public class MixinClientChunkManagerChunkMap {
|
||||
|
||||
private static final String onCompareAndSet = "Lnet/minecraft/client/world/ClientChunkManager$ClientChunkMap;compareAndSet(ILnet/minecraft/world/chunk/WorldChunk;Lnet/minecraft/world/chunk/WorldChunk;)Lnet/minecraft/world/chunk/WorldChunk;";
|
||||
|
||||
@Inject(method = onCompareAndSet, at = @At("HEAD"))
|
||||
void onSetAndCompare(int i, WorldChunk oldChunk, WorldChunk newChunk, CallbackInfoReturnable<WorldChunk> ci) {
|
||||
ClientChunkLoadCallback.EVENT.invoker().unloadChunk(oldChunk);
|
||||
}
|
||||
}
|
||||
@@ -1,44 +1,53 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.Hooks;
|
||||
import net.minecraft.block.Block;
|
||||
import mods.betterfoliage.ClientWorldLoadCallback;
|
||||
import mods.betterfoliage.Hooks;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.client.renderer.WorldRenderer;
|
||||
import net.minecraft.client.network.ClientPlayNetworkHandler;
|
||||
import net.minecraft.client.render.WorldRenderer;
|
||||
import net.minecraft.client.world.ClientWorld;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.IBlockReader;
|
||||
import net.minecraft.util.profiler.Profiler;
|
||||
import net.minecraft.util.registry.RegistryKey;
|
||||
import net.minecraft.world.World;
|
||||
import net.minecraft.world.dimension.DimensionType;
|
||||
import net.minecraft.world.level.LevelInfo;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
import org.spongepowered.asm.mixin.injection.Inject;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
import java.util.Random;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@Mixin(ClientWorld.class)
|
||||
public class MixinClientWorld {
|
||||
|
||||
private static final String worldAnimateTick = "Lnet/minecraft/client/world/ClientWorld;animateTick(IIIILjava/util/Random;ZLnet/minecraft/util/math/BlockPos$MutableBlockPos;)V";
|
||||
private static final String blockAnimateTick = "Lnet/minecraft/block/Block;animateTick(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Ljava/util/Random;)V";
|
||||
private static final String ctor = "Lnet/minecraft/client/world/ClientWorld;<init>(Lnet/minecraft/client/network/ClientPlayNetworkHandler;Lnet/minecraft/client/world/ClientWorld$Properties;Lnet/minecraft/util/registry/RegistryKey;Lnet/minecraft/world/dimension/DimensionType;ILjava/util/function/Supplier;Lnet/minecraft/client/render/WorldRenderer;ZJ)V";
|
||||
private static final String scheduleBlockRerenderIfNeeded = "Lnet/minecraft/client/world/ClientWorld;scheduleBlockRerenderIfNeeded(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)V";
|
||||
private static final String rendererNotify = "Lnet/minecraft/client/render/WorldRenderer;method_21596(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;)V";
|
||||
private static final String worldDisplayTick = "randomBlockDisplayTick(IIIILjava/util/Random;ZLnet/minecraft/util/math/BlockPos$Mutable;)V";
|
||||
private static final String blockDisplayTick = "Lnet/minecraft/block/Block;randomDisplayTick(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/World;Lnet/minecraft/util/math/BlockPos;Ljava/util/Random;)V";
|
||||
|
||||
private static final String worldNotify = "Lnet/minecraft/client/world/ClientWorld;notifyBlockUpdate(Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;I)V";
|
||||
private static final String rendererNotify = "Lnet/minecraft/client/renderer/WorldRenderer;notifyBlockUpdate(Lnet/minecraft/world/IBlockReader;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/block/BlockState;Lnet/minecraft/block/BlockState;I)V";
|
||||
/**
|
||||
* Inject callback to get notified of client-side blockstate changes.
|
||||
* Used to invalidate caches in the {@link mods.betterfoliage.chunk.ChunkOverlayManager}
|
||||
*/
|
||||
@Inject(method = scheduleBlockRerenderIfNeeded, at = @At(value = "HEAD"))
|
||||
void onClientBlockChanged(BlockPos pos, BlockState oldState, BlockState newState, CallbackInfo ci) {
|
||||
Hooks.onClientBlockChanged((ClientWorld) (Object) this, pos, oldState, newState);
|
||||
}
|
||||
|
||||
@Inject(method = ctor, at = @At("RETURN"))
|
||||
void onClientWorldCreated(ClientPlayNetworkHandler networkHandler, ClientWorld.Properties properties, RegistryKey<World> registryRef, DimensionType dimensionType, int loadDistance, Supplier<Profiler> profiler, WorldRenderer worldRenderer, boolean debugWorld, long seed, CallbackInfo ci) {
|
||||
ClientWorldLoadCallback.EVENT.invoker().loadWorld((ClientWorld) (Object) this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject a callback to call for every random display tick. Used for adding custom particle effects to blocks.
|
||||
*/
|
||||
@Redirect(method = worldAnimateTick, at = @At(value = "INVOKE", target = blockAnimateTick))
|
||||
void onAnimateTick(Block block, BlockState state, World world, BlockPos pos, Random random) {
|
||||
Hooks.onRandomDisplayTick(block, state, world, pos, random);
|
||||
block.animateTick(state, world, pos, random);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject callback to get notified of client-side blockstate changes.
|
||||
* Used to invalidate caches in the {@link mods.betterfoliage.client.chunk.ChunkOverlayManager}
|
||||
*/
|
||||
@Redirect(method = worldNotify, at = @At(value = "INVOKE", target = rendererNotify))
|
||||
void onClientBlockChanged(WorldRenderer renderer, IBlockReader world, BlockPos pos, BlockState oldState, BlockState newState, int flags) {
|
||||
Hooks.onClientBlockChanged((ClientWorld) world, pos, oldState, newState, flags);
|
||||
renderer.notifyBlockUpdate(world, pos, oldState, newState, flags);
|
||||
@Inject(method = worldDisplayTick, at = @At(value = "INVOKE", target = blockDisplayTick))
|
||||
void onRandomDisplayTick(int xCenter, int yCenter, int zCenter, int radius, Random random, boolean spawnBarrierParticles, BlockPos.Mutable mutable, CallbackInfo ci) {
|
||||
Hooks.onRandomDisplayTick((ClientWorld) (Object) this, mutable);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.BetterFoliage;
|
||||
import mods.octarinecore.client.resource.AsnycSpriteProviderManager;
|
||||
import net.minecraft.client.renderer.model.ModelBakery;
|
||||
import net.minecraft.client.renderer.texture.AtlasTexture;
|
||||
import net.minecraft.profiler.IProfiler;
|
||||
import net.minecraft.resources.IResourceManager;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
@Mixin(ModelBakery.class)
|
||||
abstract public class MixinModelBakery {
|
||||
|
||||
private static final String processLoading = "processLoading(Lnet/minecraft/profiler/IProfiler;)V";
|
||||
private static final String stitch = "Lnet/minecraft/client/renderer/texture/AtlasTexture;stitch(Lnet/minecraft/resources/IResourceManager;Ljava/lang/Iterable;Lnet/minecraft/profiler/IProfiler;)Lnet/minecraft/client/renderer/texture/AtlasTexture$SheetData;";
|
||||
|
||||
@Redirect(method = processLoading, at = @At(value = "INVOKE", target = stitch))
|
||||
AtlasTexture.SheetData onStitchModelTextures(AtlasTexture atlas, IResourceManager manager, Iterable<ResourceLocation> idList, IProfiler profiler) {
|
||||
AsnycSpriteProviderManager.StitchWrapper wrapper = BetterFoliage.INSTANCE.getBlockSprites().prepare(this, atlas, manager, idList, profiler);
|
||||
AtlasTexture.SheetData sheet = atlas.stitch(manager, wrapper.getIdList(), profiler);
|
||||
wrapper.complete(sheet);
|
||||
return sheet;
|
||||
}
|
||||
}
|
||||
37
src/main/java/mods/betterfoliage/mixin/MixinModelLoader.java
Normal file
37
src/main/java/mods/betterfoliage/mixin/MixinModelLoader.java
Normal file
@@ -0,0 +1,37 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.ModelLoadingCallback;
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager;
|
||||
import net.minecraft.client.render.model.BakedModel;
|
||||
import net.minecraft.client.render.model.ModelBakeSettings;
|
||||
import net.minecraft.client.render.model.ModelLoader;
|
||||
import net.minecraft.client.render.model.UnbakedModel;
|
||||
import net.minecraft.client.texture.Sprite;
|
||||
import net.minecraft.client.util.ModelIdentifier;
|
||||
import net.minecraft.client.util.SpriteIdentifier;
|
||||
import net.minecraft.resource.ResourceManager;
|
||||
import net.minecraft.util.Identifier;
|
||||
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.Redirect;
|
||||
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
@Mixin(ModelLoader.class)
|
||||
public class MixinModelLoader {
|
||||
|
||||
@Shadow @Final private ResourceManager resourceManager;
|
||||
|
||||
// use the same trick fabric-api does to get around the no-mixins-in-constructors policy
|
||||
@Inject(at = @At("HEAD"), method = "addModel")
|
||||
private void addModelHook(ModelIdentifier id, CallbackInfo info) {
|
||||
if (id.getPath().equals("trident_in_hand")) {
|
||||
// last step before stitching
|
||||
ModelLoadingCallback.EVENT.invoker().beginLoadModels((ModelLoader) (Object) this, resourceManager);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager;
|
||||
import net.minecraft.client.render.model.BakedModel;
|
||||
import net.minecraft.client.render.model.ModelBakeSettings;
|
||||
import net.minecraft.client.render.model.ModelLoader;
|
||||
import net.minecraft.client.render.model.UnbakedModel;
|
||||
import net.minecraft.client.texture.Sprite;
|
||||
import net.minecraft.client.util.SpriteIdentifier;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
@Mixin(ModelLoader.class)
|
||||
public class MixinModelLoaderOptifine {
|
||||
|
||||
private static final String loaderBake = "Lnet/minecraft/class_1088;getBakedModel(Lnet/minecraft/class_2960;Lnet/minecraft/class_3665;Ljava/util/function/Function;)Lnet/minecraft/class_1087;";
|
||||
private static final String modelBake = "Lnet/minecraft/class_1100;method_4753(Lnet/minecraft/class_1088;Ljava/util/function/Function;Lnet/minecraft/class_3665;Lnet/minecraft/class_2960;)Lnet/minecraft/class_1087;";
|
||||
|
||||
@SuppressWarnings("UnresolvedMixinReference")
|
||||
@Redirect(method = loaderBake, at = @At(value = "INVOKE", target = modelBake), remap = false)
|
||||
BakedModel onBakeModel(
|
||||
UnbakedModel unbaked,
|
||||
ModelLoader loader,
|
||||
Function<SpriteIdentifier, Sprite> textureGetter,
|
||||
ModelBakeSettings rotationContainer,
|
||||
Identifier modelId
|
||||
) {
|
||||
return BakeWrapperManager.INSTANCE.onBake(unbaked, loader, textureGetter, rotationContainer, modelId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager;
|
||||
import net.minecraft.client.render.model.BakedModel;
|
||||
import net.minecraft.client.render.model.ModelBakeSettings;
|
||||
import net.minecraft.client.render.model.ModelLoader;
|
||||
import net.minecraft.client.render.model.UnbakedModel;
|
||||
import net.minecraft.client.texture.Sprite;
|
||||
import net.minecraft.client.util.SpriteIdentifier;
|
||||
import net.minecraft.util.Identifier;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
@Mixin(ModelLoader.class)
|
||||
public class MixinModelLoaderVanilla {
|
||||
|
||||
private static final String loaderBake = "Lnet/minecraft/client/render/model/ModelLoader;bake(Lnet/minecraft/util/Identifier;Lnet/minecraft/client/render/model/ModelBakeSettings;)Lnet/minecraft/client/render/model/BakedModel;";
|
||||
private static final String modelBake = "Lnet/minecraft/client/render/model/UnbakedModel;bake(Lnet/minecraft/client/render/model/ModelLoader;Ljava/util/function/Function;Lnet/minecraft/client/render/model/ModelBakeSettings;Lnet/minecraft/util/Identifier;)Lnet/minecraft/client/render/model/BakedModel;";
|
||||
|
||||
@Redirect(method = loaderBake, at = @At(value = "INVOKE", target = modelBake))
|
||||
BakedModel onBakeModel(
|
||||
UnbakedModel unbaked,
|
||||
ModelLoader loader,
|
||||
Function<SpriteIdentifier, Sprite> textureGetter,
|
||||
ModelBakeSettings rotationContainer,
|
||||
Identifier modelId
|
||||
) {
|
||||
return BakeWrapperManager.INSTANCE.onBake(unbaked, loader, textureGetter, rotationContainer, modelId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.Hooks;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.util.Direction;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.util.math.shapes.VoxelShape;
|
||||
import net.minecraft.world.IBlockReader;
|
||||
import net.optifine.util.BlockUtils;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
@Mixin(BlockUtils.class)
|
||||
public class MixinOptifineBlockUtils {
|
||||
private static final String shouldSideBeRenderedCached = "shouldSideBeRenderedCached(Lnet/minecraft/block/BlockState;Lnet/minecraft/world/IBlockReader;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/Direction;Lnet/optifine/render/RenderEnv;Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;)Z";
|
||||
private static final String getVoxelShape = "Lnet/minecraft/block/BlockState;func_215702_a(Lnet/minecraft/world/IBlockReader;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/util/Direction;)Lnet/minecraft/util/math/shapes/VoxelShape;";
|
||||
|
||||
@SuppressWarnings("UnresolvedMixinReference")
|
||||
@Redirect(method = shouldSideBeRenderedCached, at = @At(value = "INVOKE", target = getVoxelShape, ordinal = 1))
|
||||
private static VoxelShape getVoxelShapeOverride(BlockState state, IBlockReader reader, BlockPos pos, Direction dir) {
|
||||
return Hooks.getVoxelShapeOverride(state, reader, pos, dir);
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.Hooks;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.client.renderer.chunk.ChunkRender;
|
||||
import net.minecraft.util.BlockRenderLayer;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Coerce;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
import org.spongepowered.asm.mixin.injection.Slice;
|
||||
|
||||
@Mixin(ChunkRender.class)
|
||||
public class MixinOptifineChunkRender {
|
||||
|
||||
private static final String rebuildChunk = "rebuildChunk(FFFLnet/minecraft/client/renderer/chunk/ChunkRenderTask;)V";
|
||||
private static final String invokeReflector = "Lnet/optifine/reflect/Reflector;callBoolean(Ljava/lang/Object;Lnet/optifine/reflect/ReflectorMethod;[Ljava/lang/Object;)Z";
|
||||
private static final String forgeBlockCanRender = "Lnet/minecraft/client/renderer/chunk/ChunkRender;FORGE_BLOCK_CAN_RENDER_IN_LAYER:Z";
|
||||
|
||||
@Redirect(
|
||||
method = rebuildChunk,
|
||||
at = @At(value = "INVOKE", target = invokeReflector),
|
||||
slice = @Slice(
|
||||
from = @At(value = "FIELD", target = forgeBlockCanRender)
|
||||
)
|
||||
)
|
||||
@SuppressWarnings("UnresolvedMixinReference")
|
||||
boolean canRenderInLayer(Object state, @Coerce Object reflector, Object[] layer) {
|
||||
return Hooks.canRenderInLayerOverride((BlockState) state, (BlockRenderLayer) layer[0]);
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.BetterFoliage;
|
||||
import mods.octarinecore.client.resource.AsnycSpriteProviderManager;
|
||||
import net.minecraft.client.particle.ParticleManager;
|
||||
import net.minecraft.client.renderer.texture.AtlasTexture;
|
||||
import net.minecraft.profiler.IProfiler;
|
||||
import net.minecraft.resources.IResourceManager;
|
||||
import net.minecraft.util.ResourceLocation;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.Redirect;
|
||||
|
||||
@Mixin(ParticleManager.class)
|
||||
public class MixinParticleManager {
|
||||
|
||||
private static final String reload = "reload(Lnet/minecraft/resources/IFutureReloadListener$IStage;Lnet/minecraft/resources/IResourceManager;Lnet/minecraft/profiler/IProfiler;Lnet/minecraft/profiler/IProfiler;Ljava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;";
|
||||
private static final String stitch = "Lnet/minecraft/client/renderer/texture/AtlasTexture;stitch(Lnet/minecraft/resources/IResourceManager;Ljava/lang/Iterable;Lnet/minecraft/profiler/IProfiler;)Lnet/minecraft/client/renderer/texture/AtlasTexture$SheetData;";
|
||||
|
||||
// ewww :S
|
||||
@SuppressWarnings("UnresolvedMixinReference")
|
||||
@Redirect(method = "*", at = @At(value = "INVOKE", target = stitch))
|
||||
AtlasTexture.SheetData onStitchModelTextures(AtlasTexture atlas, IResourceManager manager, Iterable<ResourceLocation> idList, IProfiler profiler) {
|
||||
AsnycSpriteProviderManager.StitchWrapper wrapper = BetterFoliage.INSTANCE.getParticleSprites().prepare(this, atlas, manager, idList, profiler);
|
||||
AtlasTexture.SheetData sheet = atlas.stitch(manager, wrapper.getIdList(), profiler);
|
||||
wrapper.complete(sheet);
|
||||
return sheet;
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package mods.betterfoliage.mixin;
|
||||
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration;
|
||||
import net.minecraft.block.BlockState;
|
||||
import net.minecraft.client.renderer.BlockModelRenderer;
|
||||
import net.minecraft.client.renderer.BufferBuilder;
|
||||
import net.minecraft.util.math.BlockPos;
|
||||
import net.minecraft.world.IEnviromentBlockReader;
|
||||
import org.spongepowered.asm.mixin.Mixin;
|
||||
import org.spongepowered.asm.mixin.injection.At;
|
||||
import org.spongepowered.asm.mixin.injection.ModifyArg;
|
||||
|
||||
@Mixin(BlockModelRenderer.class)
|
||||
public class MixinShadersBlockModelRenderer {
|
||||
|
||||
private static final String renderModel = "renderModel(Lnet/minecraft/world/IEnviromentBlockReader;Lnet/minecraft/client/renderer/model/IBakedModel;Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/client/renderer/BufferBuilder;ZLjava/util/Random;JLnet/minecraftforge/client/model/data/IModelData;)Z";
|
||||
private static final String pushEntity = "Lnet/optifine/shaders/SVertexBuilder;pushEntity(Lnet/minecraft/block/BlockState;Lnet/minecraft/util/math/BlockPos;Lnet/minecraft/world/IEnviromentBlockReader;Lnet/minecraft/client/renderer/BufferBuilder;)V";
|
||||
|
||||
@SuppressWarnings("UnresolvedMixinReference")
|
||||
@ModifyArg(method = renderModel, at = @At(value = "INVOKE", target = pushEntity), remap = false)
|
||||
BlockState overrideBlockState(BlockState state, BlockPos pos, IEnviromentBlockReader world, BufferBuilder buffer) {
|
||||
return ShadersModIntegration.getBlockStateOverride(state, world, pos);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
package net.optifine.util;
|
||||
|
||||
public class BlockUtils {
|
||||
// whyyyy?
|
||||
}
|
||||
@@ -1,20 +1,24 @@
|
||||
package mods.betterfoliage
|
||||
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.render.RisingSoulTextures
|
||||
import mods.octarinecore.client.gui.textComponent
|
||||
import mods.octarinecore.client.resource.AsnycSpriteProviderManager
|
||||
import mods.octarinecore.client.resource.AsyncSpriteProvider
|
||||
import mods.octarinecore.client.resource.Atlas
|
||||
import mods.octarinecore.client.resource.GeneratedBlockTexturePack
|
||||
import me.zeroeightsix.fiber.JanksonSettings
|
||||
import mods.betterfoliage.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.config.BlockConfig
|
||||
import mods.betterfoliage.config.MainConfig
|
||||
import mods.betterfoliage.render.ShadersModIntegration
|
||||
import mods.betterfoliage.render.block.vanilla.*
|
||||
import mods.betterfoliage.render.particle.LeafParticleRegistry
|
||||
import mods.betterfoliage.render.particle.RisingSoulParticle
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.BlockTypeCache
|
||||
import mods.betterfoliage.resource.generated.GeneratedBlockTexturePack
|
||||
import net.fabricmc.api.ClientModInitializer
|
||||
import net.fabricmc.fabric.api.resource.ResourceManagerHelper
|
||||
import net.fabricmc.fabric.mixin.resource.loader.ResourcePackManagerAccessor
|
||||
import net.fabricmc.loader.api.FabricLoader
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.client.particle.ParticleManager
|
||||
import net.minecraft.client.renderer.model.ModelBakery
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.text.TextFormatting
|
||||
import net.minecraft.util.text.TranslationTextComponent
|
||||
import net.minecraftforge.registries.ForgeRegistries
|
||||
import net.minecraft.client.MinecraftClient
|
||||
import net.minecraft.resource.ResourceType
|
||||
import net.minecraft.util.Identifier
|
||||
import org.apache.logging.log4j.Level
|
||||
import org.apache.logging.log4j.LogManager
|
||||
import org.apache.logging.log4j.simple.SimpleLogger
|
||||
@@ -23,54 +27,68 @@ import java.io.File
|
||||
import java.io.PrintStream
|
||||
import java.util.*
|
||||
|
||||
object BetterFoliage {
|
||||
var log = LogManager.getLogger("BetterFoliage")
|
||||
var logDetail = SimpleLogger(
|
||||
"BetterFoliage",
|
||||
Level.DEBUG,
|
||||
false, false, true, false,
|
||||
"yyyy-MM-dd HH:mm:ss",
|
||||
null,
|
||||
PropertiesUtil(Properties()),
|
||||
PrintStream(File("logs/betterfoliage.log").apply {
|
||||
parentFile.mkdirs()
|
||||
if (!exists()) createNewFile()
|
||||
})
|
||||
|
||||
object BetterFoliage : ClientModInitializer {
|
||||
const val MOD_ID = "betterfoliage"
|
||||
|
||||
val detailLogStream = PrintStream(File("logs/betterfoliage.log").apply {
|
||||
parentFile.mkdirs()
|
||||
if (!exists()) createNewFile()
|
||||
})
|
||||
|
||||
fun logger(obj: Any) = LogManager.getLogger(obj)
|
||||
fun detailLogger(obj: Any) = SimpleLogger(
|
||||
obj::class.java.simpleName, Level.DEBUG, false, true, true, false, "yyyy-MM-dd HH:mm:ss", null, PropertiesUtil(Properties()), detailLogStream
|
||||
)
|
||||
|
||||
val blockSprites = AsnycSpriteProviderManager<ModelBakery>("bf-blocks-extra")
|
||||
val particleSprites = AsnycSpriteProviderManager<ParticleManager>("bf-particles-extra")
|
||||
val asyncPack = GeneratedBlockTexturePack("bf_gen", "Better Foliage generated assets", logDetail)
|
||||
val configFile get() = File(FabricLoader.getInstance().configDirectory, "BetterFoliage.json")
|
||||
|
||||
fun getSpriteManager(atlas: Atlas) = when(atlas) {
|
||||
Atlas.BLOCKS -> blockSprites
|
||||
Atlas.PARTICLES -> particleSprites
|
||||
} as AsnycSpriteProviderManager<Any>
|
||||
|
||||
init {
|
||||
blockSprites.providers.add(asyncPack)
|
||||
val config = MainConfig().apply {
|
||||
if (configFile.exists()) JanksonSettings().deserialize(fiberNode, configFile.inputStream())
|
||||
else JanksonSettings().serialize(fiberNode, configFile.outputStream(), false)
|
||||
}
|
||||
|
||||
fun log(level: Level, msg: String) {
|
||||
log.log(level, "[BetterFoliage] $msg")
|
||||
logDetail.log(level, msg)
|
||||
val blockConfig = BlockConfig()
|
||||
val generatedPack = GeneratedBlockTexturePack(Identifier(MOD_ID, "generated"), "betterfoliage-generated", "Better Foliage", "Generated leaf textures")
|
||||
|
||||
/** List of recognized [BlockState]s */
|
||||
var blockTypes = BlockTypeCache()
|
||||
|
||||
override fun onInitializeClient() {
|
||||
// Register generated resource pack
|
||||
ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(generatedPack.reloader)
|
||||
(MinecraftClient.getInstance().resourcePackManager as ResourcePackManagerAccessor)
|
||||
.providers.add(generatedPack.finder)
|
||||
|
||||
ResourceManagerHelper.get(ResourceType.CLIENT_RESOURCES).registerReloadListener(blockConfig)
|
||||
|
||||
// Add standard block support
|
||||
BakeWrapperManager.discoverers.add(StandardCactusDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardDirtDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardGrassDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardLeafDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardLilypadDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardMyceliumDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardNetherrackDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardRoundLogDiscovery)
|
||||
BakeWrapperManager.discoverers.add(StandardSandDiscovery)
|
||||
|
||||
// Init overlay layers
|
||||
ChunkOverlayManager.layers.add(RoundLogOverlayLayer)
|
||||
|
||||
// Init singletons
|
||||
LeafParticleRegistry
|
||||
StandardLeafModel.Companion
|
||||
StandardGrassModel.Companion
|
||||
StandardRoundLogModel.Companion
|
||||
StandardCactusModel.Companion
|
||||
StandardLilypadModel.Companion
|
||||
DirtModel.Companion
|
||||
StandardSandModel.Companion
|
||||
StandardMyceliumModel.Companion
|
||||
StandardNetherrackModel.Companion
|
||||
RisingSoulParticle.Companion
|
||||
ShadersModIntegration
|
||||
}
|
||||
|
||||
fun logDetail(msg: String) {
|
||||
logDetail.log(Level.DEBUG, msg)
|
||||
}
|
||||
|
||||
fun logRenderError(state: BlockState, location: BlockPos) {
|
||||
if (state in Client.suppressRenderErrors) return
|
||||
Client.suppressRenderErrors.add(state)
|
||||
|
||||
val blockName = ForgeRegistries.BLOCKS.getKey(state.block).toString()
|
||||
val blockLoc = "${location.x},${location.y},${location.z}"
|
||||
Minecraft.getInstance().ingameGUI.chatGUI.printChatMessage(TranslationTextComponent(
|
||||
"betterfoliage.rendererror",
|
||||
textComponent(blockName, TextFormatting.GOLD),
|
||||
textComponent(blockLoc, TextFormatting.GOLD)
|
||||
))
|
||||
logDetail("Error rendering block $state at $blockLoc")
|
||||
}
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
package mods.betterfoliage
|
||||
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.octarinecore.client.resource.AsnycSpriteProviderManager
|
||||
import mods.octarinecore.client.resource.GeneratedBlockTexturePack
|
||||
import net.alexwells.kottle.FMLKotlinModLoadingContext
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.client.particle.ParticleManager
|
||||
import net.minecraft.client.renderer.model.ModelBakery
|
||||
import net.minecraftforge.fml.ModLoadingContext
|
||||
import net.minecraftforge.fml.common.Mod
|
||||
import net.minecraftforge.fml.config.ModConfig
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
import org.apache.logging.log4j.LogManager
|
||||
import org.apache.logging.log4j.simple.SimpleLogger
|
||||
import org.apache.logging.log4j.util.PropertiesUtil
|
||||
import java.io.File
|
||||
import java.io.PrintStream
|
||||
import java.util.*
|
||||
|
||||
@Mod(BetterFoliageMod.MOD_ID)
|
||||
object BetterFoliageMod {
|
||||
const val MOD_ID = "betterfoliage"
|
||||
|
||||
val bus = FMLKotlinModLoadingContext.get().modEventBus
|
||||
|
||||
init {
|
||||
ModLoadingContext.get().registerConfig(ModConfig.Type.CLIENT, Config.build())
|
||||
Minecraft.getInstance().resourcePackList.addPackFinder(BetterFoliage.asyncPack.finder)
|
||||
bus.register(BlockConfig)
|
||||
Client.init()
|
||||
}
|
||||
}
|
||||
11
src/main/kotlin/mods/betterfoliage/CommonRefs.kt
Normal file
11
src/main/kotlin/mods/betterfoliage/CommonRefs.kt
Normal file
@@ -0,0 +1,11 @@
|
||||
package mods.betterfoliage
|
||||
|
||||
import it.unimi.dsi.fastutil.ints.IntList
|
||||
import mods.betterfoliage.util.YarnHelper
|
||||
import net.minecraft.client.texture.Sprite
|
||||
import net.minecraft.world.World
|
||||
|
||||
val VertexFormat_offsets = YarnHelper.requiredField<IntList>("net.minecraft.class_293", "field_1597", "Lit/unimi/dsi/fastutil/ints/IntList;")
|
||||
val BakedQuad_sprite = YarnHelper.requiredField<Sprite>("net.minecraft.class_777", "field_4176", "Lnet/minecraft/class_1058;")
|
||||
val WorldChunk_world = YarnHelper.requiredField<World>("net.minecraft.class_2818", "field_12858", "Lnet/minecraft/class_1937;")
|
||||
val ChunkRendererRegion_world = YarnHelper.requiredField<World>("net.minecraft.class_853", "field_4490", "Lnet/minecraft/class_1937;")
|
||||
72
src/main/kotlin/mods/betterfoliage/Events.kt
Normal file
72
src/main/kotlin/mods/betterfoliage/Events.kt
Normal file
@@ -0,0 +1,72 @@
|
||||
package mods.betterfoliage
|
||||
|
||||
import net.fabricmc.fabric.api.event.Event
|
||||
import net.fabricmc.fabric.api.event.EventFactory
|
||||
import net.minecraft.client.render.block.BlockModels
|
||||
import net.minecraft.client.render.model.ModelLoader
|
||||
import net.minecraft.client.world.ClientWorld
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.world.chunk.WorldChunk
|
||||
|
||||
interface ClientChunkLoadCallback {
|
||||
fun loadChunk(chunk: WorldChunk)
|
||||
fun unloadChunk(chunk: WorldChunk)
|
||||
|
||||
companion object {
|
||||
@JvmField val EVENT: Event<ClientChunkLoadCallback> = EventFactory.createArrayBacked(ClientChunkLoadCallback::class.java) { listeners ->
|
||||
object : ClientChunkLoadCallback {
|
||||
override fun loadChunk(chunk: WorldChunk) { listeners.forEach { it.loadChunk(chunk) } }
|
||||
override fun unloadChunk(chunk: WorldChunk) { listeners.forEach { it.unloadChunk(chunk) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface ClientWorldLoadCallback {
|
||||
fun loadWorld(world: ClientWorld)
|
||||
|
||||
companion object {
|
||||
@JvmField val EVENT : Event<ClientWorldLoadCallback> = EventFactory.createArrayBacked(ClientWorldLoadCallback::class.java) { listeners ->
|
||||
object : ClientWorldLoadCallback {
|
||||
override fun loadWorld(world: ClientWorld) { listeners.forEach { it.loadWorld(world) } }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Event fired after [BlockModels.reload] finishes.
|
||||
*/
|
||||
interface BlockModelsReloadCallback {
|
||||
fun reloadBlockModels(blockModels: BlockModels)
|
||||
|
||||
companion object {
|
||||
@JvmField val EVENT: Event<BlockModelsReloadCallback> = EventFactory.createArrayBacked(BlockModelsReloadCallback::class.java) { listeners ->
|
||||
object : BlockModelsReloadCallback {
|
||||
override fun reloadBlockModels(blockModels: BlockModels) {
|
||||
listeners.forEach { it.reloadBlockModels(blockModels) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Event fired when the [ModelLoader] first starts loading models.
|
||||
*
|
||||
* This happens during the constructor, so BEWARE!
|
||||
* Try to avoid any interaction until the block texture atlas starts stitching.
|
||||
*/
|
||||
interface ModelLoadingCallback {
|
||||
fun beginLoadModels(loader: ModelLoader, manager: ResourceManager)
|
||||
|
||||
companion object {
|
||||
@JvmField val EVENT: Event<ModelLoadingCallback> = EventFactory.createArrayBacked(ModelLoadingCallback::class.java) { listeners ->
|
||||
object : ModelLoadingCallback {
|
||||
override fun beginLoadModels(loader: ModelLoader, manager: ResourceManager) {
|
||||
listeners.forEach { it.beginLoadModels(loader, manager) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
67
src/main/kotlin/mods/betterfoliage/Hooks.kt
Normal file
67
src/main/kotlin/mods/betterfoliage/Hooks.kt
Normal file
@@ -0,0 +1,67 @@
|
||||
@file:JvmName("Hooks")
|
||||
package mods.betterfoliage
|
||||
|
||||
import mods.betterfoliage.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.render.block.vanilla.LeafParticleKey
|
||||
import mods.betterfoliage.render.block.vanilla.RoundLogKey
|
||||
import mods.betterfoliage.render.particle.FallingLeafParticle
|
||||
import mods.betterfoliage.render.particle.RisingSoulParticle
|
||||
import mods.betterfoliage.util.offset
|
||||
import mods.betterfoliage.util.plus
|
||||
import mods.betterfoliage.util.random
|
||||
import mods.betterfoliage.util.randomD
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.client.MinecraftClient
|
||||
import net.minecraft.client.world.ClientWorld
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction
|
||||
import net.minecraft.util.shape.VoxelShape
|
||||
import net.minecraft.util.shape.VoxelShapes
|
||||
import net.minecraft.world.BlockView
|
||||
|
||||
fun getAmbientOcclusionLightValueOverride(original: Float, state: BlockState): Float {
|
||||
if (BetterFoliage.config.enabled &&
|
||||
BetterFoliage.config.roundLogs.enabled &&
|
||||
BetterFoliage.blockTypes.hasTyped<RoundLogKey>(state)
|
||||
) return BetterFoliage.config.roundLogs.dimming.toFloat()
|
||||
return original
|
||||
}
|
||||
|
||||
fun getUseNeighborBrightnessOverride(original: Boolean, state: BlockState): Boolean {
|
||||
return original || (BetterFoliage.config.enabled && BetterFoliage.config.roundLogs.enabled && BetterFoliage.blockConfig.logBlocks.matchesClass(state.block));
|
||||
}
|
||||
|
||||
fun onClientBlockChanged(worldClient: ClientWorld, pos: BlockPos, oldState: BlockState, newState: BlockState) {
|
||||
ChunkOverlayManager.onBlockChange(worldClient, pos)
|
||||
}
|
||||
|
||||
fun onRandomDisplayTick(world: ClientWorld, pos: BlockPos) {
|
||||
val state = world.getBlockState(pos)
|
||||
|
||||
if (BetterFoliage.config.enabled &&
|
||||
BetterFoliage.config.risingSoul.enabled &&
|
||||
state.block == Blocks.SOUL_SAND &&
|
||||
world.isAir(pos + Direction.UP.offset) &&
|
||||
Math.random() < BetterFoliage.config.risingSoul.chance) {
|
||||
RisingSoulParticle(world, pos).addIfValid()
|
||||
}
|
||||
|
||||
if (BetterFoliage.config.enabled &&
|
||||
BetterFoliage.config.fallingLeaves.enabled &&
|
||||
world.isAir(pos + Direction.DOWN.offset) &&
|
||||
randomD() < BetterFoliage.config.fallingLeaves.chance) {
|
||||
BetterFoliage.blockTypes.getTyped<LeafParticleKey>(state)?.let { key ->
|
||||
val blockColor = MinecraftClient.getInstance().blockColors.getColor(state, world, pos, 0)
|
||||
FallingLeafParticle(world, pos, key, blockColor, random).addIfValid()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getVoxelShapeOverride(state: BlockState, reader: BlockView, pos: BlockPos, dir: Direction): VoxelShape {
|
||||
if (BetterFoliage.blockTypes.hasTyped<RoundLogKey>(state)) {
|
||||
return VoxelShapes.empty()
|
||||
}
|
||||
// TODO ?
|
||||
return state.getCullingFace(reader, pos, dir)
|
||||
}
|
||||
60
src/main/kotlin/mods/betterfoliage/chunk/BlockContext.kt
Normal file
60
src/main/kotlin/mods/betterfoliage/chunk/BlockContext.kt
Normal file
@@ -0,0 +1,60 @@
|
||||
package mods.betterfoliage.chunk
|
||||
|
||||
import mods.betterfoliage.ChunkRendererRegion_world
|
||||
import mods.betterfoliage.util.Int3
|
||||
import mods.betterfoliage.util.allDirections
|
||||
import mods.betterfoliage.util.offset
|
||||
import mods.betterfoliage.util.plus
|
||||
import net.minecraft.block.Block
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.MinecraftClient
|
||||
import net.minecraft.client.render.chunk.ChunkRendererRegion
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import net.minecraft.world.WorldView
|
||||
import net.minecraft.world.biome.Biome
|
||||
|
||||
/**
|
||||
* Represents the block being rendered. Has properties and methods to query the neighborhood of the block in
|
||||
* block-relative coordinates.
|
||||
*/
|
||||
interface BlockCtx {
|
||||
val world: BlockRenderView
|
||||
val pos: BlockPos
|
||||
|
||||
fun offset(dir: Direction) = offset(dir.offset)
|
||||
fun offset(offset: Int3): BlockCtx
|
||||
|
||||
val state: BlockState get() = world.getBlockState(pos)
|
||||
fun state(dir: Direction) = world.getBlockState(pos + dir.offset)
|
||||
fun state(offset: Int3) = world.getBlockState(pos + offset)
|
||||
|
||||
val biome: Biome? get() =
|
||||
(world as? WorldView)?.getBiome(pos) ?:
|
||||
(world as? ChunkRendererRegion)?.let { ChunkRendererRegion_world[it]?.getBiome(pos) }
|
||||
|
||||
val isNormalCube: Boolean get() = state.isOpaqueFullCube(world, pos)
|
||||
|
||||
fun shouldSideBeRendered(side: Direction) = Block.shouldDrawSide(state, world, pos, side)
|
||||
|
||||
fun isNeighborSolid(dir: Direction) = offset(dir).let { it.state.isSideSolidFullSquare(it.world, it.pos, dir.opposite) }
|
||||
|
||||
fun model(dir: Direction) = state(dir).let { MinecraftClient.getInstance().blockRenderManager.getModel(it)!! }
|
||||
fun model(offset: Int3) = state(offset).let { MinecraftClient.getInstance().blockRenderManager.getModel(it)!! }
|
||||
}
|
||||
|
||||
open class BasicBlockCtx(
|
||||
override val world: BlockRenderView,
|
||||
override val pos: BlockPos
|
||||
) : BlockCtx {
|
||||
override val state = world.getBlockState(pos)
|
||||
override fun offset(offset: Int3) = BasicBlockCtx(world, pos + offset)
|
||||
fun cache() = CachedBlockCtx(world, pos)
|
||||
}
|
||||
|
||||
open class CachedBlockCtx(world: BlockRenderView, pos: BlockPos) : BasicBlockCtx(world, pos) {
|
||||
var neighbors = Array<BlockState>(6) { world.getBlockState(pos + allDirections[it].offset) }
|
||||
override var biome: Biome? = super.biome
|
||||
override fun state(dir: Direction) = neighbors[dir.ordinal]
|
||||
}
|
||||
@@ -1,11 +1,9 @@
|
||||
package mods.octarinecore.client.render
|
||||
package mods.betterfoliage.chunk
|
||||
|
||||
import mods.octarinecore.common.Int3
|
||||
import mods.octarinecore.common.plus
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.world.IBlockReader
|
||||
import net.minecraft.world.IEnviromentBlockReader
|
||||
import net.minecraft.world.BlockView
|
||||
import net.minecraft.world.LightType
|
||||
import net.minecraft.world.WorldView
|
||||
|
||||
/**
|
||||
* Delegating [IBlockAccess] that fakes a _modified_ location to return values from a _target_ location.
|
||||
@@ -14,24 +12,24 @@ import net.minecraft.world.LightType
|
||||
* @param[original] the [IBlockAccess] that is delegated to
|
||||
*/
|
||||
@Suppress("NOTHING_TO_INLINE", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS", "HasPlatformType")
|
||||
open class OffsetBlockReader(open val original: IBlockReader, val modded: BlockPos, val target: BlockPos) : IBlockReader {
|
||||
open class OffsetBlockView(open val original: BlockView, val modded: BlockPos, val target: BlockPos) : BlockView {
|
||||
inline fun actualPos(pos: BlockPos) = if (pos != null && pos.x == modded.x && pos.y == modded.y && pos.z == modded.z) target else pos
|
||||
|
||||
override fun getBlockState(pos: BlockPos) = original.getBlockState(actualPos(pos))
|
||||
override fun getTileEntity(pos: BlockPos) = original.getTileEntity(actualPos(pos))
|
||||
override fun getBlockEntity(pos: BlockPos) = original.getBlockEntity(actualPos(pos))
|
||||
override fun getFluidState(pos: BlockPos) = original.getFluidState(actualPos(pos))
|
||||
}
|
||||
|
||||
@Suppress("NOTHING_TO_INLINE", "NULLABILITY_MISMATCH_BASED_ON_JAVA_ANNOTATIONS", "HasPlatformType")
|
||||
class OffsetEnvBlockReader(val original: IEnviromentBlockReader, val modded: BlockPos, val target: BlockPos) : IEnviromentBlockReader by original {
|
||||
class OffsetExtBlockView(val original: WorldView, val modded: BlockPos, val target: BlockPos) : WorldView by original {
|
||||
inline fun actualPos(pos: BlockPos) = if (pos != null && pos.x == modded.x && pos.y == modded.y && pos.z == modded.z) target else pos
|
||||
|
||||
override fun getBlockState(pos: BlockPos) = original.getBlockState(actualPos(pos))
|
||||
override fun getTileEntity(pos: BlockPos) = original.getTileEntity(actualPos(pos))
|
||||
override fun getBlockEntity(pos: BlockPos) = original.getBlockEntity(actualPos(pos))
|
||||
override fun getFluidState(pos: BlockPos) = original.getFluidState(actualPos(pos))
|
||||
|
||||
override fun getLightFor(type: LightType, pos: BlockPos) = original.getLightFor(type, actualPos(pos))
|
||||
override fun getCombinedLight(pos: BlockPos, light: Int) = original.getCombinedLight(actualPos(pos), light)
|
||||
override fun getLightLevel(type: LightType, pos: BlockPos) = original.getLightLevel(type, actualPos(pos))
|
||||
override fun getBaseLightLevel(pos: BlockPos, light: Int) = original.getBaseLightLevel(actualPos(pos), light)
|
||||
override fun getBiome(pos: BlockPos) = original.getBiome(actualPos(pos))
|
||||
}
|
||||
|
||||
@@ -1,20 +1,17 @@
|
||||
package mods.betterfoliage.client.chunk
|
||||
package mods.betterfoliage.chunk
|
||||
|
||||
import mods.octarinecore.ChunkCacheOF
|
||||
import mods.octarinecore.client.render.BlockCtx
|
||||
import mods.octarinecore.metaprog.get
|
||||
import mods.octarinecore.metaprog.isInstance
|
||||
import net.minecraft.client.renderer.chunk.ChunkRenderCache
|
||||
import mods.betterfoliage.*
|
||||
import mods.betterfoliage.util.YarnHelper
|
||||
import mods.betterfoliage.util.get
|
||||
import net.minecraft.client.render.chunk.ChunkRendererRegion
|
||||
import net.minecraft.client.world.ClientWorld
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.ChunkPos
|
||||
import net.minecraft.world.IEnviromentBlockReader
|
||||
import net.minecraft.world.IWorldReader
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import net.minecraft.world.World
|
||||
import net.minecraft.world.WorldView
|
||||
import net.minecraft.world.chunk.WorldChunk
|
||||
import net.minecraft.world.dimension.DimensionType
|
||||
import net.minecraftforge.common.MinecraftForge
|
||||
import net.minecraftforge.event.world.ChunkEvent
|
||||
import net.minecraftforge.event.world.WorldEvent
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent
|
||||
import java.util.*
|
||||
import kotlin.collections.List
|
||||
import kotlin.collections.MutableMap
|
||||
@@ -24,10 +21,10 @@ import kotlin.collections.mutableListOf
|
||||
import kotlin.collections.mutableMapOf
|
||||
import kotlin.collections.set
|
||||
|
||||
val IEnviromentBlockReader.dimType: DimensionType get() = when {
|
||||
this is IWorldReader -> dimension.type
|
||||
this is ChunkRenderCache -> world.dimension.type
|
||||
this.isInstance(ChunkCacheOF) -> this[ChunkCacheOF.chunkCache].world.dimension.type
|
||||
val BlockRenderView.dimType: DimensionType get() = when {
|
||||
this is WorldView -> dimension
|
||||
this is ChunkRendererRegion -> this[ChunkRendererRegion_world]!!.dimension
|
||||
// this.isInstance(ChunkCacheOF) -> this[ChunkCacheOF.chunkCache]!!.dimType
|
||||
else -> throw IllegalArgumentException("DimensionType of world with class ${this::class.qualifiedName} cannot be determined!")
|
||||
}
|
||||
|
||||
@@ -36,18 +33,17 @@ val IEnviromentBlockReader.dimType: DimensionType get() = when {
|
||||
*/
|
||||
interface ChunkOverlayLayer<T> {
|
||||
fun calculate(ctx: BlockCtx): T
|
||||
fun onBlockUpdate(world: IEnviromentBlockReader, pos: BlockPos)
|
||||
fun onBlockUpdate(world: WorldView, pos: BlockPos)
|
||||
}
|
||||
|
||||
/**
|
||||
* Query, lazy calculation and lifecycle management of multiple layers of chunk overlay data.
|
||||
*/
|
||||
object ChunkOverlayManager {
|
||||
|
||||
var tempCounter = 0
|
||||
object ChunkOverlayManager : ClientChunkLoadCallback, ClientWorldLoadCallback {
|
||||
|
||||
init {
|
||||
MinecraftForge.EVENT_BUS.register(this)
|
||||
ClientWorldLoadCallback.EVENT.register(this)
|
||||
ClientChunkLoadCallback.EVENT.register(this)
|
||||
}
|
||||
|
||||
val chunkData = IdentityHashMap<DimensionType, MutableMap<ChunkPos, ChunkOverlayData>>()
|
||||
@@ -86,27 +82,25 @@ object ChunkOverlayManager {
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
fun handleLoadWorld(event: WorldEvent.Load) = (event.world as? ClientWorld)?.let { world ->
|
||||
chunkData[world.dimType] = mutableMapOf()
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
fun handleUnloadWorld(event: WorldEvent.Unload) = (event.world as? ClientWorld)?.let { world ->
|
||||
chunkData.remove(world.dimType)
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
fun handleLoadChunk(event: ChunkEvent.Load) = (event.world as? ClientWorld)?.let { world ->
|
||||
chunkData[world.dimType]?.let { chunks ->
|
||||
// check for existence first because Optifine fires a TON of these
|
||||
if (event.chunk.pos !in chunks.keys) chunks[event.chunk.pos] = ChunkOverlayData(layers)
|
||||
override fun loadChunk(chunk: WorldChunk) {
|
||||
chunk[WorldChunk_world]!!.dimType.let { dim ->
|
||||
val data = chunkData[dim] ?: mutableMapOf<ChunkPos, ChunkOverlayData>().apply { chunkData[dim] = this }
|
||||
data.let { chunks ->
|
||||
// check for existence first because Optifine fires a TON of these
|
||||
if (chunk.pos !in chunks.keys) chunks[chunk.pos] = ChunkOverlayData(layers)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
fun handleUnloadChunk(event: ChunkEvent.Unload) = (event.world as? ClientWorld)?.let { world ->
|
||||
chunkData[world.dimType]?.remove(event.chunk.pos)
|
||||
override fun unloadChunk(chunk: WorldChunk) {
|
||||
chunk[WorldChunk_world]!!.dimType.let { dim ->
|
||||
chunkData[dim]?.remove(chunk.pos)
|
||||
}
|
||||
}
|
||||
|
||||
override fun loadWorld(world: ClientWorld) {
|
||||
val dim = world.dimType
|
||||
// chunkData.keys.forEach { if (it == dim) chunkData[dim] = mutableMapOf() else chunkData.remove(dim)}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
package mods.betterfoliage.client
|
||||
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.integration.*
|
||||
import mods.betterfoliage.client.render.*
|
||||
import mods.betterfoliage.client.texture.AsyncGrassDiscovery
|
||||
import mods.betterfoliage.client.texture.AsyncLeafDiscovery
|
||||
import mods.betterfoliage.client.texture.LeafParticleRegistry
|
||||
import mods.octarinecore.client.gui.textComponent
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.client.resource.IConfigChangeListener
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.text.TextFormatting
|
||||
import net.minecraft.util.text.TranslationTextComponent
|
||||
import net.minecraftforge.registries.ForgeRegistries
|
||||
import org.apache.logging.log4j.Level
|
||||
|
||||
/**
|
||||
* Object responsible for initializing (and holding a reference to) all the infrastructure of the mod
|
||||
* except for the call hooks.
|
||||
*/
|
||||
object Client {
|
||||
var renderers= emptyList<RenderDecorator>()
|
||||
var configListeners = emptyList<IConfigChangeListener>()
|
||||
|
||||
val suppressRenderErrors = mutableSetOf<BlockState>()
|
||||
|
||||
fun init() {
|
||||
// init renderers
|
||||
renderers = listOf(
|
||||
RenderGrass(),
|
||||
RenderMycelium(),
|
||||
RenderLeaves(),
|
||||
RenderCactus(),
|
||||
RenderLilypad(),
|
||||
RenderReeds(),
|
||||
RenderAlgae(),
|
||||
RenderCoral(),
|
||||
RenderLog(),
|
||||
RenderNetherrack(),
|
||||
RenderConnectedGrass(),
|
||||
RenderConnectedGrassLog()
|
||||
)
|
||||
|
||||
// init other singletons
|
||||
val singletons = listOf(
|
||||
BlockConfig,
|
||||
ChunkOverlayManager,
|
||||
LeafWindTracker,
|
||||
RisingSoulTextures
|
||||
)
|
||||
|
||||
// init mod integrations
|
||||
val integrations = listOf(
|
||||
ShadersModIntegration,
|
||||
OptifineCustomColors,
|
||||
ForestryIntegration,
|
||||
IC2RubberIntegration,
|
||||
TechRebornRubberIntegration
|
||||
)
|
||||
|
||||
LeafParticleRegistry.init()
|
||||
|
||||
// add basic block support instances as last
|
||||
AsyncLeafDiscovery.init()
|
||||
AsyncGrassDiscovery.init()
|
||||
AsyncLogDiscovery.init()
|
||||
AsyncCactusDiscovery.init()
|
||||
|
||||
configListeners = listOf(renderers, singletons, integrations).flatten().filterIsInstance<IConfigChangeListener>()
|
||||
configListeners.forEach { it.onConfigChange() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
@file:JvmName("Hooks")
|
||||
package mods.betterfoliage.client
|
||||
|
||||
import mods.betterfoliage.client.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.render.*
|
||||
import mods.octarinecore.ThreadLocalDelegate
|
||||
import mods.octarinecore.client.render.*
|
||||
import mods.octarinecore.client.render.lighting.DefaultLightingCtx
|
||||
import mods.octarinecore.common.plus
|
||||
import net.minecraft.block.Block
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.client.renderer.BlockRendererDispatcher
|
||||
import net.minecraft.client.renderer.BufferBuilder
|
||||
import net.minecraft.client.world.ClientWorld
|
||||
import net.minecraft.util.BlockRenderLayer
|
||||
import net.minecraft.util.BlockRenderLayer.CUTOUT
|
||||
import net.minecraft.util.BlockRenderLayer.CUTOUT_MIPPED
|
||||
import net.minecraft.util.Direction
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.shapes.VoxelShape
|
||||
import net.minecraft.util.math.shapes.VoxelShapes
|
||||
import net.minecraft.world.IBlockReader
|
||||
import net.minecraft.world.IEnviromentBlockReader
|
||||
import net.minecraft.world.World
|
||||
import net.minecraftforge.client.model.data.IModelData
|
||||
import java.util.*
|
||||
|
||||
fun getAmbientOcclusionLightValueOverride(original: Float, state: BlockState): Float {
|
||||
if (Config.enabled && Config.roundLogs.enabled && BlockConfig.logBlocks.matchesClass(state.block)) return Config.roundLogs.dimming.toFloat();
|
||||
return original
|
||||
}
|
||||
|
||||
fun getUseNeighborBrightnessOverride(original: Boolean, state: BlockState): Boolean {
|
||||
return original || (Config.enabled && Config.roundLogs.enabled && BlockConfig.logBlocks.matchesClass(state.block));
|
||||
}
|
||||
|
||||
fun onClientBlockChanged(worldClient: ClientWorld, pos: BlockPos, oldState: BlockState, newState: BlockState, flags: Int) {
|
||||
ChunkOverlayManager.onBlockChange(worldClient, pos)
|
||||
}
|
||||
|
||||
fun onRandomDisplayTick(block: Block, state: BlockState, world: World, pos: BlockPos, random: Random) {
|
||||
if (Config.enabled &&
|
||||
Config.risingSoul.enabled &&
|
||||
state.block == Blocks.SOUL_SAND &&
|
||||
world.isAirBlock(pos + up1) &&
|
||||
Math.random() < Config.risingSoul.chance) {
|
||||
EntityRisingSoulFX(world, pos).addIfValid()
|
||||
}
|
||||
|
||||
if (Config.enabled &&
|
||||
Config.fallingLeaves.enabled &&
|
||||
BlockConfig.leafBlocks.matchesClass(state.block) &&
|
||||
world.isAirBlock(pos + down1) &&
|
||||
Math.random() < Config.fallingLeaves.chance) {
|
||||
EntityFallingLeavesFX(world, pos).addIfValid()
|
||||
}
|
||||
}
|
||||
|
||||
fun getVoxelShapeOverride(state: BlockState, reader: IBlockReader, pos: BlockPos, dir: Direction): VoxelShape {
|
||||
if (LogRegistry[state, reader, pos] != null) return VoxelShapes.empty()
|
||||
return state.func_215702_a(reader, pos, dir)
|
||||
}
|
||||
|
||||
val lightingCtx by ThreadLocalDelegate { DefaultLightingCtx(BasicBlockCtx(NonNullWorld, BlockPos.ZERO)) }
|
||||
fun renderWorldBlock(dispatcher: BlockRendererDispatcher,
|
||||
state: BlockState,
|
||||
pos: BlockPos,
|
||||
reader: IEnviromentBlockReader,
|
||||
buffer: BufferBuilder,
|
||||
random: Random,
|
||||
modelData: IModelData,
|
||||
layer: BlockRenderLayer
|
||||
): Boolean {
|
||||
// build context
|
||||
val blockCtx = CachedBlockCtx(reader, pos)
|
||||
val renderCtx = RenderCtx(dispatcher, buffer, layer, random)
|
||||
lightingCtx.reset(blockCtx)
|
||||
val combinedCtx = CombinedContext(blockCtx, renderCtx, lightingCtx)
|
||||
|
||||
// loop render decorators
|
||||
val doBaseRender = state.canRenderInLayer(layer) || (layer == targetCutoutLayer && state.canRenderInLayer(otherCutoutLayer))
|
||||
Client.renderers.forEach { renderer ->
|
||||
if (renderer.isEligible(combinedCtx)) {
|
||||
// render on the block's default layer
|
||||
// also render on the cutout layer if the renderer requires it
|
||||
|
||||
val doCutoutRender = renderer.renderOnCutout && layer == targetCutoutLayer
|
||||
val stopRender = renderer.onlyOnCutout && !layer.isCutout
|
||||
|
||||
if ((doBaseRender || doCutoutRender) && !stopRender) {
|
||||
renderer.render(combinedCtx)
|
||||
return combinedCtx.hasRendered
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// no render decorators have taken on this block, proceed to normal rendering
|
||||
combinedCtx.render()
|
||||
return combinedCtx.hasRendered
|
||||
}
|
||||
|
||||
fun canRenderInLayerOverride(state: BlockState, layer: BlockRenderLayer) = state.canRenderInLayer(layer) || layer == targetCutoutLayer
|
||||
|
||||
fun canRenderInLayerOverrideOptifine(state: BlockState, optifineReflector: Any?, layerArray: Array<Any>) =
|
||||
canRenderInLayerOverride(state, layerArray[0] as BlockRenderLayer)
|
||||
|
||||
val targetCutoutLayer: BlockRenderLayer get() = if (Minecraft.getInstance().gameSettings.mipmapLevels > 0) CUTOUT_MIPPED else CUTOUT
|
||||
val otherCutoutLayer: BlockRenderLayer get() = if (Minecraft.getInstance().gameSettings.mipmapLevels > 0) CUTOUT else CUTOUT_MIPPED
|
||||
@@ -1,172 +0,0 @@
|
||||
package mods.betterfoliage.client.config
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration
|
||||
import mods.octarinecore.common.config.*
|
||||
import net.minecraft.util.ResourceLocation
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent
|
||||
import net.minecraftforge.fml.config.ModConfig
|
||||
|
||||
private fun featureEnable() = boolean(true).lang("enabled")
|
||||
|
||||
// Config singleton
|
||||
object Config : DelegatingConfig(BetterFoliageMod.MOD_ID, BetterFoliageMod.MOD_ID) {
|
||||
|
||||
val enabled by boolean(true)
|
||||
val nVidia by boolean(false)
|
||||
|
||||
object leaves : ConfigCategory() {
|
||||
val enabled by featureEnable()
|
||||
val snowEnabled by boolean(true)
|
||||
val hOffset by double(max=0.4, default=0.2).lang("hOffset")
|
||||
val vOffset by double(max=0.4, default=0.1).lang("vOffset")
|
||||
val size by double(min=0.75, max=2.5, default=1.4).lang("size")
|
||||
val dense by boolean(false)
|
||||
val hideInternal by boolean(true)
|
||||
}
|
||||
|
||||
object shortGrass : ConfigCategory(){
|
||||
val grassEnabled by boolean(true)
|
||||
val myceliumEnabled by boolean(true)
|
||||
val snowEnabled by boolean(true)
|
||||
val hOffset by double(max=0.4, default=0.2).lang("hOffset")
|
||||
val heightMin by double(min=0.1, max=2.5, default=0.6).lang("heightMin")
|
||||
val heightMax by double(min=0.1, max=2.5, default=0.8).lang("heightMax")
|
||||
val size by double(min=0.5, max=1.5, default=1.0).lang("size")
|
||||
val population by int(max=64, default=64).lang("population")
|
||||
val useGenerated by boolean(false)
|
||||
val shaderWind by boolean(true).lang("shaderWind")
|
||||
val saturationThreshold by double(default=0.1)
|
||||
}
|
||||
|
||||
object connectedGrass : ConfigCategory(){
|
||||
val enabled by boolean(true)
|
||||
val snowEnabled by boolean(false)
|
||||
}
|
||||
|
||||
object roundLogs : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val radiusSmall by double(max=0.5, default=0.25)
|
||||
val radiusLarge by double(max=0.5, default=0.44)
|
||||
val dimming by double(default = 0.7)
|
||||
val connectSolids by boolean(false)
|
||||
val lenientConnect by boolean(true)
|
||||
val connectPerpendicular by boolean(true)
|
||||
val connectGrass by boolean(true)
|
||||
val defaultY by boolean(false)
|
||||
val zProtection by double(min = 0.9, default = 0.99)
|
||||
}
|
||||
|
||||
object cactus : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val size by double(min=0.5, max=1.5, default=0.8).lang("size")
|
||||
val sizeVariation by double(max=0.5, default=0.1)
|
||||
val hOffset by double(max=0.5, default=0.1).lang("hOffset")
|
||||
}
|
||||
|
||||
object lilypad : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val hOffset by double(max=0.25, default=0.1).lang("hOffset")
|
||||
val flowerChance by int(max=64, default=16, min=0)
|
||||
}
|
||||
|
||||
object reed : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val hOffset by double(max=0.4, default=0.2).lang("hOffset")
|
||||
val heightMin by double(min=1.5, max=3.5, default=1.7).lang("heightMin")
|
||||
val heightMax by double(min=1.5, max=3.5, default=2.2).lang("heightMax")
|
||||
val population by int(max=64, default=32).lang("population")
|
||||
val minBiomeTemp by double(default=0.4)
|
||||
val minBiomeRainfall by double(default=0.4)
|
||||
// val biomes by biomeList { it.filterTemp(0.4f, null) && it.filterRain(0.4f, null) }
|
||||
val shaderWind by boolean(true).lang("shaderWind")
|
||||
}
|
||||
|
||||
object algae : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val hOffset by double(max=0.25, default=0.1).lang("hOffset")
|
||||
val size by double(min=0.5, max=1.5, default=1.0).lang("size")
|
||||
val heightMin by double(min=0.1, max=1.5, default=0.5).lang("heightMin")
|
||||
val heightMax by double(min=0.1, max=1.5, default=1.0).lang("heightMax")
|
||||
val population by int(max=64, default=48).lang("population")
|
||||
// val biomes by biomeList { it.filterClass("river", "ocean") }
|
||||
val shaderWind by boolean(true).lang("shaderWind")
|
||||
}
|
||||
|
||||
object coral : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val shallowWater by boolean(false)
|
||||
val hOffset by double(max=0.4, default=0.2).lang("hOffset")
|
||||
val vOffset by double(max=0.4, default=0.1).lang("vOffset")
|
||||
val size by double(min=0.5, max=1.5, default=0.7).lang("size")
|
||||
val crustSize by double(min=0.5, max=1.5, default=1.4)
|
||||
val chance by int(max=64, default=32)
|
||||
val population by int(max=64, default=48).lang("population")
|
||||
// val biomes by biomeList { it.filterClass("river", "ocean", "beach") }
|
||||
}
|
||||
|
||||
object netherrack : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val hOffset by double(max=0.4, default=0.2).lang("hOffset")
|
||||
val heightMin by double(min=0.1, max=1.5, default=0.6).lang("heightMin")
|
||||
val heightMax by double(min=0.1, max=1.5, default=0.8).lang("heightMax")
|
||||
val size by double(min=0.5, max=1.5, default=1.0).lang("size")
|
||||
}
|
||||
|
||||
object fallingLeaves : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val speed by double(min=0.01, max=0.15, default=0.05)
|
||||
val windStrength by double(min=0.1, max=2.0, default=0.5)
|
||||
val stormStrength by double(min=0.1, max=2.0, default=0.8)
|
||||
val size by double(min=0.25, max=1.5, default=0.75).lang("size")
|
||||
val chance by double(min=0.001, max=1.0, default=0.05)
|
||||
val perturb by double(min=0.01, max=1.0, default=0.25)
|
||||
val lifetime by double(min=1.0, max=15.0, default=5.0)
|
||||
val opacityHack by boolean(true)
|
||||
}
|
||||
|
||||
object risingSoul : ConfigCategory(){
|
||||
val enabled by featureEnable()
|
||||
val chance by double(min=0.001, max=1.0, default=0.02)
|
||||
val perturb by double(min=0.01, max=0.25, default=0.05)
|
||||
val headSize by double(min=0.25, max=1.5, default=1.0)
|
||||
val trailSize by double(min=0.25, max=1.5, default=0.75)
|
||||
val opacity by double(min=0.05, max=1.0, default=0.5)
|
||||
val sizeDecay by double(min=0.5, max=1.0, default=0.97)
|
||||
val opacityDecay by double(min=0.5, max=1.0, default=0.97)
|
||||
val lifetime by double(min=1.0, max=15.0, default=4.0)
|
||||
val trailLength by int(min=2, max=128, default=48)
|
||||
val trailDensity by int(min=1, max=16, default=3)
|
||||
}
|
||||
}
|
||||
|
||||
object BlockConfig {
|
||||
private val list = mutableListOf<Any>()
|
||||
|
||||
val leafBlocks = blocks("leaves_blocks_default.cfg")
|
||||
val leafModels = models("leaves_models_default.cfg")
|
||||
val grassBlocks = blocks("grass_blocks_default.cfg")
|
||||
val grassModels = models("grass_models_default.cfg")
|
||||
val mycelium = blocks("mycelium_blocks_default.cfg")
|
||||
// val dirt = blocks("dirt_default.cfg")
|
||||
val crops = blocks("crop_default.cfg")
|
||||
val logBlocks = blocks("log_blocks_default.cfg")
|
||||
val logModels = models("log_models_default.cfg")
|
||||
val sand = blocks("sand_default.cfg")
|
||||
val lilypad = blocks("lilypad_default.cfg")
|
||||
val cactus = blocks("cactus_default.cfg")
|
||||
val netherrack = blocks("netherrack_blocks_default.cfg")
|
||||
|
||||
init { BetterFoliageMod.bus.register(this) }
|
||||
private fun blocks(cfgName: String) = ConfigurableBlockMatcher(BetterFoliage.logDetail, ResourceLocation(BetterFoliageMod.MOD_ID, cfgName)).apply { list.add(this) }
|
||||
private fun models(cfgName: String) = ModelTextureListConfiguration(BetterFoliage.logDetail, ResourceLocation(BetterFoliageMod.MOD_ID, cfgName)).apply { list.add(this) }
|
||||
|
||||
@SubscribeEvent
|
||||
fun onConfig(event: ModConfig.ModConfigEvent) {
|
||||
list.forEach { when(it) {
|
||||
is ConfigurableBlockMatcher -> it.readDefaults()
|
||||
is ModelTextureListConfiguration -> it.readDefaults()
|
||||
} }
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
package mods.betterfoliage.client.integration
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.render.AsyncLogDiscovery
|
||||
import mods.betterfoliage.client.render.column.ColumnTextureInfo
|
||||
import mods.betterfoliage.client.render.column.SimpleColumnInfo
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.betterfoliage.client.texture.LeafInfo
|
||||
import mods.betterfoliage.client.texture.defaultRegisterLeaf
|
||||
import mods.octarinecore.HasLogger
|
||||
import mods.octarinecore.Map
|
||||
import mods.octarinecore.ResourceLocation
|
||||
import mods.octarinecore.String
|
||||
import mods.octarinecore.client.resource.*
|
||||
import mods.octarinecore.metaprog.*
|
||||
import mods.octarinecore.metaprog.ClassRef.Companion.boolean
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.client.renderer.model.ModelBakery
|
||||
import net.minecraft.resources.IResourceManager
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.world.IBlockReader
|
||||
import net.minecraftforge.fml.ModList
|
||||
import org.apache.logging.log4j.Level
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import kotlin.collections.component1
|
||||
import kotlin.collections.component2
|
||||
|
||||
val TextureLeaves = ClassRef<Any>("forestry.arboriculture.models.TextureLeaves")
|
||||
val TextureLeaves_leafTextures = FieldRef(TextureLeaves, "leafTextures", Map)
|
||||
val TextureLeaves_plain = FieldRef(TextureLeaves, "plain", ResourceLocation)
|
||||
val TextureLeaves_fancy = FieldRef(TextureLeaves, "fancy", ResourceLocation)
|
||||
val TextureLeaves_pollinatedPlain = FieldRef(TextureLeaves, "pollinatedPlain", ResourceLocation)
|
||||
val TextureLeaves_pollinatedFancy = FieldRef(TextureLeaves, "pollinatedFancy", ResourceLocation)
|
||||
|
||||
|
||||
val TileLeaves = ClassRef<Any>("forestry.arboriculture.tiles.TileLeaves")
|
||||
val TileLeaves_getLeaveSprite = MethodRef(TileLeaves, "getLeaveSprite", ResourceLocation, boolean)
|
||||
val PropertyWoodType = ClassRef<Any>("forestry.arboriculture.blocks.PropertyWoodType")
|
||||
val IWoodType = ClassRef<Any>("forestry.api.arboriculture.IWoodType")
|
||||
val IWoodType_barkTex = MethodRef(IWoodType, "getBarkTexture", String)
|
||||
val IWoodType_heartTex = MethodRef(IWoodType, "getHeartTexture", String)
|
||||
|
||||
val PropertyTreeType = ClassRef<Any>("forestry.arboriculture.blocks.PropertyTreeType")
|
||||
val IAlleleTreeSpecies = ClassRef<Any>("forestry.api.arboriculture.IAlleleTreeSpecies")
|
||||
val ILeafSpriteProvider = ClassRef<Any>("forestry.api.arboriculture.ILeafSpriteProvider")
|
||||
val TreeDefinition = ClassRef<Any>("forestry.arboriculture.genetics.TreeDefinition")
|
||||
|
||||
val IAlleleTreeSpecies_getLeafSpriteProvider = MethodRef(IAlleleTreeSpecies, "getLeafSpriteProvider", ILeafSpriteProvider)
|
||||
val TreeDefinition_species = FieldRef(TreeDefinition, "species", IAlleleTreeSpecies)
|
||||
val ILeafSpriteProvider_getSprite = MethodRef(ILeafSpriteProvider, "getSprite", ResourceLocation, boolean, boolean)
|
||||
|
||||
object ForestryIntegration {
|
||||
init {
|
||||
if (ModList.get().isLoaded("forestry") && allAvailable(TileLeaves_getLeaveSprite, IAlleleTreeSpecies_getLeafSpriteProvider, ILeafSpriteProvider_getSprite)) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object ForestryLeafDiscovery : HasLogger, AsyncSpriteProvider<ModelBakery>, ModelRenderRegistry<LeafInfo> {
|
||||
override val logger = BetterFoliage.logDetail
|
||||
var idToValue = emptyMap<Identifier, LeafInfo>()
|
||||
|
||||
override fun get(state: BlockState, world: IBlockReader, pos: BlockPos): LeafInfo? {
|
||||
// check variant property (used in decorative leaves)
|
||||
state.values.entries.find {
|
||||
PropertyTreeType.isInstance(it.key) && TreeDefinition.isInstance(it.value)
|
||||
} ?.let {
|
||||
val species = it.value[TreeDefinition_species]
|
||||
val spriteProvider = species[IAlleleTreeSpecies_getLeafSpriteProvider]()
|
||||
val textureLoc = spriteProvider[ILeafSpriteProvider_getSprite](false, Minecraft.isFancyGraphicsEnabled())
|
||||
return idToValue[textureLoc]
|
||||
}
|
||||
|
||||
// extract leaf texture information from TileEntity
|
||||
val tile = world.getTileEntity(pos) ?: return null
|
||||
if (!TileLeaves.isInstance(tile)) return null
|
||||
val textureLoc = tile[TileLeaves_getLeaveSprite](Minecraft.isFancyGraphicsEnabled())
|
||||
return idToValue[textureLoc]
|
||||
}
|
||||
|
||||
override fun setup(manager: IResourceManager, bakeryF: CompletableFuture<ModelBakery>, atlasFuture: AtlasFuture): StitchPhases {
|
||||
val futures = mutableMapOf<Identifier, CompletableFuture<LeafInfo>>()
|
||||
|
||||
return StitchPhases(
|
||||
discovery = bakeryF.thenRunAsync {
|
||||
val allLeaves = TextureLeaves_leafTextures.getStatic()
|
||||
allLeaves.entries.forEach { (type, leaves) ->
|
||||
log("base leaf type $type")
|
||||
leaves!!
|
||||
listOf(
|
||||
leaves[TextureLeaves_plain], leaves[TextureLeaves_pollinatedPlain],
|
||||
leaves[TextureLeaves_fancy], leaves[TextureLeaves_pollinatedFancy]
|
||||
).forEach { textureLocation ->
|
||||
futures[textureLocation] = defaultRegisterLeaf(textureLocation, atlasFuture)
|
||||
}
|
||||
}
|
||||
},
|
||||
cleanup = atlasFuture.runAfter {
|
||||
idToValue = futures.mapValues { it.value.get() }
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
object ForestryLogDiscovery : ModelDiscovery<ColumnTextureInfo>() {
|
||||
override val logger = BetterFoliage.logDetail
|
||||
override fun processModel(ctx: ModelDiscoveryContext, atlas: AtlasFuture): CompletableFuture<ColumnTextureInfo>? {
|
||||
// respect class list to avoid triggering on fences, stairs, etc.
|
||||
if (!BlockConfig.logBlocks.matchesClass(ctx.state.block)) return null
|
||||
|
||||
// find wood type property
|
||||
val woodType = ctx.state.values.entries.find {
|
||||
PropertyWoodType.isInstance(it.key) && IWoodType.isInstance(it.value)
|
||||
}
|
||||
if (woodType != null) {
|
||||
logger.log(Level.DEBUG, "ForestryLogRegistry: block state ${ctx.state}")
|
||||
logger.log(Level.DEBUG, "ForestryLogRegistry: variant ${woodType.value}")
|
||||
|
||||
// get texture names for wood type
|
||||
val bark = woodType.value[IWoodType_barkTex]()
|
||||
val heart = woodType.value[IWoodType_heartTex]()
|
||||
logger.log(Level.DEBUG, "ForestryLogSupport: textures [heart=$heart, bark=$bark]")
|
||||
|
||||
val heartSprite = atlas.sprite(heart)
|
||||
val barkSprite = atlas.sprite(bark)
|
||||
return atlas.mapAfter {
|
||||
SimpleColumnInfo(AsyncLogDiscovery.getAxis(ctx.state), heartSprite.get(), heartSprite.get(), listOf(barkSprite.get()))
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package mods.betterfoliage.client.integration
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.octarinecore.*
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.metaprog.allAvailable
|
||||
import mods.octarinecore.metaprog.reflectField
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.client.renderer.model.BakedQuad
|
||||
import net.minecraft.client.renderer.vertex.DefaultVertexFormats
|
||||
import net.minecraft.util.Direction.UP
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import org.apache.logging.log4j.Level
|
||||
|
||||
/**
|
||||
* Integration for OptiFine custom block colors.
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
object OptifineCustomColors {
|
||||
|
||||
val isColorAvailable = allAvailable(CustomColors, CustomColors.getColorMultiplier)
|
||||
|
||||
init {
|
||||
BetterFoliage.log(Level.INFO, "Optifine custom color support is ${if (isColorAvailable) "enabled" else "disabled" }")
|
||||
}
|
||||
|
||||
val renderEnv by ThreadLocalDelegate { OptifineRenderEnv() }
|
||||
val fakeQuad = BakedQuad(IntArray(0), 1, UP, null, true, DefaultVertexFormats.BLOCK)
|
||||
|
||||
fun getBlockColor(ctx: CombinedContext): Int {
|
||||
val ofColor = if (isColorAvailable && Minecraft.getInstance().gameSettings.reflectField<Boolean>("ofCustomColors") == true) {
|
||||
renderEnv.reset(ctx.state, ctx.pos)
|
||||
CustomColors.getColorMultiplier.invokeStatic(fakeQuad, ctx.state, ctx.world, ctx.pos, renderEnv.wrapped) as? Int
|
||||
} else null
|
||||
return if (ofColor == null || ofColor == -1) ctx.lightingCtx.color else ofColor
|
||||
}
|
||||
}
|
||||
|
||||
class OptifineRenderEnv {
|
||||
val wrapped: Any = RenderEnv.element!!.getDeclaredConstructor(BlockState.element, BlockPos.element).let {
|
||||
it.isAccessible = true
|
||||
it.newInstance(null, null)
|
||||
}
|
||||
|
||||
fun reset(state: BlockState, pos: BlockPos) {
|
||||
RenderEnv.reset.invoke(wrapped, state, pos)
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
package mods.betterfoliage.client.integration
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.texture.GrassRegistry
|
||||
import mods.betterfoliage.client.texture.LeafRegistry
|
||||
import mods.octarinecore.*
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.metaprog.allAvailable
|
||||
import mods.octarinecore.metaprog.get
|
||||
import net.minecraft.block.BlockRenderType
|
||||
import net.minecraft.block.BlockRenderType.MODEL
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.client.renderer.BufferBuilder
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.world.IEnviromentBlockReader
|
||||
import org.apache.logging.log4j.Level.INFO
|
||||
|
||||
/**
|
||||
* Integration for ShadersMod.
|
||||
*/
|
||||
object ShadersModIntegration {
|
||||
|
||||
@JvmStatic val isAvailable = allAvailable(SVertexBuilder, SVertexBuilder.pushState, SVertexBuilder.pushNum, SVertexBuilder.pop)
|
||||
|
||||
val defaultLeaves = Blocks.OAK_LEAVES.defaultState
|
||||
val defaultGrass = Blocks.TALL_GRASS.defaultState
|
||||
|
||||
/**
|
||||
* Called from transformed ShadersMod code.
|
||||
* @see mods.betterfoliage.loader.BetterFoliageTransformer
|
||||
*/
|
||||
@JvmStatic fun getBlockStateOverride(state: BlockState, world: IEnviromentBlockReader, pos: BlockPos): BlockState {
|
||||
if (LeafRegistry[state, world, pos] != null) return defaultLeaves
|
||||
if (BlockConfig.crops.matchesClass(state.block)) return defaultGrass
|
||||
return state
|
||||
}
|
||||
|
||||
init {
|
||||
BetterFoliage.log(INFO, "ShadersMod integration is ${if (isAvailable) "enabled" else "disabled" }")
|
||||
}
|
||||
|
||||
inline fun renderAs(ctx: CombinedContext, renderType: BlockRenderType, enabled: Boolean = true, func: ()->Unit) =
|
||||
renderAs(ctx, ctx.state, renderType, enabled, func)
|
||||
|
||||
/** Quads rendered inside this block will use the given block entity data in shader programs. */
|
||||
inline fun renderAs(ctx: CombinedContext, state: BlockState, renderType: BlockRenderType, enabled: Boolean = true, func: ()->Unit) {
|
||||
if (isAvailable && enabled) {
|
||||
val buffer = ctx.renderCtx.renderBuffer
|
||||
val sVertexBuilder = buffer[BufferBuilder_sVertexBuilder]
|
||||
SVertexBuilder.pushState.invoke(sVertexBuilder, ctx.state, ctx.pos, ctx.world, buffer)
|
||||
func()
|
||||
SVertexBuilder.pop.invoke(sVertexBuilder)
|
||||
} else {
|
||||
func()
|
||||
}
|
||||
}
|
||||
|
||||
/** Quads rendered inside this block will behave as tallgrass blocks in shader programs. */
|
||||
inline fun grass(ctx: CombinedContext, enabled: Boolean = true, func: ()->Unit) =
|
||||
renderAs(ctx, defaultGrass, MODEL, enabled, func)
|
||||
|
||||
/** Quads rendered inside this block will behave as leaf blocks in shader programs. */
|
||||
inline fun leaves(ctx: CombinedContext, enabled: Boolean = true, func: ()->Unit) =
|
||||
renderAs(ctx, defaultLeaves, MODEL, enabled, func)
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.texture.LeafParticleRegistry
|
||||
import mods.betterfoliage.client.texture.LeafRegistry
|
||||
import mods.octarinecore.PI2
|
||||
import mods.octarinecore.client.render.AbstractEntityFX
|
||||
import mods.octarinecore.client.render.lighting.HSB
|
||||
import mods.octarinecore.common.Double3
|
||||
import mods.octarinecore.minmax
|
||||
import mods.octarinecore.random
|
||||
import net.minecraft.client.Minecraft
|
||||
import net.minecraft.client.renderer.BufferBuilder
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.MathHelper
|
||||
import net.minecraft.world.World
|
||||
import net.minecraftforge.common.MinecraftForge
|
||||
import net.minecraftforge.event.TickEvent
|
||||
import net.minecraftforge.event.world.WorldEvent
|
||||
import net.minecraftforge.eventbus.api.SubscribeEvent
|
||||
import org.lwjgl.opengl.GL11
|
||||
import java.util.*
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
const val rotationFactor = PI2.toFloat() / 64.0f
|
||||
|
||||
class EntityFallingLeavesFX(
|
||||
world: World, pos: BlockPos
|
||||
) : AbstractEntityFX(
|
||||
world, pos.x.toDouble() + 0.5, pos.y.toDouble(), pos.z.toDouble() + 0.5
|
||||
) {
|
||||
|
||||
companion object {
|
||||
@JvmStatic val biomeBrightnessMultiplier = 0.5f
|
||||
}
|
||||
|
||||
var particleRot = rand.nextInt(64)
|
||||
var rotPositive = true
|
||||
val isMirrored = (rand.nextInt() and 1) == 1
|
||||
var wasCollided = false
|
||||
|
||||
init {
|
||||
maxAge = MathHelper.floor(random(0.6, 1.0) * Config.fallingLeaves.lifetime * 20.0)
|
||||
motionY = -Config.fallingLeaves.speed
|
||||
|
||||
particleScale = Config.fallingLeaves.size.toFloat() * 0.1f
|
||||
|
||||
val state = world.getBlockState(pos)
|
||||
val leafInfo = LeafRegistry[state, world, pos]
|
||||
val blockColor = Minecraft.getInstance().blockColors.getColor(state, world, pos, 0)
|
||||
if (leafInfo != null) {
|
||||
sprite = leafInfo.particleTextures[rand.nextInt(1024)]
|
||||
calculateParticleColor(leafInfo.averageColor, blockColor)
|
||||
} else {
|
||||
sprite = LeafParticleRegistry["default"][rand.nextInt(1024)]
|
||||
setColor(blockColor)
|
||||
}
|
||||
}
|
||||
|
||||
override val isValid: Boolean get() = (sprite != null)
|
||||
|
||||
override fun update() {
|
||||
if (rand.nextFloat() > 0.95f) rotPositive = !rotPositive
|
||||
if (age > maxAge - 20) particleAlpha = 0.05f * (maxAge - age)
|
||||
|
||||
if (onGround || wasCollided) {
|
||||
velocity.setTo(0.0, 0.0, 0.0)
|
||||
if (!wasCollided) {
|
||||
age = Math.max(age, maxAge - 20)
|
||||
wasCollided = true
|
||||
}
|
||||
} else {
|
||||
velocity.setTo(cos[particleRot], 0.0, sin[particleRot]).mul(Config.fallingLeaves.perturb)
|
||||
.add(LeafWindTracker.current).add(0.0, -1.0, 0.0).mul(Config.fallingLeaves.speed)
|
||||
particleRot = (particleRot + (if (rotPositive) 1 else -1)) and 63
|
||||
particleAngle = rotationFactor * particleRot.toFloat()
|
||||
}
|
||||
}
|
||||
|
||||
override fun render(worldRenderer: BufferBuilder, partialTickTime: Float) {
|
||||
if (Config.fallingLeaves.opacityHack) GL11.glDepthMask(true)
|
||||
renderParticleQuad(worldRenderer, partialTickTime, rotation = particleRot, isMirrored = isMirrored)
|
||||
}
|
||||
|
||||
fun calculateParticleColor(textureAvgColor: Int, blockColor: Int) {
|
||||
val texture = HSB.fromColor(textureAvgColor)
|
||||
val block = HSB.fromColor(blockColor)
|
||||
|
||||
val weightTex = texture.saturation / (texture.saturation + block.saturation)
|
||||
val weightBlock = 1.0f - weightTex
|
||||
|
||||
// avoid circular average for hue for performance reasons
|
||||
// one of the color components should dominate anyway
|
||||
val particle = HSB(
|
||||
weightTex * texture.hue + weightBlock * block.hue,
|
||||
weightTex * texture.saturation + weightBlock * block.saturation,
|
||||
weightTex * texture.brightness + weightBlock * block.brightness * biomeBrightnessMultiplier
|
||||
)
|
||||
setColor(particle.asColor)
|
||||
}
|
||||
}
|
||||
|
||||
object LeafWindTracker {
|
||||
var random = Random()
|
||||
val target = Double3.zero
|
||||
val current = Double3.zero
|
||||
var nextChange: Long = 0
|
||||
|
||||
init {
|
||||
MinecraftForge.EVENT_BUS.register(this)
|
||||
}
|
||||
|
||||
fun changeWind(world: World) {
|
||||
nextChange = world.worldInfo.gameTime + 120 + random.nextInt(80)
|
||||
val direction = PI2 * random.nextDouble()
|
||||
val speed = abs(random.nextGaussian()) * Config.fallingLeaves.windStrength +
|
||||
(if (!world.isRaining) 0.0 else abs(random.nextGaussian()) * Config.fallingLeaves.stormStrength)
|
||||
target.setTo(cos(direction) * speed, 0.0, sin(direction) * speed)
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
fun handleWorldTick(event: TickEvent.ClientTickEvent) {
|
||||
if (event.phase == TickEvent.Phase.START) Minecraft.getInstance().world?.let { world ->
|
||||
// change target wind speed
|
||||
if (world.worldInfo.dayTime >= nextChange) changeWind(world)
|
||||
|
||||
// change current wind speed
|
||||
val changeRate = if (world.isRaining) 0.015 else 0.005
|
||||
current.add(
|
||||
(target.x - current.x).minmax(-changeRate, changeRate),
|
||||
0.0,
|
||||
(target.z - current.z).minmax(-changeRate, changeRate)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeEvent
|
||||
fun handleWorldLoad(event: WorldEvent.Load) { if (event.world.isRemote) changeWind(event.world.world) }
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.AbstractEntityFX
|
||||
import mods.octarinecore.client.resource.Atlas
|
||||
import mods.octarinecore.client.resource.ResourceHandler
|
||||
import mods.octarinecore.common.Double3
|
||||
import mods.octarinecore.forEachPairIndexed
|
||||
import net.minecraft.client.renderer.BufferBuilder
|
||||
import net.minecraft.util.ResourceLocation
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.MathHelper
|
||||
import net.minecraft.world.World
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
import java.util.*
|
||||
|
||||
class EntityRisingSoulFX(world: World, pos: BlockPos) :
|
||||
AbstractEntityFX(world, pos.x.toDouble() + 0.5, pos.y.toDouble() + 1.0, pos.z.toDouble() + 0.5) {
|
||||
|
||||
val particleTrail: Deque<Double3> = LinkedList<Double3>()
|
||||
val initialPhase = rand.nextInt(64)
|
||||
|
||||
init {
|
||||
motionY = 0.1
|
||||
particleGravity = 0.0f
|
||||
sprite = RisingSoulTextures.headIcons[rand.nextInt(256)]
|
||||
maxAge = MathHelper.floor((0.6 + 0.4 * rand.nextDouble()) * Config.risingSoul.lifetime * 20.0)
|
||||
}
|
||||
|
||||
override val isValid: Boolean get() = true
|
||||
|
||||
override fun update() {
|
||||
val phase = (initialPhase + age) % 64
|
||||
velocity.setTo(cos[phase] * Config.risingSoul.perturb, 0.1, sin[phase] * Config.risingSoul.perturb)
|
||||
|
||||
particleTrail.addFirst(currentPos.copy())
|
||||
while (particleTrail.size > Config.risingSoul.trailLength) particleTrail.removeLast()
|
||||
|
||||
if (!Config.enabled) setExpired()
|
||||
}
|
||||
|
||||
override fun render(worldRenderer: BufferBuilder, partialTickTime: Float) {
|
||||
var alpha = Config.risingSoul.opacity.toFloat()
|
||||
if (age > maxAge - 40) alpha *= (maxAge - age) / 40.0f
|
||||
|
||||
renderParticleQuad(worldRenderer, partialTickTime,
|
||||
size = Config.risingSoul.headSize * 0.25,
|
||||
alpha = alpha
|
||||
)
|
||||
|
||||
var scale = Config.risingSoul.trailSize * 0.25
|
||||
particleTrail.forEachPairIndexed { idx, current, previous ->
|
||||
scale *= Config.risingSoul.sizeDecay
|
||||
alpha *= Config.risingSoul.opacityDecay.toFloat()
|
||||
if (idx % Config.risingSoul.trailDensity == 0) renderParticleQuad(worldRenderer, partialTickTime,
|
||||
currentPos = current,
|
||||
prevPos = previous,
|
||||
size = scale,
|
||||
alpha = alpha,
|
||||
icon = RisingSoulTextures.trackIcon
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
object RisingSoulTextures : ResourceHandler(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus, targetAtlas = Atlas.PARTICLES) {
|
||||
val headIcons = spriteSet { idx -> ResourceLocation(BetterFoliageMod.MOD_ID, "rising_soul_$idx") }
|
||||
val trackIcon by sprite(Identifier(BetterFoliageMod.MOD_ID, "soul_track"))
|
||||
}
|
||||
@@ -1,146 +0,0 @@
|
||||
@file:JvmName("ModelColumn")
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.octarinecore.client.render.*
|
||||
import mods.octarinecore.client.render.lighting.*
|
||||
import mods.octarinecore.common.Double3
|
||||
import mods.octarinecore.exchange
|
||||
import net.minecraft.util.Direction.*
|
||||
|
||||
/** Weight of the same-side AO values on the outer edges of the 45deg chamfered column faces. */
|
||||
const val chamferAffinity = 0.9f
|
||||
|
||||
/** Amount to shrink column extension bits to stop Z-fighting. */
|
||||
val zProtectionScale: Double3 get() = Double3(Config.roundLogs.zProtection, 1.0, Config.roundLogs.zProtection)
|
||||
|
||||
fun Model.columnSide(radius: Double, yBottom: Double, yTop: Double, transform: (Quad) -> Quad = { it }) {
|
||||
val halfRadius = radius * 0.5
|
||||
listOf(
|
||||
verticalRectangle(x1 = 0.0, z1 = 0.5, x2 = 0.5 - radius, z2 = 0.5, yBottom = yBottom, yTop = yTop)
|
||||
.clampUV(minU = 0.0, maxU = 0.5 - radius)
|
||||
.setAoShader(faceOrientedInterpolate(overrideFace = SOUTH))
|
||||
.setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y)), predicate = { v, vi -> vi == 1 || vi == 2}),
|
||||
|
||||
verticalRectangle(x1 = 0.5 - radius, z1 = 0.5, x2 = 0.5 - halfRadius, z2 = 0.5 - halfRadius, yBottom = yBottom, yTop = yTop)
|
||||
.clampUV(minU = 0.5 - radius)
|
||||
.setAoShader(
|
||||
faceOrientedAuto(overrideFace = SOUTH, corner = cornerInterpolate(Axis.Y, chamferAffinity, Config.roundLogs.dimming.toFloat()))
|
||||
)
|
||||
.setAoShader(
|
||||
faceOrientedAuto(overrideFace = SOUTH, corner = cornerInterpolate(Axis.Y, 0.5f, Config.roundLogs.dimming.toFloat())),
|
||||
predicate = { v, vi -> vi == 1 || vi == 2}
|
||||
)
|
||||
).forEach { transform(it.setFlatShader(FaceFlat(SOUTH))).add() }
|
||||
|
||||
listOf(
|
||||
verticalRectangle(x1 = 0.5 - halfRadius, z1 = 0.5 - halfRadius, x2 = 0.5, z2 = 0.5 - radius, yBottom = yBottom, yTop = yTop)
|
||||
.clampUV(maxU = radius - 0.5)
|
||||
.setAoShader(
|
||||
faceOrientedAuto(overrideFace = EAST, corner = cornerInterpolate(Axis.Y, chamferAffinity, Config.roundLogs.dimming.toFloat())))
|
||||
.setAoShader(
|
||||
faceOrientedAuto(overrideFace = EAST, corner = cornerInterpolate(Axis.Y, 0.5f, Config.roundLogs.dimming.toFloat())),
|
||||
predicate = { v, vi -> vi == 0 || vi == 3}
|
||||
),
|
||||
|
||||
verticalRectangle(x1 = 0.5, z1 = 0.5 - radius, x2 = 0.5, z2 = 0.0, yBottom = yBottom, yTop = yTop)
|
||||
.clampUV(minU = radius - 0.5, maxU = 0.0)
|
||||
.setAoShader(faceOrientedInterpolate(overrideFace = EAST))
|
||||
.setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y)), predicate = { v, vi -> vi == 0 || vi == 3})
|
||||
).forEach { transform(it.setFlatShader(FaceFlat(EAST))).add() }
|
||||
|
||||
quads.exchange(1, 2)
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a model of the side of a square column quadrant.
|
||||
*
|
||||
* @param[transform] transformation to apply to the model
|
||||
*/
|
||||
fun Model.columnSideSquare(yBottom: Double, yTop: Double, transform: (Quad) -> Quad = { it }) {
|
||||
listOf(
|
||||
verticalRectangle(x1 = 0.0, z1 = 0.5, x2 = 0.5, z2 = 0.5, yBottom = yBottom, yTop = yTop)
|
||||
.clampUV(minU = 0.0)
|
||||
.setAoShader(faceOrientedInterpolate(overrideFace = SOUTH))
|
||||
.setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y)), predicate = { v, vi -> vi == 1 || vi == 2}),
|
||||
|
||||
verticalRectangle(x1 = 0.5, z1 = 0.5, x2 = 0.5, z2 = 0.0, yBottom = yBottom, yTop = yTop)
|
||||
.clampUV(maxU = 0.0)
|
||||
.setAoShader(faceOrientedInterpolate(overrideFace = EAST))
|
||||
.setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y)), predicate = { v, vi -> vi == 0 || vi == 3})
|
||||
).forEach {
|
||||
transform(it.setFlatShader(faceOrientedAuto(corner = cornerFlat))).add()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a model of the top lid of a chamfered column quadrant.
|
||||
*
|
||||
* @param[radius] the chamfer radius
|
||||
* @param[transform] transformation to apply to the model
|
||||
*/
|
||||
fun Model.columnLid(radius: Double, transform: (Quad)->Quad = { it }) {
|
||||
val v1 = Vertex(Double3(0.0, 0.5, 0.0), UV(0.0, 0.0))
|
||||
val v2 = Vertex(Double3(0.0, 0.5, 0.5), UV(0.0, 0.5))
|
||||
val v3 = Vertex(Double3(0.5 - radius, 0.5, 0.5), UV(0.5 - radius, 0.5))
|
||||
val v4 = Vertex(Double3(0.5 - radius * 0.5, 0.5, 0.5 - radius * 0.5), UV(0.5, 0.5))
|
||||
val v5 = Vertex(Double3(0.5, 0.5, 0.5 - radius), UV(0.5, 0.5 - radius))
|
||||
val v6 = Vertex(Double3(0.5, 0.5, 0.0), UV(0.5, 0.0))
|
||||
|
||||
val q1 = Quad(v1, v2, v3, v4).setAoShader(faceOrientedAuto(overrideFace = UP, corner = cornerAo(Axis.Y)))
|
||||
.transformVI { vertex, idx -> vertex.copy(aoShader = when(idx) {
|
||||
0 -> FaceCenter(UP)
|
||||
1 -> EdgeInterpolateFallback(UP, SOUTH, 0.0)
|
||||
else -> vertex.aoShader
|
||||
})}
|
||||
.cycleVertices(if (Config.nVidia) 0 else 1)
|
||||
val q2 = Quad(v1, v4, v5, v6).setAoShader(faceOrientedAuto(overrideFace = UP, corner = cornerAo(Axis.Y)))
|
||||
.transformVI { vertex, idx -> vertex.copy(aoShader = when(idx) {
|
||||
0 -> FaceCenter(UP)
|
||||
3 -> EdgeInterpolateFallback(UP, EAST, 0.0)
|
||||
else -> vertex.aoShader
|
||||
})}
|
||||
.cycleVertices(if (Config.nVidia) 0 else 1)
|
||||
listOf(q1, q2).forEach { transform(it.setFlatShader(FaceFlat(UP))).add() }
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a model of the top lid of a square column quadrant.
|
||||
*
|
||||
* @param[transform] transformation to apply to the model
|
||||
*/
|
||||
fun Model.columnLidSquare(transform: (Quad)-> Quad = { it }) {
|
||||
transform(
|
||||
horizontalRectangle(x1 = 0.0, x2 = 0.5, z1 = 0.0, z2 = 0.5, y = 0.5)
|
||||
.transformVI { vertex, idx -> vertex.copy(uv = UV(vertex.xyz.x, vertex.xyz.z), aoShader = when(idx) {
|
||||
0 -> FaceCenter(UP)
|
||||
1 -> EdgeInterpolateFallback(UP, SOUTH, 0.0)
|
||||
2 -> CornerSingleFallback(UP, SOUTH, EAST, UP)
|
||||
else -> EdgeInterpolateFallback(UP, EAST, 0.0)
|
||||
}) }
|
||||
.setFlatShader(FaceFlat(UP))
|
||||
).add()
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform a chamfered side quadrant model of a column that extends from the top of the block.
|
||||
* (clamp UV coordinates, apply some scaling to avoid Z-fighting).
|
||||
*
|
||||
* @param[size] amount that the model extends from the top
|
||||
*/
|
||||
fun topExtension(size: Double) = { q: Quad ->
|
||||
q.clampUV(minV = 0.5 - size).transformVI { vertex, idx ->
|
||||
if (idx < 2) vertex else vertex.copy(xyz = vertex.xyz * zProtectionScale)
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Transform a chamfered side quadrant model of a column that extends from the bottom of the block.
|
||||
* (clamp UV coordinates, apply some scaling to avoid Z-fighting).
|
||||
*
|
||||
* @param[size] amount that the model extends from the bottom
|
||||
*/
|
||||
fun bottomExtension(size: Double) = { q: Quad ->
|
||||
q.clampUV(maxV = -0.5 + size).transformVI { vertex, idx ->
|
||||
if (idx > 1) vertex else vertex.copy(xyz = vertex.xyz * zProtectionScale)
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import net.minecraft.block.material.Material
|
||||
import net.minecraft.tags.BlockTags
|
||||
import net.minecraft.util.ResourceLocation
|
||||
import net.minecraft.world.biome.Biome
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
|
||||
class RenderAlgae : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val noise = simplexNoise()
|
||||
|
||||
val algaeIcons = spriteSet { idx -> ResourceLocation(BetterFoliageMod.MOD_ID, "blocks/better_algae_$idx") }
|
||||
val algaeModels = modelSet(64) { idx -> RenderGrass.grassTopQuads(Config.algae.heightMin, Config.algae.heightMax)(idx) }
|
||||
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled && Config.algae.enabled &&
|
||||
ctx.state(up2).material == Material.WATER &&
|
||||
ctx.state(up1).material == Material.WATER &&
|
||||
BlockTags.DIRT_LIKE.contains(ctx.state.block) &&
|
||||
ctx.biome.category.let { it == Biome.Category.OCEAN || it == Biome.Category.BEACH || it == Biome.Category.RIVER } &&
|
||||
noise[ctx.pos] < Config.algae.population
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
ctx.render()
|
||||
if (!ctx.isCutout) return
|
||||
val rand = ctx.semiRandomArray(3)
|
||||
ShadersModIntegration.grass(ctx, Config.algae.shaderWind) {
|
||||
ctx.render(
|
||||
algaeModels[rand[2]],
|
||||
icon = { _, qi, _ -> algaeIcons[rand[qi and 1]] }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,104 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.render.column.ColumnTextureInfo
|
||||
import mods.betterfoliage.client.render.column.SimpleColumnInfo
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.*
|
||||
import mods.octarinecore.client.render.lighting.*
|
||||
import mods.octarinecore.client.resource.*
|
||||
import mods.octarinecore.common.Rotation
|
||||
import mods.octarinecore.common.config.ModelTextureList
|
||||
import mods.octarinecore.common.config.SimpleBlockMatcher
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.CactusBlock
|
||||
import net.minecraft.util.Direction.*
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
object AsyncCactusDiscovery : ConfigurableModelDiscovery<ColumnTextureInfo>() {
|
||||
override val logger = BetterFoliage.logDetail
|
||||
override val matchClasses = SimpleBlockMatcher(CactusBlock::class.java)
|
||||
override val modelTextures = listOf(ModelTextureList("block/cactus", "top", "bottom", "side"))
|
||||
override fun processModel(state: BlockState, textures: List<String>, atlas: AtlasFuture): CompletableFuture<ColumnTextureInfo>? {
|
||||
val sprites = textures.map { atlas.sprite(Identifier(it)) }
|
||||
return atlas.mapAfter {
|
||||
SimpleColumnInfo(
|
||||
Axis.Y,
|
||||
sprites[0].get(),
|
||||
sprites[1].get(),
|
||||
sprites.drop(2).map { it.get() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun init() {
|
||||
BetterFoliage.blockSprites.providers.add(this)
|
||||
}
|
||||
}
|
||||
|
||||
class RenderCactus : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val cactusStemRadius = 0.4375
|
||||
val cactusArmRotation = listOf(NORTH, SOUTH, EAST, WEST).map { Rotation.rot90[it.ordinal] }
|
||||
|
||||
val iconCross by sprite(Identifier(BetterFoliageMod.MOD_ID, "blocks/better_cactus"))
|
||||
val iconArm = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_cactus_arm_$idx") }
|
||||
|
||||
val modelStem = model {
|
||||
horizontalRectangle(x1 = -cactusStemRadius, x2 = cactusStemRadius, z1 = -cactusStemRadius, z2 = cactusStemRadius, y = 0.5)
|
||||
.scaleUV(cactusStemRadius * 2.0)
|
||||
.let { listOf(it.flipped.move(1.0 to DOWN), it) }
|
||||
.forEach { it.setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y), edge = null)).add() }
|
||||
|
||||
verticalRectangle(x1 = -0.5, z1 = cactusStemRadius, x2 = 0.5, z2 = cactusStemRadius, yBottom = -0.5, yTop = 0.5)
|
||||
.setAoShader(faceOrientedAuto(corner = cornerAo(Axis.Y), edge = null))
|
||||
.toCross(UP).addAll()
|
||||
}
|
||||
val modelCross = modelSet(64) { modelIdx ->
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = -0.5 * 1.41, yTop = 0.5 * 1.41)
|
||||
.setAoShader(edgeOrientedAuto(corner = cornerAoMaxGreen))
|
||||
.scale(1.4)
|
||||
.transformV { v ->
|
||||
val perturb = xzDisk(modelIdx) * Config.cactus.sizeVariation
|
||||
Vertex(v.xyz + (if (v.uv.u < 0.0) perturb else -perturb), v.uv, v.aoShader)
|
||||
}
|
||||
.toCross(UP).addAll()
|
||||
}
|
||||
val modelArm = modelSet(64) { modelIdx ->
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.0, yTop = 1.0)
|
||||
.scale(Config.cactus.size).move(0.5 to UP)
|
||||
|
||||
.setAoShader(faceOrientedAuto(overrideFace = UP, corner = cornerAo(Axis.Y), edge = null))
|
||||
.toCross(UP) { it.move(xzDisk(modelIdx) * Config.cactus.hOffset) }.addAll()
|
||||
}
|
||||
|
||||
override fun isEligible(ctx: CombinedContext): Boolean =
|
||||
Config.enabled && Config.cactus.enabled &&
|
||||
AsyncCactusDiscovery[ctx] != null
|
||||
|
||||
override val onlyOnCutout get() = true
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
val icons = AsyncCactusDiscovery[ctx]!!
|
||||
|
||||
ctx.render(
|
||||
modelStem.model,
|
||||
icon = { ctx, qi, q -> when(qi) {
|
||||
0 -> icons.bottom(ctx, qi, q); 1 -> icons.top(ctx, qi, q); else -> icons.side(ctx, qi, q)
|
||||
} }
|
||||
)
|
||||
ctx.render(
|
||||
modelCross[ctx.semiRandom(0)],
|
||||
icon = { _, _, _ -> iconCross }
|
||||
)
|
||||
|
||||
ctx.render(
|
||||
modelArm[ctx.semiRandom(1)],
|
||||
cactusArmRotation[ctx.semiRandom(2) % 4],
|
||||
icon = { _, _, _ -> iconArm[ctx.semiRandom(3)] }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.texture.GrassRegistry
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.common.Int3
|
||||
import mods.octarinecore.common.horizontalDirections
|
||||
import mods.octarinecore.common.offset
|
||||
import net.minecraft.tags.BlockTags
|
||||
|
||||
class RenderConnectedGrass : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled && Config.connectedGrass.enabled &&
|
||||
BlockTags.DIRT_LIKE.contains(ctx.state.block) &&
|
||||
GrassRegistry[ctx, up1] != null &&
|
||||
(Config.connectedGrass.snowEnabled || !ctx.state(up2).isSnow)
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
// if the block sides are not visible anyway, render normally
|
||||
if (horizontalDirections.none { ctx.shouldSideBeRendered(it) }) {
|
||||
ctx.render()
|
||||
} else {
|
||||
ctx.exchange(Int3.zero, up1).exchange(up1, up2).render()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class RenderConnectedGrassLog : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled && Config.roundLogs.enabled && Config.roundLogs.connectGrass &&
|
||||
BlockTags.DIRT_LIKE.contains(ctx.state.block) &&
|
||||
LogRegistry[ctx, up1] != null
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
val grassDir = horizontalDirections.find { GrassRegistry[ctx, it.offset] != null }
|
||||
if (grassDir == null) {
|
||||
ctx.render()
|
||||
} else {
|
||||
ctx.exchange(Int3.zero, grassDir.offset).render()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,63 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.octarinecore.client.render.*
|
||||
import mods.octarinecore.client.render.lighting.*
|
||||
import mods.octarinecore.common.allDirections
|
||||
import mods.octarinecore.random
|
||||
import net.minecraft.block.material.Material
|
||||
import net.minecraft.util.Direction.Axis
|
||||
import net.minecraft.util.Direction.UP
|
||||
import net.minecraft.util.ResourceLocation
|
||||
import net.minecraft.world.biome.Biome
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
|
||||
class RenderCoral : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val noise = simplexNoise()
|
||||
|
||||
val coralIcons = spriteSet { idx -> ResourceLocation(BetterFoliageMod.MOD_ID, "blocks/better_coral_$idx") }
|
||||
val crustIcons = spriteSet { idx -> ResourceLocation(BetterFoliageMod.MOD_ID, "blocks/better_crust_$idx") }
|
||||
val coralModels = modelSet(64) { modelIdx ->
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.0, yTop = 1.0)
|
||||
.scale(Config.coral.size).move(0.5 to UP)
|
||||
.toCross(UP) { it.move(xzDisk(modelIdx) * Config.coral.hOffset) }.addAll()
|
||||
|
||||
val separation = random(0.01, Config.coral.vOffset)
|
||||
horizontalRectangle(x1 = -0.5, x2 = 0.5, z1 = -0.5, z2 = 0.5, y = 0.0)
|
||||
.scale(Config.coral.crustSize).move(0.5 + separation to UP).add()
|
||||
|
||||
transformQ {
|
||||
it.setAoShader(faceOrientedAuto(overrideFace = UP, corner = cornerAo(Axis.Y)))
|
||||
.setFlatShader(faceOrientedAuto(overrideFace = UP, corner = cornerFlat))
|
||||
}
|
||||
}
|
||||
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled && Config.coral.enabled &&
|
||||
(ctx.state(up2).material == Material.WATER || Config.coral.shallowWater) &&
|
||||
ctx.state(up1).material == Material.WATER &&
|
||||
BlockConfig.sand.matchesClass(ctx.state.block) &&
|
||||
ctx.biome.category.let { it == Biome.Category.OCEAN || it == Biome.Category.BEACH } &&
|
||||
noise[ctx.pos] < Config.coral.population
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
val baseRender = ctx.render()
|
||||
if (!ctx.isCutout) return
|
||||
|
||||
allDirections.forEachIndexed { idx, face ->
|
||||
if (ctx.state(face).material == Material.WATER && ctx.semiRandom(idx) < Config.coral.chance) {
|
||||
var variation = ctx.semiRandom(6)
|
||||
ctx.render(
|
||||
coralModels[variation++],
|
||||
rotationFromUp[idx],
|
||||
icon = { _, qi, _ -> if (qi == 4) crustIcons[variation] else coralIcons[variation + (qi and 1)] }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.integration.OptifineCustomColors
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.betterfoliage.client.texture.GeneratedGrass
|
||||
import mods.betterfoliage.client.texture.GrassRegistry
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.Model
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.client.render.fullCube
|
||||
import mods.octarinecore.client.render.lighting.cornerAo
|
||||
import mods.octarinecore.client.render.lighting.cornerFlat
|
||||
import mods.octarinecore.client.render.lighting.faceOrientedAuto
|
||||
import mods.octarinecore.common.Double3
|
||||
import mods.octarinecore.common.allDirections
|
||||
import mods.octarinecore.random
|
||||
import net.minecraft.tags.BlockTags
|
||||
import net.minecraft.util.Direction.*
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
|
||||
class RenderGrass : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
companion object {
|
||||
@JvmStatic fun grassTopQuads(heightMin: Double, heightMax: Double): Model.(Int)->Unit = { modelIdx ->
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.5,
|
||||
yTop = 0.5 + random(heightMin, heightMax)
|
||||
)
|
||||
.setAoShader(faceOrientedAuto(overrideFace = UP, corner = cornerAo(Axis.Y)))
|
||||
.setFlatShader(faceOrientedAuto(overrideFace = UP, corner = cornerFlat))
|
||||
.toCross(UP) { it.move(xzDisk(modelIdx) * Config.shortGrass.hOffset) }.addAll()
|
||||
}
|
||||
}
|
||||
|
||||
val noise = simplexNoise()
|
||||
|
||||
val normalIcons = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_grass_long_$idx") }
|
||||
val snowedIcons = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_grass_snowed_$idx") }
|
||||
val normalGenIcon by sprite { GeneratedGrass(sprite = "minecraft:blocks/tallgrass", isSnowed = false).register(BetterFoliage.asyncPack) }
|
||||
val snowedGenIcon by sprite { GeneratedGrass(sprite = "minecraft:blocks/tallgrass", isSnowed = true).register(BetterFoliage.asyncPack) }
|
||||
|
||||
val grassModels = modelSet(64) { idx -> grassTopQuads(Config.shortGrass.heightMin, Config.shortGrass.heightMax)(idx) }
|
||||
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled &&
|
||||
(Config.shortGrass.grassEnabled || Config.connectedGrass.enabled) &&
|
||||
GrassRegistry[ctx] != null
|
||||
|
||||
override val onlyOnCutout get() = true
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
val isConnected = BlockTags.DIRT_LIKE.contains(ctx.state(DOWN).block) || GrassRegistry[ctx, down1] != null
|
||||
val isSnowed = ctx.state(UP).isSnow
|
||||
val connectedGrass = isConnected && Config.connectedGrass.enabled && (!isSnowed || Config.connectedGrass.snowEnabled)
|
||||
|
||||
val grass = GrassRegistry[ctx]!!
|
||||
val blockColor = OptifineCustomColors.getBlockColor(ctx)
|
||||
|
||||
if (connectedGrass) {
|
||||
// check occlusion
|
||||
val isVisible = allDirections.map { ctx.shouldSideBeRendered(it) }
|
||||
|
||||
// render full grass block
|
||||
ctx.render(
|
||||
fullCube,
|
||||
quadFilter = { qi, _ -> isVisible[qi] },
|
||||
icon = { _, _, _ -> grass.grassTopTexture },
|
||||
postProcess = { ctx, _, _, _, _ ->
|
||||
rotateUV(2)
|
||||
if (isSnowed) {
|
||||
if (!ctx.aoEnabled) setGrey(1.4f)
|
||||
} else if (ctx.aoEnabled && grass.overrideColor == null) multiplyColor(blockColor)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
ctx.render()
|
||||
}
|
||||
|
||||
if (!Config.shortGrass.grassEnabled) return
|
||||
if (isSnowed && !Config.shortGrass.snowEnabled) return
|
||||
if (ctx.offset(UP).isNormalCube) return
|
||||
if (Config.shortGrass.population < 64 && noise[ctx.pos] >= Config.shortGrass.population) return
|
||||
|
||||
// render grass quads
|
||||
val iconset = if (isSnowed) snowedIcons else normalIcons
|
||||
val iconGen = if (isSnowed) snowedGenIcon else normalGenIcon
|
||||
val rand = ctx.semiRandomArray(2)
|
||||
|
||||
ShadersModIntegration.grass(ctx, Config.shortGrass.shaderWind) {
|
||||
ctx.render(
|
||||
grassModels[rand[0]],
|
||||
translation = ctx.blockCenter + (if (isSnowed) snowOffset else Double3.zero),
|
||||
icon = { _, qi, _ -> if (Config.shortGrass.useGenerated) iconGen else iconset[rand[qi and 1]] },
|
||||
postProcess = { _, _, _, _, _ -> if (isSnowed) setGrey(1.0f) else multiplyColor(grass.overrideColor ?: blockColor) }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.integration.OptifineCustomColors
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.betterfoliage.client.texture.LeafRegistry
|
||||
import mods.octarinecore.PI2
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.client.render.lighting.FlatOffset
|
||||
import mods.octarinecore.client.render.lighting.cornerAoMaxGreen
|
||||
import mods.octarinecore.client.render.lighting.edgeOrientedAuto
|
||||
import mods.octarinecore.common.Double3
|
||||
import mods.octarinecore.common.Int3
|
||||
import mods.octarinecore.common.allDirections
|
||||
import mods.octarinecore.common.vec
|
||||
import mods.octarinecore.random
|
||||
import net.minecraft.util.Direction.UP
|
||||
import java.lang.Math.cos
|
||||
import java.lang.Math.sin
|
||||
|
||||
class RenderLeaves : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val leavesModel = model {
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = -0.5 * 1.41, yTop = 0.5 * 1.41)
|
||||
.setAoShader(edgeOrientedAuto(corner = cornerAoMaxGreen))
|
||||
.setFlatShader(FlatOffset(Int3.zero))
|
||||
.scale(Config.leaves.size)
|
||||
.toCross(UP).addAll()
|
||||
}
|
||||
val snowedIcon = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_leaves_snowed_$idx") }
|
||||
|
||||
val perturbs = vectorSet(64) { idx ->
|
||||
val angle = PI2 * idx / 64.0
|
||||
Double3(cos(angle), 0.0, sin(angle)) * Config.leaves.hOffset +
|
||||
UP.vec * random(-1.0, 1.0) * Config.leaves.vOffset
|
||||
}
|
||||
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled &&
|
||||
Config.leaves.enabled &&
|
||||
LeafRegistry[ctx] != null &&
|
||||
!(Config.leaves.hideInternal && allDirections.all { ctx.offset(it).isNormalCube } )
|
||||
|
||||
override val onlyOnCutout get() = true
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
val isSnowed = ctx.state(UP).isSnow
|
||||
val leafInfo = LeafRegistry[ctx]!!
|
||||
val blockColor = OptifineCustomColors.getBlockColor(ctx)
|
||||
|
||||
ctx.render(force = true)
|
||||
|
||||
ShadersModIntegration.leaves(ctx) {
|
||||
val rand = ctx.semiRandomArray(2)
|
||||
(if (Config.leaves.dense) denseLeavesRot else normalLeavesRot).forEach { rotation ->
|
||||
ctx.render(
|
||||
leavesModel.model,
|
||||
rotation,
|
||||
translation = ctx.blockCenter + perturbs[rand[0]],
|
||||
icon = { _, _, _ -> leafInfo.roundLeafTexture },
|
||||
postProcess = { _, _, _, _, _ ->
|
||||
rotateUV(rand[1])
|
||||
multiplyColor(blockColor)
|
||||
}
|
||||
)
|
||||
}
|
||||
if (isSnowed && Config.leaves.snowEnabled) ctx.render(
|
||||
leavesModel.model,
|
||||
translation = ctx.blockCenter + perturbs[rand[0]],
|
||||
icon = { _, _, _ -> snowedIcon[rand[1]] },
|
||||
postProcess = whitewash
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.client.render.lighting.FlatOffsetNoColor
|
||||
import mods.octarinecore.common.Int3
|
||||
import net.minecraft.util.Direction.DOWN
|
||||
import net.minecraft.util.Direction.UP
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
|
||||
class RenderLilypad : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val rootModel = model {
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = -1.5, yTop = -0.5)
|
||||
.setFlatShader(FlatOffsetNoColor(Int3.zero))
|
||||
.toCross(UP).addAll()
|
||||
}
|
||||
val flowerModel = model {
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.0, yTop = 1.0)
|
||||
.scale(0.5).move(0.5 to DOWN)
|
||||
.setFlatShader(FlatOffsetNoColor(Int3.zero))
|
||||
.toCross(UP).addAll()
|
||||
}
|
||||
val rootIcon = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_lilypad_roots_$idx") }
|
||||
val flowerIcon = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_lilypad_flower_$idx") }
|
||||
val perturbs = vectorSet(64) { modelIdx -> xzDisk(modelIdx) * Config.lilypad.hOffset }
|
||||
|
||||
override fun isEligible(ctx: CombinedContext): Boolean =
|
||||
Config.enabled && Config.lilypad.enabled &&
|
||||
BlockConfig.lilypad.matchesClass(ctx.state.block)
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
ctx.render()
|
||||
|
||||
val rand = ctx.semiRandomArray(5)
|
||||
ShadersModIntegration.grass(ctx) {
|
||||
ctx.render(
|
||||
rootModel.model,
|
||||
translation = ctx.blockCenter.add(perturbs[rand[2]]),
|
||||
forceFlat = true,
|
||||
icon = { ctx, qi, q -> rootIcon[rand[qi and 1]] }
|
||||
)
|
||||
}
|
||||
|
||||
if (rand[3] < Config.lilypad.flowerChance) ctx.render(
|
||||
flowerModel.model,
|
||||
translation = ctx.blockCenter.add(perturbs[rand[4]]),
|
||||
forceFlat = true,
|
||||
icon = { _, _, _ -> flowerIcon[rand[0]] }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.render.column.AbstractRenderColumn
|
||||
import mods.betterfoliage.client.render.column.ColumnRenderLayer
|
||||
import mods.betterfoliage.client.render.column.ColumnTextureInfo
|
||||
import mods.betterfoliage.client.render.column.SimpleColumnInfo
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.resource.*
|
||||
import mods.octarinecore.common.config.ConfigurableBlockMatcher
|
||||
import mods.octarinecore.common.config.ModelTextureList
|
||||
import mods.octarinecore.tryDefault
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.LogBlock
|
||||
import net.minecraft.util.Direction.Axis
|
||||
import org.apache.logging.log4j.Level
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
class RenderLog : AbstractRenderColumn(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
override val renderOnCutout: Boolean get() = false
|
||||
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled && Config.roundLogs.enabled &&
|
||||
LogRegistry[ctx] != null
|
||||
|
||||
override val overlayLayer = RoundLogOverlayLayer()
|
||||
override val connectPerpendicular: Boolean get() = Config.roundLogs.connectPerpendicular
|
||||
override val radiusSmall: Double get() = Config.roundLogs.radiusSmall
|
||||
override val radiusLarge: Double get() = Config.roundLogs.radiusLarge
|
||||
init {
|
||||
ChunkOverlayManager.layers.add(overlayLayer)
|
||||
}
|
||||
}
|
||||
|
||||
class RoundLogOverlayLayer : ColumnRenderLayer() {
|
||||
override val registry: ModelRenderRegistry<ColumnTextureInfo> get() = LogRegistry
|
||||
override val blockPredicate = { state: BlockState -> BlockConfig.logBlocks.matchesClass(state.block) }
|
||||
|
||||
override val connectSolids: Boolean get() = Config.roundLogs.connectSolids
|
||||
override val lenientConnect: Boolean get() = Config.roundLogs.lenientConnect
|
||||
override val defaultToY: Boolean get() = Config.roundLogs.defaultY
|
||||
}
|
||||
|
||||
object LogRegistry : ModelRenderRegistryRoot<ColumnTextureInfo>()
|
||||
|
||||
object AsyncLogDiscovery : ConfigurableModelDiscovery<ColumnTextureInfo>() {
|
||||
override val logger = BetterFoliage.logDetail
|
||||
override val matchClasses: ConfigurableBlockMatcher get() = BlockConfig.logBlocks
|
||||
override val modelTextures: List<ModelTextureList> get() = BlockConfig.logModels.modelList
|
||||
|
||||
override fun processModel(state: BlockState, textures: List<String>, atlas: AtlasFuture): CompletableFuture<ColumnTextureInfo> {
|
||||
val axis = getAxis(state)
|
||||
logger.log(Level.DEBUG, "$logName: axis $axis")
|
||||
val spriteList = textures.map { atlas.sprite(Identifier(it)) }
|
||||
return atlas.mapAfter {
|
||||
SimpleColumnInfo(
|
||||
axis,
|
||||
spriteList[0].get(),
|
||||
spriteList[1].get(),
|
||||
spriteList.drop(2).map { it.get() }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun getAxis(state: BlockState): Axis? {
|
||||
val axis = tryDefault(null) { state.get(LogBlock.AXIS).toString() } ?:
|
||||
state.values.entries.find { it.key.getName().toLowerCase() == "axis" }?.value?.toString()
|
||||
return when (axis) {
|
||||
"x" -> Axis.X
|
||||
"y" -> Axis.Y
|
||||
"z" -> Axis.Z
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
fun init() {
|
||||
LogRegistry.registries.add(this)
|
||||
BetterFoliage.blockSprites.providers.add(this)
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.client.render.noPost
|
||||
import mods.octarinecore.common.Double3
|
||||
import net.minecraft.util.Direction.UP
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
|
||||
class RenderMycelium : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val myceliumIcon = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_mycel_$idx") }
|
||||
val myceliumModel = modelSet(64) { idx -> RenderGrass.grassTopQuads(Config.shortGrass.heightMin, Config.shortGrass.heightMax)(idx) }
|
||||
|
||||
override fun isEligible(ctx: CombinedContext): Boolean {
|
||||
if (!Config.enabled || !Config.shortGrass.myceliumEnabled) return false
|
||||
return BlockConfig.mycelium.matchesClass(ctx.state.block)
|
||||
}
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
ctx.render()
|
||||
if (!ctx.isCutout) return
|
||||
|
||||
val isSnowed = ctx.state(UP).isSnow
|
||||
if (isSnowed && !Config.shortGrass.snowEnabled) return
|
||||
if (ctx.offset(UP).isNormalCube) return
|
||||
val rand = ctx.semiRandomArray(2)
|
||||
|
||||
ctx.render(
|
||||
myceliumModel[rand[0]],
|
||||
translation = ctx.blockCenter + (if (isSnowed) snowOffset else Double3.zero),
|
||||
icon = { _, qi, _ -> myceliumIcon[rand[qi and 1]] },
|
||||
postProcess = if (isSnowed) whitewash else noPost
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.*
|
||||
import mods.octarinecore.client.render.lighting.*
|
||||
import mods.octarinecore.random
|
||||
import net.minecraft.util.Direction.Axis
|
||||
import net.minecraft.util.Direction.*
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
|
||||
class RenderNetherrack : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val netherrackIcon = spriteSet { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_netherrack_$idx") }
|
||||
val netherrackModel = modelSet(64) { modelIdx ->
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yTop = -0.5,
|
||||
yBottom = -0.5 - random(Config.netherrack.heightMin, Config.netherrack.heightMax))
|
||||
.setAoShader(faceOrientedAuto(overrideFace = DOWN, corner = cornerAo(Axis.Y)))
|
||||
.setFlatShader(faceOrientedAuto(overrideFace = DOWN, corner = cornerFlat))
|
||||
.toCross(UP) { it.move(xzDisk(modelIdx) * Config.shortGrass.hOffset) }.addAll()
|
||||
|
||||
}
|
||||
|
||||
override fun isEligible(ctx: CombinedContext): Boolean {
|
||||
if (!Config.enabled || !Config.netherrack.enabled) return false
|
||||
return BlockConfig.netherrack.matchesClass(ctx.state.block)
|
||||
}
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
ctx.render()
|
||||
if (!ctx.isCutout) return
|
||||
if (ctx.offset(DOWN).isNormalCube) return
|
||||
|
||||
val rand = ctx.semiRandomArray(2)
|
||||
ctx.render(
|
||||
netherrackModel[rand[0]],
|
||||
icon = { _, qi, _ -> netherrackIcon[rand[qi and 1]] }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.client.render.lighting.FlatOffsetNoColor
|
||||
import mods.octarinecore.client.resource.CenteredSprite
|
||||
import mods.octarinecore.random
|
||||
import net.minecraft.block.material.Material
|
||||
import net.minecraft.tags.BlockTags
|
||||
import net.minecraft.util.Direction.UP
|
||||
import org.apache.logging.log4j.Level.DEBUG
|
||||
|
||||
class RenderReeds : RenderDecorator(BetterFoliageMod.MOD_ID, BetterFoliageMod.bus) {
|
||||
|
||||
val noise = simplexNoise()
|
||||
val reedIcons = spriteSetTransformed(
|
||||
check = { idx -> Identifier(BetterFoliageMod.MOD_ID, "blocks/better_reed_$idx")},
|
||||
register = { CenteredSprite(it).register(BetterFoliage.asyncPack) }
|
||||
)
|
||||
val reedModels = modelSet(64) { modelIdx ->
|
||||
val height = random(Config.reed.heightMin, Config.reed.heightMax)
|
||||
val waterline = 0.875f
|
||||
val vCutLine = 0.5 - waterline / height
|
||||
listOf(
|
||||
// below waterline
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.5, yTop = 0.5 + waterline)
|
||||
.setFlatShader(FlatOffsetNoColor(up1)).clampUV(minV = vCutLine),
|
||||
|
||||
// above waterline
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = 0.5 + waterline, yTop = 0.5 + height)
|
||||
.setFlatShader(FlatOffsetNoColor(up2)).clampUV(maxV = vCutLine)
|
||||
).forEach {
|
||||
it.clampUV(minU = -0.25, maxU = 0.25)
|
||||
.toCross(UP) { it.move(xzDisk(modelIdx) * Config.reed.hOffset) }.addAll()
|
||||
}
|
||||
}
|
||||
|
||||
override fun isEligible(ctx: CombinedContext) =
|
||||
Config.enabled && Config.reed.enabled &&
|
||||
ctx.state(up2).material == Material.AIR &&
|
||||
ctx.state(UP).material == Material.WATER &&
|
||||
BlockTags.DIRT_LIKE.contains(ctx.state.block) &&
|
||||
ctx.biome.let { it.downfall > Config.reed.minBiomeRainfall && it.defaultTemperature >= Config.reed.minBiomeTemp } &&
|
||||
noise[ctx.pos] < Config.reed.population
|
||||
|
||||
override val onlyOnCutout get() = false
|
||||
|
||||
override fun render(ctx: CombinedContext) {
|
||||
ctx.render()
|
||||
if (!ctx.isCutout) return
|
||||
|
||||
val iconVar = ctx.semiRandom(1)
|
||||
ShadersModIntegration.grass(ctx, Config.reed.shaderWind) {
|
||||
ctx.render(
|
||||
reedModels[ctx.semiRandom(0)],
|
||||
forceFlat = true,
|
||||
icon = { _, _, _ -> reedIcons[iconVar] }
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
@file:JvmName("Utils")
|
||||
package mods.betterfoliage.client.render
|
||||
|
||||
import mods.octarinecore.PI2
|
||||
import mods.octarinecore.client.render.Model
|
||||
import mods.octarinecore.client.render.lighting.PostProcessLambda
|
||||
import mods.octarinecore.client.render.Quad
|
||||
import mods.octarinecore.common.Double3
|
||||
import mods.octarinecore.common.Int3
|
||||
import mods.octarinecore.common.Rotation
|
||||
import mods.octarinecore.common.times
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.material.Material
|
||||
import net.minecraft.util.BlockRenderLayer
|
||||
import net.minecraft.util.Direction
|
||||
import net.minecraft.util.Direction.*
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
val up1 = Int3(1 to UP)
|
||||
val up2 = Int3(2 to UP)
|
||||
val down1 = Int3(1 to DOWN)
|
||||
val snowOffset = UP * 0.0625
|
||||
|
||||
val normalLeavesRot = arrayOf(Rotation.identity)
|
||||
val denseLeavesRot = arrayOf(Rotation.identity, Rotation.rot90[EAST.ordinal], Rotation.rot90[SOUTH.ordinal])
|
||||
|
||||
val whitewash: PostProcessLambda = { _, _, _, _, _ -> setGrey(1.4f) }
|
||||
val greywash: PostProcessLambda = { _, _, _, _, _ -> setGrey(1.0f) }
|
||||
|
||||
val BlockState.isSnow: Boolean get() = material.let { it == Material.SNOW }
|
||||
|
||||
fun Quad.toCross(rotAxis: Direction, trans: (Quad)->Quad) =
|
||||
(0..3).map { rotIdx ->
|
||||
trans(rotate(Rotation.rot90[rotAxis.ordinal] * rotIdx).mirrorUV(rotIdx > 1, false))
|
||||
}
|
||||
fun Quad.toCross(rotAxis: Direction) = toCross(rotAxis) { it }
|
||||
|
||||
fun xzDisk(modelIdx: Int) = (PI2 * modelIdx / 64.0).let { Double3(cos(it), 0.0, sin(it)) }
|
||||
|
||||
val rotationFromUp = arrayOf(
|
||||
Rotation.rot90[EAST.ordinal] * 2,
|
||||
Rotation.identity,
|
||||
Rotation.rot90[WEST.ordinal],
|
||||
Rotation.rot90[EAST.ordinal],
|
||||
Rotation.rot90[SOUTH.ordinal],
|
||||
Rotation.rot90[NORTH.ordinal]
|
||||
)
|
||||
|
||||
fun Model.mix(first: Model, second: Model, predicate: (Int)->Boolean) {
|
||||
first.quads.forEachIndexed { qi, quad ->
|
||||
val otherQuad = second.quads[qi]
|
||||
Quad(
|
||||
if (predicate(0)) otherQuad.v1.copy() else quad.v1.copy(),
|
||||
if (predicate(1)) otherQuad.v2.copy() else quad.v2.copy(),
|
||||
if (predicate(2)) otherQuad.v3.copy() else quad.v3.copy(),
|
||||
if (predicate(3)) otherQuad.v4.copy() else quad.v4.copy()
|
||||
).add()
|
||||
}
|
||||
}
|
||||
|
||||
val BlockRenderLayer.isCutout: Boolean get() = (this == BlockRenderLayer.CUTOUT) || (this == BlockRenderLayer.CUTOUT_MIPPED)
|
||||
|
||||
fun BlockState.canRenderInLayer(layer: BlockRenderLayer) = this.block.canRenderInLayer(this, layer)
|
||||
fun BlockState.canRenderInCutout() = this.block.canRenderInLayer(this, BlockRenderLayer.CUTOUT) || this.block.canRenderInLayer(this, BlockRenderLayer.CUTOUT_MIPPED)
|
||||
@@ -1,210 +0,0 @@
|
||||
package mods.betterfoliage.client.render.column
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.client.Client
|
||||
import mods.betterfoliage.client.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.client.integration.ShadersModIntegration.renderAs
|
||||
import mods.betterfoliage.client.render.*
|
||||
import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.BlockType.*
|
||||
import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType
|
||||
import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType.*
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.Model
|
||||
import mods.octarinecore.client.render.RenderDecorator
|
||||
import mods.octarinecore.client.render.noPost
|
||||
import mods.octarinecore.common.Rotation
|
||||
import mods.octarinecore.common.face
|
||||
import mods.octarinecore.common.rot
|
||||
import net.minecraft.block.BlockRenderType.MODEL
|
||||
import net.minecraft.util.Direction.*
|
||||
import net.minecraftforge.eventbus.api.IEventBus
|
||||
|
||||
@Suppress("NOTHING_TO_INLINE")
|
||||
abstract class AbstractRenderColumn(modId: String, modBus: IEventBus) : RenderDecorator(modId, modBus) {
|
||||
|
||||
/** The rotations necessary to bring the models in position for the 4 quadrants */
|
||||
val quadrantRotations = Array(4) { Rotation.rot90[UP.ordinal] * it }
|
||||
|
||||
// ============================
|
||||
// Configuration
|
||||
// ============================
|
||||
abstract val overlayLayer: ColumnRenderLayer
|
||||
abstract val connectPerpendicular: Boolean
|
||||
abstract val radiusSmall: Double
|
||||
abstract val radiusLarge: Double
|
||||
|
||||
// ============================
|
||||
// Models
|
||||
// ============================
|
||||
val sideSquare = model { columnSideSquare(-0.5, 0.5) }
|
||||
val sideRoundSmall = model { columnSide(radiusSmall, -0.5, 0.5) }
|
||||
val sideRoundLarge = model { columnSide(radiusLarge, -0.5, 0.5) }
|
||||
|
||||
val extendTopSquare = model { columnSideSquare(0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) }
|
||||
val extendTopRoundSmall = model { columnSide(radiusSmall, 0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) }
|
||||
val extendTopRoundLarge = model { columnSide(radiusLarge, 0.5, 0.5 + radiusLarge, topExtension(radiusLarge)) }
|
||||
inline fun extendTop(type: QuadrantType) = when(type) {
|
||||
SMALL_RADIUS -> extendTopRoundSmall.model
|
||||
LARGE_RADIUS -> extendTopRoundLarge.model
|
||||
SQUARE -> extendTopSquare.model
|
||||
INVISIBLE -> extendTopSquare.model
|
||||
else -> null
|
||||
}
|
||||
|
||||
val extendBottomSquare = model { columnSideSquare(-0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) }
|
||||
val extendBottomRoundSmall = model { columnSide(radiusSmall, -0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) }
|
||||
val extendBottomRoundLarge = model { columnSide(radiusLarge, -0.5 - radiusLarge, -0.5, bottomExtension(radiusLarge)) }
|
||||
inline fun extendBottom(type: QuadrantType) = when (type) {
|
||||
SMALL_RADIUS -> extendBottomRoundSmall.model
|
||||
LARGE_RADIUS -> extendBottomRoundLarge.model
|
||||
SQUARE -> extendBottomSquare.model
|
||||
INVISIBLE -> extendBottomSquare.model
|
||||
else -> null
|
||||
}
|
||||
|
||||
val topSquare = model { columnLidSquare() }
|
||||
val topRoundSmall = model { columnLid(radiusSmall) }
|
||||
val topRoundLarge = model { columnLid(radiusLarge) }
|
||||
inline fun flatTop(type: QuadrantType) = when(type) {
|
||||
SMALL_RADIUS -> topRoundSmall.model
|
||||
LARGE_RADIUS -> topRoundLarge.model
|
||||
SQUARE -> topSquare.model
|
||||
INVISIBLE -> topSquare.model
|
||||
else -> null
|
||||
}
|
||||
|
||||
val bottomSquare = model { columnLidSquare() { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } }
|
||||
val bottomRoundSmall = model { columnLid(radiusSmall) { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } }
|
||||
val bottomRoundLarge = model { columnLid(radiusLarge) { it.rotate(rot(EAST) * 2 + rot(UP)).mirrorUV(true, true) } }
|
||||
inline fun flatBottom(type: QuadrantType) = when(type) {
|
||||
SMALL_RADIUS -> bottomRoundSmall.model
|
||||
LARGE_RADIUS -> bottomRoundLarge.model
|
||||
SQUARE -> bottomSquare.model
|
||||
INVISIBLE -> bottomSquare.model
|
||||
else -> null
|
||||
}
|
||||
|
||||
val transitionTop = model { mix(sideRoundLarge.model, sideRoundSmall.model) { it > 1 } }
|
||||
val transitionBottom = model { mix(sideRoundSmall.model, sideRoundLarge.model) { it > 1 } }
|
||||
|
||||
inline fun continuous(q1: QuadrantType, q2: QuadrantType) =
|
||||
q1 == q2 || ((q1 == SQUARE || q1 == INVISIBLE) && (q2 == SQUARE || q2 == INVISIBLE))
|
||||
|
||||
@Suppress("NON_EXHAUSTIVE_WHEN")
|
||||
override fun render(ctx: CombinedContext) {
|
||||
|
||||
val roundLog = ChunkOverlayManager.get(overlayLayer, ctx)
|
||||
when(roundLog) {
|
||||
ColumnLayerData.SkipRender -> return
|
||||
ColumnLayerData.NormalRender -> return ctx.render()
|
||||
ColumnLayerData.ResolveError, null -> {
|
||||
BetterFoliage.logRenderError(ctx.state, ctx.pos)
|
||||
return ctx.render()
|
||||
}
|
||||
}
|
||||
|
||||
// if log axis is not defined and "Default to vertical" config option is not set, render normally
|
||||
if ((roundLog as ColumnLayerData.SpecialRender).column.axis == null && !overlayLayer.defaultToY) {
|
||||
return ctx.render()
|
||||
}
|
||||
|
||||
val baseRotation = rotationFromUp[((roundLog.column.axis ?: Axis.Y) to AxisDirection.POSITIVE).face.ordinal]
|
||||
renderAs(ctx, MODEL) {
|
||||
quadrantRotations.forEachIndexed { idx, quadrantRotation ->
|
||||
// set rotation for the current quadrant
|
||||
val rotation = baseRotation + quadrantRotation
|
||||
|
||||
// disallow sharp discontinuities in the chamfer radius, or tapering-in where inappropriate
|
||||
if (roundLog.quadrants[idx] == LARGE_RADIUS &&
|
||||
roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] != LARGE_RADIUS &&
|
||||
roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] != LARGE_RADIUS) {
|
||||
roundLog.quadrants[idx] = SMALL_RADIUS
|
||||
}
|
||||
|
||||
// render side of current quadrant
|
||||
val sideModel = when (roundLog.quadrants[idx]) {
|
||||
SMALL_RADIUS -> sideRoundSmall.model
|
||||
LARGE_RADIUS -> if (roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] == SMALL_RADIUS) transitionTop.model
|
||||
else if (roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] == SMALL_RADIUS) transitionBottom.model
|
||||
else sideRoundLarge.model
|
||||
SQUARE -> sideSquare.model
|
||||
else -> null
|
||||
}
|
||||
|
||||
if (sideModel != null) ctx.render(
|
||||
sideModel,
|
||||
rotation,
|
||||
icon = roundLog.column.side,
|
||||
postProcess = noPost
|
||||
)
|
||||
|
||||
// render top and bottom end of current quadrant
|
||||
var upModel: Model? = null
|
||||
var downModel: Model? = null
|
||||
var upIcon = roundLog.column.top
|
||||
var downIcon = roundLog.column.bottom
|
||||
var isLidUp = true
|
||||
var isLidDown = true
|
||||
|
||||
when (roundLog.upType) {
|
||||
NONSOLID -> upModel = flatTop(roundLog.quadrants[idx])
|
||||
PERPENDICULAR -> {
|
||||
if (!connectPerpendicular) {
|
||||
upModel = flatTop(roundLog.quadrants[idx])
|
||||
} else {
|
||||
upIcon = roundLog.column.side
|
||||
upModel = extendTop(roundLog.quadrants[idx])
|
||||
isLidUp = false
|
||||
}
|
||||
}
|
||||
PARALLEL -> {
|
||||
if (!continuous(roundLog.quadrants[idx], roundLog.quadrantsTop[idx])) {
|
||||
if (roundLog.quadrants[idx] == SQUARE || roundLog.quadrants[idx] == INVISIBLE) {
|
||||
upModel = topSquare.model
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
when (roundLog.downType) {
|
||||
NONSOLID -> downModel = flatBottom(roundLog.quadrants[idx])
|
||||
PERPENDICULAR -> {
|
||||
if (!connectPerpendicular) {
|
||||
downModel = flatBottom(roundLog.quadrants[idx])
|
||||
} else {
|
||||
downIcon = roundLog.column.side
|
||||
downModel = extendBottom(roundLog.quadrants[idx])
|
||||
isLidDown = false
|
||||
}
|
||||
}
|
||||
PARALLEL -> {
|
||||
if (!continuous(roundLog.quadrants[idx], roundLog.quadrantsBottom[idx]) &&
|
||||
(roundLog.quadrants[idx] == SQUARE || roundLog.quadrants[idx] == INVISIBLE)) {
|
||||
downModel = bottomSquare.model
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (upModel != null) ctx.render(
|
||||
upModel,
|
||||
rotation,
|
||||
icon = upIcon,
|
||||
postProcess = { _, _, _, _, _ ->
|
||||
if (isLidUp) {
|
||||
rotateUV(idx + if (roundLog.column.axis == Axis.X) 1 else 0)
|
||||
}
|
||||
}
|
||||
)
|
||||
if (downModel != null) ctx.render(
|
||||
downModel,
|
||||
rotation,
|
||||
icon = downIcon,
|
||||
postProcess = { _, _, _, _, _ ->
|
||||
if (isLidDown) {
|
||||
rotateUV((if (roundLog.column.axis == Axis.X) 0 else 3) - idx)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
package mods.betterfoliage.client.render.column
|
||||
|
||||
import mods.octarinecore.client.render.lighting.QuadIconResolver
|
||||
import mods.octarinecore.common.rotate
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite
|
||||
import net.minecraft.util.Direction.*
|
||||
|
||||
interface ColumnTextureInfo {
|
||||
val axis: Axis?
|
||||
val top: QuadIconResolver
|
||||
val bottom: QuadIconResolver
|
||||
val side: QuadIconResolver
|
||||
}
|
||||
|
||||
open class SimpleColumnInfo(
|
||||
override val axis: Axis?,
|
||||
val topTexture: TextureAtlasSprite,
|
||||
val bottomTexture: TextureAtlasSprite,
|
||||
val sideTextures: List<TextureAtlasSprite>
|
||||
) : ColumnTextureInfo {
|
||||
|
||||
// index offsets for EnumFacings, to make it less likely for neighboring faces to get the same bark texture
|
||||
val dirToIdx = arrayOf(0, 1, 2, 4, 3, 5)
|
||||
|
||||
override val top: QuadIconResolver = { _, _, _ -> topTexture }
|
||||
override val bottom: QuadIconResolver = { _, _, _ -> bottomTexture }
|
||||
override val side: QuadIconResolver = { ctx, idx, _ ->
|
||||
val worldFace = (if ((idx and 1) == 0) SOUTH else EAST).rotate(ctx.modelRotation)
|
||||
val sideIdx = if (sideTextures.size > 1) (ctx.semiRandom(1) + dirToIdx[worldFace.ordinal]) % sideTextures.size else 0
|
||||
sideTextures[sideIdx]
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package mods.betterfoliage.client.resource
|
||||
|
||||
import net.minecraft.client.renderer.model.ModelResourceLocation
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite
|
||||
import net.minecraft.util.ResourceLocation
|
||||
|
||||
typealias Identifier = ResourceLocation
|
||||
typealias ModelIdentifier = ModelResourceLocation
|
||||
|
||||
typealias Sprite = TextureAtlasSprite
|
||||
@@ -1,65 +0,0 @@
|
||||
package mods.betterfoliage.client.texture
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.render.lighting.HSB
|
||||
import mods.octarinecore.client.resource.*
|
||||
import mods.octarinecore.common.config.ConfigurableBlockMatcher
|
||||
import mods.octarinecore.common.config.ModelTextureList
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite
|
||||
import org.apache.logging.log4j.Level
|
||||
import java.lang.Math.min
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
const val defaultGrassColor = 0
|
||||
|
||||
/** Rendering-related information for a grass block. */
|
||||
class GrassInfo(
|
||||
/** Top texture of the grass block. */
|
||||
val grassTopTexture: TextureAtlasSprite,
|
||||
|
||||
/**
|
||||
* Color to use for Short Grass rendering instead of the biome color.
|
||||
*
|
||||
* Value is null if the texture is mostly grey (the saturation of its average color is under a configurable limit),
|
||||
* the average color of the texture otherwise.
|
||||
*/
|
||||
val overrideColor: Int?
|
||||
)
|
||||
|
||||
object GrassRegistry : ModelRenderRegistryRoot<GrassInfo>()
|
||||
|
||||
object AsyncGrassDiscovery : ConfigurableModelDiscovery<GrassInfo>() {
|
||||
override val logger = BetterFoliage.logDetail
|
||||
override val matchClasses: ConfigurableBlockMatcher get() = BlockConfig.grassBlocks
|
||||
override val modelTextures: List<ModelTextureList> get() = BlockConfig.grassModels.modelList
|
||||
|
||||
override fun processModel(state: BlockState, textures: List<String>, atlas: AtlasFuture): CompletableFuture<GrassInfo> {
|
||||
val textureName = textures[0]
|
||||
val spriteF = atlas.sprite(Identifier(textureName))
|
||||
logger.log(Level.DEBUG, "$logName: texture $textureName")
|
||||
return atlas.mapAfter {
|
||||
val sprite = spriteF.get()
|
||||
logger.log(Level.DEBUG, "$logName: block state $state")
|
||||
logger.log(Level.DEBUG, "$logName: texture $textureName")
|
||||
val hsb = HSB.fromColor(sprite.averageColor)
|
||||
val overrideColor = if (hsb.saturation >= Config.shortGrass.saturationThreshold) {
|
||||
logger.log(Level.DEBUG, "$logName: brightness ${hsb.brightness}")
|
||||
logger.log(Level.DEBUG, "$logName: saturation ${hsb.saturation} >= ${Config.shortGrass.saturationThreshold}, using texture color")
|
||||
hsb.copy(brightness = min(0.9f, hsb.brightness * 2.0f)).asColor
|
||||
} else {
|
||||
logger.log(Level.DEBUG, "$logName: saturation ${hsb.saturation} < ${Config.shortGrass.saturationThreshold}, using block color")
|
||||
null
|
||||
}
|
||||
GrassInfo(sprite, overrideColor)
|
||||
}
|
||||
}
|
||||
|
||||
fun init() {
|
||||
GrassRegistry.registries.add(this)
|
||||
BetterFoliage.blockSprites.providers.add(this)
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
package mods.betterfoliage.client.texture
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BetterFoliageMod
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.betterfoliage.client.resource.Sprite
|
||||
import mods.octarinecore.client.resource.*
|
||||
import mods.octarinecore.stripStart
|
||||
import mods.octarinecore.client.resource.Atlas
|
||||
import mods.octarinecore.common.sinkAsync
|
||||
import net.minecraft.client.particle.ParticleManager
|
||||
import net.minecraft.resources.IResourceManager
|
||||
import net.minecraft.util.ResourceLocation
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
class FixedSpriteSet(val sprites: List<Sprite>) : SpriteSet {
|
||||
override val num = sprites.size
|
||||
override fun get(idx: Int) = sprites[idx % num]
|
||||
}
|
||||
|
||||
object LeafParticleRegistry : AsyncSpriteProvider<ParticleManager> {
|
||||
val targetAtlas = Atlas.PARTICLES
|
||||
val typeMappings = TextureMatcher()
|
||||
val particles = hashMapOf<String, SpriteSet>()
|
||||
|
||||
operator fun get(type: String) = particles[type] ?: particles["default"]!!
|
||||
|
||||
override fun setup(manager: IResourceManager, particleF: CompletableFuture<ParticleManager>, atlasFuture: AtlasFuture): StitchPhases {
|
||||
particles.clear()
|
||||
val futures = mutableMapOf<String, List<CompletableFuture<Sprite>>>()
|
||||
|
||||
return StitchPhases(
|
||||
discovery = particleF.sinkAsync {
|
||||
typeMappings.loadMappings(Identifier(BetterFoliageMod.MOD_ID, "leaf_texture_mappings.cfg"))
|
||||
(typeMappings.mappings.map { it.type } + "default").distinct().forEach { leafType ->
|
||||
val ids = (0 until 16).map { idx -> Identifier(BetterFoliageMod.MOD_ID, "falling_leaf_${leafType}_$idx") }
|
||||
val wids = ids.map { Atlas.PARTICLES.wrap(it) }
|
||||
futures[leafType] = (0 until 16).map { idx -> Identifier(BetterFoliageMod.MOD_ID, "falling_leaf_${leafType}_$idx") }
|
||||
.filter { manager.hasResource(Atlas.PARTICLES.wrap(it)) }
|
||||
.map { atlasFuture.sprite(it) }
|
||||
}
|
||||
},
|
||||
cleanup = atlasFuture.runAfter {
|
||||
futures.forEach { leafType, spriteFutures ->
|
||||
val sprites = spriteFutures.filter { !it.isCompletedExceptionally }.map { it.get() }
|
||||
if (sprites.isNotEmpty()) particles[leafType] = FixedSpriteSet(sprites)
|
||||
}
|
||||
if (particles["default"] == null) particles["default"] = FixedSpriteSet(listOf(atlasFuture.missing.get()!!))
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
fun init() {
|
||||
BetterFoliage.particleSprites.providers.add(this)
|
||||
}
|
||||
}
|
||||
|
||||
class TextureMatcher {
|
||||
|
||||
data class Mapping(val domain: String?, val path: String, val type: String) {
|
||||
fun matches(iconLocation: ResourceLocation): Boolean {
|
||||
return (domain == null || domain == iconLocation.namespace) &&
|
||||
iconLocation.path.stripStart("blocks/").contains(path, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
val mappings: MutableList<Mapping> = mutableListOf()
|
||||
|
||||
fun getType(resource: ResourceLocation) = mappings.filter { it.matches(resource) }.map { it.type }.firstOrNull()
|
||||
fun getType(iconName: String) = ResourceLocation(iconName).let { getType(it) }
|
||||
|
||||
fun loadMappings(mappingLocation: ResourceLocation) {
|
||||
mappings.clear()
|
||||
resourceManager[mappingLocation]?.getLines()?.let { lines ->
|
||||
lines.filter { !it.startsWith("//") }.filter { !it.isEmpty() }.forEach { line ->
|
||||
val line2 = line.trim().split('=')
|
||||
if (line2.size == 2) {
|
||||
val mapping = line2[0].trim().split(':')
|
||||
if (mapping.size == 1) mappings.add(Mapping(null, mapping[0].trim(), line2[1].trim()))
|
||||
else if (mapping.size == 2) mappings.add(Mapping(mapping[0].trim(), mapping[1].trim(), line2[1].trim()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package mods.betterfoliage.client.texture
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.client.config.BlockConfig
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.HasLogger
|
||||
import mods.octarinecore.client.resource.*
|
||||
import mods.octarinecore.common.config.ConfigurableBlockMatcher
|
||||
import mods.octarinecore.common.config.ModelTextureList
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
const val defaultLeafColor = 0
|
||||
|
||||
/** Rendering-related information for a leaf block. */
|
||||
class LeafInfo(
|
||||
/** The generated round leaf texture. */
|
||||
val roundLeafTexture: TextureAtlasSprite,
|
||||
|
||||
/** Type of the leaf block (configurable by user). */
|
||||
val leafType: String,
|
||||
|
||||
/** Average color of the round leaf texture. */
|
||||
val averageColor: Int = roundLeafTexture.averageColor
|
||||
) {
|
||||
/** [IconSet] of the textures to use for leaf particles emitted from this block. */
|
||||
val particleTextures: SpriteSet get() = LeafParticleRegistry[leafType]
|
||||
}
|
||||
|
||||
object LeafRegistry : ModelRenderRegistryRoot<LeafInfo>()
|
||||
|
||||
object AsyncLeafDiscovery : ConfigurableModelDiscovery<LeafInfo>() {
|
||||
override val logger = BetterFoliage.logDetail
|
||||
override val matchClasses: ConfigurableBlockMatcher get() = BlockConfig.leafBlocks
|
||||
override val modelTextures: List<ModelTextureList> get() = BlockConfig.leafModels.modelList
|
||||
|
||||
override fun processModel(state: BlockState, textures: List<String>, atlas: AtlasFuture) = defaultRegisterLeaf(Identifier(textures[0]), atlas)
|
||||
|
||||
fun init() {
|
||||
LeafRegistry.registries.add(this)
|
||||
BetterFoliage.blockSprites.providers.add(this)
|
||||
}
|
||||
}
|
||||
|
||||
fun HasLogger.defaultRegisterLeaf(sprite: Identifier, atlas: AtlasFuture): CompletableFuture<LeafInfo> {
|
||||
val leafType = LeafParticleRegistry.typeMappings.getType(sprite) ?: "default"
|
||||
val generated = GeneratedLeaf(sprite, leafType).register(BetterFoliage.asyncPack)
|
||||
val roundLeaf = atlas.sprite(generated)
|
||||
|
||||
log(" leaf texture $sprite")
|
||||
log(" particle $leafType")
|
||||
return atlas.mapAfter {
|
||||
LeafInfo(roundLeaf.get(), leafType)
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
@file:JvmName("Utils")
|
||||
package mods.betterfoliage.client.texture
|
||||
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.resource.Atlas
|
||||
import mods.octarinecore.client.resource.get
|
||||
import mods.octarinecore.client.resource.loadImage
|
||||
import net.minecraft.resources.IResourceManager
|
||||
import java.io.IOException
|
||||
|
||||
fun blendRGB(rgb1: Int, rgb2: Int, weight1: Int, weight2: Int): Int {
|
||||
val r = (((rgb1 shr 16) and 255) * weight1 + ((rgb2 shr 16) and 255) * weight2) / (weight1 + weight2)
|
||||
val g = (((rgb1 shr 8) and 255) * weight1 + ((rgb2 shr 8) and 255) * weight2) / (weight1 + weight2)
|
||||
val b = ((rgb1 and 255) * weight1 + (rgb2 and 255) * weight2) / (weight1 + weight2)
|
||||
val a = (rgb1 shr 24) and 255
|
||||
val result = ((a shl 24) or (r shl 16) or (g shl 8) or b).toInt()
|
||||
return result
|
||||
}
|
||||
|
||||
fun IResourceManager.loadSprite(id: Identifier) = this.get(id)?.loadImage() ?: throw IOException("Cannot load resource $id")
|
||||
39
src/main/kotlin/mods/betterfoliage/config/BlockConfig.kt
Normal file
39
src/main/kotlin/mods/betterfoliage/config/BlockConfig.kt
Normal file
@@ -0,0 +1,39 @@
|
||||
package mods.betterfoliage.config
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.resource.VeryEarlyReloadListener
|
||||
import mods.betterfoliage.resource.discovery.ConfigurableBlockMatcher
|
||||
import mods.betterfoliage.resource.discovery.ModelTextureListConfiguration
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.util.Identifier
|
||||
|
||||
class BlockConfig : VeryEarlyReloadListener {
|
||||
private val list = mutableListOf<Any>()
|
||||
|
||||
val leafBlocks = blocks("leaves_blocks_default.cfg")
|
||||
val leafModels = models("leaves_models_default.cfg")
|
||||
val grassBlocks = blocks("grass_blocks_default.cfg")
|
||||
val grassModels = models("grass_models_default.cfg")
|
||||
// val mycelium = blocks("mycelium_blocks_default.cfg")
|
||||
// val dirt = blocks("dirt_default.cfg")
|
||||
// val crops = blocks("crop_default.cfg")
|
||||
val logBlocks = blocks("log_blocks_default.cfg")
|
||||
val logModels = models("log_models_default.cfg")
|
||||
// val sand = blocks("sand_default.cfg")
|
||||
// val lilypad = blocks("lilypad_default.cfg")
|
||||
// val cactus = blocks("cactus_default.cfg")
|
||||
// val netherrack = blocks("netherrack_blocks_default.cfg")
|
||||
|
||||
private fun blocks(cfgName: String) = ConfigurableBlockMatcher(Identifier(BetterFoliage.MOD_ID, cfgName)).apply { list.add(this) }
|
||||
private fun models(cfgName: String) = ModelTextureListConfiguration(Identifier(BetterFoliage.MOD_ID, cfgName)).apply { list.add(this) }
|
||||
|
||||
|
||||
override fun getFabricId() = Identifier(BetterFoliage.MOD_ID, "block-config")
|
||||
|
||||
override fun onReloadStarted(manager: ResourceManager) {
|
||||
list.forEach { when(it) {
|
||||
is ConfigurableBlockMatcher -> it.readDefaults(manager)
|
||||
is ModelTextureListConfiguration -> it.readDefaults(manager)
|
||||
} }
|
||||
}
|
||||
}
|
||||
141
src/main/kotlin/mods/betterfoliage/config/Delegate.kt
Normal file
141
src/main/kotlin/mods/betterfoliage/config/Delegate.kt
Normal file
@@ -0,0 +1,141 @@
|
||||
package mods.betterfoliage.config
|
||||
|
||||
import me.shedaniel.clothconfig2.api.AbstractConfigListEntry
|
||||
import me.shedaniel.clothconfig2.api.ConfigEntryBuilder
|
||||
import me.shedaniel.clothconfig2.gui.entries.SubCategoryListEntry
|
||||
import me.zeroeightsix.fiber.builder.ConfigValueBuilder
|
||||
import me.zeroeightsix.fiber.tree.ConfigLeaf
|
||||
import me.zeroeightsix.fiber.tree.ConfigNode
|
||||
import me.zeroeightsix.fiber.tree.ConfigValue
|
||||
import net.minecraft.client.resource.language.I18n
|
||||
import net.minecraft.text.LiteralText
|
||||
import java.util.*
|
||||
import kotlin.properties.ReadOnlyProperty
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
const val MAX_LINE_LEN = 30
|
||||
|
||||
fun textify(string: String) = LiteralText(string)
|
||||
fun textify(strings: Array<String>) = strings.map(::LiteralText).toTypedArray()
|
||||
|
||||
sealed class DelegatingConfigNode<N: ConfigLeaf>(val fiberNode: N) {
|
||||
abstract fun createClothNode(names: List<String>): AbstractConfigListEntry<*>
|
||||
}
|
||||
|
||||
abstract class DelegatingConfigValue<T>(fiberNode: ConfigValue<T>) : DelegatingConfigNode<ConfigValue<T>>(fiberNode), ReadOnlyProperty<DelegatingConfigGroup, T>
|
||||
|
||||
open class DelegatingConfigGroup(fiberNode: ConfigNode) : DelegatingConfigNode<ConfigNode>(fiberNode) {
|
||||
val children = mutableListOf<DelegatingConfigNode<*>>()
|
||||
override fun createClothNode(names: List<String>): SubCategoryListEntry {
|
||||
val builder = ConfigEntryBuilder.create()
|
||||
.startSubCategory(textify(names.joinToString(".").translate()))
|
||||
.setTooltip(*textify(names.joinToString(".").translateTooltip()))
|
||||
.setExpanded(false)
|
||||
children.forEach { builder.add(it.createClothNode(names + it.fiberNode.name!!)) }
|
||||
return builder.build()
|
||||
}
|
||||
operator fun get(name: String) = children.find { it.fiberNode.name == name }
|
||||
}
|
||||
|
||||
interface DelegatingConfigGroupFactory<T> {
|
||||
operator fun provideDelegate(parent: DelegatingConfigGroup, property: KProperty<*>): ReadOnlyProperty<DelegatingConfigGroup, T>
|
||||
}
|
||||
|
||||
fun <T: DelegatingConfigGroup> subNode(factory: (ConfigNode)->T) = object : DelegatingConfigGroupFactory<T> {
|
||||
override operator fun provideDelegate(parent: DelegatingConfigGroup, property: KProperty<*>): ReadOnlyProperty<DelegatingConfigGroup, T> {
|
||||
val childNode = ConfigNode(property.name, null)
|
||||
val configGroup = factory(childNode)
|
||||
parent.fiberNode.items.add(childNode)
|
||||
parent.children.add(configGroup)
|
||||
return object : ReadOnlyProperty<DelegatingConfigGroup, T> {
|
||||
override fun getValue(thisRef: DelegatingConfigGroup, property: KProperty<*>) = configGroup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
interface DelegatingConfigValueFactory<T> {
|
||||
fun createFiberNode(parent: ConfigNode, name: String): ConfigValue<T>
|
||||
fun createClothNode(node: ConfigValue<T>, names: List<String>): AbstractConfigListEntry<T>
|
||||
|
||||
operator fun provideDelegate(parent: DelegatingConfigGroup, property: KProperty<*>): ReadOnlyProperty<DelegatingConfigGroup, T> {
|
||||
return object : DelegatingConfigValue<T>(createFiberNode(parent.fiberNode, property.name)) {
|
||||
override fun createClothNode(names: List<String>) = createClothNode(fiberNode, names)
|
||||
override fun getValue(thisRef: DelegatingConfigGroup, property: KProperty<*>) = fiberNode.value!!
|
||||
}.apply { parent.children.add(this) }
|
||||
}
|
||||
}
|
||||
|
||||
fun String.translate() = I18n.translate(this)
|
||||
fun String.translateTooltip(lineLength: Int = MAX_LINE_LEN) = ("$this.tooltip").translate().let { tooltip ->
|
||||
tooltip.splitToSequence(" ").fold(mutableListOf("")) { tooltips, word ->
|
||||
if (tooltips.last().length + word.length < lineLength) {
|
||||
tooltips[tooltips.lastIndex] += "$word "
|
||||
} else {
|
||||
tooltips.add("$word ")
|
||||
}
|
||||
tooltips
|
||||
}.map { it.trim() }.toTypedArray()
|
||||
}
|
||||
|
||||
fun boolean(
|
||||
default: Boolean,
|
||||
langKey: (List<String>)->String = { it.joinToString(".") },
|
||||
valueOverride: (Boolean)->Boolean = { it }
|
||||
) = object : DelegatingConfigValueFactory<Boolean> {
|
||||
override fun createFiberNode(parent: ConfigNode, name: String) = ConfigValueBuilder(Boolean::class.java)
|
||||
.withName(name)
|
||||
.withParent(parent)
|
||||
.withDefaultValue(default)
|
||||
.build()
|
||||
|
||||
override fun createClothNode(node: ConfigValue<Boolean>, names: List<String>) = ConfigEntryBuilder.create()
|
||||
.startBooleanToggle(textify(langKey(names).translate()), node.value!!)
|
||||
.setTooltip(langKey(names).let { if (I18n.hasTranslation("$it.tooltip")) Optional.of(textify(it.translateTooltip())) else Optional.empty() })
|
||||
.setSaveConsumer { node.value = valueOverride(it) }
|
||||
.build()
|
||||
}
|
||||
|
||||
fun integer(
|
||||
default: Int, min: Int, max: Int,
|
||||
langKey: (List<String>)->String = { it.joinToString(".") },
|
||||
valueOverride: (Int)->Int = { it }
|
||||
) = object : DelegatingConfigValueFactory<Int> {
|
||||
override fun createFiberNode(parent: ConfigNode, name: String) = ConfigValueBuilder(Int::class.java)
|
||||
.withName(name)
|
||||
.withParent(parent)
|
||||
.withDefaultValue(default)
|
||||
.constraints().minNumerical(min).maxNumerical(max).finish()
|
||||
.build()
|
||||
|
||||
override fun createClothNode(node: ConfigValue<Int>, names: List<String>) = ConfigEntryBuilder.create()
|
||||
.startIntField(textify(langKey(names).translate()), node.value!!)
|
||||
.setTooltip(langKey(names).let { if (I18n.hasTranslation("$it.tooltip")) Optional.of(textify(it.translateTooltip())) else Optional.empty() })
|
||||
.setMin(min).setMax(max)
|
||||
.setSaveConsumer { node.value = valueOverride(it) }
|
||||
.build()
|
||||
}
|
||||
|
||||
fun double(
|
||||
default: Double, min: Double, max: Double,
|
||||
langKey: (List<String>)->String = { it.joinToString(".") },
|
||||
valueOverride: (Double)->Double = { it }
|
||||
) = object : DelegatingConfigValueFactory<Double> {
|
||||
override fun createFiberNode(parent: ConfigNode, name: String) = ConfigValueBuilder(Double::class.java)
|
||||
.withName(name)
|
||||
.withParent(parent)
|
||||
.withDefaultValue(default)
|
||||
.constraints().minNumerical(min).maxNumerical(max).finish()
|
||||
.build()
|
||||
|
||||
override fun createClothNode(node: ConfigValue<Double>, names: List<String>) = ConfigEntryBuilder.create()
|
||||
.startDoubleField(textify(langKey(names).translate()), node.value!!)
|
||||
.setTooltip(langKey(names).let { if (I18n.hasTranslation("$it.tooltip")) Optional.of(textify(it.translateTooltip())) else Optional.empty() })
|
||||
.setMin(min).setMax(max)
|
||||
.setSaveConsumer { node.value = valueOverride(it) }
|
||||
.build()
|
||||
}
|
||||
|
||||
val recurring = { names: List<String> -> "${names.first()}.${names.last()}" }
|
||||
fun fakeCategory(name: String) = { names: List<String> ->
|
||||
(listOf(names.first(), name) + names.drop(1)).joinToString(".")
|
||||
}
|
||||
158
src/main/kotlin/mods/betterfoliage/config/MainConfig.kt
Normal file
158
src/main/kotlin/mods/betterfoliage/config/MainConfig.kt
Normal file
@@ -0,0 +1,158 @@
|
||||
package mods.betterfoliage.config
|
||||
|
||||
import me.zeroeightsix.fiber.tree.ConfigNode
|
||||
import java.util.*
|
||||
|
||||
interface PopulationConfigData {
|
||||
val enabled: Boolean
|
||||
val population: Int
|
||||
fun enabled(random: Random) = random.nextInt(64) < population && enabled
|
||||
}
|
||||
|
||||
fun population(default: Int) = integer(default, min = 0, max = 64, langKey = recurring)
|
||||
|
||||
class MainConfig : DelegatingConfigGroup(ConfigNode("root", null)) {
|
||||
|
||||
val enabled by boolean(true, langKey = fakeCategory("global"))
|
||||
val nVidia by boolean(true, langKey = fakeCategory("global"))
|
||||
|
||||
val leaves by subNode { LeavesConfig(it) }
|
||||
val shortGrass by subNode { ShortGrassConfig(it) }
|
||||
val connectedGrass by subNode { ConnectedGrassConfig(it) }
|
||||
val roundLogs by subNode { RoundLogConfig(it) }
|
||||
val cactus by subNode { CactusConfig(it) }
|
||||
val lilypad by subNode { LilypadConfig(it) }
|
||||
val reed by subNode { ReedConfig(it) }
|
||||
val algae by subNode { AlgaeConfig(it) }
|
||||
val coral by subNode { CoralConfig(it) }
|
||||
val netherrack by subNode { NetherrackConfig(it) }
|
||||
val fallingLeaves by subNode { FallingLeavesConfig(it) }
|
||||
val risingSoul by subNode { RisingSoulConfig(it) }
|
||||
}
|
||||
|
||||
class LeavesConfig(node: ConfigNode) : DelegatingConfigGroup(node) {
|
||||
val enabled by boolean(true, langKey = recurring)
|
||||
val snowEnabled by boolean(true)
|
||||
val dense by boolean(false)
|
||||
val hideInternal by boolean(true)
|
||||
|
||||
val hOffset by double(0.2, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val vOffset by double(0.1, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val size by double(1.4, min = 0.75, max = 2.5, langKey = recurring)
|
||||
val shaderWind by boolean(true, langKey = recurring)
|
||||
val saturationThreshold by double(0.1, min = 0.0, max = 1.0, langKey = recurring)
|
||||
}
|
||||
|
||||
class ShortGrassConfig(node: ConfigNode) : DelegatingConfigGroup(node), PopulationConfigData {
|
||||
override val enabled by boolean(true, langKey = recurring)
|
||||
val myceliumEnabled by boolean(true)
|
||||
val snowEnabled by boolean(true)
|
||||
val hOffset by double(0.2, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val heightMin by double(0.6, min = 0.1, max = 2.5, langKey = recurring)
|
||||
val heightMax by double(0.6, min = 0.1, max = 2.5, langKey = recurring) { it.coerceAtLeast(heightMin) }
|
||||
val size by double(1.0, min = 0.5, max = 1.5, langKey = recurring)
|
||||
override val population by population(64)
|
||||
val useGenerated by boolean(false)
|
||||
val shaderWind by boolean(true, langKey = recurring)
|
||||
val saturationThreshold by double(0.1, min = 0.0, max = 1.0, langKey = recurring)
|
||||
}
|
||||
|
||||
class ConnectedGrassConfig(node: ConfigNode) : DelegatingConfigGroup(node) {
|
||||
val enabled by boolean(true, langKey = recurring)
|
||||
val snowEnabled by boolean(true)
|
||||
}
|
||||
|
||||
class RoundLogConfig(node: ConfigNode) : DelegatingConfigGroup(node) {
|
||||
val enabled by boolean(true, langKey = recurring)
|
||||
|
||||
val defaultY by boolean(false)
|
||||
val connectSolids by boolean(false)
|
||||
val lenientConnect by boolean(true)
|
||||
val connectPerpendicular by boolean(true)
|
||||
val connectGrass by boolean(true)
|
||||
|
||||
val radiusSmall by double(0.25, min = 0.0, max = 0.5)
|
||||
val radiusLarge by double(0.44, min = 0.0, max = 0.5) { it.coerceAtLeast(radiusSmall) }
|
||||
val dimming by double(0.7, min = 0.0, max = 1.0)
|
||||
val zProtection by double(0.99, min = 0.9, max = 1.0)
|
||||
}
|
||||
|
||||
class CactusConfig(node: ConfigNode) : DelegatingConfigGroup(node) {
|
||||
val enabled by boolean(true, langKey = recurring)
|
||||
val size by double(1.3, min = 1.0, max = 2.0, langKey = recurring)
|
||||
val sizeVariation by double(0.1, min = 0.0, max = 0.5)
|
||||
val hOffset by double(0.1, min = 0.0, max = 0.5, langKey = recurring)
|
||||
}
|
||||
|
||||
class LilypadConfig(node: ConfigNode) : DelegatingConfigGroup(node), PopulationConfigData {
|
||||
override val enabled by boolean(true, langKey = recurring)
|
||||
val hOffset by double(0.1, min = 0.0, max = 0.25, langKey = recurring)
|
||||
override val population by population(16)
|
||||
val shaderWind by boolean(true, langKey = recurring)
|
||||
}
|
||||
|
||||
class ReedConfig(node: ConfigNode) : DelegatingConfigGroup(node), PopulationConfigData {
|
||||
override val enabled by boolean(true, langKey = recurring)
|
||||
val hOffset by double(0.2, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val heightMin by double(1.7, min = 1.5, max = 3.0, langKey = recurring)
|
||||
val heightMax by double(2.2, min = 1.5, max = 3.0, langKey = recurring) { it.coerceAtLeast(heightMin) }
|
||||
override val population by population(32)
|
||||
val minBiomeTemp by double(0.4, min = 0.0, max = 2.0)
|
||||
val minBiomeRainfall by double(0.4, min = 0.0, max = 1.0)
|
||||
val shaderWind by boolean(true, langKey = recurring)
|
||||
}
|
||||
|
||||
class AlgaeConfig(node: ConfigNode) : DelegatingConfigGroup(node), PopulationConfigData {
|
||||
override val enabled by boolean(true, langKey = recurring)
|
||||
val hOffset by double(0.1, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val size by double(1.0, min = 0.5, max = 1.5, langKey = recurring)
|
||||
val heightMin by double(0.5, min = 0.1, max = 1.0, langKey = recurring)
|
||||
val heightMax by double(0.5, min = 0.1, max = 1.0, langKey = recurring) { it.coerceAtLeast(heightMin) }
|
||||
override val population by population(48)
|
||||
val shaderWind by boolean(true, langKey = recurring)
|
||||
}
|
||||
|
||||
class CoralConfig(node: ConfigNode) : DelegatingConfigGroup(node), PopulationConfigData {
|
||||
override val enabled by boolean(true, langKey = recurring)
|
||||
val shallowWater by boolean(false)
|
||||
val hOffset by double(0.2, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val vOffset by double(0.1, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val size by double(0.7, min = 0.5, max = 1.5, langKey = recurring)
|
||||
val crustSize by double(1.4, min = 0.5, max = 1.5)
|
||||
val chance by integer(32, min = 0, max = 64)
|
||||
override val population by population(48)
|
||||
}
|
||||
|
||||
class NetherrackConfig(node: ConfigNode) : DelegatingConfigGroup(node) {
|
||||
val enabled by boolean(true, langKey = recurring)
|
||||
val hOffset by double(0.2, min = 0.0, max = 0.4, langKey = recurring)
|
||||
val size by double(1.0, min = 0.5, max = 1.5, langKey = recurring)
|
||||
val heightMin by double(0.6, min = 0.5, max = 1.5, langKey = recurring)
|
||||
val heightMax by double(0.8, min = 0.5, max = 1.5, langKey = recurring) { it.coerceAtLeast(heightMin) }
|
||||
}
|
||||
|
||||
class FallingLeavesConfig(node: ConfigNode) : DelegatingConfigGroup(node) {
|
||||
val enabled by boolean(true, langKey = recurring)
|
||||
val opacityHack by boolean(false)
|
||||
val speed by double(0.05, min = 0.01, max = 0.15)
|
||||
val windStrength by double(0.5, min = 0.1, max = 2.0)
|
||||
val stormStrength by double(0.8, min = 0.1, max = 2.0) { it.coerceAtLeast(windStrength) }
|
||||
val size by double(0.75, min = 0.25, max = 1.5)
|
||||
val chance by double(0.05, min = 0.001, max = 1.0)
|
||||
val perturb by double(0.25, min = 0.01, max = 1.0)
|
||||
val lifetime by double(7.5, min = 1.0, max = 15.0)
|
||||
}
|
||||
|
||||
class RisingSoulConfig(node: ConfigNode) : DelegatingConfigGroup(node) {
|
||||
val enabled by boolean(true, langKey = recurring)
|
||||
val chance by double(0.02, min = 0.001, max = 1.0)
|
||||
val perturb by double(0.05, min = 0.01, max = 0.25)
|
||||
val headSize by double(1.0, min = 0.25, max = 1.5)
|
||||
val trailSize by double(0.75, min = 0.25, max = 1.5)
|
||||
val opacity by double(0.5, min = 0.05, max = 1.0)
|
||||
val sizeDecay by double(0.97, min = 0.5, max = 1.0)
|
||||
val opacityDecay by double(0.97, min = 0.5, max = 1.0)
|
||||
val lifetime by double(4.0, min = 1.0, max = 15.0)
|
||||
val trailLength by integer(48, min = 2, max = 128)
|
||||
val trailDensity by integer(3, min = 1, max = 16)
|
||||
}
|
||||
13
src/main/kotlin/mods/betterfoliage/config/MiscDefaults.kt
Normal file
13
src/main/kotlin/mods/betterfoliage/config/MiscDefaults.kt
Normal file
@@ -0,0 +1,13 @@
|
||||
package mods.betterfoliage.config
|
||||
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.block.Material
|
||||
import net.minecraft.world.biome.Biome
|
||||
|
||||
val CACTUS_BLOCKS = listOf(Blocks.CACTUS)
|
||||
val DIRT_BLOCKS = listOf(Blocks.DIRT, Blocks.COARSE_DIRT, Blocks.PODZOL)
|
||||
val SAND_BLOCKS = listOf(Blocks.SAND, Blocks.RED_SAND)
|
||||
val NETHERRACK_BLOCKS = listOf(Blocks.NETHERRACK)
|
||||
|
||||
val SALTWATER_BIOMES = listOf(Biome.Category.BEACH, Biome.Category.OCEAN)
|
||||
val SNOW_MATERIALS = listOf(Material.SNOW_BLOCK)
|
||||
31
src/main/kotlin/mods/betterfoliage/integration/ModMenu.kt
Normal file
31
src/main/kotlin/mods/betterfoliage/integration/ModMenu.kt
Normal file
@@ -0,0 +1,31 @@
|
||||
package mods.betterfoliage.integration
|
||||
|
||||
import io.github.prospector.modmenu.api.ModMenuApi
|
||||
import me.shedaniel.clothconfig2.api.ConfigBuilder
|
||||
import me.zeroeightsix.fiber.JanksonSettings
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import net.minecraft.client.MinecraftClient
|
||||
import net.minecraft.client.gui.screen.Screen
|
||||
import net.minecraft.client.resource.language.I18n
|
||||
import net.minecraft.text.LiteralText
|
||||
import java.util.function.Function
|
||||
|
||||
object ModMenu : ModMenuApi {
|
||||
override fun getModId() = BetterFoliage.MOD_ID
|
||||
|
||||
override fun getConfigScreenFactory() = Function { screen: Screen ->
|
||||
val builder = ConfigBuilder.create()
|
||||
.setParentScreen(screen)
|
||||
.setTitle(LiteralText(I18n.translate("betterfoliage.title")))
|
||||
BetterFoliage.config.createClothNode(listOf("betterfoliage")).value.forEach { rootOption ->
|
||||
builder.getOrCreateCategory(LiteralText("main")).addEntry(rootOption)
|
||||
}
|
||||
builder.savingRunnable = Runnable {
|
||||
JanksonSettings().serialize(BetterFoliage.config.fiberNode, BetterFoliage.configFile.outputStream(), false)
|
||||
BakeWrapperManager.invalidate()
|
||||
MinecraftClient.getInstance().worldRenderer.reload()
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
}
|
||||
@@ -1,58 +1,40 @@
|
||||
package mods.betterfoliage.client.integration
|
||||
package mods.betterfoliage.integration
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.client.render.LogRegistry
|
||||
import mods.betterfoliage.client.render.column.ColumnTextureInfo
|
||||
import mods.betterfoliage.client.render.column.SimpleColumnInfo
|
||||
import mods.octarinecore.client.render.CombinedContext
|
||||
import mods.octarinecore.client.render.Quad
|
||||
import mods.octarinecore.client.render.lighting.QuadIconResolver
|
||||
import mods.octarinecore.client.resource.*
|
||||
import mods.octarinecore.common.rotate
|
||||
import mods.octarinecore.metaprog.ClassRef
|
||||
import mods.octarinecore.metaprog.allAvailable
|
||||
import net.minecraft.client.renderer.model.BlockModel
|
||||
import net.minecraft.client.renderer.texture.TextureAtlasSprite
|
||||
import net.minecraft.util.Direction
|
||||
import net.minecraft.util.Direction.*
|
||||
import net.minecraft.util.ResourceLocation
|
||||
import net.minecraftforge.fml.ModList
|
||||
import org.apache.logging.log4j.Level
|
||||
import java.util.concurrent.CompletableFuture
|
||||
|
||||
object IC2RubberIntegration {
|
||||
|
||||
val BlockRubWood = ClassRef<Any>("ic2.core.block.BlockRubWood")
|
||||
// val BlockRubWood = ClassRefOld<Any>("ic2.core.block.BlockRubWood")
|
||||
|
||||
init {
|
||||
if (ModList.get().isLoaded("ic2") && allAvailable(BlockRubWood)) {
|
||||
BetterFoliage.log(Level.INFO, "IC2 rubber support initialized")
|
||||
LogRegistry.registries.add(IC2LogDiscovery)
|
||||
BetterFoliage.blockSprites.providers.add(IC2LogDiscovery)
|
||||
}
|
||||
// if (ModList.get().isLoaded("ic2") && allAvailable(BlockRubWood)) {
|
||||
// BetterFoliage.log(Level.INFO, "IC2 rubber support initialized")
|
||||
// LogRegistry.registries.add(IC2LogDiscovery)
|
||||
// BetterFoliage.blockSprites.providers.add(IC2LogDiscovery)
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
object TechRebornRubberIntegration {
|
||||
|
||||
val BlockRubberLog = ClassRef<Any>("techreborn.blocks.BlockRubberLog")
|
||||
// val BlockRubberLog = ClassRefOld<Any>("techreborn.blocks.BlockRubberLog")
|
||||
|
||||
init {
|
||||
if (ModList.get().isLoaded("techreborn") && allAvailable(BlockRubberLog)) {
|
||||
BetterFoliage.log(Level.INFO, "TechReborn rubber support initialized")
|
||||
LogRegistry.registries.add(TechRebornLogDiscovery)
|
||||
BetterFoliage.blockSprites.providers.add(TechRebornLogDiscovery)
|
||||
}
|
||||
// if (ModList.get().isLoaded("techreborn") && allAvailable(BlockRubberLog)) {
|
||||
// BetterFoliage.log(Level.INFO, "TechReborn rubber support initialized")
|
||||
// LogRegistry.registries.add(TechRebornLogDiscovery)
|
||||
// BetterFoliage.blockSprites.providers.add(TechRebornLogDiscovery)
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
class RubberLogInfo(
|
||||
axis: Axis?,
|
||||
val spotDir: Direction,
|
||||
topTexture: TextureAtlasSprite,
|
||||
bottomTexture: TextureAtlasSprite,
|
||||
val spotTexture: TextureAtlasSprite,
|
||||
sideTextures: List<TextureAtlasSprite>
|
||||
topTexture: Sprite,
|
||||
bottomTexture: Sprite,
|
||||
val spotTexture: Sprite,
|
||||
sideTextures: List<Sprite>
|
||||
) : SimpleColumnInfo(axis, topTexture, bottomTexture, sideTextures) {
|
||||
|
||||
override val side: QuadIconResolver = { ctx: CombinedContext, idx: Int, quad: Quad ->
|
||||
@@ -70,18 +52,18 @@ object IC2LogDiscovery : ModelDiscovery<ColumnTextureInfo>() {
|
||||
override fun processModel(ctx: ModelDiscoveryContext, atlas: AtlasFuture): CompletableFuture<ColumnTextureInfo>? {
|
||||
// check for proper block class, existence of ModelBlock, and "state" blockstate property
|
||||
if (!IC2RubberIntegration.BlockRubWood.isInstance(ctx.state.block)) return null
|
||||
val blockLoc = ctx.models.firstOrNull() as Pair<BlockModel, ResourceLocation> ?: return null
|
||||
val type = ctx.state.values.entries.find { it.key.getName() == "state" }?.value?.toString() ?: return null
|
||||
val blockLoc = ctx.models.firstOrNull() as Pair<JsonUnbakedModel, Identifier> ?: return null
|
||||
val type = ctx.state.entries.entries.find { it.key.getName() == "state" }?.value?.toString() ?: return null
|
||||
|
||||
// logs with no rubber spot
|
||||
if (blockLoc.derivesFrom(ResourceLocation("block/cube_column"))) {
|
||||
if (blockLoc.derivesFrom(Identifier("block/cube_column"))) {
|
||||
val axis = when(type) {
|
||||
"plain_y" -> Axis.Y
|
||||
"plain_x" -> Axis.X
|
||||
"plain_z" -> Axis.Z
|
||||
else -> null
|
||||
}
|
||||
val textureNames = listOf("end", "side").map { blockLoc.first.resolveTextureName(it) }
|
||||
val textureNames = listOf("end", "side").map { blockLoc.first.resolveTexture(it) }
|
||||
if (textureNames.any { it == "missingno" }) return null
|
||||
log("IC2LogSupport: block state ${ctx.state.toString()}")
|
||||
log("IC2LogSupport: axis=$axis, end=${textureNames[0]}, side=${textureNames[1]}")
|
||||
@@ -100,7 +82,7 @@ object IC2LogDiscovery : ModelDiscovery<ColumnTextureInfo>() {
|
||||
"dry_east", "wet_east" -> EAST
|
||||
else -> null
|
||||
}
|
||||
val textureNames = listOf("up", "down", "north", "south").map { blockLoc.first.resolveTextureName(it) }
|
||||
val textureNames = listOf("up", "down", "north", "south").map { blockLoc.first.resolveTexture(it) }
|
||||
if (textureNames.any { it == "missingno" }) return null
|
||||
log("IC2LogSupport: block state ${ctx.state.toString()}")
|
||||
log("IC2LogSupport: spotDir=$spotDir, up=${textureNames[0]}, down=${textureNames[1]}, side=${textureNames[2]}, spot=${textureNames[3]}")
|
||||
@@ -122,14 +104,14 @@ object TechRebornLogDiscovery : ModelDiscovery<ColumnTextureInfo>() {
|
||||
override fun processModel(ctx: ModelDiscoveryContext, atlas: AtlasFuture): CompletableFuture<ColumnTextureInfo>? {
|
||||
// check for proper block class, existence of ModelBlock
|
||||
if (!TechRebornRubberIntegration.BlockRubberLog.isInstance(ctx.state.block)) return null
|
||||
val blockLoc = ctx.models.map { it as? Pair<BlockModel, ResourceLocation> }.firstOrNull() ?: return null
|
||||
val blockLoc = ctx.models.map { it as? Pair<JsonUnbakedModel, Identifier> }.firstOrNull() ?: return null
|
||||
|
||||
val hasSap = ctx.state.values.entries.find { it.key.getName() == "hassap" }?.value as? Boolean ?: return null
|
||||
val sapSide = ctx.state.values.entries.find { it.key.getName() == "sapside" }?.value as? Direction ?: return null
|
||||
val hasSap = ctx.state.entries.entries.find { it.key.getName() == "hassap" }?.value as? Boolean ?: return null
|
||||
val sapSide = ctx.state.entries.entries.find { it.key.getName() == "sapside" }?.value as? Direction ?: return null
|
||||
|
||||
log("$logName: block state ${ctx.state}")
|
||||
if (hasSap) {
|
||||
val textureNames = listOf("end", "side", "sapside").map { blockLoc.first.resolveTextureName(it) }
|
||||
val textureNames = listOf("end", "side", "sapside").map { blockLoc.first.resolveTexture(it) }
|
||||
log("$logName: spotDir=$sapSide, end=${textureNames[0]}, side=${textureNames[2]}, spot=${textureNames[3]}")
|
||||
if (textureNames.all { it != "missingno" }) {
|
||||
val endSprite = atlas.sprite(textureNames[0])
|
||||
@@ -140,7 +122,7 @@ object TechRebornLogDiscovery : ModelDiscovery<ColumnTextureInfo>() {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
val textureNames = listOf("end", "side").map { blockLoc.first.resolveTextureName(it) }
|
||||
val textureNames = listOf("end", "side").map { blockLoc.first.resolveTexture(it) }
|
||||
log("$logName: end=${textureNames[0]}, side=${textureNames[1]}")
|
||||
if (textureNames.all { it != "missingno" }) {
|
||||
val endSprite = atlas.sprite(textureNames[0])
|
||||
@@ -152,4 +134,6 @@ object TechRebornLogDiscovery : ModelDiscovery<ColumnTextureInfo>() {
|
||||
}
|
||||
return null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*/
|
||||
117
src/main/kotlin/mods/betterfoliage/model/Meshify.kt
Normal file
117
src/main/kotlin/mods/betterfoliage/model/Meshify.kt
Normal file
@@ -0,0 +1,117 @@
|
||||
package mods.betterfoliage.model
|
||||
|
||||
import mods.betterfoliage.BakedQuad_sprite
|
||||
import mods.betterfoliage.VertexFormat_offsets
|
||||
import mods.betterfoliage.util.Double3
|
||||
import mods.betterfoliage.util.allDirections
|
||||
import mods.betterfoliage.util.findFirst
|
||||
import mods.betterfoliage.util.get
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.VertexFormat
|
||||
import net.minecraft.client.render.VertexFormatElement
|
||||
import net.minecraft.client.render.VertexFormatElement.Format.FLOAT
|
||||
import net.minecraft.client.render.VertexFormatElement.Format.UBYTE
|
||||
import net.minecraft.client.render.VertexFormatElement.Type.*
|
||||
import net.minecraft.client.render.VertexFormatElement.Type.UV
|
||||
import net.minecraft.client.render.VertexFormats
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BakedQuad
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.util.math.Direction
|
||||
import java.util.*
|
||||
|
||||
interface BakedModelConverter {
|
||||
/**
|
||||
* Convert baked model. Returns null if conversion unsuccessful (wrong input type).
|
||||
* @param model Input model
|
||||
* @param converter Converter to use for converting nested models.
|
||||
*/
|
||||
fun convert(model: BakedModel): BakedModel?
|
||||
companion object {
|
||||
fun of(func: (BakedModel)->BakedModel?) = object : BakedModelConverter {
|
||||
override fun convert(model: BakedModel) = func(model)
|
||||
}
|
||||
val identity = of { model -> model }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert [BakedModel] using the provided list of [BakedModelConverter]s (in order).
|
||||
* If all converters fail, gives the original model back.
|
||||
*/
|
||||
fun List<BakedModelConverter>.convert(model: BakedModel) = object : BakedModelConverter {
|
||||
val converters = this@convert + BakedModelConverter.identity
|
||||
override fun convert(model: BakedModel) = converters.findFirst { it.convert(model) }
|
||||
}.let { converterStack ->
|
||||
// we are guaranteed a result here because of the identity converter
|
||||
converterStack.convert(model)!!
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert [BasicBakedModel] into one using fabric-rendering-api [Mesh] instead of the vanilla pipeline.
|
||||
* @param blendMode Use the given [BlockRenderLayer] for the [Mesh]
|
||||
* instead of the one declared by the corresponding [Block]
|
||||
*/
|
||||
fun meshifyStandard(model: BasicBakedModel, state: BlockState? = null, blendMode: BlendMode? = null) =
|
||||
WrappedMeshModel.converter(state, blendModeOverride = blendMode).convert(model)!!
|
||||
|
||||
fun meshifySolid(model: BasicBakedModel) = meshifyStandard(model, null, BlendMode.SOLID)
|
||||
fun meshifyCutoutMipped(model: BasicBakedModel) = meshifyStandard(model, null, BlendMode.CUTOUT_MIPPED)
|
||||
|
||||
/**
|
||||
* Convert a vanilla [BakedModel] into intermediate [Quad]s
|
||||
* Vertex normals not supported (yet)
|
||||
* Vertex data elements not aligned to 32 bit boundaries not supported
|
||||
*/
|
||||
fun unbakeQuads(model: BakedModel, state: BlockState?, random: Random, unshade: Boolean): List<Quad> {
|
||||
return (allDirections.toList() + null as Direction?).flatMap { face ->
|
||||
model.getQuads(state, face, random).mapIndexed { qIdx, bakedQuad ->
|
||||
var quad = Quad(Vertex(), Vertex(), Vertex(), Vertex(), face = face, colorIndex = bakedQuad.colorIndex, sprite = bakedQuad[BakedQuad_sprite])
|
||||
|
||||
val format = quadVertexFormat(bakedQuad)
|
||||
val stride = format.vertexSizeInteger
|
||||
format.getIntOffset(POSITION, FLOAT, 3)?.let { posOffset ->
|
||||
quad = quad.transformVI { vertex, vIdx -> vertex.copy(xyz = Double3(
|
||||
x = java.lang.Float.intBitsToFloat(bakedQuad.vertexData[vIdx * stride + posOffset + 0]).toDouble(),
|
||||
y = java.lang.Float.intBitsToFloat(bakedQuad.vertexData[vIdx * stride + posOffset + 1]).toDouble(),
|
||||
z = java.lang.Float.intBitsToFloat(bakedQuad.vertexData[vIdx * stride + posOffset + 2]).toDouble()
|
||||
)) }
|
||||
}
|
||||
format.getIntOffset(COLOR, UBYTE, 4)?.let { colorOffset ->
|
||||
quad = quad.transformVI { vertex, vIdx -> vertex.copy(
|
||||
color = Color(bakedQuad.vertexData[vIdx * stride + colorOffset])
|
||||
) }
|
||||
}
|
||||
format.getIntOffset(UV, FLOAT, 2, 0)?.let { uvOffset ->
|
||||
quad = quad.transformVI { vertex, vIdx -> vertex.copy(uv = UV(
|
||||
u = java.lang.Float.intBitsToFloat(bakedQuad.vertexData[vIdx * stride + uvOffset + 0]).toDouble(),
|
||||
v = java.lang.Float.intBitsToFloat(bakedQuad.vertexData[vIdx * stride + uvOffset + 1]).toDouble()
|
||||
)) }
|
||||
}
|
||||
|
||||
quad = quad.transformV { it.copy(uv = it.uv.unbake(quad.sprite!!)) }.move(Double3(-0.5, -0.5, -0.5))
|
||||
if (unshade) quad = quad.transformV { it.copy(color = it.color * (1.0f / Color.bakeShade(quad.face))) }
|
||||
quad
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Get the byte offset of the [VertexFormatElement] matching the given criteria */
|
||||
fun VertexFormat.getByteOffset(type: VertexFormatElement.Type, format: VertexFormatElement.Format, count: Int, index: Int = 0): Int? {
|
||||
elements.forEachIndexed { idx, element ->
|
||||
if (element == VertexFormatElement(index, format, type, count))
|
||||
return VertexFormat_offsets[this]!!.getInt(idx)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the int (32 bit) offset of the [VertexFormatElement] matching the given criteria
|
||||
* Returns null if the element is not properly aligned
|
||||
*/
|
||||
fun VertexFormat.getIntOffset(type: VertexFormatElement.Type, format: VertexFormatElement.Format, count: Int, index: Int = 0) =
|
||||
getByteOffset(type, format, count, index)?.let { if (it % 4 == 0) it / 4 else null }
|
||||
|
||||
/** Function to determine [VertexFormat] used by [BakedQuad] */
|
||||
var quadVertexFormat: (BakedQuad)->VertexFormat = { VertexFormats.POSITION_COLOR_TEXTURE_LIGHT_NORMAL }
|
||||
230
src/main/kotlin/mods/betterfoliage/model/Quads.kt
Normal file
230
src/main/kotlin/mods/betterfoliage/model/Quads.kt
Normal file
@@ -0,0 +1,230 @@
|
||||
package mods.betterfoliage.model
|
||||
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.*
|
||||
import mods.betterfoliage.util.minmax
|
||||
import net.fabricmc.fabric.api.renderer.v1.RendererAccess
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh
|
||||
import net.minecraft.client.texture.MissingSprite
|
||||
import net.minecraft.client.texture.Sprite
|
||||
import net.minecraft.util.math.Direction
|
||||
import net.minecraft.util.math.Direction.*
|
||||
import java.lang.Math.max
|
||||
import java.lang.Math.min
|
||||
import java.util.Random
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
/**
|
||||
* Vertex UV coordinates
|
||||
*
|
||||
* Zero-centered: sprite coordinates fall between (-0.5, 0.5)
|
||||
*/
|
||||
data class UV(val u: Double, val v: Double) {
|
||||
companion object {
|
||||
val topLeft = UV(-0.5, -0.5)
|
||||
val topRight = UV(0.5, -0.5)
|
||||
val bottomLeft = UV(-0.5, 0.5)
|
||||
val bottomRight = UV(0.5, 0.5)
|
||||
}
|
||||
|
||||
val rotate: UV get() = UV(v, -u)
|
||||
|
||||
fun rotate(n: Int) = when(n % 4) {
|
||||
0 -> copy()
|
||||
1 -> UV(v, -u)
|
||||
2 -> UV(-u, -v)
|
||||
else -> UV(-v, u)
|
||||
}
|
||||
|
||||
fun clamp(minU: Double = -0.5, maxU: Double = 0.5, minV: Double = -0.5, maxV: Double = 0.5) =
|
||||
UV(u.minmax(minU, maxU), v.minmax(minV, maxV))
|
||||
|
||||
fun mirror(mirrorU: Boolean, mirrorV: Boolean) = UV(if (mirrorU) -u else u, if (mirrorV) -v else v)
|
||||
|
||||
fun unbake(sprite: Sprite) = UV(
|
||||
(u - sprite.minU.toDouble()) / (sprite.maxU - sprite.minU).toDouble() - 0.5,
|
||||
(v - sprite.minV.toDouble()) / (sprite.maxV - sprite.minV).toDouble() - 0.5
|
||||
)
|
||||
}
|
||||
|
||||
data class Color(val alpha: Int, val red: Int, val green: Int, val blue: Int) {
|
||||
constructor(combined: Int) : this(combined shr 24 and 255, combined shr 16 and 255, combined shr 8 and 255, combined and 255)
|
||||
val asInt get() = (alpha shl 24) or (red shl 16) or (green shl 8) or blue
|
||||
operator fun times(f: Float) = Color(
|
||||
alpha,
|
||||
(f * red.toFloat()).toInt().coerceIn(0 until 256),
|
||||
(f * green.toFloat()).toInt().coerceIn(0 until 256),
|
||||
(f * blue.toFloat()).toInt().coerceIn(0 until 256)
|
||||
)
|
||||
companion object {
|
||||
val white get() = Color(255, 255, 255, 255)
|
||||
/** Amount of vanilla diffuse lighting applied to face quads */
|
||||
fun bakeShade(dir: Direction?) = when(dir) {
|
||||
DOWN -> 0.5f
|
||||
NORTH, SOUTH -> 0.8f
|
||||
EAST, WEST -> 0.6f
|
||||
else -> 1.0f
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class HSB(var hue: Float, var saturation: Float, var brightness: Float) {
|
||||
companion object {
|
||||
fun fromColor(color: Int): HSB {
|
||||
val hsbVals = java.awt.Color.RGBtoHSB((color shr 16) and 255, (color shr 8) and 255, color and 255, null)
|
||||
return HSB(hsbVals[0], hsbVals[1], hsbVals[2])
|
||||
}
|
||||
}
|
||||
val asColor: Int get() = java.awt.Color.HSBtoRGB(hue, saturation, brightness)
|
||||
}
|
||||
|
||||
/**
|
||||
* Model vertex
|
||||
*
|
||||
* @param[xyz] x, y, z coordinates
|
||||
* @param[uv] u, v coordinates
|
||||
* @param[color] vertex color RGB components
|
||||
* @param[alpha] vertex color alpha component
|
||||
*/
|
||||
data class Vertex(val xyz: Double3 = Double3(0.0, 0.0, 0.0),
|
||||
val uv: UV = UV(0.0, 0.0),
|
||||
val color: Color = Color.white,
|
||||
val alpha: Int = 255,
|
||||
val normal: Double3? = null
|
||||
)
|
||||
|
||||
/**
|
||||
* Intermediate (fabric-renderer-api independent) representation of model quad
|
||||
* Immutable, double-precision
|
||||
* Zero-centered (both XYZ and UV) coordinates for simpler rotation/mirroring
|
||||
*/
|
||||
data class Quad(
|
||||
val v1: Vertex, val v2: Vertex, val v3: Vertex, val v4: Vertex,
|
||||
val sprite: Sprite? = null,
|
||||
val colorIndex: Int = -1,
|
||||
val face: Direction? = null
|
||||
) {
|
||||
val verts = arrayOf(v1, v2, v3, v4)
|
||||
|
||||
inline fun transformV(trans: (Vertex)-> Vertex): Quad = transformVI { vertex, idx -> trans(vertex) }
|
||||
inline fun transformVI(trans: (Vertex, Int)-> Vertex): Quad = copy(
|
||||
v1 = trans(v1, 0), v2 = trans(v2, 1), v3 = trans(v3, 2), v4 = trans(v4, 3)
|
||||
)
|
||||
val normal: Double3 get() = (v2.xyz - v1.xyz).cross(v4.xyz - v1.xyz).normalize
|
||||
|
||||
fun move(trans: Double3) = transformV { it.copy(xyz = it.xyz + trans) }
|
||||
fun move(trans: Pair<Double, Direction>) = move(Double3(trans.second) * trans.first)
|
||||
fun scale (scale: Double) = transformV { it.copy(xyz = it.xyz * scale) }
|
||||
fun scale (scale: Double3) = transformV { it.copy(xyz = Double3(it.xyz.x * scale.x, it.xyz.y * scale.y, it.xyz.z * scale.z)) }
|
||||
fun rotate(rot: Rotation) = transformV { it.copy(xyz = it.xyz.rotate(rot), normal = it.normal?.rotate(rot)) }.copy(face = face?.rotate(rot))
|
||||
fun rotateZ(angle: Double) = transformV { it.copy(
|
||||
xyz = Double3(it.xyz.x * cos(angle) + it.xyz.z * sin(angle), it.xyz.y, it.xyz.z * cos(angle) - it.xyz.x * sin(angle)),
|
||||
normal = it.normal?.let { normal-> Double3(normal.x * cos(angle) + normal.z * sin(angle), normal.y, normal.z * cos(angle) - normal.x * sin(angle)) }
|
||||
) }
|
||||
|
||||
fun scaleUV (scale: Double) = transformV { it.copy(uv = UV(it.uv.u * scale, it.uv.v * scale)) }
|
||||
fun rotateUV(n: Int) = transformV { it.copy(uv = it.uv.rotate(n)) }
|
||||
fun clampUV(minU: Double = -0.5, maxU: Double = 0.5, minV: Double = -0.5, maxV: Double = 0.5) =
|
||||
transformV { it.copy(uv = it.uv.clamp(minU, maxU, minV, maxV)) }
|
||||
fun mirrorUV(mirrorU: Boolean, mirrorV: Boolean) = transformV { it.copy(uv = it.uv.mirror(mirrorU, mirrorV)) }
|
||||
fun scrambleUV(random: Random, canFlipU: Boolean, canFlipV: Boolean, canRotate: Boolean) = this
|
||||
.mirrorUV(canFlipU && random.nextBoolean(), canFlipV && random.nextBoolean())
|
||||
.let { if (canRotate) it.rotateUV(random.nextInt(4)) else it }
|
||||
|
||||
fun sprite(sprite: Sprite) = copy(sprite = sprite)
|
||||
fun color(color: Color) = transformV { it.copy(color = color) }
|
||||
fun color(color: Int) = transformV { it.copy(color = Color(color)) }
|
||||
fun colorIndex(colorIndex: Int) = copy(colorIndex = colorIndex)
|
||||
fun colorAndIndex(color: Int?) = color(color ?: Color.white.asInt).colorIndex(if (color == null) 0 else -1)
|
||||
|
||||
val flipped: Quad get() = Quad(v4, v3, v2, v1, sprite, colorIndex)
|
||||
fun cycleVertices(n: Int) = when(n % 4) {
|
||||
1 -> Quad(v2, v3, v4, v1)
|
||||
2 -> Quad(v3, v4, v1, v2)
|
||||
3 -> Quad(v4, v1, v2, v3)
|
||||
else -> this.copy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun mix(first: Quad, second: Quad, vertexFactory: (Vertex, Vertex)-> Vertex) = Quad(
|
||||
v1 = vertexFactory(first.v1, second.v1),
|
||||
v2 = vertexFactory(first.v2, second.v2),
|
||||
v3 = vertexFactory(first.v3, second.v3),
|
||||
v4 = vertexFactory(first.v4, second.v4)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun List<Quad>.transform(trans: Quad.()-> Quad) = map { it.trans() }
|
||||
fun Array<List<Quad>>.transform(trans: Quad.(Int)-> Quad) = mapIndexed { idx, qList -> qList.map { it.trans(idx) } }.toTypedArray()
|
||||
|
||||
fun List<Quad>.withOpposites() = flatMap { listOf(it, it.flipped) }
|
||||
fun Array<List<Quad>>.withOpposites() = map { it.withOpposites() }.toTypedArray()
|
||||
|
||||
/**
|
||||
* Pour quad data into a fabric-renderer-api Mesh
|
||||
*/
|
||||
fun List<Quad>.build(blendMode: BlendMode, noDiffuse: Boolean = false, flatLighting: Boolean = false): Mesh {
|
||||
val renderer = RendererAccess.INSTANCE.renderer!!
|
||||
val material = renderer.materialFinder().blendMode(0, blendMode).disableAo(0, flatLighting).disableDiffuse(0, noDiffuse).find()
|
||||
val builder = renderer.meshBuilder()
|
||||
builder.emitter.apply {
|
||||
forEach { quad ->
|
||||
val sprite = quad.sprite ?: Atlas.BLOCKS[MissingSprite.getMissingSpriteId()]!!
|
||||
quad.verts.forEachIndexed { idx, vertex ->
|
||||
pos(idx, (vertex.xyz + Double3(0.5, 0.5, 0.5)).asVec3f)
|
||||
sprite(idx, 0,
|
||||
(sprite.maxU - sprite.minU) * (vertex.uv.u.toFloat() + 0.5f) + sprite.minU,
|
||||
(sprite.maxV - sprite.minV) * (vertex.uv.v.toFloat() + 0.5f) + sprite.minV
|
||||
)
|
||||
spriteColor(idx, 0, vertex.color.asInt)
|
||||
}
|
||||
cullFace(quad.face)
|
||||
colorIndex(quad.colorIndex)
|
||||
material(material)
|
||||
emit()
|
||||
}
|
||||
}
|
||||
return builder.build()
|
||||
}
|
||||
|
||||
fun Array<List<Quad>>.build(blendMode: BlendMode, noDiffuse: Boolean = false, flatLighting: Boolean = false) = map { it.build(blendMode, noDiffuse, flatLighting) }.toTypedArray()
|
||||
|
||||
/**
|
||||
* The model should be positioned so that (0,0,0) is the block center.
|
||||
* The block extends to (-0.5, 0.5) in all directions (inclusive).
|
||||
*/
|
||||
fun verticalRectangle(x1: Double, z1: Double, x2: Double, z2: Double, yBottom: Double, yTop: Double) = Quad(
|
||||
Vertex(Double3(x1, yBottom, z1), UV.bottomLeft),
|
||||
Vertex(Double3(x2, yBottom, z2), UV.bottomRight),
|
||||
Vertex(Double3(x2, yTop, z2), UV.topRight),
|
||||
Vertex(Double3(x1, yTop, z1), UV.topLeft)
|
||||
)
|
||||
|
||||
fun horizontalRectangle(x1: Double, z1: Double, x2: Double, z2: Double, y: Double): Quad {
|
||||
val xMin = min(x1, x2); val xMax = max(x1, x2)
|
||||
val zMin = min(z1, z2); val zMax = max(z1, z2)
|
||||
return Quad(
|
||||
Vertex(Double3(xMin, y, zMin), UV.topLeft),
|
||||
Vertex(Double3(xMin, y, zMax), UV.bottomLeft),
|
||||
Vertex(Double3(xMax, y, zMax), UV.bottomRight),
|
||||
Vertex(Double3(xMax, y, zMin), UV.topRight)
|
||||
)
|
||||
}
|
||||
|
||||
fun faceQuad(face: Direction): Quad {
|
||||
val base = face.vec * 0.5
|
||||
val top = boxFaces[face].top * 0.5
|
||||
val left = boxFaces[face].left * 0.5
|
||||
return Quad(
|
||||
Vertex(base + top + left, UV.topLeft),
|
||||
Vertex(base - top + left, UV.bottomLeft),
|
||||
Vertex(base - top - left, UV.bottomRight),
|
||||
Vertex(base + top - left, UV.topRight),
|
||||
face = face
|
||||
)
|
||||
}
|
||||
|
||||
fun xzDisk(modelIdx: Int) = (PI2 * modelIdx / 64.0).let { Double3(cos(it), 0.0, sin(it)) }
|
||||
75
src/main/kotlin/mods/betterfoliage/model/SpriteSets.kt
Normal file
75
src/main/kotlin/mods/betterfoliage/model/SpriteSets.kt
Normal file
@@ -0,0 +1,75 @@
|
||||
package mods.betterfoliage.model
|
||||
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.get
|
||||
import net.fabricmc.fabric.api.event.client.ClientSpriteRegistryCallback
|
||||
import net.minecraft.client.MinecraftClient
|
||||
import net.minecraft.client.texture.MissingSprite
|
||||
import net.minecraft.client.texture.Sprite
|
||||
import net.minecraft.client.texture.SpriteAtlasTexture
|
||||
import net.minecraft.util.Identifier
|
||||
import kotlin.properties.ReadOnlyProperty
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
interface SpriteSet {
|
||||
val num: Int
|
||||
operator fun get(idx: Int): Sprite
|
||||
}
|
||||
|
||||
class FixedSpriteSet(val sprites: List<Sprite>) : SpriteSet {
|
||||
override val num = sprites.size
|
||||
override fun get(idx: Int) = sprites[idx % num]
|
||||
|
||||
constructor(atlas: Atlas, ids: List<Identifier>) : this(
|
||||
ids.mapNotNull { atlas[it] }.let { sprites ->
|
||||
if (sprites.isNotEmpty()) sprites else listOf(atlas[MissingSprite.getMissingSpriteId()]!!)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
class SpriteDelegate(val atlas: Atlas, val idFunc: ()->Identifier) : ReadOnlyProperty<Any, Sprite>, ClientSpriteRegistryCallback {
|
||||
private var id: Identifier? = null
|
||||
private var value: Sprite? = null
|
||||
|
||||
init { ClientSpriteRegistryCallback.event(atlas.resourceId).register(this) }
|
||||
|
||||
override fun registerSprites(atlasTexture: SpriteAtlasTexture, registry: ClientSpriteRegistryCallback.Registry) {
|
||||
id = idFunc(); value = null
|
||||
registry.register(id)
|
||||
}
|
||||
|
||||
override fun getValue(thisRef: Any, property: KProperty<*>): Sprite {
|
||||
value?.let { return it }
|
||||
synchronized(this) {
|
||||
value?.let { return it }
|
||||
atlas[id!!]!!.let { value = it; return it }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class SpriteSetDelegate(
|
||||
val atlas: Atlas,
|
||||
val idRegister: (Identifier)->Identifier = { it },
|
||||
val idFunc: (Int)->Identifier
|
||||
) : ReadOnlyProperty<Any, SpriteSet>, ClientSpriteRegistryCallback {
|
||||
private var idList: List<Identifier> = emptyList()
|
||||
private var spriteSet: SpriteSet? = null
|
||||
init { ClientSpriteRegistryCallback.event(atlas.resourceId).register(this) }
|
||||
|
||||
override fun registerSprites(atlasTexture: SpriteAtlasTexture, registry: ClientSpriteRegistryCallback.Registry) {
|
||||
spriteSet = null
|
||||
val manager = MinecraftClient.getInstance().resourceManager
|
||||
idList = (0 until 16).map(idFunc).filter { manager.containsResource(atlas.file(it)) }.map(idRegister)
|
||||
idList.forEach { registry.register(it) }
|
||||
}
|
||||
|
||||
override fun getValue(thisRef: Any, property: KProperty<*>): SpriteSet {
|
||||
spriteSet?.let { return it }
|
||||
synchronized(this) {
|
||||
spriteSet?.let { return it }
|
||||
spriteSet = FixedSpriteSet(atlas, idList)
|
||||
return spriteSet!!
|
||||
}
|
||||
}
|
||||
}
|
||||
80
src/main/kotlin/mods/betterfoliage/model/TuftMeshes.kt
Normal file
80
src/main/kotlin/mods/betterfoliage/model/TuftMeshes.kt
Normal file
@@ -0,0 +1,80 @@
|
||||
package mods.betterfoliage.model
|
||||
|
||||
import mods.betterfoliage.util.*
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh
|
||||
import net.minecraft.client.texture.Sprite
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.Direction.UP
|
||||
|
||||
data class TuftShapeKey(
|
||||
val size: Double,
|
||||
val height: Double,
|
||||
val offset: Double3,
|
||||
val flipU1: Boolean,
|
||||
val flipU2: Boolean
|
||||
)
|
||||
|
||||
fun tuftShapeSet(size: Double, heightMin: Double, heightMax: Double, hOffset: Double): Array<TuftShapeKey> {
|
||||
return Array(64) { idx ->
|
||||
TuftShapeKey(
|
||||
size,
|
||||
randomD(heightMin, heightMax),
|
||||
xzDisk(idx) * randomD(hOffset / 2.0, hOffset),
|
||||
randomB(),
|
||||
randomB()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fun tuftQuadSingle(size: Double, height: Double, flipU: Boolean) =
|
||||
verticalRectangle(x1 = -0.5 * size, z1 = 0.5 * size, x2 = 0.5 * size, z2 = -0.5 * size, yBottom = 0.5, yTop = 0.5 + height)
|
||||
.mirrorUV(flipU, false)
|
||||
|
||||
fun tuftModelSet(shapes: Array<TuftShapeKey>, tintIndex: Int, spriteGetter: (Int)->Sprite) = shapes.mapIndexed { idx, shape ->
|
||||
listOf(
|
||||
tuftQuadSingle(shape.size, shape.height, shape.flipU1),
|
||||
tuftQuadSingle(shape.size, shape.height, shape.flipU2).rotate(rot(UP))
|
||||
).map { it.move(shape.offset) }
|
||||
.map { it.colorIndex(tintIndex) }
|
||||
.map { it.sprite(spriteGetter(idx)) }
|
||||
}.toTypedArray()
|
||||
|
||||
fun fullCubeTextured(spriteId: Identifier, tintIndex: Int, scrambleUV: Boolean = true): Mesh {
|
||||
val sprite = Atlas.BLOCKS[spriteId]!!
|
||||
return allDirections.map { faceQuad(it) }
|
||||
.map { if (!scrambleUV) it else it.rotateUV(randomI(max = 4)) }
|
||||
.map { it.sprite(sprite) }
|
||||
.map { it.colorIndex(tintIndex) }
|
||||
.build(BlendMode.SOLID, noDiffuse = true)
|
||||
}
|
||||
|
||||
fun crossModelsRaw(num: Int, size: Double, hOffset: Double, vOffset: Double): Array<List<Quad>> {
|
||||
return Array(num) { idx ->
|
||||
listOf(
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = -0.5 * 1.41, yTop = 0.5 * 1.41),
|
||||
verticalRectangle(x1 = -0.5, z1 = 0.5, x2 = 0.5, z2 = -0.5, yBottom = -0.5 * 1.41, yTop = 0.5 * 1.41)
|
||||
.rotate(rot(UP))
|
||||
).map { it.scale(size) }
|
||||
.map { it.move(xzDisk(idx) * hOffset) }
|
||||
.map { it.move(UP.vec * randomD(-1.0, 1.0) * vOffset) }
|
||||
}
|
||||
}
|
||||
|
||||
fun crossModelSingle(base: List<Quad>, sprite: Sprite, tintIndex: Int,scrambleUV: Boolean) =
|
||||
base.map { if (scrambleUV) it.scrambleUV(random, canFlipU = true, canFlipV = true, canRotate = true) else it }
|
||||
.map { it.colorIndex(tintIndex) }
|
||||
.mapIndexed { idx, quad -> quad.sprite(sprite) }
|
||||
.withOpposites()
|
||||
.build(BlendMode.CUTOUT_MIPPED)
|
||||
|
||||
fun crossModelsTextured(
|
||||
leafBase: Array<List<Quad>>,
|
||||
tintIndex: Int,
|
||||
scrambleUV: Boolean,
|
||||
spriteGetter: (Int) -> Identifier
|
||||
) = leafBase.mapIndexed { idx, leaf ->
|
||||
crossModelSingle(leaf, Atlas.BLOCKS[spriteGetter(idx)], tintIndex, scrambleUV)
|
||||
}.toTypedArray()
|
||||
|
||||
fun Array<List<Quad>>.buildTufts() = withOpposites().build(BlendMode.CUTOUT_MIPPED)
|
||||
87
src/main/kotlin/mods/betterfoliage/model/VanillaWrappers.kt
Normal file
87
src/main/kotlin/mods/betterfoliage/model/VanillaWrappers.kt
Normal file
@@ -0,0 +1,87 @@
|
||||
package mods.betterfoliage.model
|
||||
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingKey
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh
|
||||
import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.RenderLayers
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.item.ItemStack
|
||||
import net.minecraft.util.collection.WeightedPicker
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.*
|
||||
import java.util.function.Supplier
|
||||
|
||||
abstract class ModelWrapKey : ModelBakingKey, HasLogger() {
|
||||
override fun bake(ctx: ModelBakingContext): BakedModel? {
|
||||
val baseModel = super.bake(ctx)
|
||||
if (baseModel is BasicBakedModel)
|
||||
return bake(ctx, baseModel)
|
||||
else
|
||||
return baseModel
|
||||
}
|
||||
|
||||
abstract fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel): BakedModel
|
||||
}
|
||||
|
||||
abstract class WrappedBakedModel(val wrapped: BakedModel) : BakedModel by wrapped, FabricBakedModel {
|
||||
override fun isVanillaAdapter() = false
|
||||
|
||||
override fun emitItemQuads(stack: ItemStack, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
(wrapped as FabricBakedModel).emitItemQuads(stack, randomSupplier, context)
|
||||
}
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
(wrapped as FabricBakedModel).emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
}
|
||||
|
||||
class WrappedMeshModel(wrapped: BasicBakedModel, val mesh: Mesh) : WrappedBakedModel(wrapped) {
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
context.meshConsumer().accept(mesh)
|
||||
}
|
||||
|
||||
companion object {
|
||||
/**
|
||||
* Converter for [BasicBakedModel] instances.
|
||||
* @param state [BlockState] to use when querying [BakedModel]
|
||||
* @param unshade undo vanilla diffuse lighting when unbaking the [BakedModel]
|
||||
* @param noDiffuse disable diffuse lighting when baking the [Mesh]
|
||||
* @param blendModeOverride [BlockRenderLayer] to use instead of the one declared by the corresponding [Block]
|
||||
*/
|
||||
fun converter(state: BlockState?, unshade: Boolean = false, noDiffuse: Boolean = true, blendModeOverride: BlendMode? = null) = BakedModelConverter.of { model ->
|
||||
if (model is BasicBakedModel) {
|
||||
val mesh = unbakeQuads(model, state, Random(42L), unshade).build(
|
||||
blendMode = blendModeOverride ?: BlendMode.fromRenderLayer(RenderLayers.getBlockLayer(state)),
|
||||
noDiffuse = noDiffuse,
|
||||
flatLighting = !model.useAmbientOcclusion()
|
||||
)
|
||||
WrappedMeshModel(model, mesh)
|
||||
} else null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class WeightedModelWrapper(
|
||||
val models: List<WeightedModel>, baseModel: BakedModel
|
||||
): WrappedBakedModel(baseModel), FabricBakedModel {
|
||||
|
||||
class WeightedModel(val model: BakedModel, val weight: Int) : WeightedPicker.Entry(weight)
|
||||
fun getModel(random: Random) = WeightedPicker.getRandom(random, models).model
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
(getModel(randomSupplier.get()) as FabricBakedModel).emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
}
|
||||
|
||||
fun getUnderlyingModel(model: BakedModel, random: Random): BakedModel = when(model) {
|
||||
is WeightedModelWrapper -> getUnderlyingModel(model.getModel(random), random)
|
||||
is WrappedBakedModel -> model.wrapped
|
||||
else -> model
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package mods.betterfoliage.render
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.render.lighting.getBufferBuilder
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import mods.betterfoliage.util.getAllMethods
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.client.render.BufferBuilder
|
||||
import net.minecraft.client.render.RenderLayer
|
||||
|
||||
/**
|
||||
* Integration for ShadersMod.
|
||||
*/
|
||||
object ShadersModIntegration : HasLogger() {
|
||||
|
||||
val BufferBuilder_SVertexBuilder = BufferBuilder::class.java.fields.find { it.name == "sVertexBuilder" }
|
||||
val SVertexBuilder_pushState = getAllMethods("net.optifine.shaders.SVertexBuilder", "pushEntity").find { it.parameterCount == 1 }
|
||||
val SVertexBuilder_popState = getAllMethods("net.optifine.shaders.SVertexBuilder", "popEntity").find { it.parameterCount == 0 }
|
||||
val BlockAliases_getAliasBlockId = getAllMethods("net.optifine.shaders.BlockAliases", "getAliasBlockId").firstOrNull()
|
||||
|
||||
@JvmStatic val isAvailable =
|
||||
listOf(BufferBuilder_SVertexBuilder).all { it != null } &&
|
||||
listOf(SVertexBuilder_pushState, SVertexBuilder_popState, BlockAliases_getAliasBlockId).all { it != null }
|
||||
|
||||
val defaultLeaves = Blocks.OAK_LEAVES.defaultState
|
||||
val defaultGrass = Blocks.TALL_GRASS.defaultState
|
||||
|
||||
init {
|
||||
logger.info("[BetterFoliage] ShadersMod integration is ${if (isAvailable) "enabled" else "disabled" }")
|
||||
}
|
||||
|
||||
/** Quads rendered inside this block will use the given block entity data in shader programs. */
|
||||
inline fun renderAs(ctx: RenderContext, state: BlockState, layer: RenderLayer, enabled: Boolean = true, func: ()->Unit) {
|
||||
if (isAvailable && enabled) {
|
||||
val sVertexBuilder = BufferBuilder_SVertexBuilder!!.get(ctx.getBufferBuilder(layer))
|
||||
val aliasBlockId = BlockAliases_getAliasBlockId!!.invoke(null, state)
|
||||
SVertexBuilder_pushState!!.invoke(sVertexBuilder, aliasBlockId)
|
||||
func()
|
||||
SVertexBuilder_popState!!.invoke(sVertexBuilder)
|
||||
} else {
|
||||
func()
|
||||
}
|
||||
}
|
||||
|
||||
/** Quads rendered inside this block will behave as tallgrass blocks in shader programs. */
|
||||
inline fun grass(ctx: RenderContext, enabled: Boolean = true, func: ()->Unit) =
|
||||
renderAs(ctx, defaultGrass, RenderLayer.getCutoutMipped(), enabled, func)
|
||||
|
||||
/** Quads rendered inside this block will behave as leaf blocks in shader programs. */
|
||||
inline fun leaves(ctx: RenderContext, enabled: Boolean = true, func: ()->Unit) =
|
||||
renderAs(ctx, defaultLeaves, RenderLayer.getCutoutMipped(), enabled, func)
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.config.CACTUS_BLOCKS
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.SpriteDelegate
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.buildTufts
|
||||
import mods.betterfoliage.model.crossModelsRaw
|
||||
import mods.betterfoliage.model.crossModelsTextured
|
||||
import mods.betterfoliage.model.meshifyCutoutMipped
|
||||
import mods.betterfoliage.model.meshifyStandard
|
||||
import mods.betterfoliage.model.transform
|
||||
import mods.betterfoliage.model.tuftModelSet
|
||||
import mods.betterfoliage.model.tuftShapeSet
|
||||
import mods.betterfoliage.render.lighting.grassTuftLighting
|
||||
import mods.betterfoliage.render.lighting.roundLeafLighting
|
||||
import mods.betterfoliage.render.lighting.withLighting
|
||||
import mods.betterfoliage.resource.discovery.AbstractModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.LazyInvalidatable
|
||||
import mods.betterfoliage.util.Rotation
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.horizontalDirections
|
||||
import mods.betterfoliage.util.randomD
|
||||
import mods.betterfoliage.util.randomI
|
||||
import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.client.render.model.json.JsonUnbakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.DOWN
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.Random
|
||||
import java.util.function.Supplier
|
||||
|
||||
|
||||
object StandardCactusDiscovery : AbstractModelDiscovery() {
|
||||
override fun processModel(ctx: ModelDiscoveryContext) {
|
||||
val model = ctx.getUnbaked()
|
||||
if (model is JsonUnbakedModel && ctx.blockState.block in CACTUS_BLOCKS) {
|
||||
BetterFoliage.blockTypes.dirt.add(ctx.blockState)
|
||||
ctx.addReplacement(StandardCactusKey)
|
||||
ctx.sprites.add(StandardCactusModel.cactusCrossSprite)
|
||||
}
|
||||
super.processModel(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
object StandardCactusKey : ModelWrapKey() {
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel) = StandardCactusModel(meshifyCutoutMipped(wrapped))
|
||||
}
|
||||
|
||||
class StandardCactusModel(wrapped: BakedModel) : WrappedBakedModel(wrapped), FabricBakedModel {
|
||||
|
||||
val armLighting = horizontalDirections.map { grassTuftLighting(it) }
|
||||
val crossLighting = roundLeafLighting()
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
(wrapped as FabricBakedModel).emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
if (!BetterFoliage.config.enabled || !BetterFoliage.config.cactus.enabled) return
|
||||
|
||||
val random = randomSupplier.get()
|
||||
val armSide = random.nextInt() and 3
|
||||
|
||||
context.withLighting(armLighting[armSide]) {
|
||||
it.accept(cactusArmModels[armSide][random])
|
||||
}
|
||||
context.withLighting(crossLighting) {
|
||||
it.accept(cactusCrossModels[random])
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val cactusCrossSprite = Identifier(BetterFoliage.MOD_ID, "blocks/better_cactus")
|
||||
val cactusArmSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_cactus_arm_$idx")
|
||||
}
|
||||
val cactusArmModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes = BetterFoliage.config.cactus.let { tuftShapeSet(0.8, 0.8, 0.8, 0.2) }
|
||||
val models = tuftModelSet(shapes, Color.white.asInt) { cactusArmSprites[randomI()] }
|
||||
horizontalDirections.map { side ->
|
||||
models.transform { move(0.0625 to DOWN).rotate(Rotation.fromUp[side.ordinal]) }.buildTufts()
|
||||
}.toTypedArray()
|
||||
}
|
||||
val cactusCrossModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val models = BetterFoliage.config.cactus.let { config ->
|
||||
crossModelsRaw(64, config.size, 0.0, 0.0)
|
||||
.transform { rotateZ(randomD(-config.sizeVariation, config.sizeVariation)) }
|
||||
}
|
||||
crossModelsTextured(models, Color.white.asInt, true) { cactusCrossSprite }
|
||||
}
|
||||
}
|
||||
}
|
||||
142
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Dirt.kt
Normal file
142
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Dirt.kt
Normal file
@@ -0,0 +1,142 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.chunk.BasicBlockCtx
|
||||
import mods.betterfoliage.config.DIRT_BLOCKS
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.build
|
||||
import mods.betterfoliage.model.meshifyStandard
|
||||
import mods.betterfoliage.model.tuftModelSet
|
||||
import mods.betterfoliage.model.tuftShapeSet
|
||||
import mods.betterfoliage.model.withOpposites
|
||||
import mods.betterfoliage.config.SALTWATER_BIOMES
|
||||
import mods.betterfoliage.model.getUnderlyingModel
|
||||
import mods.betterfoliage.model.meshifySolid
|
||||
import mods.betterfoliage.render.ShadersModIntegration
|
||||
import mods.betterfoliage.render.lighting.grassTuftLighting
|
||||
import mods.betterfoliage.render.lighting.reedLighting
|
||||
import mods.betterfoliage.render.lighting.renderMasquerade
|
||||
import mods.betterfoliage.render.lighting.withLighting
|
||||
import mods.betterfoliage.resource.discovery.AbstractModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.resource.generated.CenteredSprite
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.Int3
|
||||
import mods.betterfoliage.util.LazyInvalidatable
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.randomI
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.block.Material
|
||||
import net.minecraft.client.render.RenderLayer
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.client.render.model.json.JsonUnbakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.UP
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.Random
|
||||
import java.util.function.Supplier
|
||||
|
||||
object StandardDirtDiscovery : AbstractModelDiscovery() {
|
||||
fun canRenderInLayer(layer: RenderLayer) = when {
|
||||
!BetterFoliage.config.enabled -> layer == RenderLayer.getSolid()
|
||||
(!BetterFoliage.config.connectedGrass.enabled &&
|
||||
!BetterFoliage.config.algae.enabled &&
|
||||
!BetterFoliage.config.reed.enabled
|
||||
) -> layer == RenderLayer.getSolid()
|
||||
else -> layer == RenderLayer.getCutoutMipped()
|
||||
}
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext) {
|
||||
if (ctx.getUnbaked() is JsonUnbakedModel && ctx.blockState.block in DIRT_BLOCKS) {
|
||||
BetterFoliage.blockTypes.dirt.add(ctx.blockState)
|
||||
ctx.addReplacement(StandardDirtKey)
|
||||
// RenderTypeLookup.setRenderLayer(ctx.blockState.block, ::canRenderInLayer)
|
||||
}
|
||||
super.processModel(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
object StandardDirtKey : ModelWrapKey() {
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel) = DirtModel(meshifySolid(wrapped))
|
||||
}
|
||||
|
||||
class DirtModel(wrapped: BakedModel) : WrappedBakedModel(wrapped) {
|
||||
|
||||
val algaeLighting = grassTuftLighting(UP)
|
||||
val reedLighting = reedLighting()
|
||||
|
||||
override fun emitBlockQuads(
|
||||
blockView: BlockRenderView,
|
||||
state: BlockState,
|
||||
pos: BlockPos,
|
||||
randomSupplier: Supplier<Random>,
|
||||
context: RenderContext
|
||||
) {
|
||||
if (!BetterFoliage.config.enabled) return super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
|
||||
val ctx = BasicBlockCtx(blockView, pos)
|
||||
val stateUp = ctx.offset(UP).state
|
||||
val isGrassUp = stateUp in BetterFoliage.blockTypes.grass
|
||||
|
||||
val isWater = stateUp.material == Material.WATER
|
||||
val isDeepWater = isWater && ctx.offset(Int3(2 to UP)).state.material == Material.WATER
|
||||
val isShallowWater = isWater && ctx.offset(Int3(2 to UP)).state.isAir
|
||||
val isSaltWater = isWater && ctx.biome?.category in SALTWATER_BIOMES
|
||||
|
||||
val random = randomSupplier.get()
|
||||
if (BetterFoliage.config.connectedGrass.enabled && isGrassUp) {
|
||||
val grassBaseModel = getUnderlyingModel(ctx.model(UP), random)
|
||||
context.renderMasquerade(grassBaseModel, blockView, stateUp, pos, randomSupplier, context)
|
||||
} else {
|
||||
super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
|
||||
if (BetterFoliage.config.algae.enabled(random) && isDeepWater) {
|
||||
ShadersModIntegration.grass(context, BetterFoliage.config.algae.shaderWind) {
|
||||
context.withLighting(algaeLighting) {
|
||||
it.accept(algaeModels[random])
|
||||
}
|
||||
}
|
||||
} else if (BetterFoliage.config.reed.enabled(random) && isShallowWater && !isSaltWater) {
|
||||
ShadersModIntegration.grass(context, BetterFoliage.config.reed.shaderWind) {
|
||||
context.withLighting(reedLighting) {
|
||||
it.accept(reedModels[random])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val algaeSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_algae_$idx")
|
||||
}
|
||||
val reedSprites by SpriteSetDelegate(Atlas.BLOCKS,
|
||||
idFunc = { idx -> Identifier(BetterFoliage.MOD_ID, "blocks/better_reed_$idx") },
|
||||
idRegister = { id -> CenteredSprite(id, aspectHeight = 2).register(BetterFoliage.generatedPack) }
|
||||
)
|
||||
val algaeModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes =
|
||||
BetterFoliage.config.algae.let { tuftShapeSet(it.size, it.heightMin, it.heightMax, it.hOffset) }
|
||||
tuftModelSet(shapes, Color.white.asInt) { algaeSprites[randomI()] }
|
||||
.withOpposites()
|
||||
.build(BlendMode.CUTOUT_MIPPED, flatLighting = false)
|
||||
|
||||
}
|
||||
val reedModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes = BetterFoliage.config.reed.let { tuftShapeSet(2.0, it.heightMin, it.heightMax, it.hOffset) }
|
||||
tuftModelSet(shapes, Color.white.asInt) { reedSprites[randomI()] }
|
||||
.withOpposites()
|
||||
.build(BlendMode.CUTOUT_MIPPED, flatLighting = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
115
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Grass.kt
Normal file
115
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Grass.kt
Normal file
@@ -0,0 +1,115 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.chunk.BasicBlockCtx
|
||||
import mods.betterfoliage.config.BlockConfig
|
||||
import mods.betterfoliage.config.SNOW_MATERIALS
|
||||
import mods.betterfoliage.render.ShadersModIntegration
|
||||
import mods.betterfoliage.render.lighting.grassTuftLighting
|
||||
import mods.betterfoliage.render.lighting.withLighting
|
||||
import mods.betterfoliage.resource.discovery.*
|
||||
import mods.betterfoliage.model.*
|
||||
import mods.betterfoliage.util.*
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.*
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.*
|
||||
import java.util.function.Consumer
|
||||
import java.util.function.Supplier
|
||||
|
||||
object StandardGrassDiscovery : ConfigurableModelDiscovery() {
|
||||
override val matchClasses: ConfigurableBlockMatcher get() = BetterFoliage.blockConfig.grassBlocks
|
||||
override val modelTextures: List<ModelTextureList> get() = BetterFoliage.blockConfig.grassModels.modelList
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext, textureMatch: List<Identifier>) {
|
||||
ctx.addReplacement(StandardGrassKey(textureMatch[0], null))
|
||||
BetterFoliage.blockTypes.grass.add(ctx.blockState)
|
||||
}
|
||||
}
|
||||
|
||||
data class StandardGrassKey(
|
||||
val grassLocation: Identifier,
|
||||
val overrideColor: Color?
|
||||
) : ModelWrapKey() {
|
||||
val tintIndex: Int get() = if (overrideColor == null) 0 else -1
|
||||
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel): BakedModel {
|
||||
val grassSpriteColor = Atlas.BLOCKS[grassLocation].averageColor.let { hsb ->
|
||||
logColorOverride(detailLogger, BetterFoliage.config.shortGrass.saturationThreshold, hsb)
|
||||
hsb.colorOverride(BetterFoliage.config.shortGrass.saturationThreshold)
|
||||
}
|
||||
return StandardGrassModel(meshifyCutoutMipped(wrapped), this.copy(overrideColor = grassSpriteColor))
|
||||
}
|
||||
}
|
||||
|
||||
class StandardGrassModel(wrapped: BakedModel, val key: StandardGrassKey) : WrappedBakedModel(wrapped) {
|
||||
|
||||
val tuftNormal by grassTuftMeshesNormal.delegate(key)
|
||||
val tuftSnowed by grassTuftMeshesSnowed.delegate(key)
|
||||
val fullBlock by grassFullBlockMeshes.delegate(key)
|
||||
|
||||
val tuftLighting = grassTuftLighting(UP)
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
if (!BetterFoliage.config.enabled) return super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
|
||||
val ctx = BasicBlockCtx(blockView, pos)
|
||||
val stateBelow = ctx.state(DOWN)
|
||||
val stateAbove = ctx.state(UP)
|
||||
|
||||
val isSnowed = stateAbove.material in SNOW_MATERIALS
|
||||
val connected = BetterFoliage.config.connectedGrass.enabled &&
|
||||
(!isSnowed || BetterFoliage.config.connectedGrass.snowEnabled) &&
|
||||
(stateBelow in BetterFoliage.blockTypes.dirt || stateBelow in BetterFoliage.blockTypes.grass)
|
||||
|
||||
val random = randomSupplier.get()
|
||||
if (connected) {
|
||||
context.meshConsumer().accept(if (isSnowed) snowFullBlockMeshes[random] else fullBlock[random])
|
||||
} else {
|
||||
super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
|
||||
if (BetterFoliage.config.shortGrass.enabled(random) && !ctx.isNeighborSolid(UP)) {
|
||||
ShadersModIntegration.grass(context, BetterFoliage.config.shortGrass.shaderWind) {
|
||||
context.withLighting(tuftLighting) {
|
||||
it.accept(if (isSnowed) tuftSnowed[random] else tuftNormal[random])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val grassTuftSpritesNormal by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_grass_long_$idx")
|
||||
}
|
||||
val grassTuftSpritesSnowed by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_grass_long_$idx")
|
||||
}
|
||||
val grassTuftShapes = LazyMap(BakeWrapperManager) { key: StandardGrassKey ->
|
||||
BetterFoliage.config.shortGrass.let { tuftShapeSet(it.size, it.heightMin, it.heightMax, it.hOffset) }
|
||||
}
|
||||
val grassTuftMeshesNormal = LazyMap(BakeWrapperManager) { key: StandardGrassKey ->
|
||||
tuftModelSet(grassTuftShapes[key], key.tintIndex) { idx -> grassTuftSpritesNormal[randomI()] }
|
||||
.withOpposites()
|
||||
.build(BlendMode.CUTOUT_MIPPED, flatLighting = false)
|
||||
}
|
||||
val grassTuftMeshesSnowed = LazyMap(BakeWrapperManager) { key: StandardGrassKey ->
|
||||
tuftModelSet(grassTuftShapes[key], Color.white.asInt) { idx -> grassTuftSpritesSnowed[randomI()] }
|
||||
.withOpposites()
|
||||
.build(BlendMode.CUTOUT_MIPPED, flatLighting = false)
|
||||
}
|
||||
val grassFullBlockMeshes = LazyMap(BakeWrapperManager) { key: StandardGrassKey ->
|
||||
Array(64) { fullCubeTextured(key.grassLocation, key.tintIndex) }
|
||||
}
|
||||
val snowFullBlockMeshes by LazyInvalidatable(BakeWrapperManager) {
|
||||
Array(64) { fullCubeTextured(Identifier("block/snow"), -1) }
|
||||
}
|
||||
}
|
||||
}
|
||||
122
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Leaf.kt
Normal file
122
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Leaf.kt
Normal file
@@ -0,0 +1,122 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.chunk.BasicBlockCtx
|
||||
import mods.betterfoliage.config.SNOW_MATERIALS
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.crossModelsRaw
|
||||
import mods.betterfoliage.model.crossModelsTextured
|
||||
import mods.betterfoliage.model.meshifyCutoutMipped
|
||||
import mods.betterfoliage.render.ShadersModIntegration
|
||||
import mods.betterfoliage.render.lighting.roundLeafLighting
|
||||
import mods.betterfoliage.render.lighting.withLighting
|
||||
import mods.betterfoliage.render.particle.LeafParticleRegistry
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ConfigurableBlockMatcher
|
||||
import mods.betterfoliage.resource.discovery.ConfigurableModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.resource.discovery.ModelTextureList
|
||||
import mods.betterfoliage.resource.generated.GeneratedLeafSprite
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.LazyMap
|
||||
import mods.betterfoliage.util.averageColor
|
||||
import mods.betterfoliage.util.colorOverride
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.logColorOverride
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.UP
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import org.apache.logging.log4j.Level
|
||||
import java.util.Random
|
||||
import java.util.function.Supplier
|
||||
|
||||
interface LeafBlockModel {
|
||||
val key: LeafParticleKey
|
||||
}
|
||||
|
||||
interface LeafParticleKey {
|
||||
val leafType: String
|
||||
val overrideColor: Color?
|
||||
}
|
||||
|
||||
object StandardLeafDiscovery : ConfigurableModelDiscovery() {
|
||||
override val matchClasses: ConfigurableBlockMatcher get() = BetterFoliage.blockConfig.leafBlocks
|
||||
override val modelTextures: List<ModelTextureList> get() = BetterFoliage.blockConfig.leafModels.modelList
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext, textureMatch: List<Identifier>) {
|
||||
val leafType = LeafParticleRegistry.typeMappings.getType(textureMatch[0]) ?: "default"
|
||||
val generated = GeneratedLeafSprite(textureMatch[0], leafType)
|
||||
.register(BetterFoliage.generatedPack)
|
||||
.apply { ctx.sprites.add(this) }
|
||||
|
||||
detailLogger.log(Level.INFO, " particle $leafType")
|
||||
ctx.addReplacement(StandardLeafKey(generated, leafType, null))
|
||||
}
|
||||
}
|
||||
|
||||
data class StandardLeafKey(
|
||||
val roundLeafTexture: Identifier,
|
||||
override val leafType: String,
|
||||
override val overrideColor: Color?
|
||||
) : ModelWrapKey(), LeafParticleKey {
|
||||
val tintIndex: Int get() = if (overrideColor == null) 0 else -1
|
||||
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel): BakedModel {
|
||||
val leafSpriteColor = Atlas.BLOCKS[roundLeafTexture].averageColor.let { hsb ->
|
||||
logColorOverride(detailLogger, BetterFoliage.config.leaves.saturationThreshold, hsb)
|
||||
hsb.colorOverride(BetterFoliage.config.leaves.saturationThreshold)
|
||||
}
|
||||
return StandardLeafModel(meshifyCutoutMipped(wrapped), this.copy(overrideColor = leafSpriteColor))
|
||||
}
|
||||
}
|
||||
|
||||
class StandardLeafModel(
|
||||
wrapped: BakedModel,
|
||||
override val key: StandardLeafKey
|
||||
) : WrappedBakedModel(wrapped), LeafBlockModel {
|
||||
|
||||
val leafNormal by leafModelsNormal.delegate(key)
|
||||
val leafSnowed by leafModelsSnowed.delegate(key)
|
||||
val leafLighting = roundLeafLighting()
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
ShadersModIntegration.leaves(context, BetterFoliage.config.leaves.shaderWind) {
|
||||
super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
if (!BetterFoliage.config.enabled || !BetterFoliage.config.leaves.enabled) return
|
||||
|
||||
val ctx = BasicBlockCtx(blockView, pos)
|
||||
val stateAbove = ctx.state(UP)
|
||||
val isSnowed = stateAbove.material in SNOW_MATERIALS
|
||||
|
||||
val random = randomSupplier.get()
|
||||
context.withLighting(leafLighting) {
|
||||
it.accept(leafNormal[random])
|
||||
if (isSnowed) it.accept(leafSnowed[random])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val leafSpritesSnowed by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_leaves_snowed_$idx")
|
||||
}
|
||||
val leafModelsBase = LazyMap(BakeWrapperManager) { key: StandardLeafKey ->
|
||||
BetterFoliage.config.leaves.let { crossModelsRaw(64, it.size, it.hOffset, it.vOffset) }
|
||||
}
|
||||
val leafModelsNormal = LazyMap(BakeWrapperManager) { key: StandardLeafKey ->
|
||||
crossModelsTextured(leafModelsBase[key], key.tintIndex, true) { key.roundLeafTexture }
|
||||
}
|
||||
val leafModelsSnowed = LazyMap(BakeWrapperManager) { key: StandardLeafKey ->
|
||||
crossModelsTextured(leafModelsBase[key], Color.white.asInt, false) { leafSpritesSnowed[it].id }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.buildTufts
|
||||
import mods.betterfoliage.model.meshifyCutoutMipped
|
||||
import mods.betterfoliage.model.meshifyStandard
|
||||
import mods.betterfoliage.model.transform
|
||||
import mods.betterfoliage.model.tuftModelSet
|
||||
import mods.betterfoliage.model.tuftShapeSet
|
||||
import mods.betterfoliage.render.ShadersModIntegration
|
||||
import mods.betterfoliage.resource.discovery.AbstractModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.LazyInvalidatable
|
||||
import mods.betterfoliage.util.get
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.client.render.model.json.JsonUnbakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.DOWN
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.Random
|
||||
import java.util.function.Supplier
|
||||
|
||||
object StandardLilypadDiscovery : AbstractModelDiscovery() {
|
||||
val LILYPAD_BLOCKS = listOf(Blocks.LILY_PAD)
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext) {
|
||||
if (ctx.getUnbaked() is JsonUnbakedModel && ctx.blockState.block in LILYPAD_BLOCKS) {
|
||||
ctx.addReplacement(StandardLilypadKey)
|
||||
}
|
||||
super.processModel(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
object StandardLilypadKey : ModelWrapKey() {
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel) = StandardLilypadModel(meshifyCutoutMipped(wrapped))
|
||||
}
|
||||
|
||||
class StandardLilypadModel(wrapped: BakedModel) : WrappedBakedModel(wrapped) {
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
if (!BetterFoliage.config.enabled || !BetterFoliage.config.lilypad.enabled) return
|
||||
|
||||
val random = randomSupplier.get()
|
||||
ShadersModIntegration.grass(context, BetterFoliage.config.lilypad.shaderWind) {
|
||||
context.meshConsumer().accept(lilypadRootModels[random])
|
||||
}
|
||||
if (random.nextInt(64) < BetterFoliage.config.lilypad.population) {
|
||||
context.meshConsumer().accept(lilypadFlowerModels[random])
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val lilypadRootSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_lilypad_roots_$idx")
|
||||
}
|
||||
val lilypadFlowerSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_lilypad_flower_$idx")
|
||||
}
|
||||
val lilypadRootModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes = tuftShapeSet(1.0, 1.0, 1.0, BetterFoliage.config.lilypad.hOffset)
|
||||
tuftModelSet(shapes, Color.white.asInt) { lilypadRootSprites[it] }
|
||||
.transform { move(2.0 to DOWN) }
|
||||
.buildTufts()
|
||||
}
|
||||
val lilypadFlowerModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes = tuftShapeSet(0.5, 0.5, 0.5, BetterFoliage.config.lilypad.hOffset)
|
||||
tuftModelSet(shapes, Color.white.asInt) { lilypadFlowerSprites[it] }
|
||||
.transform { move(1.0 to DOWN) }
|
||||
.buildTufts()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.buildTufts
|
||||
import mods.betterfoliage.model.meshifyCutoutMipped
|
||||
import mods.betterfoliage.model.meshifyStandard
|
||||
import mods.betterfoliage.model.tuftModelSet
|
||||
import mods.betterfoliage.model.tuftShapeSet
|
||||
import mods.betterfoliage.render.ShadersModIntegration
|
||||
import mods.betterfoliage.render.lighting.grassTuftLighting
|
||||
import mods.betterfoliage.render.lighting.withLighting
|
||||
import mods.betterfoliage.resource.discovery.AbstractModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.LazyInvalidatable
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.offset
|
||||
import mods.betterfoliage.util.plus
|
||||
import mods.betterfoliage.util.randomI
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.client.render.model.json.JsonUnbakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.UP
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.Random
|
||||
import java.util.function.Supplier
|
||||
|
||||
object StandardMyceliumDiscovery : AbstractModelDiscovery() {
|
||||
val MYCELIUM_BLOCKS = listOf(Blocks.MYCELIUM)
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext) {
|
||||
if (ctx.getUnbaked() is JsonUnbakedModel && ctx.blockState.block in MYCELIUM_BLOCKS) {
|
||||
ctx.addReplacement(StandardMyceliumKey)
|
||||
// RenderTypeLookup.setRenderLayer(ctx.blockState.block, RenderType.getCutout())
|
||||
}
|
||||
super.processModel(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
object StandardMyceliumKey : ModelWrapKey() {
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel) = StandardMyceliumModel(meshifyCutoutMipped(wrapped))
|
||||
}
|
||||
|
||||
class StandardMyceliumModel(wrapped: BakedModel) : WrappedBakedModel(wrapped) {
|
||||
|
||||
val tuftLighting = grassTuftLighting(UP)
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
|
||||
val random = randomSupplier.get()
|
||||
if (BetterFoliage.config.enabled &&
|
||||
BetterFoliage.config.shortGrass.let { it.myceliumEnabled && random.nextInt(64) < it.population } &&
|
||||
blockView.getBlockState(pos + UP.offset).isAir
|
||||
) {
|
||||
ShadersModIntegration.grass(context, BetterFoliage.config.shortGrass.shaderWind) {
|
||||
context.withLighting(tuftLighting) {
|
||||
it.accept(myceliumTuftModels[random])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val myceliumTuftSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_mycel_$idx")
|
||||
}
|
||||
val myceliumTuftModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes = BetterFoliage.config.shortGrass.let { tuftShapeSet(it.size, it.heightMin, it.heightMax, it.hOffset) }
|
||||
tuftModelSet(shapes, Color.white.asInt) { idx -> myceliumTuftSprites[randomI()] }.buildTufts()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.config.NETHERRACK_BLOCKS
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.build
|
||||
import mods.betterfoliage.model.meshifyCutoutMipped
|
||||
import mods.betterfoliage.model.meshifyStandard
|
||||
import mods.betterfoliage.model.transform
|
||||
import mods.betterfoliage.model.tuftModelSet
|
||||
import mods.betterfoliage.model.tuftShapeSet
|
||||
import mods.betterfoliage.model.withOpposites
|
||||
import mods.betterfoliage.render.lighting.grassTuftLighting
|
||||
import mods.betterfoliage.render.lighting.withLighting
|
||||
import mods.betterfoliage.resource.discovery.AbstractModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.LazyInvalidatable
|
||||
import mods.betterfoliage.util.Rotation
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.offset
|
||||
import mods.betterfoliage.util.plus
|
||||
import mods.betterfoliage.util.randomI
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.RenderLayer
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.client.render.model.json.JsonUnbakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.DOWN
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.Random
|
||||
import java.util.function.Supplier
|
||||
|
||||
object StandardNetherrackDiscovery : AbstractModelDiscovery() {
|
||||
|
||||
fun canRenderInLayer(layer: RenderLayer) = when {
|
||||
!BetterFoliage.config.enabled -> layer == RenderLayer.getSolid()
|
||||
!BetterFoliage.config.netherrack.enabled -> layer == RenderLayer.getSolid()
|
||||
else -> layer == RenderLayer.getCutoutMipped()
|
||||
}
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext) {
|
||||
if (ctx.getUnbaked() is JsonUnbakedModel && ctx.blockState.block in NETHERRACK_BLOCKS) {
|
||||
BetterFoliage.blockTypes.dirt.add(ctx.blockState)
|
||||
ctx.addReplacement(StandardNetherrackKey)
|
||||
// RenderTypeLookup.setRenderLayer(ctx.blockState.block, ::canRenderInLayer)
|
||||
}
|
||||
super.processModel(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
object StandardNetherrackKey : ModelWrapKey() {
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel) = StandardNetherrackModel(meshifyCutoutMipped(wrapped))
|
||||
}
|
||||
|
||||
class StandardNetherrackModel(wrapped: BakedModel) : WrappedBakedModel(wrapped) {
|
||||
|
||||
val tuftLighting = grassTuftLighting(DOWN)
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
if (BetterFoliage.config.enabled &&
|
||||
BetterFoliage.config.netherrack.enabled &&
|
||||
blockView.getBlockState(pos + DOWN.offset).isAir
|
||||
) {
|
||||
val random = randomSupplier.get()
|
||||
context.withLighting(tuftLighting) {
|
||||
it.accept(netherrackTuftModels[random])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
val netherrackTuftSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_netherrack_$idx")
|
||||
}
|
||||
val netherrackTuftModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes = BetterFoliage.config.netherrack.let { tuftShapeSet(it.size, it.heightMin, it.heightMax, it.hOffset) }
|
||||
tuftModelSet(shapes, Color.white.asInt) { netherrackTuftSprites[randomI()] }
|
||||
.transform { rotate(Rotation.fromUp[DOWN.ordinal]).rotateUV(2) }
|
||||
.withOpposites()
|
||||
.build(BlendMode.CUTOUT_MIPPED, flatLighting = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.meshifySolid
|
||||
import mods.betterfoliage.render.column.ColumnBlockKey
|
||||
import mods.betterfoliage.render.column.ColumnMeshSet
|
||||
import mods.betterfoliage.render.column.ColumnModelBase
|
||||
import mods.betterfoliage.render.column.ColumnRenderLayer
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ConfigurableBlockMatcher
|
||||
import mods.betterfoliage.resource.discovery.ConfigurableModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingKey
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.resource.discovery.ModelTextureList
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.LazyMap
|
||||
import mods.betterfoliage.util.tryDefault
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.PillarBlock
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.Direction.Axis
|
||||
import org.apache.logging.log4j.Level
|
||||
|
||||
interface RoundLogKey : ColumnBlockKey, ModelBakingKey {
|
||||
val barkSprite: Identifier
|
||||
val endSprite: Identifier
|
||||
}
|
||||
|
||||
object RoundLogOverlayLayer : ColumnRenderLayer() {
|
||||
override fun getColumnKey(state: BlockState) = BetterFoliage.blockTypes.getTyped<ColumnBlockKey>(state)
|
||||
override val connectSolids: Boolean get() = BetterFoliage.config.roundLogs.connectSolids
|
||||
override val lenientConnect: Boolean get() = BetterFoliage.config.roundLogs.lenientConnect
|
||||
override val defaultToY: Boolean get() = BetterFoliage.config.roundLogs.defaultY
|
||||
}
|
||||
|
||||
object StandardRoundLogDiscovery : ConfigurableModelDiscovery() {
|
||||
override val matchClasses: ConfigurableBlockMatcher get() = BetterFoliage.blockConfig.logBlocks
|
||||
override val modelTextures: List<ModelTextureList> get() = BetterFoliage.blockConfig.logModels.modelList
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext, textureMatch: List<Identifier>) {
|
||||
val axis = getAxis(ctx.blockState)
|
||||
detailLogger.log(Level.INFO, " axis $axis")
|
||||
ctx.addReplacement(StandardRoundLogKey(axis, textureMatch[0], textureMatch[1]))
|
||||
}
|
||||
|
||||
fun getAxis(state: BlockState): Axis? {
|
||||
val axis = tryDefault(null) { state.get(PillarBlock.AXIS).toString() } ?:
|
||||
state.entries.entries.find { it.key.getName().toLowerCase() == "axis" }?.value?.toString()
|
||||
return when (axis) {
|
||||
"x" -> Axis.X
|
||||
"y" -> Axis.Y
|
||||
"z" -> Axis.Z
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class StandardRoundLogKey(
|
||||
override val axis: Axis?,
|
||||
override val barkSprite: Identifier,
|
||||
override val endSprite: Identifier
|
||||
) : RoundLogKey, ModelWrapKey() {
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel) = StandardRoundLogModel(meshifySolid(wrapped), this)
|
||||
}
|
||||
|
||||
class StandardRoundLogModel(wrapped: BakedModel, val key: StandardRoundLogKey) : ColumnModelBase(wrapped) {
|
||||
override val enabled: Boolean get() = BetterFoliage.config.enabled && BetterFoliage.config.roundLogs.enabled
|
||||
override val overlayLayer: ColumnRenderLayer get() = RoundLogOverlayLayer
|
||||
override val connectPerpendicular: Boolean get() = BetterFoliage.config.roundLogs.connectPerpendicular
|
||||
|
||||
val modelSet by modelSets.delegate(key)
|
||||
override fun getMeshSet(axis: Axis, quadrant: Int) = modelSet
|
||||
|
||||
companion object {
|
||||
val modelSets = LazyMap(BakeWrapperManager) { key: StandardRoundLogKey ->
|
||||
val barkSprite = Atlas.BLOCKS[key.barkSprite]!!
|
||||
val endSprite = Atlas.BLOCKS[key.endSprite]!!
|
||||
BetterFoliage.config.roundLogs.let { config ->
|
||||
ColumnMeshSet(
|
||||
config.radiusSmall, config.radiusLarge, config.zProtection,
|
||||
key.axis ?: Axis.Y,
|
||||
barkSprite, barkSprite,
|
||||
endSprite, endSprite
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
122
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Sand.kt
Normal file
122
src/main/kotlin/mods/betterfoliage/render/block/vanilla/Sand.kt
Normal file
@@ -0,0 +1,122 @@
|
||||
package mods.betterfoliage.render.block.vanilla
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.chunk.CachedBlockCtx
|
||||
import mods.betterfoliage.config.SALTWATER_BIOMES
|
||||
import mods.betterfoliage.config.SAND_BLOCKS
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.ModelWrapKey
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.build
|
||||
import mods.betterfoliage.model.horizontalRectangle
|
||||
import mods.betterfoliage.model.meshifySolid
|
||||
import mods.betterfoliage.model.meshifyStandard
|
||||
import mods.betterfoliage.model.transform
|
||||
import mods.betterfoliage.model.tuftModelSet
|
||||
import mods.betterfoliage.model.tuftShapeSet
|
||||
import mods.betterfoliage.model.withOpposites
|
||||
import mods.betterfoliage.render.lighting.grassTuftLighting
|
||||
import mods.betterfoliage.render.lighting.withLighting
|
||||
import mods.betterfoliage.resource.discovery.AbstractModelDiscovery
|
||||
import mods.betterfoliage.resource.discovery.BakeWrapperManager
|
||||
import mods.betterfoliage.resource.discovery.ModelBakingContext
|
||||
import mods.betterfoliage.resource.discovery.ModelDiscoveryContext
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.LazyInvalidatable
|
||||
import mods.betterfoliage.util.Rotation
|
||||
import mods.betterfoliage.util.allDirections
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.randomB
|
||||
import mods.betterfoliage.util.randomD
|
||||
import mods.betterfoliage.util.randomI
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.block.Blocks
|
||||
import net.minecraft.block.Material
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.client.render.model.json.JsonUnbakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.UP
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.Random
|
||||
import java.util.function.Supplier
|
||||
|
||||
object StandardSandDiscovery : AbstractModelDiscovery() {
|
||||
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext) {
|
||||
if (ctx.getUnbaked() is JsonUnbakedModel && ctx.blockState.block in SAND_BLOCKS) {
|
||||
BetterFoliage.blockTypes.dirt.add(ctx.blockState)
|
||||
ctx.addReplacement(StandardSandKey)
|
||||
// RenderTypeLookup.setRenderLayer(ctx.blockState.block, RenderType.getCutoutMipped())
|
||||
}
|
||||
super.processModel(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
object StandardSandKey : ModelWrapKey() {
|
||||
override fun bake(ctx: ModelBakingContext, wrapped: BasicBakedModel) = StandardSandModel(meshifySolid(wrapped))
|
||||
}
|
||||
|
||||
class StandardSandModel(wrapped: BakedModel) : WrappedBakedModel(wrapped) {
|
||||
|
||||
val coralLighting = allDirections.map { grassTuftLighting(it) }.toTypedArray()
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
|
||||
val ctx = CachedBlockCtx(blockView, pos)
|
||||
|
||||
val random = randomSupplier.get()
|
||||
if (!BetterFoliage.config.enabled || !BetterFoliage.config.coral.enabled(random)) return
|
||||
if (ctx.biome?.category !in SALTWATER_BIOMES) return
|
||||
|
||||
allDirections.filter { random.nextInt(64) < BetterFoliage.config.coral.chance }.forEach { face ->
|
||||
val isWater = ctx.state(face).material == Material.WATER
|
||||
val isDeepWater = isWater && ctx.offset(face).state(UP).material == Material.WATER
|
||||
if (isDeepWater) context.withLighting(coralLighting[face]) {
|
||||
it.accept(coralCrustModels[face][random])
|
||||
it.accept(coralTuftModels[face][random])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
// val sandModel by LazyInvalidatable(BetterFoliage.modelReplacer) {
|
||||
// Array(64) { fullCubeTextured(Identifier("block/sand"), Color.white.asInt) }
|
||||
// }
|
||||
|
||||
val coralTuftSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_coral_$idx")
|
||||
}
|
||||
val coralCrustSprites by SpriteSetDelegate(Atlas.BLOCKS) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "blocks/better_crust_$idx")
|
||||
}
|
||||
val coralTuftModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
val shapes = BetterFoliage.config.coral.let { tuftShapeSet(it.size, 1.0, 1.0, it.hOffset) }
|
||||
allDirections.map { face ->
|
||||
tuftModelSet(shapes, Color.white.asInt) { coralTuftSprites[randomI()] }
|
||||
.transform { rotate(Rotation.fromUp[face]) }
|
||||
.withOpposites()
|
||||
.build(BlendMode.CUTOUT_MIPPED)
|
||||
}.toTypedArray()
|
||||
}
|
||||
val coralCrustModels by LazyInvalidatable(BakeWrapperManager) {
|
||||
allDirections.map { face ->
|
||||
Array(64) { idx ->
|
||||
listOf(horizontalRectangle(x1 = -0.5, x2 = 0.5, z1 = -0.5, z2 = 0.5, y = 0.0)
|
||||
.scale(BetterFoliage.config.coral.crustSize)
|
||||
.move(0.5 + randomD(0.01, BetterFoliage.config.coral.vOffset) to UP)
|
||||
.rotate(Rotation.fromUp[face])
|
||||
.mirrorUV(randomB(), randomB()).rotateUV(randomI(max = 4))
|
||||
.sprite(coralCrustSprites[idx]).colorAndIndex(null)
|
||||
).build(BlendMode.CUTOUT_MIPPED)
|
||||
}
|
||||
}.toTypedArray()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package mods.betterfoliage.render.column
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.INVISIBLE
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.LARGE_RADIUS
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.SMALL_RADIUS
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.SQUARE
|
||||
import mods.betterfoliage.model.Color
|
||||
import mods.betterfoliage.model.Quad
|
||||
import mods.betterfoliage.model.UV
|
||||
import mods.betterfoliage.model.Vertex
|
||||
import mods.betterfoliage.model.build
|
||||
import mods.betterfoliage.model.horizontalRectangle
|
||||
import mods.betterfoliage.model.verticalRectangle
|
||||
import mods.betterfoliage.util.Double3
|
||||
import mods.betterfoliage.util.Rotation
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode.SOLID
|
||||
import net.minecraft.client.texture.Sprite
|
||||
import net.minecraft.util.math.Direction.Axis
|
||||
import net.minecraft.util.math.Direction.EAST
|
||||
import net.minecraft.util.math.Direction.SOUTH
|
||||
import net.minecraft.util.math.Direction.UP
|
||||
|
||||
/**
|
||||
* Collection of dynamically generated meshes used to render rounded columns.
|
||||
*/
|
||||
class ColumnMeshSet(
|
||||
radiusSmall: Double,
|
||||
radiusLarge: Double,
|
||||
zProtection: Double,
|
||||
val axis: Axis,
|
||||
val spriteLeft: Sprite,
|
||||
val spriteRight: Sprite,
|
||||
val spriteTop: Sprite,
|
||||
val spriteBottom: Sprite
|
||||
) {
|
||||
protected fun sideRounded(radius: Double, yBottom: Double, yTop: Double): List<Quad> {
|
||||
val halfRadius = radius * 0.5
|
||||
return listOf(
|
||||
// left side of the diagonal
|
||||
verticalRectangle(0.0, 0.5, 0.5 - radius, 0.5, yBottom, yTop).clampUV(minU = 0.0, maxU = 0.5 - radius),
|
||||
verticalRectangle(0.5 - radius, 0.5, 0.5 - halfRadius, 0.5 - halfRadius, yBottom, yTop).clampUV(minU = 0.5 - radius),
|
||||
// right side of the diagonal
|
||||
verticalRectangle(0.5 - halfRadius, 0.5 - halfRadius, 0.5, 0.5 - radius, yBottom, yTop).clampUV(maxU = radius - 0.5),
|
||||
verticalRectangle(0.5, 0.5 - radius, 0.5, 0.0, yBottom, yTop).clampUV(minU = radius - 0.5, maxU = 0.0)
|
||||
)
|
||||
}
|
||||
|
||||
protected fun sideRoundedTransition(radiusBottom: Double, radiusTop: Double, yBottom: Double, yTop: Double): List<Quad> {
|
||||
val ySplit = 0.5 * (yBottom + yTop)
|
||||
val modelTop = sideRounded(radiusTop, yBottom, yTop)
|
||||
val modelBottom = sideRounded(radiusBottom, yBottom, yTop)
|
||||
return (modelBottom zip modelTop).map { (quadBottom, quadTop) ->
|
||||
Quad.mix(quadBottom, quadTop) { vBottom, vTop -> if (vBottom.xyz.y < ySplit) vBottom.copy() else vTop.copy() }
|
||||
}
|
||||
}
|
||||
|
||||
protected fun sideSquare(yBottom: Double, yTop: Double) = listOf(
|
||||
verticalRectangle(0.0, 0.5, 0.5, 0.5, yBottom, yTop).clampUV(minU = 0.0),
|
||||
verticalRectangle(0.5, 0.5, 0.5, 0.0, yBottom, yTop).clampUV(maxU = 0.0)
|
||||
)
|
||||
|
||||
protected fun lidRounded(radius: Double, y: Double, isBottom: Boolean) = Array(4) { quadrant ->
|
||||
val rotation = baseRotation(axis) + quadrantRotations[quadrant]
|
||||
val v1 = Vertex(Double3(0.0, y, 0.0), UV(0.0, 0.0))
|
||||
val v2 = Vertex(Double3(0.0, y, 0.5), UV(0.0, 0.5))
|
||||
val v3 = Vertex(Double3(0.5 - radius, y, 0.5), UV(0.5 - radius, 0.5))
|
||||
val v4 = Vertex(Double3(0.5 - radius * 0.5, y, 0.5 - radius * 0.5), UV(0.5, 0.5))
|
||||
val v5 = Vertex(Double3(0.5, y, 0.5 - radius), UV(0.5, 0.5 - radius))
|
||||
val v6 = Vertex(Double3(0.5, y, 0.0), UV(0.5, 0.0))
|
||||
listOf(Quad(v1, v2, v3, v4), Quad(v1, v4, v5, v6))
|
||||
.map { it.cycleVertices(if (isBottom xor BetterFoliage.config.nVidia) 0 else 1) }
|
||||
.map { it.rotate(rotation).rotateUV(quadrant) }
|
||||
.map { it.sprite(if (isBottom) spriteBottom else spriteTop).colorAndIndex(Color.white.asInt) }
|
||||
.map { if (isBottom) it.flipped else it }
|
||||
}
|
||||
|
||||
protected fun lidSquare(y: Double, isBottom: Boolean) = Array(4) { quadrant ->
|
||||
val rotation = baseRotation(axis) + quadrantRotations[quadrant]
|
||||
listOf(
|
||||
horizontalRectangle(x1 = 0.0, x2 = 0.5, z1 = 0.0, z2 = 0.5, y = y).clampUV(minU = 0.0, minV = 0.0)
|
||||
.rotate(rotation).rotateUV(quadrant)
|
||||
.sprite(if (isBottom) spriteBottom else spriteTop).colorAndIndex(Color.white.asInt)
|
||||
.let { if (isBottom) it.flipped else it }
|
||||
)
|
||||
}
|
||||
|
||||
protected val zProtectionScale = zProtection.let { Double3(it, 1.0, it) }
|
||||
|
||||
protected fun List<Quad>.extendTop(size: Double) = map { q -> q.clampUV(minV = 0.5 - size).transformV { v ->
|
||||
if (v.xyz.y > 0.501) v.copy(xyz = v.xyz * zProtectionScale) else v }
|
||||
}
|
||||
protected fun List<Quad>.extendBottom(size: Double) = map { q -> q.clampUV(maxV = -0.5 + size).transformV { v ->
|
||||
if (v.xyz.y < -0.501) v.copy(xyz = v.xyz * zProtectionScale) else v }
|
||||
}
|
||||
protected fun List<Quad>.buildSides(quadsPerSprite: Int) = Array(4) { quadrant ->
|
||||
val rotation = baseRotation(axis) + quadrantRotations[quadrant]
|
||||
this.map { it.rotate(rotation).colorAndIndex(Color.white.asInt) }
|
||||
.mapIndexed { idx, q -> if (idx % (2 * quadsPerSprite) >= quadsPerSprite) q.sprite(spriteRight) else q.sprite(spriteLeft) }
|
||||
.build(SOLID, flatLighting = false)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun baseRotation(axis: Axis) = when(axis) {
|
||||
Axis.X -> Rotation.fromUp[EAST.ordinal]
|
||||
Axis.Y -> Rotation.fromUp[UP.ordinal]
|
||||
Axis.Z -> Rotation.fromUp[SOUTH.ordinal]
|
||||
}
|
||||
val quadrantRotations = Array(4) { Rotation.rot90[UP.ordinal] * it }
|
||||
}
|
||||
|
||||
//
|
||||
// Mesh definitions
|
||||
// 4-element arrays hold prebuild meshes for each of the rotations around the axis
|
||||
//
|
||||
val sideSquare = sideSquare(-0.5, 0.5).buildSides(quadsPerSprite = 1)
|
||||
val sideRoundSmall = sideRounded(radiusSmall, -0.5, 0.5).buildSides(quadsPerSprite = 2)
|
||||
val sideRoundLarge = sideRounded(radiusLarge, -0.5, 0.5).buildSides(quadsPerSprite = 2)
|
||||
|
||||
val sideExtendTopSquare = sideSquare(0.5, 0.5 + radiusLarge).extendTop(radiusLarge).buildSides(quadsPerSprite = 1)
|
||||
val sideExtendTopRoundSmall = sideRounded(radiusSmall, 0.5, 0.5 + radiusLarge).extendTop(radiusLarge).buildSides(quadsPerSprite = 2)
|
||||
val sideExtendTopRoundLarge = sideRounded(radiusLarge, 0.5, 0.5 + radiusLarge).extendTop(radiusLarge).buildSides(quadsPerSprite = 2)
|
||||
|
||||
val sideExtendBottomSquare = sideSquare(-0.5 - radiusLarge, -0.5).extendBottom(radiusLarge).buildSides(quadsPerSprite = 1)
|
||||
val sideExtendBottomRoundSmall = sideRounded(radiusSmall, -0.5 - radiusLarge, -0.5).extendBottom(radiusLarge).buildSides(quadsPerSprite = 2)
|
||||
val sideExtendBottomRoundLarge = sideRounded(radiusLarge, -0.5 - radiusLarge, -0.5).extendBottom(radiusLarge).buildSides(quadsPerSprite = 2)
|
||||
|
||||
val lidTopSquare = lidSquare(0.5, false).build(SOLID, flatLighting = false)
|
||||
val lidTopRoundSmall = lidRounded(radiusSmall, 0.5, false).build(SOLID, flatLighting = false)
|
||||
val lidTopRoundLarge = lidRounded(radiusLarge, 0.5, false).build(SOLID, flatLighting = false)
|
||||
|
||||
val lidBottomSquare = lidSquare(-0.5, true).build(SOLID, flatLighting = false)
|
||||
val lidBottomRoundSmall = lidRounded(radiusSmall, -0.5, true).build(SOLID, flatLighting = false)
|
||||
val lidBottomRoundLarge = lidRounded(radiusLarge, -0.5, true).build(SOLID, flatLighting = false)
|
||||
|
||||
val transitionTop = sideRoundedTransition(radiusLarge, radiusSmall, -0.5, 0.5).buildSides(quadsPerSprite = 2)
|
||||
val transitionBottom = sideRoundedTransition(radiusSmall, radiusLarge, -0.5, 0.5).buildSides(quadsPerSprite = 2)
|
||||
|
||||
//
|
||||
// Helper fuctions for lids (block ends)
|
||||
//
|
||||
fun flatTop(quadrantTypes: Array<QuadrantType>, quadrant: Int) = when(quadrantTypes[quadrant]) {
|
||||
SMALL_RADIUS -> lidTopRoundSmall[quadrant]
|
||||
LARGE_RADIUS -> lidTopRoundLarge[quadrant]
|
||||
SQUARE -> lidTopSquare[quadrant]
|
||||
INVISIBLE -> lidTopSquare[quadrant]
|
||||
}
|
||||
|
||||
fun flatBottom(quadrantTypes: Array<QuadrantType>, quadrant: Int) = when(quadrantTypes[quadrant]) {
|
||||
SMALL_RADIUS -> lidBottomRoundSmall[quadrant]
|
||||
LARGE_RADIUS -> lidBottomRoundLarge[quadrant]
|
||||
SQUARE -> lidBottomSquare[quadrant]
|
||||
INVISIBLE -> lidBottomSquare[quadrant]
|
||||
}
|
||||
|
||||
fun extendTop(quadrantTypes: Array<QuadrantType>, quadrant: Int) = when(quadrantTypes[quadrant]) {
|
||||
SMALL_RADIUS -> sideExtendTopRoundSmall[quadrant]
|
||||
LARGE_RADIUS -> sideExtendTopRoundLarge[quadrant]
|
||||
SQUARE -> sideExtendTopSquare[quadrant]
|
||||
INVISIBLE -> sideExtendTopSquare[quadrant]
|
||||
}
|
||||
|
||||
fun extendBottom(quadrantTypes: Array<QuadrantType>, quadrant: Int) = when(quadrantTypes[quadrant]) {
|
||||
SMALL_RADIUS -> sideExtendBottomRoundSmall[quadrant]
|
||||
LARGE_RADIUS -> sideExtendBottomRoundLarge[quadrant]
|
||||
SQUARE -> sideExtendBottomSquare[quadrant]
|
||||
INVISIBLE -> sideExtendBottomSquare[quadrant]
|
||||
}
|
||||
}
|
||||
109
src/main/kotlin/mods/betterfoliage/render/column/ColumnModel.kt
Normal file
109
src/main/kotlin/mods/betterfoliage/render/column/ColumnModel.kt
Normal file
@@ -0,0 +1,109 @@
|
||||
package mods.betterfoliage.render.column
|
||||
|
||||
import mods.betterfoliage.chunk.CachedBlockCtx
|
||||
import mods.betterfoliage.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.NormalRender
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.BlockType.*
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.*
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.Direction.Axis
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.*
|
||||
import java.util.function.Supplier
|
||||
|
||||
abstract class ColumnModelBase(wrapped: BakedModel) : WrappedBakedModel(wrapped) {
|
||||
abstract val enabled: Boolean
|
||||
abstract val overlayLayer: ColumnRenderLayer
|
||||
abstract val connectPerpendicular: Boolean
|
||||
abstract fun getMeshSet(axis: Axis, quadrant: Int): ColumnMeshSet
|
||||
|
||||
override fun emitBlockQuads(blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) {
|
||||
if (!enabled) return super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
val ctx = CachedBlockCtx(blockView, pos)
|
||||
val roundLog = ChunkOverlayManager.get(overlayLayer, ctx)
|
||||
|
||||
when(roundLog) {
|
||||
ColumnLayerData.SkipRender -> return
|
||||
NormalRender -> return super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
ColumnLayerData.ResolveError, null -> {
|
||||
return super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
}
|
||||
|
||||
// if log axis is not defined and "Default to vertical" config option is not set, render normally
|
||||
if ((roundLog as ColumnLayerData.SpecialRender).column.axis == null && !overlayLayer.defaultToY) {
|
||||
return super.emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
|
||||
val axis = roundLog.column.axis ?: Axis.Y
|
||||
val baseRotation = ColumnMeshSet.baseRotation(axis)
|
||||
ColumnMeshSet.quadrantRotations.forEachIndexed { idx, quadrantRotation ->
|
||||
// set rotation for the current quadrant
|
||||
val rotation = baseRotation + quadrantRotation
|
||||
val meshSet = getMeshSet(axis, idx)
|
||||
|
||||
// disallow sharp discontinuities in the chamfer radius, or tapering-in where inappropriate
|
||||
if (roundLog.quadrants[idx] == LARGE_RADIUS &&
|
||||
roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] != LARGE_RADIUS &&
|
||||
roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] != LARGE_RADIUS) {
|
||||
roundLog.quadrants[idx] = SMALL_RADIUS
|
||||
}
|
||||
|
||||
// select meshes for current quadrant based on connectivity rules
|
||||
val sideMesh = when (roundLog.quadrants[idx]) {
|
||||
SMALL_RADIUS -> meshSet.sideRoundSmall[idx]
|
||||
LARGE_RADIUS -> if (roundLog.upType == PARALLEL && roundLog.quadrantsTop[idx] == SMALL_RADIUS) meshSet.transitionTop[idx]
|
||||
else if (roundLog.downType == PARALLEL && roundLog.quadrantsBottom[idx] == SMALL_RADIUS) meshSet.transitionBottom[idx]
|
||||
else meshSet.sideRoundLarge[idx]
|
||||
SQUARE -> meshSet.sideSquare[idx]
|
||||
else -> null
|
||||
}
|
||||
|
||||
val upMesh = when(roundLog.upType) {
|
||||
NONSOLID -> meshSet.flatTop(roundLog.quadrants, idx)
|
||||
PERPENDICULAR -> {
|
||||
if (!connectPerpendicular) {
|
||||
meshSet.flatTop(roundLog.quadrants, idx)
|
||||
} else {
|
||||
meshSet.extendTop(roundLog.quadrants, idx)
|
||||
}
|
||||
}
|
||||
PARALLEL -> {
|
||||
if (roundLog.quadrants[idx] discontinuousWith roundLog.quadrantsTop[idx] &&
|
||||
roundLog.quadrants[idx].let { it == SQUARE || it == INVISIBLE } )
|
||||
meshSet.flatTop(roundLog.quadrants, idx)
|
||||
else null
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
val downMesh = when(roundLog.downType) {
|
||||
NONSOLID -> meshSet.flatBottom(roundLog.quadrants, idx)
|
||||
PERPENDICULAR -> {
|
||||
if (!connectPerpendicular) {
|
||||
meshSet.flatBottom(roundLog.quadrants, idx)
|
||||
} else {
|
||||
meshSet.extendBottom(roundLog.quadrants, idx)
|
||||
}
|
||||
}
|
||||
PARALLEL -> {
|
||||
if (roundLog.quadrants[idx] discontinuousWith roundLog.quadrantsBottom[idx] &&
|
||||
roundLog.quadrants[idx].let { it == SQUARE || it == INVISIBLE } )
|
||||
meshSet.flatBottom(roundLog.quadrants, idx)
|
||||
else null
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
|
||||
// render
|
||||
sideMesh?.let { context.meshConsumer().accept(it) }
|
||||
upMesh?.let { context.meshConsumer().accept(it) }
|
||||
downMesh?.let { context.meshConsumer().accept(it) }
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,31 @@
|
||||
package mods.betterfoliage.client.render.column
|
||||
package mods.betterfoliage.render.column
|
||||
|
||||
import mods.betterfoliage.client.chunk.ChunkOverlayLayer
|
||||
import mods.betterfoliage.client.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.client.chunk.dimType
|
||||
import mods.betterfoliage.client.config.Config
|
||||
import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.BlockType.*
|
||||
import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType
|
||||
import mods.betterfoliage.client.render.column.ColumnLayerData.SpecialRender.QuadrantType.*
|
||||
import mods.betterfoliage.client.render.rotationFromUp
|
||||
import mods.octarinecore.client.render.BlockCtx
|
||||
import mods.octarinecore.client.resource.ModelRenderRegistry
|
||||
import mods.octarinecore.common.*
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.chunk.BlockCtx
|
||||
import mods.betterfoliage.chunk.ChunkOverlayLayer
|
||||
import mods.betterfoliage.chunk.ChunkOverlayManager
|
||||
import mods.betterfoliage.chunk.dimType
|
||||
import mods.betterfoliage.render.block.vanilla.RoundLogKey
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.BlockType.NONSOLID
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.BlockType.PARALLEL
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.BlockType.PERPENDICULAR
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.BlockType.SOLID
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.INVISIBLE
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.LARGE_RADIUS
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.SMALL_RADIUS
|
||||
import mods.betterfoliage.render.column.ColumnLayerData.SpecialRender.QuadrantType.SQUARE
|
||||
import mods.betterfoliage.util.Int3
|
||||
import mods.betterfoliage.util.Rotation
|
||||
import mods.betterfoliage.util.allDirections
|
||||
import mods.betterfoliage.util.face
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.plus
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.util.Direction.Axis
|
||||
import net.minecraft.util.Direction.AxisDirection
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.world.IEnviromentBlockReader
|
||||
import net.minecraft.util.math.Direction.Axis
|
||||
import net.minecraft.util.math.Direction.AxisDirection
|
||||
import net.minecraft.world.WorldView
|
||||
|
||||
/** Index of SOUTH-EAST quadrant. */
|
||||
const val SE = 0
|
||||
@@ -26,6 +36,10 @@ const val NW = 2
|
||||
/** Index of SOUTH-WEST quadrant. */
|
||||
const val SW = 3
|
||||
|
||||
interface ColumnBlockKey {
|
||||
val axis: Axis?
|
||||
}
|
||||
|
||||
/**
|
||||
* Sealed class hierarchy for all possible render outcomes
|
||||
*/
|
||||
@@ -35,7 +49,7 @@ sealed class ColumnLayerData {
|
||||
*/
|
||||
@Suppress("ArrayInDataClass") // not used in comparisons anywhere
|
||||
data class SpecialRender(
|
||||
val column: ColumnTextureInfo,
|
||||
val column: ColumnBlockKey,
|
||||
val upType: BlockType,
|
||||
val downType: BlockType,
|
||||
val quadrants: Array<QuadrantType>,
|
||||
@@ -43,7 +57,12 @@ sealed class ColumnLayerData {
|
||||
val quadrantsBottom: Array<QuadrantType>
|
||||
) : ColumnLayerData() {
|
||||
enum class BlockType { SOLID, NONSOLID, PARALLEL, PERPENDICULAR }
|
||||
enum class QuadrantType { SMALL_RADIUS, LARGE_RADIUS, SQUARE, INVISIBLE }
|
||||
enum class QuadrantType {
|
||||
SMALL_RADIUS, LARGE_RADIUS, SQUARE, INVISIBLE;
|
||||
infix fun continuousWith(other: QuadrantType) =
|
||||
this == other || ((this == SQUARE || this == INVISIBLE) && (other == SQUARE || other == INVISIBLE))
|
||||
infix fun discontinuousWith(other: QuadrantType) = !continuousWith(other)
|
||||
}
|
||||
}
|
||||
|
||||
/** Column block should not be rendered at all */
|
||||
@@ -56,30 +75,31 @@ sealed class ColumnLayerData {
|
||||
object ResolveError : ColumnLayerData()
|
||||
}
|
||||
|
||||
|
||||
abstract class ColumnRenderLayer : ChunkOverlayLayer<ColumnLayerData> {
|
||||
|
||||
abstract val registry: ModelRenderRegistry<ColumnTextureInfo>
|
||||
abstract val blockPredicate: (BlockState)->Boolean
|
||||
abstract val connectSolids: Boolean
|
||||
abstract val lenientConnect: Boolean
|
||||
abstract val defaultToY: Boolean
|
||||
|
||||
abstract fun getColumnKey(state: BlockState): ColumnBlockKey?
|
||||
|
||||
val allNeighborOffsets = (-1..1).flatMap { offsetX -> (-1..1).flatMap { offsetY -> (-1..1).map { offsetZ -> Int3(offsetX, offsetY, offsetZ) }}}
|
||||
|
||||
override fun onBlockUpdate(world: IEnviromentBlockReader, pos: BlockPos) {
|
||||
override fun onBlockUpdate(world: WorldView, pos: BlockPos) {
|
||||
allNeighborOffsets.forEach { offset -> ChunkOverlayManager.clear(world.dimType, this, pos + offset) }
|
||||
}
|
||||
|
||||
override fun calculate(ctx: BlockCtx): ColumnLayerData {
|
||||
if (allDirections.all { ctx.offset(it).isNormalCube }) return ColumnLayerData.SkipRender
|
||||
val columnTextures = registry[ctx] ?: return ColumnLayerData.ResolveError
|
||||
if (allDirections.all { dir ->
|
||||
ctx.offset(dir).let { it.isNormalCube && !BetterFoliage.blockTypes.hasTyped<RoundLogKey>(it.state) }
|
||||
}) return ColumnLayerData.SkipRender
|
||||
val columnTextures = getColumnKey(ctx.state) ?: return ColumnLayerData.ResolveError
|
||||
|
||||
// if log axis is not defined and "Default to vertical" config option is not set, render normally
|
||||
val logAxis = columnTextures.axis ?: if (defaultToY) Axis.Y else return ColumnLayerData.NormalRender
|
||||
|
||||
// check log neighborhood
|
||||
val baseRotation = rotationFromUp[(logAxis to AxisDirection.POSITIVE).face.ordinal]
|
||||
val baseRotation = Rotation.fromUp[(logAxis to AxisDirection.POSITIVE).face.ordinal]
|
||||
|
||||
val upType = ctx.blockType(baseRotation, logAxis, Int3(0, 1, 0))
|
||||
val downType = ctx.blockType(baseRotation, logAxis, Int3(0, -1, 0))
|
||||
@@ -167,11 +187,11 @@ abstract class ColumnRenderLayer : ChunkOverlayLayer<ColumnLayerData> {
|
||||
*/
|
||||
fun BlockCtx.blockType(rotation: Rotation, axis: Axis, offset: Int3): ColumnLayerData.SpecialRender.BlockType {
|
||||
val offsetRot = offset.rotate(rotation)
|
||||
val state = state(offsetRot)
|
||||
return if (!blockPredicate(state)) {
|
||||
val key = getColumnKey(state(offsetRot))
|
||||
return if (key == null) {
|
||||
if (offset(offsetRot).isNormalCube) SOLID else NONSOLID
|
||||
} else {
|
||||
(registry[state, world, pos + offsetRot]?.axis ?: if (Config.roundLogs.defaultY) Axis.Y else null)?.let {
|
||||
(key.axis ?: if (BetterFoliage.config.roundLogs.defaultY) Axis.Y else null)?.let {
|
||||
if (it == axis) PARALLEL else PERPENDICULAR
|
||||
} ?: SOLID
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package mods.betterfoliage.render.lighting
|
||||
|
||||
import mods.betterfoliage.util.*
|
||||
import net.fabricmc.fabric.api.renderer.v1.mesh.QuadView
|
||||
import net.minecraft.util.math.Direction
|
||||
import net.minecraft.util.math.Direction.*
|
||||
import kotlin.math.abs
|
||||
|
||||
val EPSILON = 0.05
|
||||
|
||||
interface CustomLighting {
|
||||
fun applyLighting(lighting: CustomLightingMeshConsumer, quad: QuadView, flat: Boolean, emissive: Boolean)
|
||||
}
|
||||
|
||||
interface CustomLightingMeshConsumer {
|
||||
/** Clear cached block brightness and AO values */
|
||||
fun clearLighting()
|
||||
/** Fill AO/light cache for given face */
|
||||
fun fillAoData(lightFace: Direction)
|
||||
/** Set AO/light values for quad vertex */
|
||||
fun setLighting(vIdx: Int, ao: Float, light: Int)
|
||||
/** Get neighbor block brightness */
|
||||
fun brNeighbor(dir: Direction): Int
|
||||
/** Block brightness value */
|
||||
val brSelf: Int
|
||||
/** Cached AO values for all box face corners */
|
||||
val aoFull: FloatArray
|
||||
/** Cached light values for all box face corners */
|
||||
val lightFull: IntArray
|
||||
}
|
||||
|
||||
/** Custom lighting used for protruding tuft quads (short grass, algae, cactus arms, etc.) */
|
||||
fun grassTuftLighting(lightFace: Direction) = object : CustomLighting {
|
||||
override fun applyLighting(lighting: CustomLightingMeshConsumer, quad : QuadView, flat: Boolean, emissive: Boolean) {
|
||||
if (flat) lighting.flatForceNeighbor(quad, lightFace) else lighting.smoothWithFaceOverride(quad, lightFace)
|
||||
}
|
||||
}
|
||||
|
||||
/** Custom lighting used for round leaves */
|
||||
fun roundLeafLighting() = object : CustomLighting {
|
||||
override fun applyLighting(lighting: CustomLightingMeshConsumer, quad: QuadView, flat: Boolean, emissive: Boolean) {
|
||||
if (flat) lighting.flatMax(quad) else lighting.smooth45PreferUp(quad)
|
||||
}
|
||||
}
|
||||
|
||||
/** Custom lighting used for reeds */
|
||||
fun reedLighting() = object : CustomLighting {
|
||||
override fun applyLighting(lighting: CustomLightingMeshConsumer, quad: QuadView, flat: Boolean, emissive: Boolean) {
|
||||
lighting.flatForceNeighbor(quad, UP)
|
||||
}
|
||||
}
|
||||
|
||||
/** Flat lighting, use neighbor brightness in the given direction */
|
||||
fun CustomLightingMeshConsumer.flatForceNeighbor(quad: QuadView, lightFace: Direction) {
|
||||
for (vIdx in 0 until 4) {
|
||||
setLighting(vIdx, 1.0f, brNeighbor(lightFace))
|
||||
}
|
||||
}
|
||||
|
||||
/** Smooth lighting, use *only* AO/light values on the given face (closest corner) */
|
||||
fun CustomLightingMeshConsumer.smoothWithFaceOverride(quad: QuadView, lightFace: Direction) {
|
||||
fillAoData(lightFace)
|
||||
forEachVertex(quad) { vIdx, x, y, z ->
|
||||
val cornerUndir = getCornerUndir(x, y, z)
|
||||
cornerDirFromUndir[lightFace.ordinal][cornerUndir]?.let { aoCorner ->
|
||||
setLighting(vIdx, aoFull[aoCorner], lightFull[aoCorner])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Smooth lighting scheme for 45-degree quads bisecting the box along 2 opposing face diagonals.
|
||||
*
|
||||
* Determine 2 *primary faces* based on the normal direction.
|
||||
* Take AO/light values *only* from the 2 primary faces *or* the UP direction,
|
||||
* based on which box corner is closest. Prefer taking values from the top face.
|
||||
*/
|
||||
fun CustomLightingMeshConsumer.smooth45PreferUp(quad: QuadView) {
|
||||
getAngles45(quad)?.let { normalFaces ->
|
||||
fillAoData(normalFaces.first)
|
||||
fillAoData(normalFaces.second)
|
||||
if (normalFaces.first != UP && normalFaces.second != UP) fillAoData(UP)
|
||||
forEachVertex(quad) { vIdx, x, y, z ->
|
||||
val isUp = y > 0.5f
|
||||
val cornerUndir = getCornerUndir(x, y, z)
|
||||
val preferredFace = if (isUp) UP else normalFaces.minBy { faceDistance(it, x, y, z) }
|
||||
val aoCorner = cornerDirFromUndir[preferredFace.ordinal][cornerUndir]!!
|
||||
setLighting(vIdx, aoFull[aoCorner], lightFull[aoCorner])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Flat lighting, use maximum neighbor brightness at the nearest box corner */
|
||||
fun CustomLightingMeshConsumer.flatMax(quad: QuadView) {
|
||||
forEachVertex(quad) { vIdx, x, y, z ->
|
||||
val maxBrightness = cornersUndir[getCornerUndir(x, y, z)].maxValueBy { brNeighbor(it) }
|
||||
setLighting(vIdx, 1.0f, maxBrightness)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If the quad normal approximately bisects 2 axes at a 45 degree angle,
|
||||
* and is approximately perpendicular to the third, returns the 2 directions
|
||||
* the quad normal points towards.
|
||||
* Returns null otherwise.
|
||||
*/
|
||||
fun getAngles45(quad: QuadView): Pair<Direction, Direction>? {
|
||||
val normal = quad.faceNormal()
|
||||
// one of the components must be close to zero
|
||||
val zeroAxis = when {
|
||||
abs(normal.x) < EPSILON -> Axis.X
|
||||
abs(normal.y) < EPSILON -> Axis.Y
|
||||
abs(normal.z) < EPSILON -> Axis.Z
|
||||
else -> return null
|
||||
}
|
||||
// the other two must be of similar magnitude
|
||||
val diff = when(zeroAxis) {
|
||||
Axis.X -> abs(abs(normal.y) - abs(normal.z))
|
||||
Axis.Y -> abs(abs(normal.x) - abs(normal.z))
|
||||
Axis.Z -> abs(abs(normal.x) - abs(normal.y))
|
||||
}
|
||||
if (diff > EPSILON) return null
|
||||
return when(zeroAxis) {
|
||||
Axis.X -> Pair(if (normal.y > 0.0f) UP else DOWN, if (normal.z > 0.0f) SOUTH else NORTH)
|
||||
Axis.Y -> Pair(if (normal.x > 0.0f) EAST else WEST, if (normal.z > 0.0f) SOUTH else NORTH)
|
||||
Axis.Z -> Pair(if (normal.x > 0.0f) EAST else WEST, if (normal.y > 0.0f) UP else DOWN)
|
||||
}
|
||||
}
|
||||
|
||||
fun faceDistance(face: Direction, x: Float, y: Float, z: Float) = when(face) {
|
||||
WEST -> x; EAST -> 1.0f - x
|
||||
DOWN -> y; UP -> 1.0f - y
|
||||
NORTH -> z; SOUTH -> 1.0f - z
|
||||
}
|
||||
|
||||
inline fun forEachVertex(quad: QuadView, func: (vIdx: Int, x: Float, y: Float, z: Float)->Unit) {
|
||||
for (vIdx in 0..3) {
|
||||
func(vIdx, quad.x(vIdx), quad.y(vIdx), quad.z(vIdx))
|
||||
}
|
||||
}
|
||||
78
src/main/kotlin/mods/betterfoliage/render/lighting/Indigo.kt
Normal file
78
src/main/kotlin/mods/betterfoliage/render/lighting/Indigo.kt
Normal file
@@ -0,0 +1,78 @@
|
||||
package mods.betterfoliage.render.lighting
|
||||
|
||||
import mods.betterfoliage.util.YarnHelper
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.reflectField
|
||||
import net.fabricmc.fabric.api.renderer.v1.mesh.Mesh
|
||||
import net.fabricmc.fabric.api.renderer.v1.model.FabricBakedModel
|
||||
import net.fabricmc.fabric.api.renderer.v1.render.RenderContext
|
||||
import net.fabricmc.fabric.impl.client.indigo.renderer.aocalc.AoCalculator
|
||||
import net.fabricmc.fabric.impl.client.indigo.renderer.render.*
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.RenderLayer
|
||||
import net.minecraft.client.render.VertexConsumer
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.world.BlockRenderView
|
||||
import java.util.*
|
||||
import java.util.function.Consumer
|
||||
import java.util.function.Supplier
|
||||
|
||||
val AbstractQuadRenderer_blockInfo2 = YarnHelper.requiredField<TerrainBlockRenderInfo>(
|
||||
"net.fabricmc.fabric.impl.client.indigo.renderer.render.AbstractQuadRenderer",
|
||||
"blockInfo", "Lnet/fabricmc/fabric/impl/client/indigo/renderer/render/TerrainBlockRenderInfo;"
|
||||
)
|
||||
val AbstractQuadRenderer_bufferFunc2 = YarnHelper.requiredField<java.util.function.Function<RenderLayer, VertexConsumer>>(
|
||||
"net.fabricmc.fabric.impl.client.indigo.renderer.render.AbstractQuadRenderer",
|
||||
"bufferFunc", "Ljava/util/function/Function;"
|
||||
)
|
||||
val AbstractQuadRenderer_aoCalc = YarnHelper.requiredField<AoCalculator>(
|
||||
"net.fabricmc.fabric.impl.client.indigo.renderer.render.AbstractQuadRenderer",
|
||||
"aoCalc", "Lnet/fabricmc/fabric/impl/client/indigo/renderer/aocalc/AoCalculator;"
|
||||
)
|
||||
val AbstractQuadRenderer_transform = YarnHelper.requiredField<RenderContext.QuadTransform>(
|
||||
"net.fabricmc.fabric.impl.client.indigo.renderer.render.AbstractQuadRenderer",
|
||||
"transform", "Lnet/fabricmc/fabric/api/renderer/v1/render/RenderContext\$QuadTransform;"
|
||||
)
|
||||
|
||||
val MODIFIED_CONSUMER_POOL = ThreadLocal<ModifiedTerrainMeshConsumer>()
|
||||
|
||||
fun AbstractMeshConsumer.modified() = MODIFIED_CONSUMER_POOL.get() ?: let {
|
||||
ModifiedTerrainMeshConsumer(this)
|
||||
}.apply { MODIFIED_CONSUMER_POOL.set(this) }
|
||||
|
||||
/**
|
||||
* Render the given model at the given position.
|
||||
* Mutates the state of the [RenderContext]!!
|
||||
*/
|
||||
fun RenderContext.renderMasquerade(model: BakedModel, blockView: BlockRenderView, state: BlockState, pos: BlockPos, randomSupplier: Supplier<Random>, context: RenderContext) = when(this) {
|
||||
is TerrainRenderContext -> {
|
||||
val blockInfo = meshConsumer()[AbstractQuadRenderer_blockInfo2]!!
|
||||
blockInfo.prepareForBlock(state, pos, model.useAmbientOcclusion())
|
||||
(model as FabricBakedModel).emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
else -> {
|
||||
(model as FabricBakedModel).emitBlockQuads(blockView, state, pos, randomSupplier, context)
|
||||
}
|
||||
}
|
||||
|
||||
/** Execute the provided block with a mesh consumer using the given custom lighting. */
|
||||
fun RenderContext.withLighting(lighter: CustomLighting, func: (Consumer<Mesh>)->Unit) = when(this) {
|
||||
is TerrainRenderContext -> {
|
||||
val consumer = (meshConsumer() as AbstractMeshConsumer).modified()
|
||||
consumer.clearLighting()
|
||||
consumer.lighter = lighter
|
||||
func(consumer)
|
||||
consumer.lighter = null
|
||||
}
|
||||
else -> func(meshConsumer())
|
||||
}
|
||||
|
||||
/** Get the [BufferBuilder] responsible for a given [BlockRenderLayer] */
|
||||
fun RenderContext.getBufferBuilder(layer: RenderLayer) = when(this) {
|
||||
is TerrainRenderContext -> {
|
||||
val bufferFunc = meshConsumer()[AbstractQuadRenderer_bufferFunc2]!!
|
||||
bufferFunc.apply(layer)
|
||||
}
|
||||
else -> null
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package mods.betterfoliage.render.particle
|
||||
|
||||
import mods.betterfoliage.util.Double3
|
||||
import net.minecraft.client.MinecraftClient
|
||||
import net.minecraft.client.particle.SpriteBillboardParticle
|
||||
import net.minecraft.client.render.Camera
|
||||
import net.minecraft.client.render.VertexConsumer
|
||||
import net.minecraft.client.texture.Sprite
|
||||
import net.minecraft.client.util.math.Vector3f
|
||||
import net.minecraft.client.world.ClientWorld
|
||||
import net.minecraft.util.math.MathHelper
|
||||
import net.minecraft.world.World
|
||||
|
||||
abstract class AbstractParticle(world: ClientWorld, x: Double, y: Double, z: Double) : SpriteBillboardParticle(world, x, y, z) {
|
||||
|
||||
companion object {
|
||||
// @JvmStatic val sin = Array(64) { idx -> Math.sin(PI2 / 64.0 * idx) }
|
||||
// @JvmStatic val cos = Array(64) { idx -> Math.cos(PI2 / 64.0 * idx) }
|
||||
}
|
||||
|
||||
val billboardRot = Pair(Double3.zero, Double3.zero)
|
||||
val currentPos = Double3.zero
|
||||
val prevPos = Double3.zero
|
||||
val velocity = Double3.zero
|
||||
|
||||
override fun tick() {
|
||||
super.tick()
|
||||
currentPos.setTo(x, y, z)
|
||||
prevPos.setTo(prevPosX, prevPosY, prevPosZ)
|
||||
velocity.setTo(velocityX, velocityY, velocityZ)
|
||||
update()
|
||||
x = currentPos.x; y = currentPos.y; z = currentPos.z;
|
||||
velocityX = velocity.x; velocityY = velocity.y; velocityZ = velocity.z;
|
||||
}
|
||||
|
||||
/** Update particle on world tick. */
|
||||
abstract fun update()
|
||||
|
||||
/** True if the particle is renderable. */
|
||||
abstract val isValid: Boolean
|
||||
|
||||
/** Add the particle to the effect renderer if it is valid. */
|
||||
fun addIfValid() { if (isValid) MinecraftClient.getInstance().particleManager.addParticle(this) }
|
||||
|
||||
override fun buildGeometry(vertexConsumer: VertexConsumer, camera: Camera, tickDelta: Float) {
|
||||
renderParticleQuad(vertexConsumer, camera, tickDelta)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a particle quad.
|
||||
*
|
||||
* @param[tessellator] the [Tessellator] instance to use
|
||||
* @param[tickDelta] partial tick time
|
||||
* @param[currentPos] render position
|
||||
* @param[prevPos] previous tick position for interpolation
|
||||
* @param[size] particle size
|
||||
* @param[currentAngle] viewpoint-dependent particle rotation (64 steps)
|
||||
* @param[sprite] particle texture
|
||||
* @param[isMirrored] mirror particle texture along V-axis
|
||||
* @param[alpha] aplha blending
|
||||
*/
|
||||
fun renderParticleQuad(vertexConsumer: VertexConsumer,
|
||||
camera: Camera,
|
||||
tickDelta: Float,
|
||||
currentPos: Double3 = this.currentPos,
|
||||
prevPos: Double3 = this.prevPos,
|
||||
size: Double = scale.toDouble(),
|
||||
currentAngle: Float = this.angle,
|
||||
prevAngle: Float = this.prevAngle,
|
||||
sprite: Sprite = this.sprite,
|
||||
alpha: Float = this.colorAlpha) {
|
||||
|
||||
val center = Double3.lerp(tickDelta.toDouble(), prevPos, currentPos)
|
||||
val angle = MathHelper.lerp(tickDelta, prevAngle, currentAngle)
|
||||
val rotation = camera.rotation.copy().apply { hamiltonProduct(Vector3f.POSITIVE_Z.getRadialQuaternion(angle)) }
|
||||
val lightmapCoord = getColorMultiplier(tickDelta)
|
||||
|
||||
val coords = arrayOf(
|
||||
Double3(-1.0, -1.0, 0.0),
|
||||
Double3(-1.0, 1.0, 0.0),
|
||||
Double3(1.0, 1.0, 0.0),
|
||||
Double3(1.0, -1.0, 0.0)
|
||||
).map { it.rotate(rotation).mul(size).add(center).sub(camera.pos.x, camera.pos.y, camera.pos.z) }
|
||||
|
||||
fun renderVertex(vertex: Double3, u: Float, v: Float) = vertexConsumer
|
||||
.vertex(vertex.x, vertex.y, vertex.z).texture(u, v)
|
||||
.color(colorRed, colorGreen, colorBlue, alpha).light(lightmapCoord)
|
||||
.next()
|
||||
|
||||
renderVertex(coords[0], sprite.maxU, sprite.maxV)
|
||||
renderVertex(coords[1], sprite.maxU, sprite.minV)
|
||||
renderVertex(coords[2], sprite.minU, sprite.minV)
|
||||
renderVertex(coords[3], sprite.minU, sprite.maxV)
|
||||
}
|
||||
|
||||
fun setColor(color: Int) {
|
||||
colorBlue = (color and 255) / 256.0f
|
||||
colorGreen = ((color shr 8) and 255) / 256.0f
|
||||
colorRed = ((color shr 16) and 255) / 256.0f
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package mods.betterfoliage.render.particle
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.ClientWorldLoadCallback
|
||||
import mods.betterfoliage.render.block.vanilla.LeafParticleKey
|
||||
import mods.betterfoliage.util.Double3
|
||||
import mods.betterfoliage.util.PI2
|
||||
import mods.betterfoliage.util.minmax
|
||||
import mods.betterfoliage.util.randomB
|
||||
import mods.betterfoliage.util.randomD
|
||||
import mods.betterfoliage.util.randomF
|
||||
import mods.betterfoliage.util.randomI
|
||||
import net.fabricmc.fabric.api.event.world.WorldTickCallback
|
||||
import net.minecraft.client.particle.ParticleTextureSheet
|
||||
import net.minecraft.client.world.ClientWorld
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.MathHelper
|
||||
import net.minecraft.world.World
|
||||
import java.util.Random
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
class FallingLeafParticle(
|
||||
world: ClientWorld, pos: BlockPos, leaf: LeafParticleKey, blockColor: Int, random: Random
|
||||
) : AbstractParticle(
|
||||
world, pos.x.toDouble() + 0.5, pos.y.toDouble(), pos.z.toDouble() + 0.5
|
||||
) {
|
||||
|
||||
companion object {
|
||||
@JvmStatic val biomeBrightnessMultiplier = 0.5f
|
||||
}
|
||||
|
||||
var rotationSpeed = random.randomF(min = PI2 / 80.0, max = PI2 / 50.0)
|
||||
val isMirrored = randomB()
|
||||
var wasCollided = false
|
||||
|
||||
init {
|
||||
angle = random.randomF(max = PI2)
|
||||
prevAngle = angle - rotationSpeed
|
||||
|
||||
maxAge = MathHelper.floor(randomD(0.6, 1.0) * BetterFoliage.config.fallingLeaves.lifetime * 20.0)
|
||||
velocityY = -BetterFoliage.config.fallingLeaves.speed
|
||||
|
||||
scale = BetterFoliage.config.fallingLeaves.size.toFloat() * 0.1f
|
||||
|
||||
val state = world.getBlockState(pos)
|
||||
|
||||
setColor(leaf.overrideColor?.asInt ?: blockColor)
|
||||
sprite = LeafParticleRegistry[leaf.leafType][randomI(max = 1024)]
|
||||
}
|
||||
|
||||
override val isValid: Boolean get() = (sprite != null)
|
||||
|
||||
override fun update() {
|
||||
if (randomF() > 0.95f) rotationSpeed = -rotationSpeed
|
||||
if (age > maxAge - 20) colorAlpha = 0.05f * (maxAge - age)
|
||||
|
||||
if (onGround || wasCollided) {
|
||||
velocity.setTo(0.0, 0.0, 0.0)
|
||||
prevAngle = angle
|
||||
if (!wasCollided) {
|
||||
age = age.coerceAtLeast(maxAge - 20)
|
||||
wasCollided = true
|
||||
}
|
||||
} else {
|
||||
val cosRotation = cos(angle).toDouble(); val sinRotation = sin(angle).toDouble()
|
||||
velocity.setTo(cosRotation, 0.0, sinRotation).mul(BetterFoliage.config.fallingLeaves.perturb)
|
||||
.add(LeafWindTracker.current).add(0.0, -1.0, 0.0).mul(BetterFoliage.config.fallingLeaves.speed)
|
||||
prevAngle = angle
|
||||
angle += rotationSpeed
|
||||
}
|
||||
}
|
||||
|
||||
fun setParticleColor(overrideColor: Int?, blockColor: Int) {
|
||||
val color = overrideColor ?: blockColor
|
||||
setColor(color)
|
||||
}
|
||||
|
||||
override fun getType() =
|
||||
if (BetterFoliage.config.fallingLeaves.opacityHack) ParticleTextureSheet.PARTICLE_SHEET_OPAQUE
|
||||
else ParticleTextureSheet.PARTICLE_SHEET_TRANSLUCENT
|
||||
}
|
||||
|
||||
object LeafWindTracker : WorldTickCallback, ClientWorldLoadCallback {
|
||||
val random = Random()
|
||||
val target = Double3.zero
|
||||
val current = Double3.zero
|
||||
var nextChange: Long = 0
|
||||
|
||||
fun changeWindTarget(world: World) {
|
||||
nextChange = world.time + 120 + random.nextInt(80)
|
||||
val direction = PI2 * random.nextDouble()
|
||||
val speed = abs(random.nextGaussian()) * BetterFoliage.config.fallingLeaves.windStrength +
|
||||
(if (!world.isRaining) 0.0 else abs(random.nextGaussian()) * BetterFoliage.config.fallingLeaves.stormStrength)
|
||||
target.setTo(cos(direction) * speed, 0.0, sin(direction) * speed)
|
||||
}
|
||||
|
||||
override fun tick(world: World) {
|
||||
if (world.isClient) {
|
||||
// change target wind speed
|
||||
if (world.time >= nextChange) changeWindTarget(world)
|
||||
|
||||
// change current wind speed
|
||||
val changeRate = if (world.isRaining) 0.015 else 0.005
|
||||
current.add(
|
||||
(target.x - current.x).minmax(-changeRate, changeRate),
|
||||
0.0,
|
||||
(target.z - current.z).minmax(-changeRate, changeRate)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun loadWorld(world: ClientWorld) {
|
||||
changeWindTarget(world)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
package mods.betterfoliage.render.particle
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.model.FixedSpriteSet
|
||||
import mods.betterfoliage.model.SpriteSet
|
||||
import mods.betterfoliage.resource.VeryEarlyReloadListener
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import mods.betterfoliage.util.get
|
||||
import mods.betterfoliage.util.getLines
|
||||
import mods.betterfoliage.util.resourceManager
|
||||
import mods.betterfoliage.util.stripStart
|
||||
import net.fabricmc.fabric.api.event.client.ClientSpriteRegistryCallback
|
||||
import net.minecraft.client.texture.MissingSprite
|
||||
import net.minecraft.client.texture.SpriteAtlasTexture
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.util.Identifier
|
||||
import org.apache.logging.log4j.Level
|
||||
import kotlin.collections.MutableList
|
||||
import kotlin.collections.distinct
|
||||
import kotlin.collections.filter
|
||||
import kotlin.collections.firstOrNull
|
||||
import kotlin.collections.forEach
|
||||
import kotlin.collections.isNotEmpty
|
||||
import kotlin.collections.joinToString
|
||||
import kotlin.collections.listOf
|
||||
import kotlin.collections.map
|
||||
import kotlin.collections.mutableListOf
|
||||
import kotlin.collections.mutableMapOf
|
||||
import kotlin.collections.plus
|
||||
import kotlin.collections.set
|
||||
|
||||
object LeafParticleRegistry : HasLogger(), ClientSpriteRegistryCallback, VeryEarlyReloadListener {
|
||||
val typeMappings = TextureMatcher()
|
||||
val allTypes get() = (typeMappings.mappings.map { it.type } + "default").distinct()
|
||||
|
||||
val spriteSets = mutableMapOf<String, SpriteSet>()
|
||||
|
||||
override fun getFabricId() = Identifier(BetterFoliage.MOD_ID, "leaf-particles")
|
||||
|
||||
override fun onReloadStarted(resourceManager: ResourceManager) {
|
||||
typeMappings.loadMappings(Identifier(BetterFoliage.MOD_ID, "leaf_texture_mappings.cfg"))
|
||||
detailLogger.log(Level.INFO, "Loaded leaf particle mappings, types = [${allTypes.joinToString(", ")}]")
|
||||
}
|
||||
|
||||
override fun registerSprites(atlasTexture: SpriteAtlasTexture, registry: ClientSpriteRegistryCallback.Registry) {
|
||||
spriteSets.clear()
|
||||
allTypes.forEach { leafType ->
|
||||
val validIds = (0 until 16).map { idx -> Identifier(BetterFoliage.MOD_ID, "particle/falling_leaf_${leafType}_$idx") }
|
||||
.filter { resourceManager.containsResource(Atlas.PARTICLES.file(it)) }
|
||||
validIds.forEach { registry.register(it) }
|
||||
}
|
||||
}
|
||||
|
||||
operator fun get(leafType: String): SpriteSet {
|
||||
spriteSets[leafType]?.let { return it }
|
||||
|
||||
val sprites = (0 until 16)
|
||||
.map { idx -> Identifier(BetterFoliage.MOD_ID, "particle/falling_leaf_${leafType}_$idx") }
|
||||
.map { Atlas.PARTICLES[it] }
|
||||
.filter { it !is MissingSprite }
|
||||
|
||||
detailLogger.log(Level.INFO, "Leaf particle type [$leafType], ${sprites.size} sprites in atlas")
|
||||
if (sprites.isNotEmpty()) return FixedSpriteSet(sprites).apply { spriteSets[leafType] = this }
|
||||
|
||||
return if (leafType == "default")
|
||||
FixedSpriteSet(listOf(Atlas.PARTICLES[MissingSprite.getMissingSpriteId()])).apply { spriteSets[leafType] = this }
|
||||
else
|
||||
get("default").apply { spriteSets[leafType] = this }
|
||||
}
|
||||
|
||||
init {
|
||||
ClientSpriteRegistryCallback.event(SpriteAtlasTexture.PARTICLE_ATLAS_TEXTURE).register(this)
|
||||
}
|
||||
}
|
||||
|
||||
class TextureMatcher {
|
||||
|
||||
data class Mapping(val domain: String?, val path: String, val type: String) {
|
||||
fun matches(iconLocation: Identifier): Boolean {
|
||||
return (domain == null || domain == iconLocation.namespace) &&
|
||||
iconLocation.path.stripStart("blocks/").contains(path, ignoreCase = true)
|
||||
}
|
||||
}
|
||||
|
||||
val mappings: MutableList<Mapping> = mutableListOf()
|
||||
|
||||
fun getType(resource: Identifier) = mappings.filter { it.matches(resource) }.map { it.type }.firstOrNull()
|
||||
fun getType(iconName: String) = Identifier(iconName).let { getType(it) }
|
||||
|
||||
fun loadMappings(mappingLocation: Identifier) {
|
||||
mappings.clear()
|
||||
resourceManager[mappingLocation]?.getLines()?.let { lines ->
|
||||
lines.filter { !it.startsWith("//") }.filter { it.isNotEmpty() }.forEach { line ->
|
||||
val line2 = line.trim().split('=')
|
||||
if (line2.size == 2) {
|
||||
val mapping = line2[0].trim().split(':')
|
||||
if (mapping.size == 1) mappings.add(Mapping(null, mapping[0].trim(), line2[1].trim()))
|
||||
else if (mapping.size == 2) mappings.add(Mapping(mapping[0].trim(), mapping[1].trim(), line2[1].trim()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package mods.betterfoliage.render.particle
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.model.SpriteDelegate
|
||||
import mods.betterfoliage.model.SpriteSetDelegate
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.Double3
|
||||
import mods.betterfoliage.util.PI2
|
||||
import mods.betterfoliage.util.forEachPairIndexed
|
||||
import mods.betterfoliage.util.randomD
|
||||
import mods.betterfoliage.util.randomI
|
||||
import net.minecraft.client.particle.ParticleTextureSheet
|
||||
import net.minecraft.client.render.Camera
|
||||
import net.minecraft.client.render.VertexConsumer
|
||||
import net.minecraft.client.world.ClientWorld
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.math.BlockPos
|
||||
import net.minecraft.util.math.MathHelper
|
||||
import java.util.Deque
|
||||
import java.util.LinkedList
|
||||
import kotlin.math.cos
|
||||
import kotlin.math.sin
|
||||
|
||||
class RisingSoulParticle(
|
||||
world: ClientWorld, pos: BlockPos
|
||||
) : AbstractParticle(
|
||||
world, pos.x.toDouble() + 0.5, pos.y.toDouble() + 1.0, pos.z.toDouble() + 0.5
|
||||
) {
|
||||
|
||||
val particleTrail: Deque<Double3> = LinkedList()
|
||||
val initialPhase = randomD(max = PI2)
|
||||
|
||||
init {
|
||||
velocityY = 0.1
|
||||
gravityStrength = 0.0f
|
||||
sprite = headIcons[randomI(max = 1024)]
|
||||
maxAge = MathHelper.floor((0.6 + 0.4 * randomD()) * BetterFoliage.config.risingSoul.lifetime * 20.0)
|
||||
}
|
||||
|
||||
override val isValid: Boolean get() = true
|
||||
|
||||
override fun update() {
|
||||
val phase = initialPhase + (age.toDouble() * PI2 / 64.0)
|
||||
val cosPhase = cos(phase);
|
||||
val sinPhase = sin(phase)
|
||||
velocity.setTo(BetterFoliage.config.risingSoul.perturb.let { Double3(cosPhase * it, 0.1, sinPhase * it) })
|
||||
|
||||
particleTrail.addFirst(currentPos.copy())
|
||||
while (particleTrail.size > BetterFoliage.config.risingSoul.trailLength) particleTrail.removeLast()
|
||||
|
||||
if (!BetterFoliage.config.enabled) markDead()
|
||||
}
|
||||
|
||||
override fun buildGeometry(vertexConsumer: VertexConsumer, camera: Camera, tickDelta: Float) {
|
||||
var alpha = BetterFoliage.config.risingSoul.opacity.toFloat()
|
||||
if (age > maxAge - 40) alpha *= (maxAge - age) / 40.0f
|
||||
|
||||
renderParticleQuad(
|
||||
vertexConsumer, camera, tickDelta,
|
||||
size = BetterFoliage.config.risingSoul.headSize * 0.25,
|
||||
alpha = alpha
|
||||
)
|
||||
|
||||
var scale = BetterFoliage.config.risingSoul.trailSize * 0.25
|
||||
particleTrail.forEachPairIndexed { idx, current, previous ->
|
||||
scale *= BetterFoliage.config.risingSoul.sizeDecay
|
||||
alpha *= BetterFoliage.config.risingSoul.opacityDecay.toFloat()
|
||||
if (idx % BetterFoliage.config.risingSoul.trailDensity == 0)
|
||||
renderParticleQuad(
|
||||
vertexConsumer, camera, tickDelta,
|
||||
currentPos = current,
|
||||
prevPos = previous,
|
||||
size = scale,
|
||||
alpha = alpha,
|
||||
sprite = trackIcon
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getType() = ParticleTextureSheet.PARTICLE_SHEET_TRANSLUCENT
|
||||
|
||||
companion object {
|
||||
val headIcons by SpriteSetDelegate(Atlas.PARTICLES) { idx ->
|
||||
Identifier(BetterFoliage.MOD_ID, "particle/rising_soul_$idx")
|
||||
}
|
||||
val trackIcon by SpriteDelegate(Atlas.PARTICLES) { Identifier(BetterFoliage.MOD_ID, "particle/soul_track") }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package mods.betterfoliage.resource
|
||||
|
||||
import net.fabricmc.fabric.api.resource.IdentifiableResourceReloadListener
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.resource.ResourceReloadListener
|
||||
import net.minecraft.util.profiler.Profiler
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import java.util.concurrent.Executor
|
||||
|
||||
/**
|
||||
* Catch resource reload extremely early, before any of the reloaders
|
||||
* have started working.
|
||||
*/
|
||||
interface VeryEarlyReloadListener : ResourceReloadListener, IdentifiableResourceReloadListener {
|
||||
override fun reload(
|
||||
synchronizer: ResourceReloadListener.Synchronizer,
|
||||
resourceManager: ResourceManager,
|
||||
preparationsProfiler: Profiler,
|
||||
reloadProfiler: Profiler,
|
||||
backgroundExecutor: Executor,
|
||||
gameExecutor: Executor
|
||||
): CompletableFuture<Void> {
|
||||
onReloadStarted(resourceManager)
|
||||
return synchronizer.whenPrepared(null)
|
||||
}
|
||||
|
||||
fun onReloadStarted(resourceManager: ResourceManager) {}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package mods.betterfoliage.resource.discovery
|
||||
|
||||
import mods.betterfoliage.BetterFoliage
|
||||
import mods.betterfoliage.BlockModelsReloadCallback
|
||||
import mods.betterfoliage.ModelLoadingCallback
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import mods.betterfoliage.util.Invalidator
|
||||
import net.fabricmc.fabric.api.event.client.ClientSpriteRegistryCallback
|
||||
import net.minecraft.block.BlockState
|
||||
import net.minecraft.client.render.block.BlockModels
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.ModelBakeSettings
|
||||
import net.minecraft.client.render.model.ModelLoader
|
||||
import net.minecraft.client.render.model.UnbakedModel
|
||||
import net.minecraft.client.texture.Sprite
|
||||
import net.minecraft.client.texture.SpriteAtlasTexture
|
||||
import net.minecraft.client.util.SpriteIdentifier
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.util.Identifier
|
||||
import org.apache.logging.log4j.Level.INFO
|
||||
import org.apache.logging.log4j.Level.WARN
|
||||
import org.apache.logging.log4j.Logger
|
||||
import java.lang.ref.WeakReference
|
||||
import java.util.function.Function
|
||||
|
||||
data class ModelDiscoveryContext(
|
||||
val bakery: ModelLoader,
|
||||
val blockState: BlockState,
|
||||
val modelLocation: Identifier,
|
||||
val sprites: MutableSet<Identifier>,
|
||||
val replacements: MutableMap<Identifier, ModelBakingKey>,
|
||||
val logger: Logger
|
||||
) {
|
||||
fun getUnbaked(location: Identifier = modelLocation) = bakery.getOrLoadModel(location)
|
||||
fun addReplacement(key: ModelBakingKey, addToStateKeys: Boolean = true) {
|
||||
replacements[modelLocation] = key
|
||||
if (addToStateKeys) BetterFoliage.blockTypes.stateKeys[blockState] = key
|
||||
logger.log(INFO, "Adding model replacement $modelLocation -> $key")
|
||||
}
|
||||
}
|
||||
|
||||
interface ModelDiscovery {
|
||||
fun onModelsLoaded(
|
||||
bakery: ModelLoader,
|
||||
sprites: MutableSet<Identifier>,
|
||||
replacements: MutableMap<Identifier, ModelBakingKey>
|
||||
)
|
||||
}
|
||||
|
||||
data class ModelBakingContext(
|
||||
val bakery: ModelLoader,
|
||||
val spriteGetter: Function<SpriteIdentifier, Sprite>,
|
||||
val location: Identifier,
|
||||
val transform: ModelBakeSettings,
|
||||
val logger: Logger
|
||||
) {
|
||||
fun getUnbaked() = bakery.getOrLoadModel(location)
|
||||
fun getBaked() = bakery.bake(location, transform)
|
||||
}
|
||||
|
||||
interface ModelBakingKey {
|
||||
fun bake(ctx: ModelBakingContext): BakedModel? =
|
||||
ctx.getUnbaked().bake(ctx.bakery, ctx.spriteGetter, ctx.transform, ctx.location)
|
||||
}
|
||||
|
||||
object BakeWrapperManager : HasLogger(), Invalidator, ModelLoadingCallback, ClientSpriteRegistryCallback, BlockModelsReloadCallback {
|
||||
init {
|
||||
ModelLoadingCallback.EVENT.register(this)
|
||||
ClientSpriteRegistryCallback.event(SpriteAtlasTexture.BLOCK_ATLAS_TEXTURE).register(this)
|
||||
}
|
||||
val discoverers = mutableListOf<ModelDiscovery>()
|
||||
override val callbacks = mutableListOf<WeakReference<()->Unit>>()
|
||||
|
||||
private val replacements = mutableMapOf<Identifier, ModelBakingKey>()
|
||||
private val sprites = mutableSetOf<Identifier>()
|
||||
|
||||
override fun beginLoadModels(loader: ModelLoader, manager: ResourceManager) {
|
||||
val startTime = System.currentTimeMillis()
|
||||
replacements.clear()
|
||||
sprites.clear()
|
||||
invalidate()
|
||||
BetterFoliage.blockTypes = BlockTypeCache()
|
||||
|
||||
logger.log(INFO, "starting model discovery (${discoverers.size} listeners)")
|
||||
discoverers.forEach { listener ->
|
||||
val replacementsLocal = mutableMapOf<Identifier, ModelBakingKey>()
|
||||
listener.onModelsLoaded(loader, sprites, replacements)
|
||||
}
|
||||
|
||||
val elapsed = System.currentTimeMillis() - startTime
|
||||
logger.log(INFO, "finished model discovery in $elapsed ms, ${replacements.size} top-level replacements")
|
||||
}
|
||||
|
||||
override fun registerSprites(atlas: SpriteAtlasTexture, registry: ClientSpriteRegistryCallback.Registry) {
|
||||
logger.log(INFO, "Adding ${sprites.size} sprites to block atlas")
|
||||
sprites.forEach { registry.register(it) }
|
||||
sprites.clear()
|
||||
}
|
||||
|
||||
override fun reloadBlockModels(blockModels: BlockModels) {
|
||||
replacements.clear()
|
||||
}
|
||||
|
||||
fun onBake(
|
||||
unbaked: UnbakedModel,
|
||||
bakery: ModelLoader,
|
||||
spriteGetter: Function<SpriteIdentifier, Sprite>,
|
||||
transform: ModelBakeSettings,
|
||||
location: Identifier
|
||||
): BakedModel? {
|
||||
val ctx = ModelBakingContext(bakery, spriteGetter, location, transform, detailLogger)
|
||||
// bake replacement if available
|
||||
replacements[location]?.let { replacement ->
|
||||
detailLogger.log(INFO, "Baking replacement for [${unbaked::class.java.simpleName}] $location -> $replacement")
|
||||
try {
|
||||
return replacement.bake(ctx)
|
||||
} catch (e: Exception) {
|
||||
detailLogger.log(WARN, "Error while baking $replacement", e)
|
||||
logger.log(WARN, "Error while baking $replacement", e)
|
||||
}
|
||||
}
|
||||
return unbaked.bake(bakery, spriteGetter, transform, location)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package mods.betterfoliage.resource.discovery
|
||||
|
||||
import net.minecraft.block.BlockState
|
||||
|
||||
class BlockTypeCache {
|
||||
val leaf = mutableSetOf<BlockState>()
|
||||
val grass = mutableSetOf<BlockState>()
|
||||
val dirt = mutableSetOf<BlockState>()
|
||||
|
||||
val stateKeys = mutableMapOf<BlockState, ModelBakingKey>()
|
||||
|
||||
inline fun <reified T> getTyped(state: BlockState) = stateKeys[state] as? T
|
||||
inline fun <reified T> hasTyped(state: BlockState) = stateKeys[state] is T
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package mods.betterfoliage.resource.discovery
|
||||
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import mods.betterfoliage.util.getLines
|
||||
import mods.betterfoliage.util.INTERMEDIARY
|
||||
import mods.betterfoliage.util.getJavaClass
|
||||
import net.fabricmc.loader.api.FabricLoader
|
||||
import net.minecraft.block.Block
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.util.Identifier
|
||||
import org.apache.logging.log4j.Level
|
||||
import org.apache.logging.log4j.Level.INFO
|
||||
import org.apache.logging.log4j.Logger
|
||||
|
||||
interface IBlockMatcher {
|
||||
fun matchesClass(block: Block): Boolean
|
||||
fun matchingClass(block: Block): Class<*>?
|
||||
}
|
||||
|
||||
class SimpleBlockMatcher(vararg val classes: Class<*>) : IBlockMatcher {
|
||||
override fun matchesClass(block: Block) = matchingClass(block) != null
|
||||
|
||||
override fun matchingClass(block: Block): Class<*>? {
|
||||
val blockClass = block.javaClass
|
||||
classes.forEach { if (it.isAssignableFrom(blockClass)) return it }
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
class ConfigurableBlockMatcher(val location: Identifier) : HasLogger(), IBlockMatcher {
|
||||
|
||||
val blackList = mutableListOf<Class<*>>()
|
||||
val whiteList = mutableListOf<Class<*>>()
|
||||
|
||||
override fun matchesClass(block: Block): Boolean {
|
||||
val blockClass = block.javaClass
|
||||
blackList.forEach { if (it.isAssignableFrom(blockClass)) return false }
|
||||
whiteList.forEach { if (it.isAssignableFrom(blockClass)) return true }
|
||||
return false
|
||||
}
|
||||
|
||||
override fun matchingClass(block: Block): Class<*>? {
|
||||
val blockClass = block.javaClass
|
||||
blackList.forEach { if (it.isAssignableFrom(blockClass)) return null }
|
||||
whiteList.forEach { if (it.isAssignableFrom(blockClass)) return it }
|
||||
return null
|
||||
}
|
||||
|
||||
fun readDefaults(manager: ResourceManager) {
|
||||
blackList.clear()
|
||||
whiteList.clear()
|
||||
manager.getAllResources(location).forEach { resource ->
|
||||
detailLogger.log(INFO, "Reading class list $location from pack ${resource.resourcePackName}")
|
||||
resource.getLines().map{ it.trim() }.filter { !it.startsWith("//") && it.isNotEmpty() }.forEach { line ->
|
||||
val name = if (line.startsWith("-")) line.substring(1) else line
|
||||
val mappedName = FabricLoader.getInstance().mappingResolver.mapClassName(INTERMEDIARY, name)
|
||||
if (name != mappedName) logger.debug(" found yarn mapping for class: $name -> $mappedName")
|
||||
val klass = getJavaClass(mappedName)
|
||||
|
||||
val list = if (line.startsWith("-")) "blacklist" to blackList else "whitelist" to whiteList
|
||||
|
||||
if (klass != null) {
|
||||
logger.debug(" ${list.first} class $name found")
|
||||
list.second.add(klass)
|
||||
} else {
|
||||
logger.debug(" ${list.first} class $name not found")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data class ModelTextureList(val modelLocation: Identifier, val textureNames: List<String>) {
|
||||
constructor(vararg args: String) : this(Identifier(args[0]), listOf(*args).drop(1))
|
||||
}
|
||||
|
||||
class ModelTextureListConfiguration(val location: Identifier) : HasLogger() {
|
||||
val modelList = mutableListOf<ModelTextureList>()
|
||||
fun readDefaults(manager: ResourceManager) {
|
||||
manager.getAllResources(location).forEach { resource ->
|
||||
detailLogger.log(INFO, "Reading model configuration $location from pack ${resource.resourcePackName}")
|
||||
resource.getLines().map{ it.trim() }.filter { !it.startsWith("//") && it.isNotEmpty() }.forEach { line ->
|
||||
val elements = line.split(",")
|
||||
modelList.add(ModelTextureList(Identifier(elements.first()), elements.drop(1)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package mods.betterfoliage.resource.discovery
|
||||
|
||||
import com.google.common.base.Joiner
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import mods.betterfoliage.util.YarnHelper
|
||||
import mods.betterfoliage.util.get
|
||||
import net.minecraft.block.Block
|
||||
import net.minecraft.client.render.block.BlockModels
|
||||
import net.minecraft.client.render.model.ModelLoader
|
||||
import net.minecraft.client.render.model.json.JsonUnbakedModel
|
||||
import net.minecraft.client.render.model.json.WeightedUnbakedModel
|
||||
import net.minecraft.client.texture.MissingSprite
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.registry.Registry
|
||||
import org.apache.logging.log4j.Level
|
||||
|
||||
abstract class AbstractModelDiscovery : HasLogger(), ModelDiscovery {
|
||||
override fun onModelsLoaded(
|
||||
bakery: ModelLoader,
|
||||
sprites: MutableSet<Identifier>,
|
||||
replacements: MutableMap<Identifier, ModelBakingKey>
|
||||
) {
|
||||
(Registry.BLOCK as Iterable<Block>)
|
||||
.flatMap { block -> block.stateManager.states }
|
||||
.forEach { state ->
|
||||
val location = BlockModels.getModelId(state)
|
||||
val ctx = ModelDiscoveryContext(bakery, state, location, sprites, replacements, detailLogger)
|
||||
try {
|
||||
processModel(ctx)
|
||||
} catch (e: Exception) {
|
||||
logger.log(Level.WARN, "Discovery error in $location", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
open fun processModel(ctx: ModelDiscoveryContext) {
|
||||
val model = ctx.getUnbaked()
|
||||
|
||||
// built-in support for container models
|
||||
if (model is WeightedUnbakedModel) {
|
||||
// per-location replacements need to be scoped to the variant list, as replacement models
|
||||
// may need information from the BlockState which is not available at baking time
|
||||
val scopedReplacements = mutableMapOf<Identifier, ModelBakingKey>()
|
||||
model.variants.forEach { variant ->
|
||||
processModel(ctx.copy(modelLocation = variant.location, replacements = scopedReplacements))
|
||||
}
|
||||
if (scopedReplacements.isNotEmpty()) {
|
||||
ctx.addReplacement(WeightedUnbakedKey(scopedReplacements), addToStateKeys = false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abstract class ConfigurableModelDiscovery : AbstractModelDiscovery() {
|
||||
abstract val matchClasses: IBlockMatcher
|
||||
abstract val modelTextures: List<ModelTextureList>
|
||||
|
||||
abstract fun processModel(
|
||||
ctx: ModelDiscoveryContext,
|
||||
textureMatch: List<Identifier>
|
||||
)
|
||||
|
||||
override fun processModel(ctx: ModelDiscoveryContext) {
|
||||
val model = ctx.getUnbaked()
|
||||
if (model is JsonUnbakedModel) {
|
||||
val matchClass = matchClasses.matchingClass(ctx.blockState.block) ?: return
|
||||
|
||||
detailLogger.log(Level.INFO, "block state ${ctx.blockState}")
|
||||
detailLogger.log(Level.INFO, " model ${ctx.modelLocation}")
|
||||
detailLogger.log(Level.INFO, " class ${ctx.blockState.block.javaClass.name} matches ${matchClass.name}")
|
||||
|
||||
modelTextures
|
||||
.filter { matcher -> ctx.bakery.modelDerivesFrom(model, ctx.modelLocation, matcher.modelLocation) }
|
||||
.forEach { match ->
|
||||
detailLogger.log(Level.INFO, " model $model matches ${match.modelLocation}")
|
||||
|
||||
val materials = match.textureNames.map { it to model.resolveSprite(it) }
|
||||
val texMapString = Joiner.on(", ").join(materials.map { "${it.first}=${it.second.textureId}" })
|
||||
detailLogger.log(Level.INFO, " sprites [$texMapString]")
|
||||
|
||||
if (materials.all { it.second.textureId != MissingSprite.getMissingSpriteId() }) {
|
||||
// found a valid model (all required textures exist)
|
||||
processModel(ctx, materials.map { it.second.textureId })
|
||||
}
|
||||
}
|
||||
}
|
||||
return super.processModel(ctx)
|
||||
}
|
||||
}
|
||||
|
||||
// net.minecraft.client.render.model.json.JsonUnbakedModel.parentId
|
||||
val JsonUnbakedModel_parentId = YarnHelper.requiredField<Identifier>("net.minecraft.class_793", "field_4247", "Lnet/minecraft/class_2960;")
|
||||
|
||||
fun ModelLoader.modelDerivesFrom(model: JsonUnbakedModel, location: Identifier, target: Identifier): Boolean =
|
||||
if (location == target) true
|
||||
else model[JsonUnbakedModel_parentId]
|
||||
?.let { getOrLoadModel(it) as? JsonUnbakedModel }
|
||||
?.let { parent -> modelDerivesFrom(parent, model[JsonUnbakedModel_parentId]!!, target) }
|
||||
?: false
|
||||
@@ -0,0 +1,61 @@
|
||||
package mods.betterfoliage.resource.discovery
|
||||
|
||||
import mods.betterfoliage.model.WeightedModelWrapper
|
||||
import mods.betterfoliage.model.WrappedBakedModel
|
||||
import mods.betterfoliage.model.WrappedMeshModel
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import net.fabricmc.fabric.api.renderer.v1.material.BlendMode
|
||||
import net.minecraft.client.render.model.BakedModel
|
||||
import net.minecraft.client.render.model.BasicBakedModel
|
||||
import net.minecraft.client.render.model.json.WeightedUnbakedModel
|
||||
import net.minecraft.util.Identifier
|
||||
import org.apache.logging.log4j.Level.INFO
|
||||
import org.apache.logging.log4j.Level.WARN
|
||||
|
||||
class WeightedUnbakedKey(
|
||||
val replacements: Map<Identifier, ModelBakingKey>
|
||||
) : ModelBakingKey {
|
||||
|
||||
override fun bake(ctx: ModelBakingContext): BakedModel? {
|
||||
val unbaked = ctx.getUnbaked()
|
||||
if (unbaked !is WeightedUnbakedModel) return super.bake(ctx)
|
||||
|
||||
// bake all variants, replace as needed
|
||||
val bakedModels = unbaked.variants.mapNotNull {
|
||||
val variantCtx = ctx.copy(location = it.location, transform = it)
|
||||
val replacement = replacements[it.location]
|
||||
val baked = replacement?.let { replacement ->
|
||||
ctx.logger.log(INFO, "Baking replacement for variant [${variantCtx.getUnbaked()::class.java.simpleName}] ${variantCtx.location} -> $replacement")
|
||||
replacement.bake(variantCtx)
|
||||
} ?: variantCtx.getBaked()
|
||||
when(baked) {
|
||||
is WrappedBakedModel -> it to baked
|
||||
// just in case we replaced some variants in the list, but not others
|
||||
// this should not realistically happen, this is just a best-effort fallback
|
||||
is BasicBakedModel -> it to WrappedMeshModel.converter(
|
||||
state = null, unshade = false, noDiffuse = true, blendModeOverride = BlendMode.CUTOUT_MIPPED
|
||||
).convert(baked)!!
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
// something fishy going on, possibly unknown model type
|
||||
// let it through unchanged
|
||||
if (bakedModels.isEmpty()) return super.bake(ctx)
|
||||
|
||||
if (bakedModels.size < unbaked.variants.size) {
|
||||
detailLogger.log(
|
||||
WARN,
|
||||
"Dropped ${unbaked.variants.size - bakedModels.size} variants from model ${ctx.location}"
|
||||
)
|
||||
}
|
||||
val weightedSpecials = bakedModels.map { (variant, model) ->
|
||||
WeightedModelWrapper.WeightedModel(model, variant.weight)
|
||||
}
|
||||
return WeightedModelWrapper(weightedSpecials, weightedSpecials[0].model)
|
||||
}
|
||||
|
||||
override fun toString() = "[WeightedUnbakedKey, ${replacements.size} replacements]"
|
||||
|
||||
companion object : HasLogger()
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package mods.octarinecore.client.resource
|
||||
package mods.betterfoliage.resource.generated
|
||||
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.betterfoliage.client.texture.loadSprite
|
||||
import net.minecraft.resources.IResourceManager
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.bytes
|
||||
import mods.betterfoliage.util.loadSprite
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.util.Identifier
|
||||
import java.awt.image.BufferedImage
|
||||
import java.lang.Math.max
|
||||
|
||||
@@ -10,16 +12,16 @@ data class CenteredSprite(val sprite: Identifier, val atlas: Atlas = Atlas.BLOCK
|
||||
|
||||
fun register(pack: GeneratedBlockTexturePack) = pack.register(this, this::draw)
|
||||
|
||||
fun draw(resourceManager: IResourceManager): ByteArray {
|
||||
val baseTexture = resourceManager.loadSprite(atlas.wrap(sprite))
|
||||
fun draw(resourceManager: ResourceManager): ByteArray {
|
||||
val baseTexture = resourceManager.loadSprite(atlas.file(sprite))
|
||||
|
||||
val frameWidth = baseTexture.width
|
||||
val frameHeight = baseTexture.width * aspectHeight / aspectWidth
|
||||
val frames = baseTexture.height / frameHeight
|
||||
val size = max(frameWidth, frameHeight)
|
||||
|
||||
val resultTexture = BufferedImage(size, size * frames, BufferedImage.TYPE_4BYTE_ABGR)
|
||||
val graphics = resultTexture.createGraphics()
|
||||
val result = BufferedImage(size, size * frames, BufferedImage.TYPE_4BYTE_ABGR)
|
||||
val graphics = result.createGraphics()
|
||||
|
||||
// iterate all frames
|
||||
for (frame in 0 until frames) {
|
||||
@@ -32,6 +34,6 @@ data class CenteredSprite(val sprite: Identifier, val atlas: Atlas = Atlas.BLOCK
|
||||
graphics.drawImage(resultFrame, 0, size * frame, null)
|
||||
}
|
||||
|
||||
return resultTexture.bytes
|
||||
return result.bytes
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package mods.betterfoliage.resource.generated
|
||||
|
||||
import mods.betterfoliage.util.Atlas
|
||||
import mods.betterfoliage.util.HasLogger
|
||||
import net.fabricmc.fabric.api.resource.IdentifiableResourceReloadListener
|
||||
import net.minecraft.resource.*
|
||||
import net.minecraft.resource.ResourceType.CLIENT_RESOURCES
|
||||
import net.minecraft.resource.metadata.ResourceMetadataReader
|
||||
import net.minecraft.text.LiteralText
|
||||
import net.minecraft.util.Identifier
|
||||
import net.minecraft.util.profiler.Profiler
|
||||
import org.apache.logging.log4j.Level.INFO
|
||||
import java.io.IOException
|
||||
import java.util.*
|
||||
import java.util.concurrent.CompletableFuture
|
||||
import java.util.concurrent.ExecutionException
|
||||
import java.util.concurrent.Executor
|
||||
import java.util.function.Consumer
|
||||
import java.util.function.Predicate
|
||||
|
||||
/**
|
||||
* [ResourcePack] containing generated block textures
|
||||
*
|
||||
* @param[reloadId] Fabric ID of the pack
|
||||
* @param[nameSpace] Resource namespace of pack
|
||||
* @param[packName] Friendly name of pack
|
||||
* @param[packDesc] Description of pack
|
||||
* @param[logger] Logger to log to when generating resources
|
||||
*/
|
||||
class GeneratedBlockTexturePack(
|
||||
val reloadId: Identifier, val nameSpace: String, val packName: String, val packDesc: String
|
||||
) : HasLogger(), ResourcePack {
|
||||
|
||||
override fun getName() = reloadId.toString()
|
||||
override fun getNamespaces(type: ResourceType) = setOf(nameSpace)
|
||||
override fun <T : Any?> parseMetadata(deserializer: ResourceMetadataReader<T>) = null
|
||||
override fun openRoot(id: String) = null
|
||||
override fun findResources(type: ResourceType, path: String, prefix: String, maxDepth: Int, filter: Predicate<String>) = emptyList<Identifier>()
|
||||
|
||||
override fun close() {}
|
||||
|
||||
protected var manager: ResourceManager? = null
|
||||
val identifiers: MutableMap<Any, Identifier> = Collections.synchronizedMap(mutableMapOf<Any, Identifier>())
|
||||
val resources: MutableMap<Identifier, ByteArray> = Collections.synchronizedMap(mutableMapOf<Identifier, ByteArray>())
|
||||
|
||||
fun register(key: Any, func: (ResourceManager)->ByteArray): Identifier {
|
||||
if (manager == null) throw IllegalStateException("Cannot register resources unless resource manager is being reloaded")
|
||||
identifiers[key]?.let { return it }
|
||||
|
||||
val id = Identifier(nameSpace, UUID.randomUUID().toString())
|
||||
val resource = func(manager!!)
|
||||
|
||||
identifiers[key] = id
|
||||
resources[Atlas.BLOCKS.file(id)] = resource
|
||||
detailLogger.log(INFO, "generated resource $key -> $id")
|
||||
return id
|
||||
}
|
||||
|
||||
override fun open(type: ResourceType, id: Identifier) =
|
||||
if (type != CLIENT_RESOURCES) null else
|
||||
try { resources[id]!!.inputStream() }
|
||||
catch (e: ExecutionException) { (e.cause as? IOException)?.let { throw it } } // rethrow wrapped IOException if present
|
||||
|
||||
override fun contains(type: ResourceType, id: Identifier) =
|
||||
type == CLIENT_RESOURCES && resources.containsKey(id)
|
||||
|
||||
/**
|
||||
* Provider for this resource pack. Adds pack as always-on and hidden.
|
||||
*/
|
||||
val finder = object : ResourcePackProvider {
|
||||
val packInfo = ResourcePackProfile(
|
||||
packName, true, { this@GeneratedBlockTexturePack },
|
||||
LiteralText(packName),
|
||||
LiteralText(packDesc),
|
||||
ResourcePackCompatibility.COMPATIBLE, ResourcePackProfile.InsertionPosition.TOP, true, ResourcePackSource.field_25347
|
||||
)
|
||||
|
||||
override fun register(consumer: Consumer<ResourcePackProfile>, factory: ResourcePackProfile.Factory) {
|
||||
consumer.accept(packInfo)
|
||||
}
|
||||
}
|
||||
|
||||
val reloader = object : IdentifiableResourceReloadListener {
|
||||
override fun getFabricId() = reloadId
|
||||
|
||||
override fun reload(synchronizer: ResourceReloadListener.Synchronizer, manager: ResourceManager, prepareProfiler: Profiler, applyProfiler: Profiler, prepareExecutor: Executor, applyExecutor: Executor): CompletableFuture<Void> {
|
||||
this@GeneratedBlockTexturePack.manager = manager
|
||||
return synchronizer.whenPrepared(null).thenRun {
|
||||
this@GeneratedBlockTexturePack.manager = null
|
||||
identifiers.clear()
|
||||
resources.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
package mods.betterfoliage.client.texture
|
||||
package mods.betterfoliage.resource.generated
|
||||
|
||||
import mods.betterfoliage.client.resource.Identifier
|
||||
import mods.octarinecore.client.resource.*
|
||||
import net.minecraft.resources.IResourceManager
|
||||
import mods.betterfoliage.util.*
|
||||
import net.minecraft.resource.ResourceManager
|
||||
import net.minecraft.util.Identifier
|
||||
import java.awt.image.BufferedImage
|
||||
|
||||
/**
|
||||
@@ -11,13 +11,13 @@ import java.awt.image.BufferedImage
|
||||
*
|
||||
* @param[domain] Resource domain of generator
|
||||
*/
|
||||
data class GeneratedGrass(val sprite: Identifier, val isSnowed: Boolean, val atlas: Atlas = Atlas.BLOCKS) {
|
||||
data class GeneratedGrassSprite(val sprite: Identifier, val isSnowed: Boolean, val atlas: Atlas = Atlas.BLOCKS) {
|
||||
constructor(sprite: String, isSnowed: Boolean) : this(Identifier(sprite), isSnowed)
|
||||
|
||||
fun register(pack: GeneratedBlockTexturePack) = pack.register(this, this::draw)
|
||||
|
||||
fun draw(resourceManager: IResourceManager): ByteArray {
|
||||
val baseTexture = resourceManager.loadSprite(atlas.wrap(sprite))
|
||||
fun draw(resourceManager: ResourceManager): ByteArray {
|
||||
val baseTexture = resourceManager.loadSprite(atlas.file(sprite))
|
||||
|
||||
val result = BufferedImage(baseTexture.width, baseTexture.height, BufferedImage.TYPE_4BYTE_ABGR)
|
||||
val graphics = result.createGraphics()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user