Merge remote-tracking branch 'origin/dev/bukkit/biome-settings' into dev/biomes3

This commit is contained in:
Zoe Gidiere 2024-10-29 13:53:08 -06:00
commit f98062d417
57 changed files with 426 additions and 381 deletions

View File

@ -9,27 +9,27 @@ object Versions {
const val strata = "1.3.2" const val strata = "1.3.2"
const val cloud = "2.0.0" const val cloud = "2.0.0"
const val cloudPaper = "2.0.0-beta.10"
const val cloudFabric = "2.0.0-beta.9"
const val caffeine = "3.1.8" const val caffeine = "3.1.8"
const val slf4j = "2.0.16" const val slf4j = "2.0.16"
object Internal { object Internal {
const val shadow = "8.3.1" const val shadow = "8.3.3"
const val apacheText = "1.12.0" const val apacheText = "1.12.0"
const val apacheIO = "2.16.1" const val apacheIO = "2.17.0"
const val guava = "33.3.0-jre" const val guava = "33.3.1-jre"
const val asm = "9.7" const val asm = "9.7.1"
const val snakeYml = "2.3" const val snakeYml = "2.3"
const val jetBrainsAnnotations = "24.1.0" const val jetBrainsAnnotations = "26.0.1"
const val junit = "5.11.0" const val junit = "5.11.3"
const val nbt = "6.1"
} }
} }
object Fabric { object Fabric {
const val fabricAPI = "0.104.0+${Mod.minecraft}" const val fabricAPI = "0.106.1+${Mod.minecraft}"
const val cloud = "2.0.0-beta.9"
} }
// //
// object Quilt { // object Quilt {
@ -40,12 +40,13 @@ object Versions {
object Mod { object Mod {
const val mixin = "0.15.3+mixin.0.8.7" const val mixin = "0.15.3+mixin.0.8.7"
const val minecraft = "1.21.1" const val minecraft = "1.21.3"
const val yarn = "$minecraft+build.3" const val yarn = "$minecraft+build.2"
const val fabricLoader = "0.16.5" const val fabricLoader = "0.16.7"
const val architecuryLoom = "1.7.413" const val architecuryLoom = "1.7.413"
const val architecturyPlugin = "3.4.159" const val architecturyPlugin = "3.4.159"
} }
// //
// object Forge { // object Forge {
@ -54,14 +55,15 @@ object Versions {
// } // }
object Bukkit { object Bukkit {
const val minecraft = "1.21.1" const val minecraft = "1.21.3"
const val paperBuild = "$minecraft-R0.1-20240917.151311-80" const val paperBuild = "$minecraft-R0.1-20241025.163321-1"
const val paper = paperBuild const val paper = paperBuild
const val paperLib = "1.0.8" const val paperLib = "1.0.8"
const val reflectionRemapper = "0.1.1" const val reflectionRemapper = "0.1.1"
const val paperDevBundle = paperBuild const val paperDevBundle = paperBuild
const val runPaper = "2.3.1" const val runPaper = "2.3.1"
const val paperWeight = "1.7.2" const val paperWeight = "1.7.2"
const val cloud = "2.0.0-beta.10"
} }
// //
@ -72,7 +74,6 @@ object Versions {
// } // }
// //
object CLI { object CLI {
const val nbt = "6.1"
const val logback = "1.5.8" const val logback = "1.5.8"
const val picocli = "4.7.6" const val picocli = "4.7.6"
} }

View File

@ -6,8 +6,3 @@ dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader")) compileOnlyApi(project(":common:addons:manifest-addon-loader"))
api("com.dfsek", "paralithic", Versions.Libraries.paralithic) api("com.dfsek", "paralithic", Versions.Libraries.paralithic)
} }
tasks.named<ShadowJar>("shadowJar") {
relocate("com.dfsek.paralithic", "com.dfsek.terra.addons.numberpredicate.lib.paralithic")
}

View File

@ -8,7 +8,6 @@
package com.dfsek.terra.addons.palette; package com.dfsek.terra.addons.palette;
import com.dfsek.terra.addons.palette.palette.PaletteImpl; import com.dfsek.terra.addons.palette.palette.PaletteImpl;
import com.dfsek.terra.addons.palette.palette.PaletteLayerHolder;
import com.dfsek.terra.api.Platform; import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.config.ConfigFactory; import com.dfsek.terra.api.config.ConfigFactory;
import com.dfsek.terra.api.world.chunk.generation.util.Palette; import com.dfsek.terra.api.world.chunk.generation.util.Palette;
@ -17,10 +16,6 @@ import com.dfsek.terra.api.world.chunk.generation.util.Palette;
public class PaletteFactory implements ConfigFactory<PaletteTemplate, Palette> { public class PaletteFactory implements ConfigFactory<PaletteTemplate, Palette> {
@Override @Override
public Palette build(PaletteTemplate config, Platform platform) { public Palette build(PaletteTemplate config, Platform platform) {
PaletteImpl palette = new PaletteImpl(config.getNoise()); return new PaletteImpl(config.getPalette(), config.getDefaultSampler());
for(PaletteLayerHolder layer : config.getPalette()) {
palette.add(layer.getLayer(), layer.getSize(), layer.getSampler());
}
return palette;
} }
} }

View File

@ -23,7 +23,7 @@ import com.dfsek.terra.api.noise.NoiseSampler;
public class PaletteTemplate implements AbstractableTemplate { public class PaletteTemplate implements AbstractableTemplate {
@Value("sampler") @Value("sampler")
@Default @Default
private @Meta NoiseSampler noise = NoiseSampler.zero(); private @Meta NoiseSampler defaultSampler = NoiseSampler.zero();
@Value("id") @Value("id")
@Final @Final
@ -40,7 +40,7 @@ public class PaletteTemplate implements AbstractableTemplate {
return palette; return palette;
} }
public NoiseSampler getNoise() { public NoiseSampler getDefaultSampler() {
return noise; return defaultSampler;
} }
} }

View File

@ -15,73 +15,45 @@ import com.dfsek.terra.api.noise.NoiseSampler;
import com.dfsek.terra.api.util.collection.ProbabilityCollection; import com.dfsek.terra.api.util.collection.ProbabilityCollection;
import com.dfsek.terra.api.world.chunk.generation.util.Palette; import com.dfsek.terra.api.world.chunk.generation.util.Palette;
/** /**
* A class representation of a "slice" of the world. * A class representation of a "slice" of the world.
* Used to get a section of blocks, based on the depth at which they are found. * Used to get a section of blocks, based on the depth at which they are found.
*/ */
public class PaletteImpl implements Palette { public class PaletteImpl implements Palette {
private final List<PaletteLayer> pallet = new ArrayList<>(); private final PaletteLayer[] layers;
private final NoiseSampler sampler;
public PaletteImpl(NoiseSampler sampler) { public PaletteImpl(List<PaletteLayerHolder> layers, NoiseSampler defaultSampler) {
this.sampler = sampler; List<PaletteLayer> layerArray = new ArrayList<>();
for (PaletteLayerHolder holder : layers) {
PaletteLayer layer;
ProbabilityCollection<BlockState> materials = holder.getLayer();
NoiseSampler sampler = holder.getSampler() == null ? defaultSampler : holder.getSampler();
layer = new PaletteLayer(materials, sampler);
for (int i = 0; i < holder.getSize(); i++)
layerArray.add(layer);
} }
public Palette add(ProbabilityCollection<BlockState> m, int layers, NoiseSampler sampler) { this.layers = layerArray.toArray(new PaletteLayer[0]);
for(int i = 0; i < layers; i++) {
pallet.add(new PaletteLayer(m, sampler));
}
return this;
} }
@Override @Override
public BlockState get(int layer, double x, double y, double z, long seed) { public BlockState get(int layer, double x, double y, double z, long seed) {
PaletteLayer paletteLayer; int idx = layer < layers.length ? layer : layers.length - 1;
if(layer > this.getSize()) paletteLayer = this.getLayers().get(this.getLayers().size() - 1); return layers[idx].get(x, y, z, seed);
else {
List<PaletteLayer> pl = getLayers();
if(layer >= pl.size()) paletteLayer = pl.get(pl.size() - 1);
else paletteLayer = pl.get(layer);
}
NoiseSampler paletteSampler = paletteLayer.getSampler();
return paletteLayer.get(paletteSampler == null ? sampler : paletteSampler, x, y, z, seed);
} }
static class PaletteLayer {
public int getSize() {
return pallet.size();
}
public List<PaletteLayer> getLayers() {
return pallet;
}
/**
* Class representation of a layer of a BlockPalette.
*/
public static class PaletteLayer {
private final NoiseSampler sampler; private final NoiseSampler sampler;
private final ProbabilityCollection<BlockState> collection; private final ProbabilityCollection<BlockState> collection;
/**
* Constructs a PaletteLayerHolder with a ProbabilityCollection of materials and a number of layers.
*
* @param type The collection of materials to choose from.
* @param sampler Noise sampler to use
*/
public PaletteLayer(ProbabilityCollection<BlockState> type, NoiseSampler sampler) { public PaletteLayer(ProbabilityCollection<BlockState> type, NoiseSampler sampler) {
this.sampler = sampler; this.sampler = sampler;
this.collection = type; this.collection = type;
} }
public BlockState get(NoiseSampler random, double x, double y, double z, long seed) { public BlockState get(double x, double y, double z, long seed) {
return this.collection.get(random, x, y, z, seed); return this.collection.get(sampler, x, y, z, seed);
} }
public NoiseSampler getSampler() {
return sampler;
}
} }
} }

View File

@ -1,8 +1,8 @@
version = version("1.0.0") version = version("1.0.0")
dependencies { dependencies {
api("commons-io:commons-io:2.7") api("commons-io", "commons-io", Versions.Libraries.Internal.apacheIO)
implementation("com.dfsek.tectonic:yaml:${Versions.Libraries.tectonic}") implementation("com.dfsek.tectonic", "yaml", Versions.Libraries.tectonic)
} }
tasks.withType<Jar> { tasks.withType<Jar> {

View File

@ -3,11 +3,7 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
version = version("1.0.0") version = version("1.0.0")
dependencies { dependencies {
api("commons-io:commons-io:2.7") api("commons-io", "commons-io", Versions.Libraries.Internal.apacheIO)
api("com.github.Querz:NBT:6.1") api("com.github.Querz", "NBT", Versions.Libraries.Internal.nbt)
compileOnlyApi(project(":common:addons:manifest-addon-loader")) compileOnlyApi(project(":common:addons:manifest-addon-loader"))
} }
tasks.named<ShadowJar>("shadowJar") {
relocate("org.apache.commons", "com.dfsek.terra.addons.sponge.lib.commons")
}

View File

@ -3,10 +3,6 @@ import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
version = version("1.2.0") version = version("1.2.0")
dependencies { dependencies {
api("commons-io:commons-io:2.7") api("commons-io", "commons-io", Versions.Libraries.Internal.apacheIO)
compileOnlyApi(project(":common:addons:manifest-addon-loader")) compileOnlyApi(project(":common:addons:manifest-addon-loader"))
} }
tasks.named<ShadowJar>("shadowJar") {
relocate("org.apache.commons", "com.dfsek.terra.addons.terrascript.lib.commons")
}

View File

@ -43,23 +43,27 @@ public class ProbabilityCollectionLoader implements TypeLoader<ProbabilityCollec
AnnotatedType generic = pType.getAnnotatedActualTypeArguments()[0]; AnnotatedType generic = pType.getAnnotatedActualTypeArguments()[0];
if(o instanceof Map) { if(o instanceof Map) {
Map<Object, Object> map = (Map<Object, Object>) o; Map<Object, Object> map = (Map<Object, Object>) o;
if (map.size() == 1) {
Object onlyKey = map.keySet().iterator().next();
return new ProbabilityCollection.Singleton<>(configLoader.loadType(generic, onlyKey, depthTracker));
}
for(Map.Entry<Object, Object> entry : map.entrySet()) { for(Map.Entry<Object, Object> entry : map.entrySet()) {
collection.add(configLoader.loadType(generic, entry.getKey(), depthTracker.entry((String) entry.getKey())), collection.add(configLoader.loadType(generic, entry.getKey(), depthTracker.entry((String) entry.getKey())),
configLoader.loadType(Integer.class, entry.getValue(), depthTracker.entry((String) entry.getKey()))); configLoader.loadType(Integer.class, entry.getValue(), depthTracker.entry((String) entry.getKey())));
} }
} else if(o instanceof List) { } else if(o instanceof List) {
List<Map<Object, Object>> map = (List<Map<Object, Object>>) o; List<Map<Object, Object>> list = (List<Map<Object, Object>>) o;
if(list.size() == 1) {
Map<Object, Object> map = list.getFirst();
if(map.size() == 1) { if(map.size() == 1) {
Map<Object, Object> entry = map.get(0); for(Object value : map.keySet()) {
if(entry.size() == 1) {
for(Object value : entry.keySet()) {
return new ProbabilityCollection.Singleton<>(configLoader.loadType(generic, value, depthTracker)); return new ProbabilityCollection.Singleton<>(configLoader.loadType(generic, value, depthTracker));
} }
} }
} }
for(int i = 0; i < map.size(); i++) { for(int i = 0; i < list.size(); i++) {
Map<Object, Object> l = map.get(i); Map<Object, Object> map = list.get(i);
for(Entry<Object, Object> entry : l.entrySet()) { for(Entry<Object, Object> entry : map.entrySet()) {
if(entry.getValue() == null) throw new LoadException("No probability defined for entry \"" + entry.getKey() + "\"", if(entry.getValue() == null) throw new LoadException("No probability defined for entry \"" + entry.getKey() + "\"",
depthTracker); depthTracker);
Object val = configLoader.loadType(generic, entry.getKey(), depthTracker.index(i).entry((String) entry.getKey())); Object val = configLoader.loadType(generic, entry.getKey(), depthTracker.index(i).entry((String) entry.getKey()));

Binary file not shown.

View File

@ -1,7 +1,7 @@
distributionBase=GRADLE_USER_HOME distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists distributionPath=wrapper/dists
distributionSha256Sum=1541fa36599e12857140465f3c91a97409b4512501c26f9631fb113e392c5bd1 distributionSha256Sum=31c55713e40233a8303827ceb42ca48a47267a0ad4bab9177123121e71524c26
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.1-bin.zip distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
networkTimeout=10000 networkTimeout=10000
validateDistributionUrl=true validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME zipStoreBase=GRADLE_USER_HOME

5
gradlew vendored
View File

@ -15,6 +15,8 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
# #
# SPDX-License-Identifier: Apache-2.0
#
############################################################################## ##############################################################################
# #
@ -84,7 +86,8 @@ done
# shellcheck disable=SC2034 # shellcheck disable=SC2034
APP_BASE_NAME=${0##*/} APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value. # Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum MAX_FD=maximum

2
gradlew.bat vendored
View File

@ -13,6 +13,8 @@
@rem See the License for the specific language governing permissions and @rem See the License for the specific language governing permissions and
@rem limitations under the License. @rem limitations under the License.
@rem @rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off @if "%DEBUG%"=="" @echo off
@rem ########################################################################## @rem ##########################################################################

View File

@ -11,5 +11,5 @@ dependencies {
shadedApi("com.google.guava", "guava", Versions.Libraries.Internal.guava) shadedApi("com.google.guava", "guava", Versions.Libraries.Internal.guava)
shadedApi("org.incendo", "cloud-paper", Versions.Libraries.cloudPaper) shadedApi("org.incendo", "cloud-paper", Versions.Bukkit.cloud)
} }

View File

@ -4,18 +4,15 @@ import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version; import ca.solostudios.strata.version.Version;
import com.dfsek.terra.api.addon.BaseAddon; import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent; import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler; import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions; import com.dfsek.terra.bukkit.config.PreLoadCompatibilityOptions;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties;
public class BukkitAddon implements BaseAddon { public class BukkitAddon implements BaseAddon {
private static final Version VERSION = Versions.getVersion(1, 0, 0); private static final Version VERSION = Versions.getVersion(1, 0, 0);
private final PlatformImpl terraBukkitPlugin; protected final PlatformImpl terraBukkitPlugin;
public BukkitAddon(PlatformImpl terraBukkitPlugin) { public BukkitAddon(PlatformImpl terraBukkitPlugin) {
this.terraBukkitPlugin = terraBukkitPlugin; this.terraBukkitPlugin = terraBukkitPlugin;
@ -28,16 +25,6 @@ public class BukkitAddon implements BaseAddon {
.register(this, ConfigPackPreLoadEvent.class) .register(this, ConfigPackPreLoadEvent.class)
.then(event -> event.getPack().getContext().put(event.loadTemplate(new PreLoadCompatibilityOptions()))) .then(event -> event.getPack().getContext().put(event.loadTemplate(new PreLoadCompatibilityOptions())))
.global(); .global();
terraBukkitPlugin.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigurationLoadEvent.class)
.then(event -> {
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
}
})
.global();
} }
@Override @Override

View File

@ -20,6 +20,9 @@ package com.dfsek.terra.bukkit;
import com.dfsek.tectonic.api.TypeRegistry; import com.dfsek.tectonic.api.TypeRegistry;
import com.dfsek.tectonic.api.depth.DepthTracker; import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.LoadException; import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.terra.bukkit.nms.Initializer;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.entity.EntityType; import org.bukkit.entity.EntityType;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
@ -96,7 +99,7 @@ public class PlatformImpl extends AbstractPlatform {
@Override @Override
protected Iterable<BaseAddon> platformAddon() { protected Iterable<BaseAddon> platformAddon() {
return List.of(new BukkitAddon(this)); return List.of(Initializer.nmsAddon(this));
} }
@Override @Override

View File

@ -1,58 +0,0 @@
package com.dfsek.terra.bukkit.config;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import com.dfsek.terra.api.properties.Properties;
public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Value("colors.grass")
@Default
private Integer grassColor = null;
@Value("colors.fog")
@Default
private Integer fogColor = null;
@Value("colors.water")
@Default
private Integer waterColor = null;
@Value("colors.water-fog")
@Default
private Integer waterFogColor = null;
@Value("colors.foliage")
@Default
private Integer foliageColor = null;
@Value("colors.sky")
@Default
private Integer skyColor = null;
public Integer getFogColor() {
return fogColor;
}
public Integer getFoliageColor() {
return foliageColor;
}
public Integer getGrassColor() {
return grassColor;
}
public Integer getWaterColor() {
return waterColor;
}
public Integer getWaterFogColor() {
return waterFogColor;
}
public Integer getSkyColor() {
return skyColor;
}
}

View File

@ -1,5 +1,7 @@
package com.dfsek.terra.bukkit.nms; package com.dfsek.terra.bukkit.nms;
import com.dfsek.terra.bukkit.BukkitAddon;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -13,20 +15,11 @@ public interface Initializer {
static boolean init(PlatformImpl platform) { static boolean init(PlatformImpl platform) {
Logger logger = LoggerFactory.getLogger(Initializer.class); Logger logger = LoggerFactory.getLogger(Initializer.class);
try {
String packageVersion = NMS;
if(NMS.equals("v1_21_1")) {
packageVersion = "v1_21";
}
Class<?> initializerClass = Class.forName(TERRA_PACKAGE + "." + packageVersion + ".NMSInitializer"); Initializer initializer = constructInitializer();
try { if(initializer != null) {
Initializer initializer = (Initializer) initializerClass.getConstructor().newInstance();
initializer.initialize(platform); initializer.initialize(platform);
} catch(ReflectiveOperationException e) { } else {
throw new RuntimeException("Error initializing NMS bindings. Report this to Terra.", e);
}
} catch(ClassNotFoundException e) {
logger.error("NMS bindings for version {} do not exist. Support for this version is limited.", NMS); logger.error("NMS bindings for version {} do not exist. Support for this version is limited.", NMS);
logger.error("This is usually due to running Terra on an unsupported Minecraft version."); logger.error("This is usually due to running Terra on an unsupported Minecraft version.");
String bypassKey = "IKnowThereAreNoNMSBindingsFor" + NMS + "ButIWillProceedAnyway"; String bypassKey = "IKnowThereAreNoNMSBindingsFor" + NMS + "ButIWillProceedAnyway";
@ -49,8 +42,34 @@ public interface Initializer {
logger.error("Since you enabled the \"{}\" flag, we won't disable Terra. But be warned.", bypassKey); logger.error("Since you enabled the \"{}\" flag, we won't disable Terra. But be warned.", bypassKey);
} }
} }
return true; return true;
} }
void initialize(PlatformImpl plugin); static BukkitAddon nmsAddon(PlatformImpl platform) {
Initializer initializer = constructInitializer();
return initializer != null ? initializer.getNMSAddon(platform) : new BukkitAddon(platform);
}
private static Initializer constructInitializer() {
try {
String packageVersion = NMS;
if(NMS.equals("v1_21_3")) {
packageVersion = "v1_21"; // TODO: Refactor nms package to v1_21_3
}
Class<?> initializerClass = Class.forName(TERRA_PACKAGE + "." + packageVersion + ".NMSInitializer");
try {
return (Initializer) initializerClass.getConstructor().newInstance();
} catch(ReflectiveOperationException e) {
throw new RuntimeException("Error initializing NMS bindings. Report this to Terra.", e);
}
} catch(ClassNotFoundException e) {
return null;
}
}
void initialize(PlatformImpl plugin);
BukkitAddon getNMSAddon(PlatformImpl plugin);
} }

View File

@ -19,7 +19,6 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects;
import com.dfsek.terra.bukkit.world.BukkitPlatformBiome; import com.dfsek.terra.bukkit.world.BukkitPlatformBiome;
import com.dfsek.terra.registry.master.ConfigRegistry; import com.dfsek.terra.registry.master.ConfigRegistry;
@ -43,7 +42,7 @@ public class AwfulBukkitHacks {
NamespacedKey vanillaBukkitKey = platformBiome.getHandle().getKey(); NamespacedKey vanillaBukkitKey = platformBiome.getHandle().getKey();
ResourceLocation vanillaMinecraftKey = ResourceLocation.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(), ResourceLocation vanillaMinecraftKey = ResourceLocation.fromNamespaceAndPath(vanillaBukkitKey.getNamespace(),
vanillaBukkitKey.getKey()); vanillaBukkitKey.getKey());
Biome platform = NMSBiomeInjector.createBiome(biome, Objects.requireNonNull(biomeRegistry.get(vanillaMinecraftKey))); Biome platform = NMSBiomeInjector.createBiome(biome, biomeRegistry.get(vanillaMinecraftKey).orElseThrow().value());
ResourceKey<Biome> delegateKey = ResourceKey.create( ResourceKey<Biome> delegateKey = ResourceKey.create(
Registries.BIOME, Registries.BIOME,
@ -70,7 +69,7 @@ public class AwfulBukkitHacks {
.getTags() // streamKeysAndEntries .getTags() // streamKeysAndEntries
.collect(HashMap::new, .collect(HashMap::new,
(map, pair) -> (map, pair) ->
map.put(pair.getFirst(), new ArrayList<>(pair.getSecond().stream().toList())), map.put(pair.key(), new ArrayList<>(Reflection.HOLDER_SET.invokeContents(pair).stream().toList())),
HashMap::putAll); HashMap::putAll);
terraBiomeMap terraBiomeMap
@ -91,8 +90,8 @@ public class AwfulBukkitHacks {
() -> LOGGER.error("No such biome: {}", tb))), () -> LOGGER.error("No such biome: {}", tb))),
() -> LOGGER.error("No vanilla biome: {}", vb))); () -> LOGGER.error("No vanilla biome: {}", vb)));
biomeRegistry.resetTags(); ((MappedRegistry<Biome>) biomeRegistry).bindAllTagsToEmpty();
biomeRegistry.bindTags(ImmutableMap.copyOf(collect)); ImmutableMap.copyOf(collect).forEach(biomeRegistry::bindTag);
} catch(SecurityException | IllegalArgumentException exception) { } catch(SecurityException | IllegalArgumentException exception) {
throw new RuntimeException(exception); throw new RuntimeException(exception);

View File

@ -0,0 +1,31 @@
package com.dfsek.terra.bukkit.nms.v1_21;
import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.world.biome.Biome;
import com.dfsek.terra.bukkit.BukkitAddon;
import com.dfsek.terra.bukkit.PlatformImpl;
import com.dfsek.terra.bukkit.nms.v1_21.config.VanillaBiomeProperties;
public class NMSAddon extends BukkitAddon {
public NMSAddon(PlatformImpl platform) {
super(platform);
}
@Override
public void initialize() {
super.initialize();
terraBukkitPlugin.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(this, ConfigurationLoadEvent.class)
.then(event -> {
if(event.is(Biome.class)) {
event.getLoadedObject(Biome.class).getContext().put(event.load(new VanillaBiomeProperties()));
}
})
.global();
}
}

View File

@ -11,7 +11,7 @@ import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import com.dfsek.terra.api.config.ConfigPack; import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.bukkit.config.VanillaBiomeProperties; import com.dfsek.terra.bukkit.nms.v1_21.config.VanillaBiomeProperties;
public class NMSBiomeInjector { public class NMSBiomeInjector {
@ -19,56 +19,69 @@ public class NMSBiomeInjector {
public static <T> Optional<Holder<T>> getEntry(Registry<T> registry, ResourceLocation identifier) { public static <T> Optional<Holder<T>> getEntry(Registry<T> registry, ResourceLocation identifier) {
return registry.getOptional(identifier) return registry.getOptional(identifier)
.flatMap(registry::getResourceKey) .flatMap(registry::getResourceKey)
.flatMap(registry::getHolder); .flatMap(registry::get);
} }
public static Biome createBiome(com.dfsek.terra.api.world.biome.Biome biome, Biome vanilla) public static Biome createBiome(com.dfsek.terra.api.world.biome.Biome biome, Biome vanilla)
throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
Biome.BiomeBuilder builder = new Biome.BiomeBuilder(); Biome.BiomeBuilder builder = new Biome.BiomeBuilder();
builder
.downfall(vanilla.climateSettings.downfall())
.temperature(vanilla.getBaseTemperature())
.mobSpawnSettings(vanilla.getMobSettings())
.generationSettings(vanilla.getGenerationSettings());
BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder(); BiomeSpecialEffects.Builder effects = new BiomeSpecialEffects.Builder();
effects.grassColorModifier(vanilla.getSpecialEffects().getGrassColorModifier());
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);
effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor())) effects.fogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getFogColor(), vanilla.getFogColor()))
.waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor())) .waterColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterColor(), vanilla.getWaterColor()))
.waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor())) .waterFogColor(Objects.requireNonNullElse(vanillaBiomeProperties.getWaterFogColor(), vanilla.getWaterFogColor()))
.skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor()))
.grassColorModifier(Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColorModifier(), vanilla.getSpecialEffects().getGrassColorModifier()))
.grassColorOverride(Objects.requireNonNullElse(vanillaBiomeProperties.getGrassColor(), vanilla.getSpecialEffects().getGrassColorOverride().orElseGet(() -> Reflection.BIOME.invokeGrassColorFromTexture(vanilla))))
.foliageColorOverride(Objects.requireNonNullElse(vanillaBiomeProperties.getFoliageColor(), vanilla.getFoliageColor()));
.skyColor(Objects.requireNonNullElse(vanillaBiomeProperties.getSkyColor(), vanilla.getSkyColor())); if(vanillaBiomeProperties.getParticleConfig() == null) {
vanilla.getSpecialEffects().getAmbientParticleSettings().ifPresent(effects::ambientParticle);
if(vanillaBiomeProperties.getFoliageColor() == null) {
vanilla.getSpecialEffects().getFoliageColorOverride().ifPresent(effects::foliageColorOverride);
} else { } else {
effects.foliageColorOverride(vanillaBiomeProperties.getFoliageColor()); effects.ambientParticle(vanillaBiomeProperties.getParticleConfig());
} }
if(vanillaBiomeProperties.getGrassColor() == null) { if(vanillaBiomeProperties.getLoopSound() == null) {
vanilla.getSpecialEffects().getGrassColorOverride().ifPresent(effects::grassColorOverride); vanilla.getSpecialEffects().getAmbientLoopSoundEvent().ifPresent(effects::ambientLoopSound);
} else { } else {
// grass RegistryFetcher.soundEventRegistry().get(vanillaBiomeProperties.getLoopSound().location()).ifPresent(effects::ambientLoopSound);
effects.grassColorOverride(vanillaBiomeProperties.getGrassColor());
} }
vanilla.getAmbientLoop().ifPresent(effects::ambientLoopSound); if(vanillaBiomeProperties.getMoodSound() == null) {
vanilla.getAmbientAdditions().ifPresent(effects::ambientAdditionsSound); vanilla.getSpecialEffects().getAmbientMoodSettings().ifPresent(effects::ambientMoodSound);
vanilla.getAmbientMood().ifPresent(effects::ambientMoodSound); } else {
vanilla.getBackgroundMusic().ifPresent(effects::backgroundMusic); effects.ambientMoodSound(vanillaBiomeProperties.getMoodSound());
vanilla.getAmbientParticle().ifPresent(effects::ambientParticle); }
builder.specialEffects(effects.build()); if(vanillaBiomeProperties.getAdditionsSound() == null) {
vanilla.getSpecialEffects().getAmbientAdditionsSettings().ifPresent(effects::ambientAdditionsSound);
} else {
effects.ambientAdditionsSound(vanillaBiomeProperties.getAdditionsSound());
}
return builder.build(); if(vanillaBiomeProperties.getMusic() == null) {
vanilla.getSpecialEffects().getBackgroundMusic().ifPresent(effects::backgroundMusic);
} else {
effects.backgroundMusic(vanillaBiomeProperties.getMusic());
}
builder.hasPrecipitation(Objects.requireNonNullElse(vanillaBiomeProperties.getPrecipitation(), vanilla.hasPrecipitation()));
builder.temperature(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperature(), vanilla.getBaseTemperature()));
builder.downfall(Objects.requireNonNullElse(vanillaBiomeProperties.getDownfall(), vanilla.climateSettings.downfall()));
builder.temperatureAdjustment(Objects.requireNonNullElse(vanillaBiomeProperties.getTemperatureModifier(), vanilla.climateSettings.temperatureModifier()));
builder.mobSpawnSettings(Objects.requireNonNullElse(vanillaBiomeProperties.getSpawnSettings(), vanilla.getMobSettings()));
return builder
.specialEffects(effects.build())
.generationSettings(vanilla.getGenerationSettings())
.build();
} }
public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) { public static String createBiomeID(ConfigPack pack, com.dfsek.terra.api.registry.key.RegistryKey biomeID) {

View File

@ -29,7 +29,7 @@ public class NMSBiomeProvider extends BiomeSource {
protected Stream<Holder<Biome>> collectPossibleBiomes() { protected Stream<Holder<Biome>> collectPossibleBiomes() {
return delegate.stream() return delegate.stream()
.map(biome -> RegistryFetcher.biomeRegistry() .map(biome -> RegistryFetcher.biomeRegistry()
.getHolderOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext() .getOrThrow(((BukkitPlatformBiome) biome.getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class) .get(NMSBiomeInfo.class)
.biomeKey())); .biomeKey()));
} }
@ -45,7 +45,7 @@ public class NMSBiomeProvider extends BiomeSource {
@Override @Override
public @NotNull Holder<Biome> getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) { public @NotNull Holder<Biome> getNoiseBiome(int x, int y, int z, @NotNull Sampler sampler) {
return biomeRegistry.getHolderOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed) return biomeRegistry.getOrThrow(((BukkitPlatformBiome) delegate.getBiome(x << 2, y << 2, z << 2, seed)
.getPlatformBiome()).getContext() .getPlatformBiome()).getContext()
.get(NMSBiomeInfo.class) .get(NMSBiomeInfo.class)
.biomeKey()); .biomeKey());

View File

@ -15,7 +15,6 @@ import net.minecraft.world.level.chunk.ChunkAccess;
import net.minecraft.world.level.chunk.ChunkGenerator; import net.minecraft.world.level.chunk.ChunkGenerator;
import net.minecraft.world.level.levelgen.Beardifier; import net.minecraft.world.level.levelgen.Beardifier;
import net.minecraft.world.level.levelgen.DensityFunction.SinglePointContext; import net.minecraft.world.level.levelgen.DensityFunction.SinglePointContext;
import net.minecraft.world.level.levelgen.GenerationStep.Carving;
import net.minecraft.world.level.levelgen.Heightmap.Types; import net.minecraft.world.level.levelgen.Heightmap.Types;
import net.minecraft.world.level.levelgen.RandomState; import net.minecraft.world.level.levelgen.RandomState;
import net.minecraft.world.level.levelgen.blending.Blender; import net.minecraft.world.level.levelgen.blending.Blender;
@ -59,7 +58,7 @@ public class NMSChunkGeneratorDelegate extends ChunkGenerator {
@Override @Override
public void applyCarvers(@NotNull WorldGenRegion chunkRegion, long seed, @NotNull RandomState noiseConfig, @NotNull BiomeManager world, public void applyCarvers(@NotNull WorldGenRegion chunkRegion, long seed, @NotNull RandomState noiseConfig, @NotNull BiomeManager world,
@NotNull StructureManager structureAccessor, @NotNull ChunkAccess chunk, @NotNull Carving carverStep) { @NotNull StructureManager structureAccessor, @NotNull ChunkAccess chunk) {
// no-op // no-op
} }

View File

@ -1,5 +1,7 @@
package com.dfsek.terra.bukkit.nms.v1_21; package com.dfsek.terra.bukkit.nms.v1_21;
import com.dfsek.terra.bukkit.BukkitAddon;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import com.dfsek.terra.bukkit.PlatformImpl; import com.dfsek.terra.bukkit.PlatformImpl;
@ -12,4 +14,9 @@ public class NMSInitializer implements Initializer {
AwfulBukkitHacks.registerBiomes(platform.getRawConfigRegistry()); AwfulBukkitHacks.registerBiomes(platform.getRawConfigRegistry());
Bukkit.getPluginManager().registerEvents(new NMSInjectListener(), platform.getPlugin()); Bukkit.getPluginManager().registerEvents(new NMSInjectListener(), platform.getPlugin());
} }
@Override
public BukkitAddon getNMSAddon(PlatformImpl plugin) {
return new NMSAddon(plugin);
}
} }

View File

@ -41,19 +41,15 @@ public class NMSInjectListener implements Listener {
ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator(); ChunkGenerator vanilla = serverWorld.getChunkSource().getGenerator();
NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed()); NMSBiomeProvider provider = new NMSBiomeProvider(pack.getBiomeProvider(), craftWorld.getSeed());
ChunkMap chunkMap = serverWorld.getChunkSource().chunkMap; ChunkMap chunkMap = serverWorld.getChunkSource().chunkMap;
WorldGenContext worldGenContext = chunkMap.worldGenContext; WorldGenContext worldGenContext = Reflection.CHUNKMAP.getWorldGenContext(chunkMap);
Reflection.CHUNKMAP.setWorldGenContext(chunkMap, new WorldGenContext(
try {
ReflectionUtil.setFinalField(chunkMap, "worldGenContext", new WorldGenContext(
worldGenContext.level(), worldGenContext.level(),
new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed()), new NMSChunkGeneratorDelegate(vanilla, pack, provider, craftWorld.getSeed()),
worldGenContext.structureManager(), worldGenContext.structureManager(),
worldGenContext.lightEngine(), worldGenContext.lightEngine(),
worldGenContext.mainThreadMailBox() worldGenContext.mainThreadExecutor(),
worldGenContext.unsavedListener()
)); ));
} catch(NoSuchFieldException e) {
throw new RuntimeException(e);
}
LOGGER.info("Successfully injected into world."); LOGGER.info("Successfully injected into world.");

View File

@ -26,11 +26,11 @@ public class NMSWorldProperties implements WorldProperties {
@Override @Override
public int getMaxHeight() { public int getMaxHeight() {
return height.getMaxBuildHeight(); return height.getMaxY();
} }
@Override @Override
public int getMinHeight() { public int getMinHeight() {
return height.getMinBuildHeight(); return height.getMinY();
} }
} }

View File

@ -2,9 +2,13 @@ package com.dfsek.terra.bukkit.nms.v1_21;
import net.minecraft.core.Holder; import net.minecraft.core.Holder;
import net.minecraft.core.Holder.Reference; import net.minecraft.core.Holder.Reference;
import net.minecraft.core.HolderSet;
import net.minecraft.core.MappedRegistry; import net.minecraft.core.MappedRegistry;
import net.minecraft.server.level.ChunkMap;
import net.minecraft.world.level.LevelAccessor; import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.StructureManager; import net.minecraft.world.level.StructureManager;
import net.minecraft.world.level.biome.Biome;
import net.minecraft.world.level.chunk.status.WorldGenContext;
import xyz.jpenilla.reflectionremapper.ReflectionRemapper; import xyz.jpenilla.reflectionremapper.ReflectionRemapper;
import xyz.jpenilla.reflectionremapper.proxy.ReflectionProxyFactory; import xyz.jpenilla.reflectionremapper.proxy.ReflectionProxyFactory;
import xyz.jpenilla.reflectionremapper.proxy.annotation.FieldGetter; import xyz.jpenilla.reflectionremapper.proxy.annotation.FieldGetter;
@ -12,6 +16,8 @@ import xyz.jpenilla.reflectionremapper.proxy.annotation.FieldSetter;
import xyz.jpenilla.reflectionremapper.proxy.annotation.MethodName; import xyz.jpenilla.reflectionremapper.proxy.annotation.MethodName;
import xyz.jpenilla.reflectionremapper.proxy.annotation.Proxies; import xyz.jpenilla.reflectionremapper.proxy.annotation.Proxies;
import java.util.List;
public class Reflection { public class Reflection {
public static final MappedRegistryProxy MAPPED_REGISTRY; public static final MappedRegistryProxy MAPPED_REGISTRY;
@ -19,6 +25,11 @@ public class Reflection {
public static final ReferenceProxy REFERENCE; public static final ReferenceProxy REFERENCE;
public static final ChunkMapProxy CHUNKMAP;
public static final HolderSetProxy HOLDER_SET;
public static final BiomeProxy BIOME;
static { static {
ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar(); ReflectionRemapper reflectionRemapper = ReflectionRemapper.forReobfMappingsInPaperJar();
ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper, ReflectionProxyFactory reflectionProxyFactory = ReflectionProxyFactory.create(reflectionRemapper,
@ -27,6 +38,9 @@ public class Reflection {
MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class); MAPPED_REGISTRY = reflectionProxyFactory.reflectionProxy(MappedRegistryProxy.class);
STRUCTURE_MANAGER = reflectionProxyFactory.reflectionProxy(StructureManagerProxy.class); STRUCTURE_MANAGER = reflectionProxyFactory.reflectionProxy(StructureManagerProxy.class);
REFERENCE = reflectionProxyFactory.reflectionProxy(ReferenceProxy.class); REFERENCE = reflectionProxyFactory.reflectionProxy(ReferenceProxy.class);
CHUNKMAP = reflectionProxyFactory.reflectionProxy(ChunkMapProxy.class);
HOLDER_SET = reflectionProxyFactory.reflectionProxy(HolderSetProxy.class);
BIOME = reflectionProxyFactory.reflectionProxy(BiomeProxy.class);
} }
@ -49,4 +63,25 @@ public class Reflection {
@MethodName("bindValue") @MethodName("bindValue")
<T> void invokeBindValue(Reference<T> instance, T value); <T> void invokeBindValue(Reference<T> instance, T value);
} }
@Proxies(ChunkMap.class)
public interface ChunkMapProxy {
@FieldGetter("worldGenContext")
WorldGenContext getWorldGenContext(ChunkMap instance);
@FieldSetter("worldGenContext")
void setWorldGenContext(ChunkMap instance, WorldGenContext worldGenContext);
}
@Proxies(HolderSet.class)
public interface HolderSetProxy {
@MethodName("contents")
<T> List<Holder<T>> invokeContents(HolderSet<T> instance);
}
@Proxies(Biome.class)
public interface BiomeProxy {
@MethodName("getGrassColorFromTexture")
int invokeGrassColorFromTexture(Biome instance);
}
} }

View File

@ -4,6 +4,7 @@ import net.minecraft.core.Registry;
import net.minecraft.core.registries.Registries; import net.minecraft.core.registries.Registries;
import net.minecraft.resources.ResourceKey; import net.minecraft.resources.ResourceKey;
import net.minecraft.server.dedicated.DedicatedServer; import net.minecraft.server.dedicated.DedicatedServer;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.level.biome.Biome; import net.minecraft.world.level.biome.Biome;
import org.bukkit.Bukkit; import org.bukkit.Bukkit;
import org.bukkit.craftbukkit.CraftServer; import org.bukkit.craftbukkit.CraftServer;
@ -15,10 +16,16 @@ public class RegistryFetcher {
DedicatedServer dedicatedserver = craftserver.getServer(); DedicatedServer dedicatedserver = craftserver.getServer();
return dedicatedserver return dedicatedserver
.registryAccess() .registryAccess()
.registryOrThrow(key); .get(key)
.orElseThrow()
.value();
} }
public static Registry<Biome> biomeRegistry() { public static Registry<Biome> biomeRegistry() {
return getRegistry(Registries.BIOME); return getRegistry(Registries.BIOME);
} }
public static Registry<SoundEvent> soundEventRegistry() {
return getRegistry(Registries.SOUND_EVENT);
}
} }

View File

@ -3,27 +3,21 @@ package com.dfsek.terra.bukkit.nms.v1_21.config;
import com.dfsek.tectonic.api.config.template.ConfigTemplate; import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default; import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value; import com.dfsek.tectonic.api.config.template.annotations.Value;
import java.util.List;
import net.minecraft.resources.ResourceLocation; import com.dfsek.terra.api.properties.Properties;
import net.minecraft.sounds.Music; import net.minecraft.sounds.Music;
import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvent;
import net.minecraft.world.entity.npc.VillagerType; import net.minecraft.world.entity.npc.VillagerType;
import net.minecraft.world.level.biome.AmbientAdditionsSettings; import net.minecraft.world.level.biome.AmbientAdditionsSettings;
import net.minecraft.world.level.biome.AmbientMoodSettings; import net.minecraft.world.level.biome.AmbientMoodSettings;
import net.minecraft.world.level.biome.AmbientParticleSettings; import net.minecraft.world.level.biome.AmbientParticleSettings;
import net.minecraft.world.level.biome.Biome.Precipitation;
import net.minecraft.world.level.biome.Biome.TemperatureModifier; import net.minecraft.world.level.biome.Biome.TemperatureModifier;
import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier; import net.minecraft.world.level.biome.BiomeSpecialEffects.GrassColorModifier;
import net.minecraft.world.level.biome.MobSpawnSettings; import net.minecraft.world.level.biome.MobSpawnSettings;
import com.dfsek.terra.api.properties.Properties;
public class VanillaBiomeProperties implements ConfigTemplate, Properties { public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Value("tags")
@Default
private List<ResourceLocation> tags = null;
@Value("colors.grass") @Value("colors.grass")
@Default @Default
private Integer grassColor = null; private Integer grassColor = null;
@ -58,7 +52,7 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Value("climate.precipitation") @Value("climate.precipitation")
@Default @Default
private Boolean precipitation = null; private Boolean precipitation = true;
@Value("climate.temperature") @Value("climate.temperature")
@Default @Default
@ -96,18 +90,18 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
@Default @Default
private VillagerType villagerType = null; private VillagerType villagerType = null;
public List<ResourceLocation> getTags() { public Integer getFogColor() {
return tags; return fogColor;
}
public Integer getFoliageColor() {
return foliageColor;
} }
public Integer getGrassColor() { public Integer getGrassColor() {
return grassColor; return grassColor;
} }
public Integer getFogColor() {
return fogColor;
}
public Integer getWaterColor() { public Integer getWaterColor() {
return waterColor; return waterColor;
} }
@ -116,10 +110,6 @@ public class VanillaBiomeProperties implements ConfigTemplate, Properties {
return waterFogColor; return waterFogColor;
} }
public Integer getFoliageColor() {
return foliageColor;
}
public Integer getSkyColor() { public Integer getSkyColor() {
return skyColor; return skyColor;
} }

View File

@ -8,7 +8,7 @@ dependencies {
shadedApi(project(":common:implementation:base")) shadedApi(project(":common:implementation:base"))
shadedApi("commons-io", "commons-io", Versions.Libraries.Internal.apacheIO) shadedApi("commons-io", "commons-io", Versions.Libraries.Internal.apacheIO)
shadedApi("com.github.Querz", "NBT", Versions.CLI.nbt) shadedApi("com.github.Querz", "NBT", Versions.Libraries.Internal.nbt)
shadedImplementation("info.picocli", "picocli", Versions.CLI.picocli) shadedImplementation("info.picocli", "picocli", Versions.CLI.picocli)
annotationProcessor("info.picocli", "picocli-codegen", Versions.CLI.picocli) annotationProcessor("info.picocli", "picocli-codegen", Versions.CLI.picocli)

View File

@ -26,8 +26,8 @@ dependencies {
modImplementation("net.fabricmc:fabric-loader:${Versions.Mod.fabricLoader}") modImplementation("net.fabricmc:fabric-loader:${Versions.Mod.fabricLoader}")
modImplementation("org.incendo", "cloud-fabric", Versions.Libraries.cloudFabric) modImplementation("org.incendo", "cloud-fabric", Versions.Fabric.cloud)
include("org.incendo", "cloud-fabric", Versions.Libraries.cloudFabric) include("org.incendo", "cloud-fabric", Versions.Fabric.cloud)
modRuntimeOnly("net.fabricmc.fabric-api", "fabric-api", Versions.Fabric.fabricAPI) modRuntimeOnly("net.fabricmc.fabric-api", "fabric-api", Versions.Fabric.fabricAPI)
} }

View File

@ -32,9 +32,9 @@
"terra.common.mixins.json" "terra.common.mixins.json"
], ],
"depends": { "depends": {
"fabricloader": ">=0.16.5", "fabricloader": ">=0.16.7",
"java": ">=21", "java": ">=21",
"minecraft": ">=1.21.1", "minecraft": ">=1.21.3",
"fabric": "*" "fabric": "*"
} }
} }

View File

@ -29,7 +29,7 @@ public class BiomeParticleConfigTemplate implements ObjectTemplate<BiomeParticle
try { try {
return new BiomeParticleConfig( return new BiomeParticleConfig(
ParticleEffectArgumentType.readParameters(new StringReader(particle), ParticleEffectArgumentType.readParameters(new StringReader(particle),
(RegistryWrapper.WrapperLookup) Registries.PARTICLE_TYPE.getReadOnlyWrapper()), (RegistryWrapper.WrapperLookup) Registries.PARTICLE_TYPE),
probability); probability);
} catch(CommandSyntaxException e) { } catch(CommandSyntaxException e) {
throw new RuntimeException(e); throw new RuntimeException(e);

View File

@ -15,6 +15,6 @@ public class EntityTypeTemplate implements ObjectTemplate<EntityType<?>> {
@Override @Override
public EntityType<?> get() { public EntityType<?> get() {
return Registries.ENTITY_TYPE.get(id); return Registries.ENTITY_TYPE.getEntry(id).orElseThrow().value();
} }
} }

View File

@ -15,6 +15,6 @@ public class VillagerTypeTemplate implements ObjectTemplate<VillagerType> {
@Override @Override
public VillagerType get() { public VillagerType get() {
return Registries.VILLAGER_TYPE.get(id); return Registries.VILLAGER_TYPE.getEntry(id).orElseThrow().value();
} }
} }

View File

@ -35,7 +35,6 @@ import net.minecraft.world.StructureWorldAccess;
import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.Biome;
import net.minecraft.world.biome.source.BiomeAccess; import net.minecraft.world.biome.source.BiomeAccess;
import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.GenerationStep.Carver;
import net.minecraft.world.gen.StructureAccessor; import net.minecraft.world.gen.StructureAccessor;
import net.minecraft.world.gen.StructureWeightSampler; import net.minecraft.world.gen.StructureWeightSampler;
import net.minecraft.world.gen.chunk.Blender; import net.minecraft.world.gen.chunk.Blender;
@ -97,7 +96,7 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun
public void populateEntities(ChunkRegion region) { public void populateEntities(ChunkRegion region) {
if(!this.settings.value().mobGenerationDisabled()) { if(!this.settings.value().mobGenerationDisabled()) {
ChunkPos chunkPos = region.getCenterPos(); ChunkPos chunkPos = region.getCenterPos();
RegistryEntry<Biome> registryEntry = region.getBiome(chunkPos.getStartPos().withY(region.getTopY() - 1)); RegistryEntry<Biome> registryEntry = region.getBiome(chunkPos.getStartPos().withY(region.getTopYInclusive() - 1));
ChunkRandom chunkRandom = new ChunkRandom(new CheckedRandom(RandomSeed.getSeed())); ChunkRandom chunkRandom = new ChunkRandom(new CheckedRandom(RandomSeed.getSeed()));
chunkRandom.setPopulationSeed(region.getSeed(), chunkPos.getStartX(), chunkPos.getStartZ()); chunkRandom.setPopulationSeed(region.getSeed(), chunkPos.getStartX(), chunkPos.getStartZ());
SpawnHelper.populateEntities(region, registryEntry, chunkPos, chunkRandom); SpawnHelper.populateEntities(region, registryEntry, chunkPos, chunkRandom);
@ -179,7 +178,7 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun
WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.getMultiNoiseSampler())); WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.getMultiNoiseSampler()));
BiomeProvider biomeProvider = pack.getBiomeProvider(); BiomeProvider biomeProvider = pack.getBiomeProvider();
int min = height.getBottomY(); int min = height.getBottomY();
for(int y = height.getTopY() - 1; y >= min; y--) { for(int y = height.getTopYInclusive() - 1; y >= min; y--) {
if(heightmap if(heightmap
.getBlockPredicate() .getBlockPredicate()
.test((BlockState) delegate.getBlock(properties, x, y, z, biomeProvider))) return y + 1; .test((BlockState) delegate.getBlock(properties, x, y, z, biomeProvider))) return y + 1;
@ -192,14 +191,14 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun
BlockState[] array = new BlockState[height.getHeight()]; BlockState[] array = new BlockState[height.getHeight()];
WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.getMultiNoiseSampler())); WorldProperties properties = MinecraftAdapter.adapt(height, SeedHack.getSeed(noiseConfig.getMultiNoiseSampler()));
BiomeProvider biomeProvider = pack.getBiomeProvider(); BiomeProvider biomeProvider = pack.getBiomeProvider();
for(int y = height.getTopY() - 1; y >= height.getBottomY(); y--) { for(int y = height.getTopYInclusive() - 1; y >= height.getBottomY(); y--) {
array[y - height.getBottomY()] = (BlockState) delegate.getBlock(properties, x, y, z, biomeProvider); array[y - height.getBottomY()] = (BlockState) delegate.getBlock(properties, x, y, z, biomeProvider);
} }
return new VerticalBlockSample(height.getBottomY(), array); return new VerticalBlockSample(height.getBottomY(), array);
} }
@Override @Override
public void getDebugHudText(List<String> text, NoiseConfig noiseConfig, BlockPos pos) { public void appendDebugHudText(List<String> text, NoiseConfig noiseConfig, BlockPos pos) {
} }
@ -215,9 +214,10 @@ public class MinecraftChunkGeneratorWrapper extends net.minecraft.world.gen.chun
logger.debug("Loading world with config pack {}", pack.getID()); logger.debug("Loading world with config pack {}", pack.getID());
} }
@Override @Override
public void carve(ChunkRegion chunkRegion, long seed, NoiseConfig noiseConfig, BiomeAccess world, StructureAccessor structureAccessor, public void carve(ChunkRegion chunkRegion, long seed, NoiseConfig noiseConfig, BiomeAccess biomeAccess,
Chunk chunk, Carver carverStep) { StructureAccessor structureAccessor, Chunk chunk) {
//no op //no op
} }

View File

@ -24,6 +24,7 @@ import net.minecraft.command.argument.ItemStackArgumentType;
import net.minecraft.registry.Registry; import net.minecraft.registry.Registry;
import net.minecraft.registry.RegistryKey; import net.minecraft.registry.RegistryKey;
import net.minecraft.registry.RegistryWrapper.Impl; import net.minecraft.registry.RegistryWrapper.Impl;
import net.minecraft.resource.featuretoggle.FeatureSet;
import net.minecraft.util.Identifier; import net.minecraft.util.Identifier;
import java.util.Optional; import java.util.Optional;
@ -43,14 +44,19 @@ public class MinecraftItemHandle implements ItemHandle {
public Item createItem(String data) { public Item createItem(String data) {
try { try {
return (Item) new ItemStackArgumentType(new CommandRegistryAccess() { return (Item) new ItemStackArgumentType(new CommandRegistryAccess() {
@Override
public FeatureSet getEnabledFeatures() {
return FeatureSet.empty();
}
@Override @Override
public Stream<RegistryKey<? extends Registry<?>>> streamAllRegistryKeys() { public Stream<RegistryKey<? extends Registry<?>>> streamAllRegistryKeys() {
return CommonPlatform.get().getServer().getRegistryManager().streamAllRegistryKeys(); return CommonPlatform.get().getServer().getRegistryManager().streamAllRegistryKeys();
} }
@Override @Override
public <T> Optional<Impl<T>> getOptionalWrapper(RegistryKey<? extends Registry<? extends T>> registryRef) { public <T> Optional<Impl<T>> getOptional(RegistryKey<? extends Registry<? extends T>> registryRef) {
return Optional.of(CommonPlatform.get().getServer().getRegistryManager().getWrapperOrThrow(registryRef)); return Optional.of(CommonPlatform.get().getServer().getRegistryManager().getOrThrow(registryRef));
} }
}).parse(new StringReader(data)).getItem(); }).parse(new StringReader(data)).getItem();
} catch(CommandSyntaxException e) { } catch(CommandSyntaxException e) {
@ -60,7 +66,7 @@ public class MinecraftItemHandle implements ItemHandle {
@Override @Override
public Enchantment getEnchantment(String id) { public Enchantment getEnchantment(String id) {
return (Enchantment) (Object) (CommonPlatform.get().enchantmentRegistry().get(Identifier.tryParse(id))); return (Enchantment) (Object) (CommonPlatform.get().enchantmentRegistry().getEntry(Identifier.tryParse(id)));
} }
@Override @Override

View File

@ -48,7 +48,7 @@ public class MinecraftWorldHandle implements WorldHandle {
". You are advised to perform this rename in your config packs as this translation will be removed in the next major " + ". You are advised to perform this rename in your config packs as this translation will be removed in the next major " +
"version of Terra."); "version of Terra.");
} }
net.minecraft.block.BlockState state = BlockArgumentParser.block(Registries.BLOCK.getReadOnlyWrapper(), data, true) net.minecraft.block.BlockState state = BlockArgumentParser.block(Registries.BLOCK, data, true)
.blockState(); .blockState();
if(state == null) throw new IllegalArgumentException("Invalid data: " + data); if(state == null) throw new IllegalArgumentException("Invalid data: " + data);
return (BlockState) state; return (BlockState) state;
@ -76,6 +76,6 @@ public class MinecraftWorldHandle implements WorldHandle {
if(!id.contains(":")) throw new IllegalArgumentException("Invalid entity identifier " + id); if(!id.contains(":")) throw new IllegalArgumentException("Invalid entity identifier " + id);
Identifier identifier = Identifier.tryParse(id); Identifier identifier = Identifier.tryParse(id);
if(identifier == null) identifier = Identifier.tryParse(id); if(identifier == null) identifier = Identifier.tryParse(id);
return (EntityType) Registries.ENTITY_TYPE.get(identifier); return (EntityType) Registries.ENTITY_TYPE.getEntry(identifier).orElseThrow().value();
} }
} }

View File

@ -54,8 +54,8 @@ public abstract class MobSpawnerBlockEntityMixin extends BlockEntity {
public abstract void setEntityType(net.minecraft.entity.EntityType<?> entityType, Random random); public abstract void setEntityType(net.minecraft.entity.EntityType<?> entityType, Random random);
public EntityType terra$getSpawnedType() { public EntityType terra$getSpawnedType() {
return (EntityType) Registries.ENTITY_TYPE.get( return (EntityType) Registries.ENTITY_TYPE.getEntry(
Identifier.tryParse(((MobSpawnerLogicAccessor) getLogic()).getSpawnEntry().getNbt().getString("id"))); Identifier.tryParse(((MobSpawnerLogicAccessor) getLogic()).getSpawnEntry().getNbt().getString("id"))).orElseThrow();
} }
public void terra$setSpawnedType(@NotNull EntityType creatureType) { public void terra$setSpawnedType(@NotNull EntityType creatureType) {

View File

@ -9,6 +9,7 @@ import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.Shadow;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import com.dfsek.terra.api.block.state.properties.Property; import com.dfsek.terra.api.block.state.properties.Property;
@ -24,7 +25,7 @@ public abstract class PropertyMixin<T> {
private String name; private String name;
@Shadow @Shadow
public abstract Collection<T> getValues(); public abstract List<T> getValues();
@Intrinsic @Intrinsic
public Collection<T> terra$values() { public Collection<T> terra$values() {

View File

@ -49,9 +49,6 @@ public abstract class WorldChunkMixin {
@Nullable @Nullable
public abstract net.minecraft.block.BlockState setBlockState(BlockPos pos, net.minecraft.block.BlockState state, boolean moved); public abstract net.minecraft.block.BlockState setBlockState(BlockPos pos, net.minecraft.block.BlockState state, boolean moved);
@Shadow
public abstract TickSchedulers getTickSchedulers();
public void terra$setBlock(int x, int y, int z, BlockState data, boolean physics) { public void terra$setBlock(int x, int y, int z, BlockState data, boolean physics) {
BlockPos blockPos = new BlockPos(x, y, z); BlockPos blockPos = new BlockPos(x, y, z);
setBlockState(blockPos, (net.minecraft.block.BlockState) data, false); setBlockState(blockPos, (net.minecraft.block.BlockState) data, false);

View File

@ -48,6 +48,6 @@ public abstract class ProtoChunkMixin {
} }
public int terra$getMaxHeight() { public int terra$getMaxHeight() {
return getHeightLimitView().getTopY(); return getHeightLimitView().getTopYInclusive();
} }
} }

View File

@ -19,7 +19,7 @@ package com.dfsek.terra.mod.mixin.implementations.terra.inventory.item;
import net.minecraft.component.ComponentChanges; import net.minecraft.component.ComponentChanges;
import net.minecraft.component.ComponentMap; import net.minecraft.component.ComponentMap;
import net.minecraft.component.ComponentMapImpl; import net.minecraft.component.MergedComponentMap;
import net.minecraft.item.ItemStack; import net.minecraft.item.ItemStack;
import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Implements;
@ -37,7 +37,7 @@ import com.dfsek.terra.api.inventory.item.ItemMeta;
public abstract class ItemStackMixin { public abstract class ItemStackMixin {
@Shadow @Shadow
@Final @Final
private ComponentMapImpl components; private MergedComponentMap components;
@Shadow @Shadow
public abstract int getCount(); public abstract int getCount();

View File

@ -18,6 +18,7 @@
package com.dfsek.terra.mod.mixin.implementations.terra.world; package com.dfsek.terra.mod.mixin.implementations.terra.world;
import net.minecraft.block.FluidBlock; import net.minecraft.block.FluidBlock;
import net.minecraft.entity.SpawnReason;
import net.minecraft.fluid.Fluid; import net.minecraft.fluid.Fluid;
import net.minecraft.util.collection.BoundedRegionArray; import net.minecraft.util.collection.BoundedRegionArray;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
@ -99,7 +100,7 @@ public abstract class ChunkRegionMixin {
} }
public int terraWorld$getMaxHeight() { public int terraWorld$getMaxHeight() {
return world.getTopY(); return world.getTopYInclusive();
} }
@Intrinsic(displace = true) @Intrinsic(displace = true)
@ -125,7 +126,7 @@ public abstract class ChunkRegionMixin {
} }
public Entity terraWorld$spawnEntity(double x, double y, double z, EntityType entityType) { public Entity terraWorld$spawnEntity(double x, double y, double z, EntityType entityType) {
net.minecraft.entity.Entity entity = ((net.minecraft.entity.EntityType<?>) entityType).create(world); net.minecraft.entity.Entity entity = ((net.minecraft.entity.EntityType<?>) entityType).create(world, SpawnReason.CHUNK_GENERATION);
entity.setPos(x, y, z); entity.setPos(x, y, z);
((ChunkRegion) (Object) this).spawnEntity(entity); ((ChunkRegion) (Object) this).spawnEntity(entity);
return (Entity) entity; return (Entity) entity;

View File

@ -17,6 +17,7 @@
package com.dfsek.terra.mod.mixin.implementations.terra.world; package com.dfsek.terra.mod.mixin.implementations.terra.world;
import net.minecraft.entity.SpawnReason;
import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.BlockPos;
import net.minecraft.world.WorldAccess; import net.minecraft.world.WorldAccess;
import org.spongepowered.asm.mixin.Implements; import org.spongepowered.asm.mixin.Implements;
@ -42,7 +43,7 @@ import com.dfsek.terra.mod.util.MinecraftUtil;
@Implements(@Interface(iface = ServerWorld.class, prefix = "terra$")) @Implements(@Interface(iface = ServerWorld.class, prefix = "terra$"))
public abstract class ServerWorldMixin { public abstract class ServerWorldMixin {
public Entity terra$spawnEntity(double x, double y, double z, EntityType entityType) { public Entity terra$spawnEntity(double x, double y, double z, EntityType entityType) {
net.minecraft.entity.Entity entity = ((net.minecraft.entity.EntityType<?>) entityType).create(null); net.minecraft.entity.Entity entity = ((net.minecraft.entity.EntityType<?>) entityType).create(null, SpawnReason.CHUNK_GENERATION);
entity.setPos(x, y, z); entity.setPos(x, y, z);
((net.minecraft.server.world.ServerWorld) (Object) this).spawnEntity(entity); ((net.minecraft.server.world.ServerWorld) (Object) this).spawnEntity(entity);
return (Entity) entity; return (Entity) entity;

View File

@ -1,10 +1,16 @@
package com.dfsek.terra.mod.mixin.lifecycle; package com.dfsek.terra.mod.mixin.lifecycle;
import net.minecraft.registry.CombinedDynamicRegistries;
import net.minecraft.registry.DynamicRegistryManager; import net.minecraft.registry.DynamicRegistryManager;
import net.minecraft.registry.Registry; import net.minecraft.registry.Registry;
import net.minecraft.registry.Registry.PendingTagLoad;
import net.minecraft.registry.RegistryKeys; import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.ReloadableRegistries; import net.minecraft.registry.ReloadableRegistries;
import net.minecraft.registry.ServerDynamicRegistryType;
import net.minecraft.resource.ResourceManager;
import net.minecraft.resource.featuretoggle.FeatureSet;
import net.minecraft.server.DataPackContents; import net.minecraft.server.DataPackContents;
import net.minecraft.server.command.CommandManager;
import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.Biome;
import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
@ -16,6 +22,12 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import com.dfsek.terra.mod.util.MinecraftUtil; import com.dfsek.terra.mod.util.MinecraftUtil;
import com.dfsek.terra.mod.util.TagUtil; import com.dfsek.terra.mod.util.TagUtil;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
@Mixin(DataPackContents.class) @Mixin(DataPackContents.class)
public class DataPackContentsMixin { public class DataPackContentsMixin {
@ -26,12 +38,17 @@ public class DataPackContentsMixin {
/* /*
* #refresh populates all tags in the registries * #refresh populates all tags in the registries
*/ */
@Inject(method = "refresh()V", at = @At("RETURN")) @Inject(method = "reload(Lnet/minecraft/resource/ResourceManager;Lnet/minecraft/registry/CombinedDynamicRegistries;Ljava/util/List;Lnet/minecraft/resource/featuretoggle/FeatureSet;Lnet/minecraft/server/command/CommandManager$RegistrationEnvironment;ILjava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;", at = @At("RETURN"))
private void injectReload(CallbackInfo ci) { private static void injectReload(ResourceManager resourceManager,
DynamicRegistryManager.Immutable dynamicRegistryManager = this.reloadableRegistries.getRegistryManager(); CombinedDynamicRegistries<ServerDynamicRegistryType> dynamicRegistries,
TagUtil.registerWorldPresetTags(dynamicRegistryManager.get(RegistryKeys.WORLD_PRESET)); List<PendingTagLoad<?>> pendingTagLoads, FeatureSet enabledFeatures,
CommandManager.RegistrationEnvironment environment, int functionPermissionLevel,
Executor prepareExecutor,
Executor applyExecutor, CallbackInfoReturnable<CompletableFuture<DataPackContents>> cir) {
DynamicRegistryManager.Immutable dynamicRegistryManager = dynamicRegistries.getCombinedRegistryManager();
TagUtil.registerWorldPresetTags(dynamicRegistryManager.getOrThrow(RegistryKeys.WORLD_PRESET));
Registry<Biome> biomeRegistry = dynamicRegistryManager.get(RegistryKeys.BIOME); Registry<Biome> biomeRegistry = dynamicRegistryManager.getOrThrow(RegistryKeys.BIOME);
TagUtil.registerBiomeTags(biomeRegistry); TagUtil.registerBiomeTags(biomeRegistry);
MinecraftUtil.registerFlora(biomeRegistry); MinecraftUtil.registerFlora(biomeRegistry);
} }

View File

@ -39,7 +39,7 @@ public final class MinecraftAdapter {
@Override @Override
public int getMaxHeight() { public int getMaxHeight() {
return height.getTopY(); return height.getTopYInclusive();
} }
@Override @Override

View File

@ -44,9 +44,8 @@ public final class MinecraftUtil {
} }
public static <T> Optional<RegistryEntry<T>> getEntry(Registry<T> registry, Identifier identifier) { public static <T> Optional<RegistryEntry<T>> getEntry(Registry<T> registry, Identifier identifier) {
return registry.getOrEmpty(identifier) return registry.getOptionalValue(identifier)
.flatMap(registry::getKey) .flatMap(id -> Optional.ofNullable(registry.getEntry(id)));
.flatMap(registry::getEntry);
} }
public static BlockEntity createState(WorldAccess worldAccess, BlockPos pos) { public static BlockEntity createState(WorldAccess worldAccess, BlockPos pos) {
@ -65,9 +64,9 @@ public final class MinecraftUtil {
logger.info("Injecting flora into Terra biomes..."); logger.info("Injecting flora into Terra biomes...");
BiomeUtil.TERRA_BIOME_MAP BiomeUtil.TERRA_BIOME_MAP
.forEach((vb, terraBiomes) -> .forEach((vb, terraBiomes) ->
biomes.getOrEmpty(vb) biomes.getOptionalValue(vb)
.ifPresentOrElse(vanilla -> terraBiomes .ifPresentOrElse(vanilla -> terraBiomes
.forEach(tb -> biomes.getOrEmpty(tb) .forEach(tb -> biomes.getOptionalValue(tb)
.ifPresentOrElse( .ifPresentOrElse(
terra -> { terra -> {
List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf( List<ConfiguredFeature<?, ?>> flowerFeatures = List.copyOf(

View File

@ -40,9 +40,8 @@ public class PresetUtil {
platform.multiNoiseBiomeSourceParameterListRegistry(); platform.multiNoiseBiomeSourceParameterListRegistry();
RegistryEntry<DimensionType> overworldDimensionType = dimensionTypeRegistry.getEntry(DimensionTypes.OVERWORLD).orElseThrow(); RegistryEntry<DimensionType> overworldDimensionType = dimensionTypeRegistry.getEntry(dimensionTypeRegistry.get(DimensionTypes.OVERWORLD));
RegistryEntry<ChunkGeneratorSettings> overworld = chunkGeneratorSettingsRegistry.getEntry(ChunkGeneratorSettings.OVERWORLD) RegistryEntry<ChunkGeneratorSettings> overworld = chunkGeneratorSettingsRegistry.getEntry(chunkGeneratorSettingsRegistry.get(ChunkGeneratorSettings.OVERWORLD));
.orElseThrow();
Identifier generatorID = Identifier.tryParse( Identifier generatorID = Identifier.tryParse(
@ -51,15 +50,13 @@ public class PresetUtil {
PRESETS.add(generatorID); PRESETS.add(generatorID);
RegistryEntry<DimensionType> registryEntry = dimensionTypeRegistry.getEntry(DimensionTypes.THE_NETHER).orElseThrow(); RegistryEntry<DimensionType> registryEntry = dimensionTypeRegistry.getEntry(dimensionTypeRegistry.get(DimensionTypes.THE_NETHER));
RegistryEntry.Reference<MultiNoiseBiomeSourceParameterList> reference = multiNoiseBiomeSourceParameterLists.getEntry( RegistryEntry<MultiNoiseBiomeSourceParameterList> reference = multiNoiseBiomeSourceParameterLists.getEntry(
MultiNoiseBiomeSourceParameterLists.NETHER).orElseThrow(); multiNoiseBiomeSourceParameterLists.get(MultiNoiseBiomeSourceParameterLists.NETHER));
RegistryEntry<ChunkGeneratorSettings> registryEntry2 = chunkGeneratorSettingsRegistry.getEntry(ChunkGeneratorSettings.NETHER) RegistryEntry<ChunkGeneratorSettings> registryEntry2 = chunkGeneratorSettingsRegistry.getEntry(chunkGeneratorSettingsRegistry.get(ChunkGeneratorSettings.NETHER));
.orElseThrow();
RegistryEntry<DimensionType> registryEntry3 = dimensionTypeRegistry.getEntry(DimensionTypes.THE_END).orElseThrow(); RegistryEntry<DimensionType> registryEntry3 = dimensionTypeRegistry.getEntry(dimensionTypeRegistry.get(DimensionTypes.THE_END));
RegistryEntry<ChunkGeneratorSettings> registryEntry4 = chunkGeneratorSettingsRegistry.getEntry(ChunkGeneratorSettings.END) RegistryEntry<ChunkGeneratorSettings> registryEntry4 = chunkGeneratorSettingsRegistry.getEntry(chunkGeneratorSettingsRegistry.get(ChunkGeneratorSettings.END));
.orElseThrow();
TerraBiomeSource biomeSource = new TerraBiomeSource(pack); TerraBiomeSource biomeSource = new TerraBiomeSource(pack);
ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(biomeSource, pack, overworld); ChunkGenerator generator = new MinecraftChunkGeneratorWrapper(biomeSource, pack, overworld);
@ -69,7 +66,7 @@ public class PresetUtil {
new NoiseChunkGenerator(MultiNoiseBiomeSource.create(reference), new NoiseChunkGenerator(MultiNoiseBiomeSource.create(reference),
registryEntry2)); registryEntry2));
DimensionOptions endDimensionOptions = new DimensionOptions(registryEntry3, new NoiseChunkGenerator( DimensionOptions endDimensionOptions = new DimensionOptions(registryEntry3, new NoiseChunkGenerator(
TheEndBiomeSource.createVanilla(platform.biomeRegistry().getReadOnlyWrapper()), registryEntry4)); TheEndBiomeSource.createVanilla(platform.biomeRegistry()), registryEntry4));
WorldPreset preset = createPreset(dimensionOptions, netherDimensionOptions, endDimensionOptions); WorldPreset preset = createPreset(dimensionOptions, netherDimensionOptions, endDimensionOptions);
LOGGER.info("Created world type \"{}\"", generatorID); LOGGER.info("Created world type \"{}\"", generatorID);

View File

@ -1,8 +1,8 @@
package com.dfsek.terra.mod.util; package com.dfsek.terra.mod.util;
import com.google.common.collect.ImmutableMap;
import net.minecraft.registry.Registry; import net.minecraft.registry.Registry;
import net.minecraft.registry.entry.RegistryEntry; import net.minecraft.registry.entry.RegistryEntry;
import net.minecraft.registry.tag.TagGroupLoader.RegistryTags;
import net.minecraft.registry.tag.TagKey; import net.minecraft.registry.tag.TagKey;
import net.minecraft.registry.tag.WorldPresetTags; import net.minecraft.registry.tag.WorldPresetTags;
import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.Biome;
@ -14,6 +14,7 @@ import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors;
public final class TagUtil { public final class TagUtil {
@ -24,11 +25,8 @@ public final class TagUtil {
} }
private static <T> Map<TagKey<T>, List<RegistryEntry<T>>> tagsToMutableMap(Registry<T> registry) { private static <T> Map<TagKey<T>, List<RegistryEntry<T>>> tagsToMutableMap(Registry<T> registry) {
return registry return registry.streamTags().collect(HashMap::new,
.streamTagsAndEntries() (map, tag) -> map.put(tag.getTag(), tag.stream().collect(Collectors.toList())),
.collect(HashMap::new,
(map, pair) ->
map.put(pair.getFirst(), new ArrayList<>(pair.getSecond().stream().toList())),
HashMap::putAll); HashMap::putAll);
} }
@ -46,8 +44,14 @@ public final class TagUtil {
.add(preset), .add(preset),
() -> logger.error("Preset {} does not exist!", id))); () -> logger.error("Preset {} does not exist!", id)));
registry.clearTags(); registry.startTagReload(new RegistryTags<>(registry.getKey(), collect)).apply();
registry.populateTags(ImmutableMap.copyOf(collect));
if(logger.isDebugEnabled()) {
registry.streamEntries()
.map(e -> e.registryKey().getValue() + ": " +
e.streamTags().reduce("", (s, t) -> t.id() + ", " + s, String::concat))
.forEach(logger::debug);
}
} }
public static void registerBiomeTags(Registry<Biome> registry) { public static void registerBiomeTags(Registry<Biome> registry) {
@ -90,8 +94,7 @@ public final class TagUtil {
tb))), tb))),
() -> logger.error("No vanilla biome: {}", vb))); () -> logger.error("No vanilla biome: {}", vb)));
registry.clearTags(); registry.startTagReload(new RegistryTags<>(registry.getKey(), collect)).apply();
registry.populateTags(ImmutableMap.copyOf(collect));
if(logger.isDebugEnabled()) { if(logger.isDebugEnabled()) {
registry.streamEntries() registry.streamEntries()

View File

@ -15,7 +15,7 @@ dependencies {
minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}") minecraft("com.mojang:minecraft:${Versions.Mod.minecraft}")
mappings("net.fabricmc:yarn:${Versions.Mod.yarn}:v2") mappings("net.fabricmc:yarn:${Versions.Mod.yarn}:v2")
modImplementation("org.incendo", "cloud-fabric", Versions.Libraries.cloudFabric) { modImplementation("org.incendo", "cloud-fabric", Versions.Fabric.cloud) {
exclude("net.fabricmc") exclude("net.fabricmc")
exclude("net.fabricmc.fabric-api") exclude("net.fabricmc.fabric-api")
} }

View File

@ -0,0 +1,27 @@
package com.dfsek.terra.lifecycle.mixin.lifecycle;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.mod.CommonPlatform;
import com.dfsek.terra.mod.ModPlatform;
import net.minecraft.client.gui.screen.world.CreateWorldScreen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import static com.dfsek.terra.lifecycle.util.LifecycleUtil.initialized;
@Mixin(CreateWorldScreen.class)
public class CreateWorldScreenMixin {
@Inject(method = "onCloseScreen()V", at = @At("HEAD"))
public void onClose(CallbackInfo ci) {
ModPlatform platform = CommonPlatform.get();
platform.getRawConfigRegistry().clear();
initialized = false;
}
}

View File

@ -1,5 +1,8 @@
package com.dfsek.terra.lifecycle.mixin.lifecycle; package com.dfsek.terra.lifecycle.mixin.lifecycle;
import com.dfsek.terra.mod.CommonPlatform;
import com.dfsek.terra.mod.ModPlatform;
import com.mojang.datafixers.DataFixer; import com.mojang.datafixers.DataFixer;
import net.minecraft.resource.ResourcePackManager; import net.minecraft.resource.ResourcePackManager;
import net.minecraft.server.MinecraftServer; import net.minecraft.server.MinecraftServer;
@ -34,6 +37,8 @@ public class MinecraftServerMixin {
@Inject(method = "shutdown()V", at = @At("RETURN")) @Inject(method = "shutdown()V", at = @At("RETURN"))
private void injectShutdown(CallbackInfo ci) { private void injectShutdown(CallbackInfo ci) {
ModPlatform platform = CommonPlatform.get();
platform.getRawConfigRegistry().clear();
initialized = false; initialized = false;
} }
} }

View File

@ -39,8 +39,7 @@ public class RegistryLoaderMixin {
private static Logger LOGGER; private static Logger LOGGER;
@Redirect( @Redirect(
method = "load(Lnet/minecraft/registry/RegistryLoader$RegistryLoadable;Lnet/minecraft/registry/DynamicRegistryManager;" + method = "load(Lnet/minecraft/registry/RegistryLoader$RegistryLoadable;Ljava/util/List;Ljava/util/List;)Lnet/minecraft/registry/DynamicRegistryManager$Immutable;",
"Ljava/util/List;)Lnet/minecraft/registry/DynamicRegistryManager$Immutable;",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V", target = "Ljava/util/List;forEach(Ljava/util/function/Consumer;)V",

View File

@ -1,7 +1,8 @@
package com.dfsek.terra.lifecycle.mixin.lifecycle; package com.dfsek.terra.lifecycle.mixin.lifecycle;
import net.minecraft.registry.DynamicRegistryManager; import net.minecraft.registry.CombinedDynamicRegistries;
import net.minecraft.registry.RegistryKeys; import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.ServerDynamicRegistryType;
import net.minecraft.server.SaveLoading; import net.minecraft.server.SaveLoading;
import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.At;
@ -18,13 +19,11 @@ public class SaveLoadingMixin {
"Ljava/util/concurrent/CompletableFuture;", "Ljava/util/concurrent/CompletableFuture;",
at = @At( at = @At(
value = "INVOKE", value = "INVOKE",
target = "Lnet/minecraft/registry/RegistryLoader;loadFromResource(Lnet/minecraft/resource/ResourceManager;" + target = "Lnet/minecraft/server/DataPackContents;reload(Lnet/minecraft/resource/ResourceManager;Lnet/minecraft/registry/CombinedDynamicRegistries;Ljava/util/List;Lnet/minecraft/resource/featuretoggle/FeatureSet;Lnet/minecraft/server/command/CommandManager$RegistrationEnvironment;ILjava/util/concurrent/Executor;Ljava/util/concurrent/Executor;)Ljava/util/concurrent/CompletableFuture;"),
"Lnet/minecraft/registry/DynamicRegistryManager;Ljava/util/List;)" +
"Lnet/minecraft/registry/DynamicRegistryManager$Immutable;"),
index = 1 index = 1
) )
private static DynamicRegistryManager grabManager(DynamicRegistryManager registryManager) { private static CombinedDynamicRegistries<ServerDynamicRegistryType> grabManager(CombinedDynamicRegistries<ServerDynamicRegistryType> dynamicRegistries) {
MinecraftUtil.registerFlora(registryManager.get(RegistryKeys.BIOME)); MinecraftUtil.registerFlora(dynamicRegistries.getCombinedRegistryManager().getOrThrow(RegistryKeys.BIOME));
return registryManager; return dynamicRegistries;
} }
} }

View File

@ -53,7 +53,7 @@ public final class LifecycleBiomeUtil {
if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) { if(pack.getContext().get(PreLoadCompatibilityOptions.class).useVanillaBiomes()) {
((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(registry.getEntry(vanilla).orElseThrow()); ((ProtoPlatformBiome) biome.getPlatformBiome()).setDelegate(registry.getEntry(registry.get(vanilla)));
} else { } else {
VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class); VanillaBiomeProperties vanillaBiomeProperties = biome.getContext().get(VanillaBiomeProperties.class);

View File

@ -13,6 +13,7 @@
"lifecycle.SaveLoadingMixin" "lifecycle.SaveLoadingMixin"
], ],
"client": [ "client": [
"lifecycle.CreateWorldScreenMixin"
], ],
"server": [ "server": [
], ],