mirror of
https://github.com/PolyhedralDev/Terra.git
synced 2026-11-30 09:55:32 +00:00
feat: build Bukkit biomes, dimensions and timelines from environment attributes
This commit is contained in:
1 parent
44408a1b72
commit
bfa126bc12
85 files changed
+3191
-1621
No files matched your search
+71
@@ -0,0 +1,71 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
|
||||
|
||||
public final class BiomeTags {
|
||||
private static final Logger logger = LoggerFactory.getLogger(BiomeTags.class);
|
||||
|
||||
private BiomeTags() {
|
||||
|
||||
}
|
||||
|
||||
public record PlatformTagSource(AttributeReport report, String config, Set<RegistryKey> tags) { }
|
||||
|
||||
public static void addTerraBiomes(Map<TagKey<Biome>, List<Holder<Biome>>> collect,
|
||||
Function<Identifier, Optional<Holder<Biome>>> lookup,
|
||||
Map<Identifier, List<Identifier>> byParent, Map<Identifier, PlatformTagSource> platformTags) {
|
||||
byParent.forEach((vb, terraBiomes) ->
|
||||
lookup.apply(vb).ifPresentOrElse(
|
||||
vanilla -> terraBiomes.forEach(tb -> lookup.apply(tb).ifPresentOrElse(
|
||||
terra -> {
|
||||
logger.debug(vanilla.unwrapKey().orElseThrow().identifier() + " (vanilla for " +
|
||||
terra.unwrapKey().orElseThrow().identifier() + ": " + vanilla.tags().toList());
|
||||
vanilla.tags().forEach(tag -> collect.computeIfAbsent(tag, t -> new ArrayList<>()).add(terra));
|
||||
},
|
||||
() -> logger.error("No such biome: {}", tb))),
|
||||
() -> logger.error("No vanilla biome: {}", vb)));
|
||||
|
||||
Set<TagKey<Biome>> existing = new HashSet<>(collect.keySet());
|
||||
platformTags.forEach((tb, source) -> {
|
||||
if(source.tags().isEmpty()) return;
|
||||
Optional<Holder<Biome>> terra = lookup.apply(tb);
|
||||
if(terra.isEmpty()) {
|
||||
logger.error("No such biome: {}", tb);
|
||||
return;
|
||||
}
|
||||
for(RegistryKey key : source.tags()) {
|
||||
Identifier id;
|
||||
try {
|
||||
id = VanillaIds.identifier(key);
|
||||
} catch(IllegalArgumentException e) {
|
||||
source.report().ignored(source.config(), key.toString(), e.getMessage());
|
||||
continue;
|
||||
}
|
||||
TagKey<Biome> tag = TagKey.create(Registries.BIOME, id);
|
||||
if(!existing.contains(tag) && id.getNamespace().equals(Identifier.DEFAULT_NAMESPACE)) {
|
||||
source.report().tagCreated(source.config(), key.toString());
|
||||
}
|
||||
List<Holder<Biome>> biomes = collect.computeIfAbsent(tag, t -> new ArrayList<>());
|
||||
if(!biomes.contains(terra.get())) biomes.add(terra.get());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.core.HolderGetter;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeParents;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
import com.dfsek.terra.world.attribute.platform.ParentEntryHolder;
|
||||
import com.dfsek.terra.world.attribute.platform.ParentFold;
|
||||
|
||||
|
||||
public final class MinecraftAttributeParents implements AttributeParents {
|
||||
private static final String PACK_CONFIG = "pack.yml";
|
||||
private static final String VANILLA = "vanilla";
|
||||
private static final String VANILLA_GENERATION = "vanilla-generation";
|
||||
private static final PackParents[] NO_PACKS = new PackParents[0];
|
||||
|
||||
private final AttributeHandle handle;
|
||||
// Replaced, never mutated: a read sees one load's context and packs together.
|
||||
private volatile State state = new State(null, NO_PACKS, 0);
|
||||
|
||||
public MinecraftAttributeParents(AttributeHandle handle) {
|
||||
this.handle = Objects.requireNonNull(handle, "handle");
|
||||
}
|
||||
|
||||
public synchronized void beginLoad(VanillaContext context) {
|
||||
state = new State(Objects.requireNonNull(context, "context"), NO_PACKS, 0);
|
||||
MinecraftTimelines.clear();
|
||||
}
|
||||
|
||||
public synchronized void clearPacks() {
|
||||
state = new State(state.context(), NO_PACKS, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Old packs keep their parents until {@link #endPackReload}; worlds may still be generating with them.
|
||||
*/
|
||||
public synchronized void beginPackReload() {
|
||||
State current = state;
|
||||
state = new State(current.context(), current.packs(), current.packs().length);
|
||||
}
|
||||
|
||||
public synchronized void endPackReload() {
|
||||
State current = state;
|
||||
state = new State(current.context(), Arrays.copyOfRange(current.packs(), current.reloadedFrom(), current.packs().length), 0);
|
||||
}
|
||||
|
||||
public @Nullable VanillaContext context() {
|
||||
return state.context();
|
||||
}
|
||||
|
||||
public PackParents prepare(ConfigPack pack, Optional<PackAttributes> attributes, AttributeReport report) {
|
||||
return prepare(pack, attributes, report, BuiltinDimensionTypes.OVERWORLD);
|
||||
}
|
||||
|
||||
public synchronized PackParents prepare(ConfigPack pack, Optional<PackAttributes> attributes, AttributeReport report,
|
||||
ResourceKey<DimensionType> defaultDimension) {
|
||||
State current = state;
|
||||
VanillaContext context = current.context();
|
||||
if(context == null) throw new IllegalStateException("no registry load has begun");
|
||||
ResourceKey<DimensionType> fallback = context.dimensionTypes().get(defaultDimension).isPresent()
|
||||
? defaultDimension
|
||||
: BuiltinDimensionTypes.OVERWORLD;
|
||||
PackAttributes packAttributes = attributes.orElse(null);
|
||||
PackParents[] prepared = current.packs();
|
||||
for(int i = current.reloadedFrom(); i < prepared.length; i++) {
|
||||
PackParents candidate = prepared[i];
|
||||
if(candidate.pack() == pack && candidate.attributes() == packAttributes
|
||||
&& (!candidate.dimensionDefaulted() || candidate.dimensionKey().equals(fallback))) return candidate;
|
||||
}
|
||||
|
||||
ResourceKey<DimensionType> named = parent(packAttributes, VANILLA, Registries.DIMENSION_TYPE, context.dimensionTypes(),
|
||||
"dimension type", report);
|
||||
ResourceKey<DimensionType> dimensionKey = named == null ? fallback : named;
|
||||
ResourceKey<NoiseGeneratorSettings> namedGeneration = parent(packAttributes, VANILLA_GENERATION, Registries.NOISE_SETTINGS,
|
||||
context.noiseSettings(), "noise settings", report);
|
||||
ResourceKey<NoiseGeneratorSettings> generationKey = namedGeneration == null ? NoiseGeneratorSettings.OVERWORLD : namedGeneration;
|
||||
DimensionType dimension = context.dimensionTypes().getOrThrow(dimensionKey).value();
|
||||
NoiseGeneratorSettings generation = context.noiseSettings().getOrThrow(generationKey).value();
|
||||
|
||||
PackAttributeTable table = PackAttributeTable.of(pack.getRegistry(Attribute.REGISTRY_TYPE));
|
||||
VanillaParentReader reader = new VanillaParentReader(handle, context);
|
||||
AttributeSlots dimensionSlots = reader.dimension(dimension, table, parentSkipped(report, dimensionKey.identifier().toString()));
|
||||
AttributeSlots generationSlots = reader.generation(generation, table);
|
||||
|
||||
PackParents parents = new PackParents(pack, dimensionKey, named == null, dimension, generationKey, generation, table,
|
||||
fold(table, dimensionSlots, generationSlots), packAttributes, report, reader);
|
||||
PackParents[] packs = Arrays.copyOf(prepared, prepared.length + 1);
|
||||
packs[packs.length - 1] = parents;
|
||||
state = new State(context, packs, current.reloadedFrom());
|
||||
return parents;
|
||||
}
|
||||
|
||||
public AttributeSlots biomeEntries(PackParents pack, ResourceKey<Biome> key, Biome biome) {
|
||||
AttributeSlots cached = pack.biomeEntries().get(key);
|
||||
if(cached != null) return cached;
|
||||
// Warn outside the map's bin lock, and only for the read that gets cached.
|
||||
record Skipped(Attribute<?> attribute, String reason) { }
|
||||
List<Skipped> skipped = new ArrayList<>(0);
|
||||
AttributeSlots read = pack.reader().biome(key, biome, pack.table(),
|
||||
(attribute, reason) -> skipped.add(new Skipped(attribute, reason)));
|
||||
AttributeSlots raced = pack.biomeEntries().putIfAbsent(key, read);
|
||||
if(raced != null) return raced;
|
||||
BiConsumer<Attribute<?>, String> report = parentSkipped(pack.report(), key.identifier().toString());
|
||||
for(Skipped s : skipped) report.accept(s.attribute(), s.reason());
|
||||
return read;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable AttributeEntry<T> biomeOrNull(com.dfsek.terra.api.world.biome.Biome biome, Attribute<T> attribute) {
|
||||
return biome.getPlatformBiome() instanceof ParentEntryHolder holder ? holder.parentEntries().get(attribute) : null;
|
||||
}
|
||||
|
||||
// Hot path: no allocation, hashing or boxing.
|
||||
@Override
|
||||
public <T> @Nullable AttributeEntry<T> packOrNull(PackAttributes pack, Attribute<T> attribute) {
|
||||
PackParents[] packs = state.packs();
|
||||
for(PackParents prepared : packs) {
|
||||
if(prepared.attributes() == pack) return prepared.packEntries().get(attribute);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static <T> @Nullable ResourceKey<T> parent(@Nullable PackAttributes attributes, String configKey,
|
||||
ResourceKey<? extends Registry<T>> registry, HolderGetter<T> getter,
|
||||
String what, AttributeReport report) {
|
||||
RegistryKey id = attributes == null ? null : attributes.parents().get(configKey);
|
||||
if(id == null) return null;
|
||||
ResourceKey<T> key;
|
||||
try {
|
||||
key = ResourceKey.create(registry, VanillaIds.identifier(id));
|
||||
} catch(IllegalArgumentException e) {
|
||||
report.ignored(PACK_CONFIG, configKey, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
if(getter.get(key).isPresent()) return key;
|
||||
report.ignored(PACK_CONFIG, configKey, "no such " + what + " \"" + key.identifier() + "\"");
|
||||
return null;
|
||||
}
|
||||
|
||||
private AttributeSlots fold(PackAttributeTable table, AttributeSlots dimension, AttributeSlots generation) {
|
||||
List<Attribute<?>> attributes = new ArrayList<>();
|
||||
for(PackAttributeTable.Bound bound : table.environment()) attributes.add(bound.attribute());
|
||||
for(PackAttributeTable.Field field : table.dimension()) attributes.add(field.attribute());
|
||||
if(table.seaLevel() != null) attributes.add(table.seaLevel());
|
||||
if(table.mobGeneration() != null) attributes.add(table.mobGeneration());
|
||||
return ParentFold.fold(handle, attributes, dimension, generation);
|
||||
}
|
||||
|
||||
static BiConsumer<Attribute<?>, String> parentSkipped(AttributeReport report, String parent) {
|
||||
return (attribute, reason) -> report.attributeSkipped(PACK_CONFIG, attribute.getRegistryKey().toString(),
|
||||
"vanilla parent \"" + parent + "\": " + reason);
|
||||
}
|
||||
|
||||
|
||||
// reloadedFrom: the first pack prepared since a pack reload began, or 0 outside one.
|
||||
private record State(@Nullable VanillaContext context, PackParents[] packs, int reloadedFrom) { }
|
||||
}
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeMap;
|
||||
import net.minecraft.world.entity.npc.villager.VillagerType;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeGenerationSettings;
|
||||
import net.minecraft.world.level.biome.BiomeSpecialEffects;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
import com.dfsek.terra.world.attribute.platform.ParentEntryHolder;
|
||||
|
||||
|
||||
public final class MinecraftBiomeFactory {
|
||||
private final AttributeHandle handle;
|
||||
private final VanillaContext context;
|
||||
private final VanillaAttributeMaps maps;
|
||||
|
||||
public MinecraftBiomeFactory(AttributeHandle handle, VanillaContext context) {
|
||||
this.handle = Objects.requireNonNull(handle, "handle");
|
||||
this.context = Objects.requireNonNull(context, "context");
|
||||
this.maps = new VanillaAttributeMaps(handle, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code terraBiome}'s parent entries must already be set from {@link MinecraftAttributeParents#biomeEntries}.
|
||||
*/
|
||||
public Built create(ResourceKey<Biome> parentKey, Biome parent, com.dfsek.terra.api.world.biome.Biome terraBiome, PackParents pack,
|
||||
AttributeReport report, BiomeGenerationSettings generation) {
|
||||
Objects.requireNonNull(generation, "generation");
|
||||
String config = terraBiome.getID();
|
||||
PackAttributes attributes = pack.attributes();
|
||||
PackAttributeTable table = pack.table();
|
||||
|
||||
Biome.ClimateSettings climate = parent.climateSettings;
|
||||
BiomeSpecialEffects effects = parent.getSpecialEffects();
|
||||
EnvironmentAttributeMap environment = parent.getAttributes();
|
||||
ResourceKey<VillagerType> villagerType = null;
|
||||
if(attributes != null) {
|
||||
climate = fields(Biome.ClimateSettings.CODEC.codec(), climate, table.climate(), attributes, terraBiome, config, report);
|
||||
effects = fields(BiomeSpecialEffects.CODEC, effects, table.effects(), attributes, terraBiome, config, report);
|
||||
environment = environment(environment, table, attributes, terraBiome, config, report);
|
||||
if(table.villagerType() != null) villagerType = villagerType(table.villagerType(), attributes, terraBiome, config, report);
|
||||
for(Attribute<?> unapplied : table.unapplied()) {
|
||||
if(attributes.biomeEntryOrNull(unapplied, terraBiome) != null) report.notApplied(unapplied.getRegistryKey().toString());
|
||||
}
|
||||
}
|
||||
if(villagerType == null) villagerType = Objects.requireNonNullElse(context.villagerTypes().apply(parentKey), VillagerType.PLAINS);
|
||||
|
||||
Biome biome = new Biome.BiomeBuilder()
|
||||
.hasPrecipitation(climate.hasPrecipitation())
|
||||
.temperature(climate.temperature())
|
||||
.temperatureAdjustment(climate.temperatureModifier())
|
||||
.downfall(climate.downfall())
|
||||
.specialEffects(effects)
|
||||
.putAttributes(environment)
|
||||
.generationSettings(generation)
|
||||
.build();
|
||||
return new Built(biome, villagerType);
|
||||
}
|
||||
|
||||
private <V> V fields(Codec<V> codec, V parent, List<PackAttributeTable.Field> fields, PackAttributes attributes,
|
||||
com.dfsek.terra.api.world.biome.Biome terraBiome, String config, AttributeReport report) {
|
||||
if(fields.isEmpty()) return parent;
|
||||
Map<?, ?> original = (Map<?, ?>) VanillaCodecs.encode(codec, parent, context.ops());
|
||||
Map<Object, Object> all = new LinkedHashMap<>(original);
|
||||
for(PackAttributeTable.Field field : fields) set(all, field, attributes, terraBiome);
|
||||
// Parsing it again would give colours an opaque alpha.
|
||||
if(all.equals(original)) return parent;
|
||||
try {
|
||||
return VanillaCodecs.parse(codec, all, context.ops());
|
||||
} catch(DecodeException whole) {
|
||||
V value = parent;
|
||||
Map<Object, Object> accepted = new LinkedHashMap<>(original);
|
||||
for(PackAttributeTable.Field field : fields) {
|
||||
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
|
||||
set(trial, field, attributes, terraBiome);
|
||||
if(trial.equals(accepted)) continue;
|
||||
try {
|
||||
value = VanillaCodecs.parse(codec, trial, context.ops());
|
||||
accepted = trial;
|
||||
} catch(DecodeException e) {
|
||||
report.attributeSkipped(config, field.attribute().getRegistryKey().toString(), e.getMessage());
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
private static void set(Map<Object, Object> fields, PackAttributeTable.Field field, PackAttributes attributes,
|
||||
com.dfsek.terra.api.world.biome.Biome terraBiome) {
|
||||
Object value = resolveEncoded(field.attribute(), attributes, terraBiome);
|
||||
if(value == null) {
|
||||
fields.remove(field.name());
|
||||
} else {
|
||||
fields.put(field.name(), value);
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> @Nullable Object resolveEncoded(Attribute<T> attribute, PackAttributes attributes,
|
||||
com.dfsek.terra.api.world.biome.Biome biome) {
|
||||
T value = attributes.resolve(attribute, biome);
|
||||
return value == null ? null : attribute.type().encode(value);
|
||||
}
|
||||
|
||||
private EnvironmentAttributeMap environment(EnvironmentAttributeMap parent, PackAttributeTable table, PackAttributes attributes,
|
||||
com.dfsek.terra.api.world.biome.Biome terraBiome, String config,
|
||||
AttributeReport report) {
|
||||
AttributeSlots parentSlots = terraBiome.getPlatformBiome() instanceof ParentEntryHolder holder
|
||||
? holder.parentEntries()
|
||||
: AttributeSlots.EMPTY;
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
for(PackAttributeTable.Bound bound : table.environment()) {
|
||||
AttributeEntry<?> entry = entry(bound.attribute(), parentSlots, attributes, terraBiome);
|
||||
if(entry != null) entries.put(bound.attribute(), entry);
|
||||
}
|
||||
if(entries.isEmpty()) return parent;
|
||||
return maps.toVanilla(parent, entries, true,
|
||||
(attribute, reason) -> report.attributeSkipped(config, attribute.getRegistryKey().toString(), reason));
|
||||
}
|
||||
|
||||
private <T> @Nullable AttributeEntry<T> entry(Attribute<T> attribute, AttributeSlots parentSlots, PackAttributes attributes,
|
||||
com.dfsek.terra.api.world.biome.Biome terraBiome) {
|
||||
AttributeEntry<T> entry = attributes.biomeEntryOrNull(attribute, terraBiome);
|
||||
if(entry == null) return null;
|
||||
return handle.compose(attribute, parentSlots.get(attribute), entry)
|
||||
.orElseGet(() -> AttributeEntry.override(attributes.resolve(attribute, terraBiome)));
|
||||
}
|
||||
|
||||
private static @Nullable ResourceKey<VillagerType> villagerType(Attribute<?> attribute, PackAttributes attributes,
|
||||
com.dfsek.terra.api.world.biome.Biome terraBiome, String config,
|
||||
AttributeReport report) {
|
||||
Object encoded = resolveEncoded(attribute, attributes, terraBiome);
|
||||
if(encoded == null) return null;
|
||||
String key = attribute.getRegistryKey().toString();
|
||||
Identifier id;
|
||||
try {
|
||||
id = VanillaIds.identifier(RegistryKey.parseNamespaced(String.valueOf(encoded)));
|
||||
} catch(IllegalArgumentException e) {
|
||||
report.attributeSkipped(config, key, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
ResourceKey<VillagerType> type = ResourceKey.create(Registries.VILLAGER_TYPE, id);
|
||||
if(BuiltInRegistries.VILLAGER_TYPE.containsKey(type)) return type;
|
||||
report.attributeSkipped(config, key, "no such villager type \"" + id + "\"");
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public record Built(Biome biome, ResourceKey<VillagerType> villagerType) { }
|
||||
}
|
||||
+188
@@ -0,0 +1,188 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeMap;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
|
||||
|
||||
public final class MinecraftDimensionFactory {
|
||||
private static final String TERRA = "terra";
|
||||
private static final String PACK_CONFIG = "pack.yml";
|
||||
private static final String ATTRIBUTES = "attributes";
|
||||
private static final String TIMELINES = "timelines";
|
||||
private static final String SCHEDULES = "schedules";
|
||||
private static final int DEFAULT_SPAWN_HEIGHT = 64;
|
||||
|
||||
private final AttributeHandle handle;
|
||||
private final VanillaContext context;
|
||||
private final VanillaAttributeMaps maps;
|
||||
|
||||
public MinecraftDimensionFactory(AttributeHandle handle, VanillaContext context) {
|
||||
this.handle = Objects.requireNonNull(handle, "handle");
|
||||
this.context = Objects.requireNonNull(context, "context");
|
||||
this.maps = new VanillaAttributeMaps(handle, context);
|
||||
}
|
||||
|
||||
public DimensionType create(PackParents pack, @Nullable TimelineRef timelines) {
|
||||
DimensionType parent = pack.dimension();
|
||||
PackAttributes attributes = pack.attributes();
|
||||
PackAttributeTable table = pack.table();
|
||||
AttributeReport report = pack.report();
|
||||
|
||||
Map<?, ?> original = (Map<?, ?>) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, parent, context.ops());
|
||||
Map<Object, Object> all = new LinkedHashMap<>(original);
|
||||
if(attributes != null) {
|
||||
for(PackAttributeTable.Field field : table.dimension()) set(all, field, pack);
|
||||
all.put(ATTRIBUTES, environment(parent.attributes(), pack, attributes, report));
|
||||
for(Attribute<?> unapplied : table.unapplied()) {
|
||||
if(attributes.entries().get(unapplied.key()).isPresent()) report.notApplied(unapplied.getRegistryKey().toString());
|
||||
}
|
||||
}
|
||||
if(timelines != null) all.put(TIMELINES, timelines.encoded());
|
||||
if(all.equals(original)) return copy(parent);
|
||||
|
||||
DimensionType built;
|
||||
try {
|
||||
built = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, all, context.ops());
|
||||
} catch(DecodeException whole) {
|
||||
built = fieldByField(parent, original, all, table.dimension(), pack, timelines, report);
|
||||
}
|
||||
// Terra may encode a field in another number type, e.g. coordinate_scale as a float.
|
||||
return original.equals(VanillaCodecs.encode(DimensionType.DIRECT_CODEC, built, context.ops())) ? copy(parent) : built;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fabric saves this ID in the world: it must not depend on the pack's {@code vanilla} parent. Overworld keeps
|
||||
* {@code terra:<pack>} for worlds from older Terra versions.
|
||||
*/
|
||||
public static Identifier typeId(ConfigPack pack, ResourceKey<DimensionType> base, boolean baseValuesApplied) {
|
||||
String id = pack.getID().toLowerCase(Locale.ROOT);
|
||||
if(!baseValuesApplied && BuiltinDimensionTypes.OVERWORLD.equals(base)) return Identifier.fromNamespaceAndPath(TERRA, id);
|
||||
Identifier key = base.identifier();
|
||||
return Identifier.fromNamespaceAndPath(TERRA, id + "/" + key.getNamespace() + "/" + key.getPath());
|
||||
}
|
||||
|
||||
// A registry refuses the same value under a second key.
|
||||
private static DimensionType copy(DimensionType parent) {
|
||||
return new DimensionType(parent.hasFixedTime(), parent.hasSkyLight(), parent.hasCeiling(), parent.hasEnderDragonFight(),
|
||||
parent.coordinateScale(), parent.minY(), parent.height(), parent.logicalHeight(), parent.infiniburn(), parent.ambientLight(),
|
||||
parent.monsterSettings(), parent.skybox(), parent.cardinalLightType(), parent.attributes(), parent.timelines(),
|
||||
parent.defaultClock());
|
||||
}
|
||||
|
||||
private DimensionType fieldByField(DimensionType parent, Map<?, ?> original, Map<Object, Object> all,
|
||||
List<PackAttributeTable.Field> fields, PackParents pack,
|
||||
@Nullable TimelineRef timelines, AttributeReport report) {
|
||||
PackAttributes attributes = pack.attributes();
|
||||
DimensionType value = parent;
|
||||
Map<Object, Object> accepted = new LinkedHashMap<>(original);
|
||||
if(all.containsKey(ATTRIBUTES)) {
|
||||
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
|
||||
trial.put(ATTRIBUTES, all.get(ATTRIBUTES));
|
||||
try {
|
||||
value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops());
|
||||
accepted = trial;
|
||||
} catch(DecodeException e) {
|
||||
report.ignored(PACK_CONFIG, ATTRIBUTES, e.getMessage());
|
||||
}
|
||||
}
|
||||
if(attributes != null) {
|
||||
for(PackAttributeTable.Field field : fields) {
|
||||
if(attributes.entries().get(field.attribute().key()).isEmpty()) continue;
|
||||
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
|
||||
set(trial, field, pack);
|
||||
if(trial.equals(accepted)) continue;
|
||||
try {
|
||||
value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops());
|
||||
accepted = trial;
|
||||
} catch(DecodeException e) {
|
||||
report.attributeSkipped(PACK_CONFIG, field.attribute().getRegistryKey().toString(), e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
if(timelines != null) {
|
||||
Map<Object, Object> trial = new LinkedHashMap<>(accepted);
|
||||
trial.put(TIMELINES, all.get(TIMELINES));
|
||||
try {
|
||||
value = VanillaCodecs.parse(DimensionType.DIRECT_CODEC, trial, context.ops());
|
||||
} catch(DecodeException e) {
|
||||
report.ignored(PACK_CONFIG, SCHEDULES, e.getMessage());
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private void set(Map<Object, Object> fields, PackAttributeTable.Field field, PackParents pack) {
|
||||
Object value = resolveEncoded(field.attribute(), pack);
|
||||
if(value == null) {
|
||||
fields.remove(field.name());
|
||||
} else {
|
||||
fields.put(field.name(), value);
|
||||
}
|
||||
}
|
||||
|
||||
private <T> @Nullable Object resolveEncoded(Attribute<T> attribute, PackParents pack) {
|
||||
T value = pack.resolvePack(handle, attribute);
|
||||
return value == null ? null : attribute.type().encode(value);
|
||||
}
|
||||
|
||||
private Object environment(EnvironmentAttributeMap parent, PackParents pack, PackAttributes attributes, AttributeReport report) {
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
for(PackAttributeTable.Bound bound : pack.table().environment()) {
|
||||
AttributeEntry<?> entry = entry(bound.attribute(), pack, attributes);
|
||||
if(entry != null) entries.put(bound.attribute(), entry);
|
||||
}
|
||||
EnvironmentAttributeMap map = entries.isEmpty() ? parent : maps.toVanilla(parent, entries, false,
|
||||
(attribute, reason) -> report.attributeSkipped(PACK_CONFIG, attribute.getRegistryKey().toString(), reason));
|
||||
return VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops());
|
||||
}
|
||||
|
||||
private <T> @Nullable AttributeEntry<T> entry(Attribute<T> attribute, PackParents pack, PackAttributes attributes) {
|
||||
Optional<AttributeEntry<T>> entry = attributes.entries().get(attribute.key());
|
||||
if(entry.isEmpty()) return null;
|
||||
return handle.compose(attribute, pack.packEntries().get(attribute), entry.get())
|
||||
.orElseGet(() -> AttributeEntry.override(pack.resolvePack(handle, attribute)));
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry
|
||||
public WorldSettings worldSettings(PackParents pack, DimensionType dimension) {
|
||||
PackAttributes attributes = pack.attributes();
|
||||
PackAttributeTable table = pack.table();
|
||||
int minY = dimension.minY();
|
||||
int height = dimension.height();
|
||||
int seaLevel = pack.generation().seaLevel();
|
||||
boolean mobGeneration = !pack.generation().disableMobGeneration();
|
||||
int spawnHeight = DEFAULT_SPAWN_HEIGHT;
|
||||
if(attributes != null) {
|
||||
seaLevel = intValue(table.seaLevel(), pack, seaLevel);
|
||||
spawnHeight = intValue(table.spawnHeight(), pack, spawnHeight);
|
||||
if(table.mobGeneration() != null && resolveEncoded(table.mobGeneration(), pack) instanceof Boolean value) {
|
||||
mobGeneration = value;
|
||||
}
|
||||
}
|
||||
return new WorldSettings(minY, height, seaLevel, mobGeneration, spawnHeight);
|
||||
}
|
||||
|
||||
private int intValue(@Nullable Attribute<?> attribute, PackParents pack, int fallback) {
|
||||
if(attribute == null) return fallback;
|
||||
return resolveEncoded(attribute, pack) instanceof Number value ? value.intValue() : fallback;
|
||||
}
|
||||
}
|
||||
+281
@@ -0,0 +1,281 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.datafixers.util.Either;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderGetter;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.RegistrationInfo;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.WritableRegistry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.clock.WorldClock;
|
||||
import net.minecraft.world.timeline.Timeline;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
|
||||
|
||||
public final class MinecraftTimelines {
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(MinecraftTimelines.class);
|
||||
private static final String EXISTS = "a timeline with this ID already exists";
|
||||
private static final String NO_TIMELINE = "no such timeline";
|
||||
private static final String NO_TAG = "no such timeline tag";
|
||||
private static final String PACK_CONFIG = "pack.yml";
|
||||
private static final String SCHEDULES = "schedules";
|
||||
private static final String NO_VALID_SCHEDULE = "no valid schedule; the parent's timelines are kept";
|
||||
|
||||
private static final Map<TagKey<Timeline>, Pending> PENDING = new LinkedHashMap<>();
|
||||
// Holders stay unbound until the registry freezes.
|
||||
private static final Map<Holder.Reference<Timeline>, Timeline> REGISTERED = new IdentityHashMap<>();
|
||||
|
||||
private MinecraftTimelines() { }
|
||||
|
||||
public static @Nullable Timeline create(RegistryKey id, AttributeSchedule schedule, PackAttributeTable table, AttributeHandle handle,
|
||||
VanillaContext context, AttributeReport report) {
|
||||
String name = id.toString();
|
||||
ResourceKey<WorldClock> clock;
|
||||
try {
|
||||
VanillaIds.identifier(id);
|
||||
clock = ResourceKey.create(Registries.WORLD_CLOCK, VanillaIds.identifier(schedule.clock()));
|
||||
for(RegistryKey marker : schedule.timeMarkers().keySet()) VanillaIds.identifier(marker);
|
||||
} catch(IllegalArgumentException e) {
|
||||
report.scheduleSkipped(name, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
Optional<HolderGetter<WorldClock>> clocks = context.ops().getter(Registries.WORLD_CLOCK);
|
||||
if(clocks.isEmpty() || clocks.get().get(clock).isEmpty()) {
|
||||
report.scheduleSkipped(name, "no such clock \"" + clock.identifier() + "\"");
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return VanillaCodecs.parse(Timeline.DIRECT_CODEC, handle.encodeSchedule(vanillaTracks(schedule, table, report)),
|
||||
context.ops());
|
||||
} catch(DecodeException | IllegalArgumentException e) {
|
||||
report.scheduleSkipped(name, e.getMessage());
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static AttributeSchedule vanillaTracks(AttributeSchedule schedule, PackAttributeTable table, AttributeReport report) {
|
||||
Set<Attribute<?>> vanilla = new HashSet<>();
|
||||
for(PackAttributeTable.Bound bound : table.environment()) vanilla.add(bound.attribute());
|
||||
Map<Attribute<?>, ScheduleTrack<?>> tracks = new LinkedHashMap<>();
|
||||
schedule.tracks().forEach((attribute, track) -> {
|
||||
if(vanilla.contains(attribute)) {
|
||||
tracks.put(attribute, track);
|
||||
} else {
|
||||
report.notApplied(attribute.getRegistryKey().toString());
|
||||
}
|
||||
});
|
||||
if(tracks.size() == schedule.tracks().size()) return schedule;
|
||||
return new AttributeSchedule(schedule.clock(), schedule.periodTicks(), tracks, schedule.timeMarkers());
|
||||
}
|
||||
|
||||
public static void register(ConfigPack pack, PackParents parents, WritableRegistry<Timeline> timelines, AttributeHandle handle,
|
||||
VanillaContext context) {
|
||||
PackAttributes attributes = parents.attributes();
|
||||
if(attributes == null) return;
|
||||
AttributeReport report = parents.report();
|
||||
for(Map.Entry<RegistryKey, AttributeSchedule> entry : attributes.scheduleDefinitions().entrySet()) {
|
||||
RegistryKey id = entry.getKey();
|
||||
Identifier location;
|
||||
try {
|
||||
location = VanillaIds.identifier(id);
|
||||
} catch(IllegalArgumentException e) {
|
||||
report.scheduleSkipped(id.toString(), e.getMessage());
|
||||
continue;
|
||||
}
|
||||
if(timelines.containsKey(location)) {
|
||||
report.scheduleSkipped(id.toString(), EXISTS);
|
||||
continue;
|
||||
}
|
||||
AttributeSchedule schedule = withoutClashingMarkers(id.toString(), entry.getValue(), timelines, report);
|
||||
Timeline timeline = create(id, schedule, parents.table(), handle, context, report);
|
||||
if(timeline == null) continue;
|
||||
Holder.Reference<Timeline> holder = timelines.register(ResourceKey.create(Registries.TIMELINE, location), timeline,
|
||||
RegistrationInfo.BUILT_IN);
|
||||
synchronized(REGISTERED) {
|
||||
REGISTERED.put(holder, timeline);
|
||||
}
|
||||
LOGGER.debug("Registered timeline {} from pack {}", location, pack.getID());
|
||||
}
|
||||
}
|
||||
|
||||
// Vanilla fails the whole load on a time marker its clock already has.
|
||||
private static AttributeSchedule withoutClashingMarkers(String name, AttributeSchedule schedule, Registry<Timeline> timelines,
|
||||
AttributeReport report) {
|
||||
if(schedule.timeMarkers().isEmpty()) return schedule;
|
||||
ResourceKey<WorldClock> clock;
|
||||
try {
|
||||
clock = ResourceKey.create(Registries.WORLD_CLOCK, VanillaIds.identifier(schedule.clock()));
|
||||
} catch(IllegalArgumentException e) {
|
||||
return schedule;
|
||||
}
|
||||
Set<Identifier> defined = markersOn(clock, timelines);
|
||||
Map<RegistryKey, TimeMarker> kept = new LinkedHashMap<>();
|
||||
schedule.timeMarkers().forEach((id, marker) -> {
|
||||
Identifier location;
|
||||
try {
|
||||
location = VanillaIds.identifier(id);
|
||||
} catch(IllegalArgumentException e) {
|
||||
kept.put(id, marker);
|
||||
return;
|
||||
}
|
||||
if(defined.contains(location)) {
|
||||
report.timeMarkerDropped(name, id.toString(), clock.identifier().toString());
|
||||
} else {
|
||||
kept.put(id, marker);
|
||||
}
|
||||
});
|
||||
if(kept.size() == schedule.timeMarkers().size()) return schedule;
|
||||
return new AttributeSchedule(schedule.clock(), schedule.periodTicks(), schedule.tracks(), kept);
|
||||
}
|
||||
|
||||
private static Set<Identifier> markersOn(ResourceKey<WorldClock> clock, Registry<Timeline> timelines) {
|
||||
Set<Identifier> markers = new HashSet<>();
|
||||
Optional<ResourceKey<WorldClock>> wanted = Optional.of(clock);
|
||||
for(Holder.Reference<Timeline> holder : timelines.listElements().toList()) {
|
||||
Timeline other;
|
||||
if(holder.isBound()) {
|
||||
other = holder.value();
|
||||
} else {
|
||||
synchronized(REGISTERED) {
|
||||
other = REGISTERED.get(holder);
|
||||
}
|
||||
}
|
||||
if(other != null && other.clock().unwrapKey().equals(wanted)) {
|
||||
other.registerTimeMarkers((key, marker) -> markers.add(key.identifier()));
|
||||
}
|
||||
}
|
||||
return markers;
|
||||
}
|
||||
|
||||
public static @Nullable TagKey<Timeline> tagFor(Identifier type, ConfigPack pack, PackParents parents) {
|
||||
Pending pending = pending(pack, parents);
|
||||
if(pending == null) return null;
|
||||
TagKey<Timeline> key = TagKey.create(Registries.TIMELINE, type);
|
||||
synchronized(PENDING) {
|
||||
PENDING.put(key, pending);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
public static @Nullable Pending pending(ConfigPack pack, PackParents parents) {
|
||||
PackAttributes attributes = parents.attributes();
|
||||
if(attributes == null || attributes.scheduleRefs().isEmpty()) return null;
|
||||
AttributeReport report = parents.report();
|
||||
List<Either<Identifier, TagKey<Timeline>>> refs = new ArrayList<>();
|
||||
for(com.dfsek.terra.api.util.generic.either.Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> ref
|
||||
: attributes.scheduleRefs()) {
|
||||
Optional<RegistryKey> id = ref.getLeft();
|
||||
Optional<com.dfsek.terra.api.registry.key.TagKey> tag = ref.getRight();
|
||||
try {
|
||||
if(id.isPresent()) {
|
||||
refs.add(Either.left(VanillaIds.identifier(id.get())));
|
||||
} else if(tag.isPresent()) {
|
||||
refs.add(Either.right(TagKey.create(Registries.TIMELINE, VanillaIds.identifier(tag.get().key()))));
|
||||
}
|
||||
} catch(IllegalArgumentException e) {
|
||||
report.scheduleSkipped(id.map(Object::toString).orElseGet(() -> String.valueOf(tag.orElse(null))), e.getMessage());
|
||||
}
|
||||
}
|
||||
return new Pending(report, refs, parents.dimension().timelines());
|
||||
}
|
||||
|
||||
/**
|
||||
* Vanilla won't freeze a registry with an unbound tag.
|
||||
*/
|
||||
public static void bindPendingTags(WritableRegistry<Timeline> timelines) {
|
||||
HolderGetter<Timeline> registration = timelines.createRegistrationLookup();
|
||||
Map<TagKey<Timeline>, List<Holder<Timeline>>> unbound = new HashMap<>();
|
||||
synchronized(PENDING) {
|
||||
for(TagKey<Timeline> key : PENDING.keySet()) {
|
||||
if(!registration.getOrThrow(key).isBound()) unbound.put(key, List.of());
|
||||
}
|
||||
}
|
||||
timelines.bindTags(unbound);
|
||||
}
|
||||
|
||||
public static void fillTags(Map<TagKey<Timeline>, List<Holder<Timeline>>> collect, Registry<Timeline> registry) {
|
||||
synchronized(PENDING) {
|
||||
PENDING.forEach((key, pending) -> collect.put(key, contents(pending, collect::get, registry)));
|
||||
}
|
||||
}
|
||||
|
||||
public static List<Holder<Timeline>> contents(Pending pending, Function<TagKey<Timeline>, @Nullable List<Holder<Timeline>>> tags,
|
||||
Registry<Timeline> registry) {
|
||||
Set<Holder<Timeline>> contents = new LinkedHashSet<>();
|
||||
for(Either<Identifier, TagKey<Timeline>> ref : pending.refs()) {
|
||||
ref.ifLeft(id -> registry.get(id).ifPresentOrElse(contents::add,
|
||||
() -> pending.report().scheduleSkipped(id.toString(), NO_TIMELINE)))
|
||||
.ifRight(tag -> {
|
||||
List<Holder<Timeline>> members = tags.apply(tag);
|
||||
if(members == null) {
|
||||
pending.report().scheduleSkipped("#" + tag.location(), NO_TAG);
|
||||
} else {
|
||||
contents.addAll(members);
|
||||
}
|
||||
});
|
||||
}
|
||||
if(contents.isEmpty()) {
|
||||
pending.report().ignored(PACK_CONFIG, SCHEDULES, NO_VALID_SCHEDULE);
|
||||
parentTimelines(pending.parent(), tags, registry, contents);
|
||||
}
|
||||
return List.copyOf(contents);
|
||||
}
|
||||
|
||||
private static void parentTimelines(HolderSet<Timeline> parent, Function<TagKey<Timeline>, @Nullable List<Holder<Timeline>>> tags,
|
||||
Registry<Timeline> registry, Set<Holder<Timeline>> contents) {
|
||||
parent.unwrap()
|
||||
.ifLeft(tag -> {
|
||||
List<Holder<Timeline>> members = tags.apply(tag);
|
||||
if(members != null) contents.addAll(members);
|
||||
})
|
||||
.ifRight(direct -> {
|
||||
for(Holder<Timeline> holder : direct) holder.unwrapKey().flatMap(registry::get).ifPresent(contents::add);
|
||||
});
|
||||
}
|
||||
|
||||
static void clear() {
|
||||
synchronized(PENDING) {
|
||||
PENDING.clear();
|
||||
}
|
||||
synchronized(REGISTERED) {
|
||||
REGISTERED.clear();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public record Pending(AttributeReport report, List<Either<Identifier, TagKey<Timeline>>> refs, HolderSet<Timeline> parent) {
|
||||
public Pending {
|
||||
refs = List.copyOf(refs);
|
||||
}
|
||||
}
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.world.attribute.EnvironmentAttribute;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
|
||||
|
||||
public final class PackAttributeTable {
|
||||
public static final PackAttributeTable EMPTY = new PackAttributeTable(List.of(), List.of(), List.of(), List.of(), null, null, null,
|
||||
null, List.of());
|
||||
|
||||
private static final String MINECRAFT = "minecraft";
|
||||
private static final String TERRA = "terra";
|
||||
private static final String BIOME = "biome/";
|
||||
private static final String DIMENSION = "dimension/";
|
||||
private static final Set<String> CLIMATE_FIELDS = Set.of("has_precipitation", "temperature", "temperature_modifier", "downfall");
|
||||
private static final Set<String> EFFECTS_FIELDS = Set.of("water_color", "foliage_color", "dry_foliage_color", "grass_color",
|
||||
"grass_color_modifier");
|
||||
private static final RegistryKey VILLAGER_TYPE = AttributeKey.parse("terra:biome/villager_type").getRegistryKey();
|
||||
private static final RegistryKey SEA_LEVEL = AttributeKey.parse("terra:world/sea_level").getRegistryKey();
|
||||
private static final RegistryKey SPAWN_HEIGHT = AttributeKey.parse("terra:world/spawn_height").getRegistryKey();
|
||||
private static final RegistryKey MOB_GENERATION = AttributeKey.parse("terra:world/mob_generation").getRegistryKey();
|
||||
|
||||
private final List<Bound> environment;
|
||||
private final List<Field> climate;
|
||||
private final List<Field> effects;
|
||||
private final List<Field> dimension;
|
||||
private final @Nullable Attribute<?> villagerType;
|
||||
private final @Nullable Attribute<?> seaLevel;
|
||||
private final @Nullable Attribute<?> spawnHeight;
|
||||
private final @Nullable Attribute<?> mobGeneration;
|
||||
private final List<Attribute<?>> unapplied;
|
||||
|
||||
private PackAttributeTable(List<Bound> environment, List<Field> climate, List<Field> effects, List<Field> dimension,
|
||||
@Nullable Attribute<?> villagerType, @Nullable Attribute<?> seaLevel, @Nullable Attribute<?> spawnHeight,
|
||||
@Nullable Attribute<?> mobGeneration, List<Attribute<?>> unapplied) {
|
||||
this.environment = environment;
|
||||
this.climate = climate;
|
||||
this.effects = effects;
|
||||
this.dimension = dimension;
|
||||
this.villagerType = villagerType;
|
||||
this.seaLevel = seaLevel;
|
||||
this.spawnHeight = spawnHeight;
|
||||
this.mobGeneration = mobGeneration;
|
||||
this.unapplied = unapplied;
|
||||
}
|
||||
|
||||
public static PackAttributeTable of(@Nullable Registry<Attribute<?>> registry) {
|
||||
if(registry == null) return EMPTY;
|
||||
Builder builder = new Builder();
|
||||
registry.forEach(builder::add);
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
public List<Bound> environment() {
|
||||
return environment;
|
||||
}
|
||||
|
||||
public List<Field> climate() {
|
||||
return climate;
|
||||
}
|
||||
|
||||
public List<Field> effects() {
|
||||
return effects;
|
||||
}
|
||||
|
||||
public List<Field> dimension() {
|
||||
return dimension;
|
||||
}
|
||||
|
||||
public @Nullable Attribute<?> villagerType() {
|
||||
return villagerType;
|
||||
}
|
||||
|
||||
public @Nullable Attribute<?> seaLevel() {
|
||||
return seaLevel;
|
||||
}
|
||||
|
||||
public @Nullable Attribute<?> spawnHeight() {
|
||||
return spawnHeight;
|
||||
}
|
||||
|
||||
public @Nullable Attribute<?> mobGeneration() {
|
||||
return mobGeneration;
|
||||
}
|
||||
|
||||
public List<Attribute<?>> unapplied() {
|
||||
return unapplied;
|
||||
}
|
||||
|
||||
|
||||
public record Bound(Attribute<?> attribute, EnvironmentAttribute<?> vanilla) { }
|
||||
|
||||
|
||||
public record Field(Attribute<?> attribute, String name) { }
|
||||
|
||||
|
||||
private static final class Builder {
|
||||
private final List<Bound> environment = new ArrayList<>();
|
||||
private final List<Field> climate = new ArrayList<>();
|
||||
private final List<Field> effects = new ArrayList<>();
|
||||
private final List<Field> dimension = new ArrayList<>();
|
||||
private final List<Attribute<?>> unapplied = new ArrayList<>();
|
||||
private @Nullable Attribute<?> villagerType;
|
||||
private @Nullable Attribute<?> seaLevel;
|
||||
private @Nullable Attribute<?> spawnHeight;
|
||||
private @Nullable Attribute<?> mobGeneration;
|
||||
|
||||
private void add(RegistryKey key, Attribute<?> attribute) {
|
||||
String namespace = key.getNamespace();
|
||||
String path = key.getID();
|
||||
if(namespace.equals(MINECRAFT)) {
|
||||
// tryBuild returns null for the upper case Terra allows.
|
||||
Identifier id = Identifier.tryBuild(namespace, path);
|
||||
EnvironmentAttribute<?> vanilla = id == null ? null : BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getValue(id);
|
||||
if(vanilla != null) {
|
||||
environment.add(new Bound(attribute, vanilla));
|
||||
return;
|
||||
}
|
||||
} else if(namespace.equals(TERRA)) {
|
||||
if(key.equals(VILLAGER_TYPE)) {
|
||||
villagerType = attribute;
|
||||
return;
|
||||
} else if(key.equals(SEA_LEVEL)) {
|
||||
seaLevel = attribute;
|
||||
return;
|
||||
} else if(key.equals(SPAWN_HEIGHT)) {
|
||||
spawnHeight = attribute;
|
||||
return;
|
||||
} else if(key.equals(MOB_GENERATION)) {
|
||||
mobGeneration = attribute;
|
||||
return;
|
||||
} else if(path.startsWith(BIOME)) {
|
||||
String name = path.substring(BIOME.length());
|
||||
if(CLIMATE_FIELDS.contains(name)) {
|
||||
climate.add(new Field(attribute, name));
|
||||
return;
|
||||
} else if(EFFECTS_FIELDS.contains(name)) {
|
||||
effects.add(new Field(attribute, name));
|
||||
return;
|
||||
}
|
||||
} else if(path.startsWith(DIMENSION) && path.length() > DIMENSION.length()) {
|
||||
dimension.add(new Field(attribute, path.substring(DIMENSION.length())));
|
||||
return;
|
||||
}
|
||||
}
|
||||
unapplied.add(attribute);
|
||||
}
|
||||
|
||||
private PackAttributeTable build() {
|
||||
return new PackAttributeTable(List.copyOf(environment), List.copyOf(climate), List.copyOf(effects), List.copyOf(dimension),
|
||||
villagerType, seaLevel, spawnHeight, mobGeneration, List.copyOf(unapplied));
|
||||
}
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
|
||||
|
||||
public final class PackParents {
|
||||
private final ConfigPack pack;
|
||||
private final ResourceKey<DimensionType> dimensionKey;
|
||||
private final boolean dimensionDefaulted;
|
||||
private final DimensionType dimension;
|
||||
private final ResourceKey<NoiseGeneratorSettings> generationKey;
|
||||
private final NoiseGeneratorSettings generation;
|
||||
private final PackAttributeTable table;
|
||||
private final AttributeSlots packEntries;
|
||||
private final @Nullable PackAttributes attributes;
|
||||
private final AttributeReport report;
|
||||
private final VanillaParentReader reader;
|
||||
private final Map<ResourceKey<Biome>, AttributeSlots> biomeEntries = new ConcurrentHashMap<>();
|
||||
|
||||
PackParents(ConfigPack pack, ResourceKey<DimensionType> dimensionKey, boolean dimensionDefaulted, DimensionType dimension,
|
||||
ResourceKey<NoiseGeneratorSettings> generationKey, NoiseGeneratorSettings generation, PackAttributeTable table,
|
||||
AttributeSlots packEntries, @Nullable PackAttributes attributes, AttributeReport report, VanillaParentReader reader) {
|
||||
this.pack = pack;
|
||||
this.dimensionKey = dimensionKey;
|
||||
this.dimensionDefaulted = dimensionDefaulted;
|
||||
this.dimension = dimension;
|
||||
this.generationKey = generationKey;
|
||||
this.generation = generation;
|
||||
this.table = table;
|
||||
this.packEntries = packEntries;
|
||||
this.attributes = attributes;
|
||||
this.report = report;
|
||||
this.reader = reader;
|
||||
}
|
||||
|
||||
public ResourceKey<DimensionType> dimensionKey() {
|
||||
return dimensionKey;
|
||||
}
|
||||
|
||||
public boolean dimensionDefaulted() {
|
||||
return dimensionDefaulted;
|
||||
}
|
||||
|
||||
public DimensionType dimension() {
|
||||
return dimension;
|
||||
}
|
||||
|
||||
public ResourceKey<NoiseGeneratorSettings> generationKey() {
|
||||
return generationKey;
|
||||
}
|
||||
|
||||
public NoiseGeneratorSettings generation() {
|
||||
return generation;
|
||||
}
|
||||
|
||||
public PackAttributeTable table() {
|
||||
return table;
|
||||
}
|
||||
|
||||
public AttributeSlots packEntries() {
|
||||
return packEntries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlike {@link PackAttributes#resolvePack}, uses these parents, which may be another default's. Allocates.
|
||||
*/
|
||||
public <T> @Nullable T resolvePack(AttributeHandle handle, Attribute<T> attribute) {
|
||||
AttributeEntry<T> own = attributes == null ? null : attributes.entries().get(attribute.key()).orElse(null);
|
||||
return handle.resolve(attribute, packEntries.get(attribute), own, null);
|
||||
}
|
||||
|
||||
public @Nullable PackAttributes attributes() {
|
||||
return attributes;
|
||||
}
|
||||
|
||||
public AttributeReport report() {
|
||||
return report;
|
||||
}
|
||||
|
||||
ConfigPack pack() {
|
||||
return pack;
|
||||
}
|
||||
|
||||
VanillaParentReader reader() {
|
||||
return reader;
|
||||
}
|
||||
|
||||
Map<ResourceKey<Biome>, AttributeSlots> biomeEntries() {
|
||||
return biomeEntries;
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.timeline.Timeline;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
|
||||
public sealed interface TimelineRef {
|
||||
Object encoded();
|
||||
|
||||
record Tag(TagKey<Timeline> key) implements TimelineRef {
|
||||
public Tag {
|
||||
Objects.requireNonNull(key, "key");
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object encoded() {
|
||||
return "#" + key.location();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Every key must be registered where the dimension type is decoded.
|
||||
*/
|
||||
record Direct(List<ResourceKey<Timeline>> keys) implements TimelineRef {
|
||||
public Direct {
|
||||
keys = List.copyOf(keys);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object encoded() {
|
||||
return keys.stream().map(key -> key.identifier().toString()).toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeMap;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
|
||||
final class VanillaAttributeMaps {
|
||||
private final AttributeHandle handle;
|
||||
private final VanillaContext context;
|
||||
|
||||
VanillaAttributeMaps(AttributeHandle handle, VanillaContext context) {
|
||||
this.handle = handle;
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
void toTerra(EnvironmentAttributeMap map, PackAttributeTable table, AttributeEntry<?>[] into,
|
||||
BiConsumer<Attribute<?>, String> unreadable) {
|
||||
if(map.keySet().isEmpty() || table.environment().isEmpty()) return;
|
||||
Map<?, ?> encoded = (Map<?, ?>) VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, context.ops());
|
||||
for(PackAttributeTable.Bound bound : table.environment()) {
|
||||
if(!map.contains(bound.vanilla())) continue;
|
||||
Object raw = encoded.get(String.valueOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getKey(bound.vanilla())));
|
||||
Attribute<?> attribute = bound.attribute();
|
||||
try {
|
||||
into[attribute.index()] = handle.decodeEntry(attribute, raw, handle.plainContext());
|
||||
} catch(DecodeException e) {
|
||||
unreadable.accept(attribute, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
EnvironmentAttributeMap toVanilla(EnvironmentAttributeMap base, Map<Attribute<?>, AttributeEntry<?>> entries, boolean positionalOnly,
|
||||
BiConsumer<Attribute<?>, String> skipped) {
|
||||
Codec<EnvironmentAttributeMap> codec = positionalOnly
|
||||
? EnvironmentAttributeMap.CODEC_ONLY_POSITIONAL
|
||||
: EnvironmentAttributeMap.CODEC;
|
||||
EnvironmentAttributeMap.Builder builder = EnvironmentAttributeMap.builder().putAll(base);
|
||||
for(Map.Entry<Attribute<?>, AttributeEntry<?>> entry : entries.entrySet()) {
|
||||
Attribute<?> attribute = entry.getKey();
|
||||
AttributeEntry<?> value = entry.getValue();
|
||||
if(value == null || (value.isOverride() && value.argument() == null)) continue;
|
||||
Map<String, Object> single = Map.of(attribute.getRegistryKey().toString(), encode(attribute, value));
|
||||
try {
|
||||
builder.putAll(VanillaCodecs.parse(codec, single, context.ops()));
|
||||
} catch(DecodeException e) {
|
||||
skipped.accept(attribute, e.getMessage());
|
||||
}
|
||||
}
|
||||
return builder.build();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <T> Object encode(Attribute<T> attribute, AttributeEntry<?> entry) {
|
||||
return handle.encodeEntry(attribute, (AttributeEntry<T>) entry);
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.DataResult;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
|
||||
|
||||
public final class VanillaCodecs {
|
||||
private static final String CAUGHT = "Caught exception decoding ";
|
||||
|
||||
private VanillaCodecs() { }
|
||||
|
||||
public static <V> Object encode(Codec<V> codec, V value, RegistryOps<Object> ops) {
|
||||
return codec.encodeStart(ops, value).getOrThrow(IllegalStateException::new);
|
||||
}
|
||||
|
||||
public static <V> V parse(Codec<V> codec, Object raw, RegistryOps<Object> ops) throws DecodeException {
|
||||
DataResult<V> result = codec.parse(ops, raw);
|
||||
Optional<DataResult.Error<V>> error = result.error();
|
||||
if(error.isPresent()) {
|
||||
String message = error.get().message();
|
||||
// ExtraCodecs.catchDecoderException's form; only the outermost one names raw itself.
|
||||
String caught = CAUGHT + raw + ": ";
|
||||
throw new DecodeException(lowerFirst(message.startsWith(caught) ? message.substring(caught.length()) : message));
|
||||
}
|
||||
return result.getOrThrow();
|
||||
}
|
||||
|
||||
private static String lowerFirst(String reason) {
|
||||
if(reason.isEmpty()) return reason;
|
||||
return Character.toLowerCase(reason.charAt(0)) + reason.substring(1);
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.JavaOps;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderGetter;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderOwner;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.WritableRegistry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.entity.npc.villager.VillagerType;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Function;
|
||||
|
||||
|
||||
public record VanillaContext(RegistryOps<Object> ops, HolderGetter<DimensionType> dimensionTypes,
|
||||
HolderGetter<NoiseGeneratorSettings> noiseSettings, HolderGetter<Biome> biomes,
|
||||
Function<ResourceKey<Biome>, @Nullable ResourceKey<VillagerType>> villagerTypes) {
|
||||
public static VanillaContext of(HolderLookup.Provider registries,
|
||||
Function<ResourceKey<Biome>, @Nullable ResourceKey<VillagerType>> villagerTypes) {
|
||||
return new VanillaContext(registries.createSerializationContext(JavaOps.INSTANCE),
|
||||
registries.lookupOrThrow(Registries.DIMENSION_TYPE),
|
||||
registries.lookupOrThrow(Registries.NOISE_SETTINGS),
|
||||
registries.lookupOrThrow(Registries.BIOME),
|
||||
villagerTypes);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@code context} must be the list vanilla's loader received: until the load finishes, only it has the static registries'
|
||||
* new tags.
|
||||
*/
|
||||
public static VanillaContext ofLoad(List<? extends WritableRegistry<?>> loaded, List<? extends HolderLookup.RegistryLookup<?>> context,
|
||||
Function<ResourceKey<Biome>, @Nullable ResourceKey<VillagerType>> villagerTypes) {
|
||||
Map<ResourceKey<?>, HolderGetter<?>> getters = new HashMap<>();
|
||||
// Vanilla's order: the context first, then the registries being loaded over it.
|
||||
for(HolderLookup.RegistryLookup<?> lookup : context) getters.put(lookup.key(), lookup);
|
||||
for(WritableRegistry<?> registry : loaded) getters.put(registry.key(), loadGetter(registry));
|
||||
RegistryOps.RegistryInfoLookup lookup = new RegistryOps.RegistryInfoLookup() {
|
||||
@Override
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> Optional<HolderGetter<T>> lookup(ResourceKey<? extends Registry<? extends T>> key) {
|
||||
return Optional.ofNullable((HolderGetter<T>) getters.get(key));
|
||||
}
|
||||
};
|
||||
return new VanillaContext(RegistryOps.create(JavaOps.INSTANCE, lookup),
|
||||
loadedGetter(lookup, Registries.DIMENSION_TYPE),
|
||||
loadedGetter(lookup, Registries.NOISE_SETTINGS),
|
||||
loadedGetter(lookup, Registries.BIOME),
|
||||
villagerTypes);
|
||||
}
|
||||
|
||||
// The registration lookup makes a holder for any key, and an unbound one fails Registry.freeze() for the whole load.
|
||||
private static <T> HolderGetter<T> loadGetter(WritableRegistry<T> registry) {
|
||||
HolderGetter<T> registration = registry.createRegistrationLookup();
|
||||
return new HolderGetter<>() {
|
||||
@Override
|
||||
public Optional<Holder.Reference<T>> get(ResourceKey<T> key) {
|
||||
return registry.get(key.identifier());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<HolderSet.Named<T>> get(TagKey<T> key) {
|
||||
return registration.get(key);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean canSerialize(HolderOwner<T> owner) {
|
||||
return registration.canSerialize(owner);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static <T> HolderGetter<T> loadedGetter(RegistryOps.RegistryInfoLookup lookup, ResourceKey<? extends Registry<T>> key) {
|
||||
return lookup.<T>lookup(key).orElseThrow(() -> new IllegalArgumentException("registry " + key.identifier() + " is not loaded"));
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
|
||||
|
||||
public final class VanillaIds {
|
||||
private VanillaIds() { }
|
||||
|
||||
public static Identifier identifier(RegistryKey key) {
|
||||
Identifier identifier = Identifier.tryBuild(key.getNamespace(), key.getID());
|
||||
if(identifier == null) {
|
||||
throw new IllegalArgumentException(
|
||||
"invalid ID \"" + key + "\": Minecraft IDs use only lower-case a-z, 0-9, _, . and -, and / in the path");
|
||||
}
|
||||
return identifier;
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.entity.npc.villager.VillagerType;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeSpecialEffects;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
|
||||
|
||||
final class VanillaParentReader {
|
||||
private static final String DEFAULT_CLOCK = "default_clock";
|
||||
|
||||
private final AttributeHandle handle;
|
||||
private final VanillaContext context;
|
||||
private final VanillaAttributeMaps maps;
|
||||
|
||||
VanillaParentReader(AttributeHandle handle, VanillaContext context) {
|
||||
this.handle = handle;
|
||||
this.context = context;
|
||||
this.maps = new VanillaAttributeMaps(handle, context);
|
||||
}
|
||||
|
||||
AttributeSlots biome(ResourceKey<Biome> key, Biome biome, PackAttributeTable table, BiConsumer<Attribute<?>, String> unreadable) {
|
||||
AttributeEntry<?>[] slots = slots();
|
||||
maps.toTerra(biome.getAttributes(), table, slots, unreadable);
|
||||
if(!table.climate().isEmpty()) {
|
||||
readFields(encode(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings), table.climate(), slots, unreadable);
|
||||
}
|
||||
if(!table.effects().isEmpty()) {
|
||||
readFields(encode(BiomeSpecialEffects.CODEC, biome.getSpecialEffects()), table.effects(), slots, unreadable);
|
||||
}
|
||||
Attribute<?> villagerType = table.villagerType();
|
||||
if(villagerType != null) {
|
||||
ResourceKey<VillagerType> type = context.villagerTypes().apply(key);
|
||||
if(type != null) read(villagerType, type.identifier().toString(), slots, unreadable);
|
||||
}
|
||||
return AttributeSlots.of(slots);
|
||||
}
|
||||
|
||||
AttributeSlots dimension(DimensionType type, PackAttributeTable table, BiConsumer<Attribute<?>, String> unreadable) {
|
||||
AttributeEntry<?>[] slots = slots();
|
||||
maps.toTerra(type.attributes(), table, slots, unreadable);
|
||||
if(!table.dimension().isEmpty()) {
|
||||
Map<?, ?> fields = encode(DimensionType.DIRECT_CODEC, type);
|
||||
for(PackAttributeTable.Field field : table.dimension()) {
|
||||
Object raw = fields.get(field.name());
|
||||
if(raw != null) {
|
||||
read(field.attribute(), raw, slots, unreadable);
|
||||
} else if(field.name().equals(DEFAULT_CLOCK)) {
|
||||
slots[field.attribute().index()] = AttributeEntry.override(null);
|
||||
}
|
||||
}
|
||||
}
|
||||
return AttributeSlots.of(slots);
|
||||
}
|
||||
|
||||
@SuppressWarnings("deprecation") // disableMobGeneration is still what vanilla's settings carry
|
||||
AttributeSlots generation(NoiseGeneratorSettings settings, PackAttributeTable table) {
|
||||
AttributeEntry<?>[] slots = slots();
|
||||
Attribute<?> seaLevel = table.seaLevel();
|
||||
if(seaLevel != null) read(seaLevel, settings.seaLevel(), slots, (attribute, reason) -> { });
|
||||
Attribute<?> mobGeneration = table.mobGeneration();
|
||||
if(mobGeneration != null) read(mobGeneration, !settings.disableMobGeneration(), slots, (attribute, reason) -> { });
|
||||
return AttributeSlots.of(slots);
|
||||
}
|
||||
|
||||
private AttributeEntry<?>[] slots() {
|
||||
return new AttributeEntry<?>[handle.attributeCount()];
|
||||
}
|
||||
|
||||
private void readFields(Map<?, ?> fields, List<PackAttributeTable.Field> table, AttributeEntry<?>[] slots,
|
||||
BiConsumer<Attribute<?>, String> unreadable) {
|
||||
for(PackAttributeTable.Field field : table) {
|
||||
Object raw = fields.get(field.name());
|
||||
if(raw != null) read(field.attribute(), raw, slots, unreadable);
|
||||
}
|
||||
}
|
||||
|
||||
private void read(Attribute<?> attribute, Object raw, AttributeEntry<?>[] slots, BiConsumer<Attribute<?>, String> unreadable) {
|
||||
try {
|
||||
slots[attribute.index()] = AttributeEntry.override(attribute.type().decode(raw, handle.plainContext()));
|
||||
} catch(DecodeException e) {
|
||||
unreadable.accept(attribute, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private <V> Map<?, ?> encode(Codec<V> codec, V value) {
|
||||
return (Map<?, ?>) VanillaCodecs.encode(codec, value, context.ops());
|
||||
}
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
public record WorldSettings(int minY, int height, int seaLevel, boolean mobGeneration, int spawnHeight) {
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.minecraft.attribute.BiomeTags.PlatformTagSource;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.VanillaContextTest.copy;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
class BiomeTagsTest {
|
||||
private static final Identifier TERRA_ID = Identifier.parse("terra:test/biome");
|
||||
private static final TagKey<Biome> HAS_SNOW = tag("mypack:has_snow");
|
||||
private static final TagKey<Biome> IS_FOREST = net.minecraft.tags.BiomeTags.IS_FOREST;
|
||||
|
||||
private final List<String> warnings = new ArrayList<>();
|
||||
private final AttributeReport report = new AttributeReport("test", warnings::add, m -> { });
|
||||
private final MappedRegistry<Biome> registry = copy(Registries.BIOME);
|
||||
private final Holder<Biome> terra = registry.get(Biomes.DESERT).orElseThrow();
|
||||
private final Map<TagKey<Biome>, List<Holder<Biome>>> collect = new HashMap<>();
|
||||
|
||||
private static TagKey<Biome> tag(String id) {
|
||||
return TagKey.create(Registries.BIOME, Identifier.parse(id));
|
||||
}
|
||||
|
||||
private Optional<Holder<Biome>> lookup(Identifier id) {
|
||||
return id.equals(TERRA_ID) ? Optional.of(terra) : registry.get(ResourceKey.create(Registries.BIOME, id))
|
||||
.map(h -> h);
|
||||
}
|
||||
|
||||
private void add(Map<Identifier, List<Identifier>> byParent, String... tags) {
|
||||
Set<RegistryKey> keys = new LinkedHashSet<>();
|
||||
for(String t : tags) keys.add(RegistryKey.parse(t));
|
||||
BiomeTags.addTerraBiomes(collect, this::lookup, byParent, Map.of(TERRA_ID, new PlatformTagSource(report, "BIOME", keys)));
|
||||
}
|
||||
|
||||
private static void bindTags(Holder<Biome> holder, TagKey<Biome> tag) throws ReflectiveOperationException {
|
||||
Method bind = Holder.Reference.class.getDeclaredMethod("bindTags", Collection.class);
|
||||
bind.setAccessible(true);
|
||||
bind.invoke(holder, List.of(tag));
|
||||
}
|
||||
|
||||
@Test
|
||||
void platformTagsAreAdded() {
|
||||
Holder<Biome> forest = registry.get(Biomes.FOREST).orElseThrow();
|
||||
collect.put(IS_FOREST, new ArrayList<>(List.of(forest)));
|
||||
|
||||
add(Map.of(), "mypack:has_snow", "minecraft:is_forest");
|
||||
|
||||
assertEquals(List.of(terra), collect.get(HAS_SNOW));
|
||||
assertEquals(List.of(forest, terra), collect.get(IS_FOREST));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inheritedTagsStillApply() throws ReflectiveOperationException {
|
||||
Holder<Biome> forest = registry.get(Biomes.FOREST).orElseThrow();
|
||||
bindTags(forest, IS_FOREST);
|
||||
Identifier forestId = Biomes.FOREST.identifier();
|
||||
|
||||
add(Map.of(forestId, List.of(TERRA_ID)));
|
||||
|
||||
assertEquals(List.of(terra), collect.get(IS_FOREST));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void upperCaseTagIsIgnored() {
|
||||
add(Map.of(), "mypack:Has_Snow");
|
||||
|
||||
assertTrue(collect.isEmpty(), collect.toString());
|
||||
assertEquals(1, warnings.size(), warnings.toString());
|
||||
assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": \"mypack:Has_Snow\" ignored: invalid ID "),
|
||||
warnings.getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingMinecraftTagWarnsAndIsCreated() {
|
||||
add(Map.of(), "minecraft:is_forrest");
|
||||
|
||||
assertEquals(List.of("Pack \"test\", config \"BIOME\": tag \"minecraft:is_forrest\" created: no such tag in the minecraft namespace"),
|
||||
warnings);
|
||||
assertEquals(List.of(terra), collect.get(tag("minecraft:is_forrest")));
|
||||
}
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.reflect.Proxy;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
import com.dfsek.terra.api.world.biome.PlatformBiome;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
|
||||
class MinecraftAttributeParentsTest {
|
||||
private static final com.dfsek.terra.api.registry.Registry<Attribute<?>> REGISTRY = registry();
|
||||
private static final ConfigPack PACK = pack("test", REGISTRY);
|
||||
|
||||
private static final Attribute<Boolean> RESPAWN_ANCHOR = attr(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS);
|
||||
private static final Attribute<Float> SKY_LIGHT = attr(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL);
|
||||
private static final Attribute<Boolean> HAS_CEILING = attr(MinecraftAttributes.DIMENSION_HAS_CEILING);
|
||||
private static final Attribute<Integer> SEA_LEVEL = attr(MinecraftAttributes.WORLD_SEA_LEVEL);
|
||||
private static final Attribute<Boolean> PRECIPITATION = attr(MinecraftAttributes.BIOME_HAS_PRECIPITATION);
|
||||
|
||||
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
|
||||
|
||||
private final List<String> warnings = new ArrayList<>();
|
||||
private final List<String> debugs = new ArrayList<>();
|
||||
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
|
||||
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
|
||||
|
||||
private static <T> Attribute<T> attr(AttributeKey<T> key) {
|
||||
return attribute(key.getRegistryKey().toString());
|
||||
}
|
||||
|
||||
static ConfigPack pack(String id, com.dfsek.terra.api.registry.Registry<Attribute<?>> attributes) {
|
||||
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
|
||||
(proxy, method, args) -> switch(method.getName()) {
|
||||
case "getID" -> id;
|
||||
case "getRegistry" -> attributes;
|
||||
case "hashCode" -> System.identityHashCode(proxy);
|
||||
case "equals" -> proxy == args[0];
|
||||
case "toString" -> "ConfigPack[" + id + "]";
|
||||
default -> throw new UnsupportedOperationException(method.getName());
|
||||
});
|
||||
}
|
||||
|
||||
private FakePackAttributes fake(Map<String, RegistryKey> parentIds) {
|
||||
return new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), parentIds, Map.of());
|
||||
}
|
||||
|
||||
private static <T> T value(ResourceKey<? extends Registry<T>> registry, ResourceKey<T> key) {
|
||||
return REGISTRIES.lookupOrThrow(registry).getOrThrow(key).value();
|
||||
}
|
||||
|
||||
private static PackAttributeTable table() {
|
||||
return PackAttributeTable.of(REGISTRY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void overworldByDefault() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
FakePackAttributes fake = fake(Map.of());
|
||||
PackParents pack = parents.prepare(PACK, Optional.of(fake), report);
|
||||
|
||||
DimensionType overworld = value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.OVERWORLD);
|
||||
AttributeSlots expected = new VanillaParentReader(HANDLE, CONTEXT).dimension(overworld, table(), FAIL);
|
||||
assertEquals(expected.get(RESPAWN_ANCHOR), parents.packOrNull(fake, RESPAWN_ANCHOR));
|
||||
assertFalse(fake.resolvePack(RESPAWN_ANCHOR));
|
||||
assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING));
|
||||
assertEquals(AttributeEntry.override(63), parents.packOrNull(fake, SEA_LEVEL));
|
||||
|
||||
assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey());
|
||||
assertSame(overworld, pack.dimension());
|
||||
assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey());
|
||||
assertSame(value(Registries.NOISE_SETTINGS, NoiseGeneratorSettings.OVERWORLD), pack.generation());
|
||||
assertSame(fake, pack.attributes());
|
||||
assertSame(report, pack.report());
|
||||
assertEquals(List.of(), warnings);
|
||||
|
||||
PackParents bare = parents.prepare(pack("bare", REGISTRY), Optional.empty(), report);
|
||||
assertNull(bare.attributes());
|
||||
assertEquals(BuiltinDimensionTypes.OVERWORLD, bare.dimensionKey());
|
||||
assertEquals(NoiseGeneratorSettings.OVERWORLD, bare.generationKey());
|
||||
assertEquals(AttributeEntry.override(63), bare.packEntries().get(SEA_LEVEL));
|
||||
}
|
||||
|
||||
@Test
|
||||
void namedParentsAreUsed() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
FakePackAttributes dimension = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")));
|
||||
PackParents nether = parents.prepare(PACK, Optional.of(dimension), report);
|
||||
assertEquals(BuiltinDimensionTypes.NETHER, nether.dimensionKey());
|
||||
assertSame(value(Registries.DIMENSION_TYPE, BuiltinDimensionTypes.NETHER), nether.dimension());
|
||||
assertEquals(AttributeEntry.override(true), parents.packOrNull(dimension, HAS_CEILING));
|
||||
assertEquals(AttributeEntry.override(4f), parents.packOrNull(dimension, SKY_LIGHT));
|
||||
assertEquals(NoiseGeneratorSettings.OVERWORLD, nether.generationKey());
|
||||
assertEquals(AttributeEntry.override(63), parents.packOrNull(dimension, SEA_LEVEL));
|
||||
|
||||
FakePackAttributes generation = fake(Map.of("vanilla-generation", RegistryKey.parse("minecraft:nether")));
|
||||
PackParents netherGeneration = parents.prepare(PACK, Optional.of(generation), report);
|
||||
assertEquals(NoiseGeneratorSettings.NETHER, netherGeneration.generationKey());
|
||||
assertEquals(AttributeEntry.override(32), parents.packOrNull(generation, SEA_LEVEL));
|
||||
assertEquals(BuiltinDimensionTypes.OVERWORLD, netherGeneration.dimensionKey());
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void givenDefaultDimension() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
FakePackAttributes fake = fake(Map.of());
|
||||
PackParents nether = parents.prepare(PACK, Optional.of(fake), report, BuiltinDimensionTypes.NETHER);
|
||||
assertEquals(BuiltinDimensionTypes.NETHER, nether.dimensionKey());
|
||||
assertTrue(nether.dimensionDefaulted());
|
||||
assertEquals(AttributeEntry.override(true), nether.packEntries().get(HAS_CEILING));
|
||||
assertSame(nether, parents.prepare(PACK, Optional.of(fake), report, BuiltinDimensionTypes.NETHER));
|
||||
|
||||
PackParents overworld = parents.prepare(PACK, Optional.of(fake), report);
|
||||
assertNotSame(nether, overworld);
|
||||
assertEquals(BuiltinDimensionTypes.OVERWORLD, overworld.dimensionKey());
|
||||
assertTrue(overworld.dimensionDefaulted());
|
||||
|
||||
ResourceKey<DimensionType> missing = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("terra:nope"));
|
||||
assertSame(overworld, parents.prepare(PACK, Optional.of(fake), report, missing));
|
||||
|
||||
FakePackAttributes named = fake(Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")));
|
||||
PackParents explicit = parents.prepare(PACK, Optional.of(named), report, BuiltinDimensionTypes.OVERWORLD);
|
||||
assertEquals(BuiltinDimensionTypes.NETHER, explicit.dimensionKey());
|
||||
assertFalse(explicit.dimensionDefaulted());
|
||||
assertSame(explicit, parents.prepare(PACK, Optional.of(named), report, BuiltinDimensionTypes.END));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void badParentWarnsAndFallsBack() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
PackParents upper = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:The_Nether")))),
|
||||
report);
|
||||
FakePackAttributes unknownIds = fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"),
|
||||
"vanilla-generation", RegistryKey.parse("minecraft:nope")));
|
||||
PackParents unknown = parents.prepare(PACK, Optional.of(unknownIds), report);
|
||||
|
||||
assertEquals(List.of(
|
||||
"Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: invalid ID \"minecraft:The_Nether\": Minecraft IDs use only "
|
||||
+ "lower-case a-z, 0-9, _, . and -, and / in the path",
|
||||
"Pack \"test\", config \"pack.yml\": \"vanilla\" ignored: no such dimension type \"minecraft:nope\"",
|
||||
"Pack \"test\", config \"pack.yml\": \"vanilla-generation\" ignored: no such noise settings \"minecraft:nope\""),
|
||||
warnings);
|
||||
for(PackParents pack : List.of(upper, unknown)) {
|
||||
assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey());
|
||||
assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey());
|
||||
assertEquals(AttributeEntry.override(false), pack.packEntries().get(HAS_CEILING));
|
||||
}
|
||||
|
||||
assertSame(unknown, parents.prepare(PACK, Optional.of(unknownIds), report));
|
||||
assertEquals(3, warnings.size(), warnings.toString());
|
||||
PackParents bare = parents.prepare(PACK, Optional.empty(), report);
|
||||
assertNotSame(unknown, bare);
|
||||
assertSame(bare, parents.prepare(PACK, Optional.empty(), report));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownParentCreatesNoHolder() {
|
||||
MappedRegistry<DimensionType> dimensionTypes = VanillaContextTest.copy(Registries.DIMENSION_TYPE);
|
||||
MappedRegistry<NoiseGeneratorSettings> noiseSettings = VanillaContextTest.copy(Registries.NOISE_SETTINGS);
|
||||
MappedRegistry<Biome> biomes = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable());
|
||||
VanillaContext load = VanillaContext.ofLoad(List.of(dimensionTypes, noiseSettings, biomes), MinecraftTestSupport.loadContext(),
|
||||
key -> null);
|
||||
parents.beginLoad(new VanillaContext(CONTEXT.ops(), load.dimensionTypes(), load.noiseSettings(), load.biomes(), key -> null));
|
||||
dimensionTypes.freeze();
|
||||
noiseSettings.freeze();
|
||||
|
||||
PackParents pack = parents.prepare(PACK, Optional.of(fake(Map.of("vanilla", RegistryKey.parse("minecraft:nope"),
|
||||
"vanilla-generation", RegistryKey.parse("minecraft:nope")))),
|
||||
report);
|
||||
|
||||
assertEquals(BuiltinDimensionTypes.OVERWORLD, pack.dimensionKey());
|
||||
assertEquals(NoiseGeneratorSettings.OVERWORLD, pack.generationKey());
|
||||
assertEquals(2, warnings.size(), warnings.toString());
|
||||
assertFalse(dimensionTypes.containsKey(ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("minecraft:nope"))));
|
||||
assertFalse(noiseSettings.containsKey(ResourceKey.create(Registries.NOISE_SETTINGS, Identifier.parse("minecraft:nope"))));
|
||||
}
|
||||
|
||||
@Test
|
||||
void biomeOrNullReadsEntryHolder() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
PackParents pack = parents.prepare(PACK, Optional.empty(), report);
|
||||
TestBiome biome = new TestBiome("BIOME", 0, Biomes.DESERT.identifier());
|
||||
assertSame(AttributeSlots.EMPTY, biome.platform().parentEntries());
|
||||
assertNull(parents.biomeOrNull(biome, PRECIPITATION));
|
||||
|
||||
AttributeSlots desert = parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT));
|
||||
assertSame(desert, parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)), "cached per parent key");
|
||||
biome.platform().setParentEntries(desert);
|
||||
|
||||
assertEquals(AttributeEntry.override(false), parents.biomeOrNull(biome, PRECIPITATION));
|
||||
PlatformBiome other = () -> "other";
|
||||
assertNull(parents.biomeOrNull(new TestBiome("OTHER", 1, other), PRECIPITATION));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unreadableBiomeParentIsReportedOnce() {
|
||||
Attribute<RegistryKey> downfall = HANDLE.attributeBuilder(AttributeKey.<RegistryKey>parse("terra:biome/downfall"),
|
||||
HANDLE.types().identifier("minecraft"),
|
||||
RegistryKey.parse("minecraft:none")).build();
|
||||
parents.beginLoad(CONTEXT);
|
||||
PackParents pack = parents.prepare(pack("test", registry(downfall)), Optional.empty(), report);
|
||||
Biome plains = value(Registries.BIOME, Biomes.PLAINS);
|
||||
|
||||
AttributeSlots first = parents.biomeEntries(pack, Biomes.PLAINS, plains);
|
||||
assertSame(first, parents.biomeEntries(pack, Biomes.PLAINS, plains));
|
||||
|
||||
assertEquals(1, warnings.size(), warnings.toString());
|
||||
assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"pack.yml\": attribute \"terra:biome/downfall\" skipped: "
|
||||
+ "vanilla parent \"minecraft:plains\": "), warnings.getFirst());
|
||||
assertNull(first.get(downfall));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsAllocateNothing() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
parents.prepare(PACK, Optional.of(fake(Map.of())), report);
|
||||
parents.prepare(pack("other", REGISTRY), Optional.empty(), report);
|
||||
TestBiome biome = new TestBiome("BIOME", 0, Biomes.DESERT.identifier());
|
||||
TestBiome plain = new TestBiome("PLAIN", 1, (PlatformBiome) () -> "plain");
|
||||
FakePackAttributes fake = new FakePackAttributes(HANDLE, parents,
|
||||
AttributeMap.builder().put(RESPAWN_ANCHOR.key(), AttributeEntry.override(true)).build(),
|
||||
Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")),
|
||||
Map.of(biome, AttributeMap.builder().put(HAS_CEILING.key(), AttributeEntry.override(true)).build()));
|
||||
PackParents pack = parents.prepare(PACK, Optional.of(fake), report);
|
||||
biome.platform().setParentEntries(parents.biomeEntries(pack, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT)));
|
||||
FakePackAttributes unprepared = fake(Map.of());
|
||||
assertEquals(List.of(), warnings);
|
||||
assertEquals(1023, reads(fake, unprepared, biome, plain), "every read sees the expected entry or value");
|
||||
|
||||
com.sun.management.ThreadMXBean threads = (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
|
||||
long thread = Thread.currentThread().threadId();
|
||||
int sink = 0;
|
||||
for(int i = 0; i < 100_000; i++) sink += reads(fake, unprepared, biome, plain);
|
||||
long before = threads.getThreadAllocatedBytes(thread);
|
||||
for(int i = 0; i < 10_000; i++) sink += reads(fake, unprepared, biome, plain);
|
||||
long allocated = threads.getThreadAllocatedBytes(thread) - before;
|
||||
|
||||
assertEquals(110_000 * 1023, sink);
|
||||
assertTrue(allocated < 1024, allocated + " bytes allocated");
|
||||
System.out.println("readsAllocateNothing: " + allocated + " bytes over 10000 measured iterations");
|
||||
}
|
||||
|
||||
private int reads(FakePackAttributes fake, FakePackAttributes unprepared, TestBiome biome, TestBiome plain) {
|
||||
int hash = 0;
|
||||
hash += parents.biomeOrNull(biome, PRECIPITATION) == null ? 0 : 1;
|
||||
hash += parents.biomeOrNull(plain, PRECIPITATION) == null ? 2 : 0;
|
||||
hash += parents.packOrNull(fake, HAS_CEILING) == null ? 0 : 4;
|
||||
hash += parents.packOrNull(fake, SKY_LIGHT) == null ? 0 : 8;
|
||||
hash += parents.packOrNull(unprepared, SKY_LIGHT) == null ? 16 : 0;
|
||||
hash += fake.resolve(PRECIPITATION, biome) ? 0 : 32;
|
||||
hash += fake.resolve(HAS_CEILING, plain) ? 64 : 0;
|
||||
hash += fake.resolve(HAS_CEILING, biome) ? 128 : 0;
|
||||
hash += fake.resolvePack(RESPAWN_ANCHOR) ? 256 : 0;
|
||||
hash += fake.resolvePack(HAS_CEILING) ? 512 : 0;
|
||||
return hash;
|
||||
}
|
||||
|
||||
@Test
|
||||
void beginLoadAndClearPacksDropOldPacks() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
FakePackAttributes fake = fake(Map.of());
|
||||
PackParents first = parents.prepare(PACK, Optional.of(fake), report);
|
||||
assertNotNull(parents.packOrNull(fake, HAS_CEILING));
|
||||
|
||||
parents.beginLoad(CONTEXT);
|
||||
assertNull(parents.packOrNull(fake, HAS_CEILING));
|
||||
PackParents second = parents.prepare(PACK, Optional.of(fake), report);
|
||||
assertNotSame(first, second);
|
||||
assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING));
|
||||
AttributeSlots desert = parents.biomeEntries(second, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT));
|
||||
|
||||
parents.clearPacks();
|
||||
assertSame(CONTEXT, parents.context());
|
||||
assertNull(parents.packOrNull(fake, HAS_CEILING));
|
||||
FakePackAttributes reloaded = fake(Map.of());
|
||||
assertNull(parents.packOrNull(reloaded, HAS_CEILING));
|
||||
PackParents third = parents.prepare(PACK, Optional.of(reloaded), report);
|
||||
|
||||
assertNotSame(second, third);
|
||||
assertSame(third, parents.prepare(PACK, Optional.of(reloaded), report));
|
||||
assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING));
|
||||
assertNull(parents.packOrNull(fake, HAS_CEILING), "the old pack's attributes get no parents");
|
||||
AttributeSlots again = parents.biomeEntries(third, Biomes.DESERT, value(Registries.BIOME, Biomes.DESERT));
|
||||
assertNotSame(desert, again, "biome entries are read again for the new pack");
|
||||
assertEquals(AttributeEntry.override(false), again.get(PRECIPITATION));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void packReloadKeepsOldPacks() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
FakePackAttributes fake = fake(Map.of());
|
||||
PackParents first = parents.prepare(PACK, Optional.of(fake), report);
|
||||
|
||||
parents.beginPackReload();
|
||||
assertSame(CONTEXT, parents.context());
|
||||
assertEquals(AttributeEntry.override(false), parents.packOrNull(fake, HAS_CEILING), "the old pack keeps its parents");
|
||||
FakePackAttributes reloaded = fake(Map.of());
|
||||
PackParents second = parents.prepare(PACK, Optional.of(reloaded), report);
|
||||
assertNotSame(first, second);
|
||||
assertNotSame(first, parents.prepare(PACK, Optional.of(fake), report), "prepared fresh during the reload");
|
||||
assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING));
|
||||
assertNotNull(parents.packOrNull(fake, HAS_CEILING));
|
||||
|
||||
parents.endPackReload();
|
||||
assertSame(second, parents.prepare(PACK, Optional.of(reloaded), report));
|
||||
assertEquals(AttributeEntry.override(false), parents.packOrNull(reloaded, HAS_CEILING));
|
||||
assertNotNull(parents.packOrNull(fake, HAS_CEILING), "re-prepared during the reload, so kept");
|
||||
assertEquals(List.of(), warnings);
|
||||
|
||||
parents.beginPackReload();
|
||||
parents.endPackReload();
|
||||
assertNull(parents.packOrNull(reloaded, HAS_CEILING), "not prepared again, so dropped");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unpreparedPackHasNoParents() {
|
||||
FakePackAttributes fake = fake(Map.of());
|
||||
assertNull(parents.context());
|
||||
assertNull(parents.packOrNull(fake, HAS_CEILING));
|
||||
assertThrows(IllegalStateException.class, () -> parents.prepare(PACK, Optional.of(fake), report));
|
||||
|
||||
parents.beginLoad(CONTEXT);
|
||||
assertSame(CONTEXT, parents.context());
|
||||
assertNull(parents.packOrNull(fake, HAS_CEILING));
|
||||
}
|
||||
}
|
||||
+459
@@ -0,0 +1,459 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.RegistrationInfo;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.attribute.EnvironmentAttribute;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeMap;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributes;
|
||||
import net.minecraft.world.entity.npc.villager.VillagerType;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeGenerationSettings;
|
||||
import net.minecraft.world.level.biome.BiomeSpecialEffects;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.registry.OpenRegistryImpl;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
|
||||
class MinecraftBiomeFactoryTest {
|
||||
private static final Registry<Attribute<?>> REGISTRY = registry();
|
||||
private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY);
|
||||
private static final RegistryOps<Object> OPS = CONTEXT.ops();
|
||||
private static final DecodeContext PLAIN = HANDLE.plainContext();
|
||||
private static final VanillaAttributeMaps MAPS = new VanillaAttributeMaps(HANDLE, CONTEXT);
|
||||
|
||||
private static final String CONFIG = "BIOME";
|
||||
private static final String FOG_COLOR = "minecraft:visual/fog_color";
|
||||
private static final String SKY_COLOR = "minecraft:visual/sky_color";
|
||||
private static final String AMBIENT_PARTICLES = "minecraft:visual/ambient_particles";
|
||||
private static final String SPAWN_PROBABILITY = "minecraft:gameplay/creature_world_gen_spawn_probability";
|
||||
private static final String VILLAGER_TYPE = "terra:biome/villager_type";
|
||||
|
||||
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
|
||||
|
||||
private final List<String> warnings = new ArrayList<>();
|
||||
private final List<String> debugs = new ArrayList<>();
|
||||
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
|
||||
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
|
||||
|
||||
private static Biome biome(ResourceKey<Biome> key) {
|
||||
return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <V> Object encode(Codec<V> codec, Object value) {
|
||||
return VanillaCodecs.encode(codec, (V) value, OPS);
|
||||
}
|
||||
|
||||
private static Object climate(Biome biome) {
|
||||
return encode(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings);
|
||||
}
|
||||
|
||||
private static Object effects(Biome biome) {
|
||||
return encode(BiomeSpecialEffects.CODEC, biome.getSpecialEffects());
|
||||
}
|
||||
|
||||
private static Map<?, ?> environment(Biome biome) {
|
||||
return (Map<?, ?>) encode(EnvironmentAttributeMap.CODEC, biome.getAttributes());
|
||||
}
|
||||
|
||||
private static AttributeEntry<?> decoded(String id, Object raw) {
|
||||
try {
|
||||
return HANDLE.decodeEntry(attribute(id), raw, PLAIN);
|
||||
} catch(DecodeException e) {
|
||||
throw new AssertionError(id + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, AttributeEntry<?> entry) {
|
||||
builder.put(attribute.key(), (AttributeEntry<T>) entry);
|
||||
}
|
||||
|
||||
private record Fixture(TestBiome biome, FakePackAttributes attributes, PackParents pack, MinecraftBiomeFactory factory,
|
||||
ResourceKey<Biome> parentKey, Biome parent) {
|
||||
MinecraftBiomeFactory.Built create(AttributeReport report) {
|
||||
return create(report, parent.getGenerationSettings());
|
||||
}
|
||||
|
||||
MinecraftBiomeFactory.Built create(AttributeReport report, BiomeGenerationSettings generation) {
|
||||
return factory.create(parentKey, parent, biome, pack, report, generation);
|
||||
}
|
||||
}
|
||||
|
||||
private Fixture fixture(ResourceKey<Biome> parentKey, Biome parent, Map<Attribute<?>, AttributeEntry<?>> entries) {
|
||||
return fixture(CONTEXT, PACK, parentKey, parent, entries);
|
||||
}
|
||||
|
||||
private Fixture fixture(VanillaContext context, ConfigPack pack, ResourceKey<Biome> parentKey, Biome parent,
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries) {
|
||||
TestBiome biome = new TestBiome(CONFIG, 0, parentKey.identifier());
|
||||
AttributeMap.Builder builder = AttributeMap.builder();
|
||||
entries.forEach((attribute, entry) -> put(builder, attribute, entry));
|
||||
FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(),
|
||||
Map.of(biome, builder.build()));
|
||||
parents.beginLoad(context);
|
||||
PackParents prepared = parents.prepare(pack, Optional.of(attributes), report);
|
||||
biome.platform().setParentEntries(parents.biomeEntries(prepared, parentKey, parent));
|
||||
return new Fixture(biome, attributes, prepared, new MinecraftBiomeFactory(HANDLE, context), parentKey, parent);
|
||||
}
|
||||
|
||||
private static Map<Attribute<?>, AttributeEntry<?>> entries(Object... idsAndRaw) {
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
for(int i = 0; i < idsAndRaw.length; i += 2) {
|
||||
String id = (String) idsAndRaw[i];
|
||||
entries.put(attribute(id), decoded(id, idsAndRaw[i + 1]));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private static void assertMatches(Biome expected, Biome actual) {
|
||||
assertEquals(expected.hasPrecipitation(), actual.hasPrecipitation());
|
||||
assertEquals(expected.getBaseTemperature(), actual.getBaseTemperature());
|
||||
assertEquals(expected.climateSettings, actual.climateSettings);
|
||||
assertEquals(climate(expected), climate(actual));
|
||||
assertEquals(effects(expected), effects(actual));
|
||||
assertEquals(expected.getAttributes().keySet(), actual.getAttributes().keySet());
|
||||
assertEquals(environment(expected), environment(actual));
|
||||
assertSame(expected.getGenerationSettings(), actual.getGenerationSettings());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noEntriesMatchesParent() {
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
Fixture fixture = fixture(Biomes.PLAINS, plains, Map.of());
|
||||
MinecraftBiomeFactory.Built built = fixture.create(report);
|
||||
|
||||
assertMatches(plains, built.biome());
|
||||
assertEquals(VillagerType.PLAINS, built.villagerType());
|
||||
MappedRegistry<Biome> registry = new MappedRegistry<>(Registries.BIOME, Lifecycle.stable());
|
||||
registry.register(Biomes.PLAINS, plains, RegistrationInfo.BUILT_IN);
|
||||
ResourceKey<Biome> key = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("terra", "test"));
|
||||
assertDoesNotThrow(() -> registry.register(key, built.biome(), RegistrationInfo.BUILT_IN));
|
||||
|
||||
Biome empty = fixture.create(report, BiomeGenerationSettings.EMPTY).biome();
|
||||
assertSame(BiomeGenerationSettings.EMPTY, empty.getGenerationSettings());
|
||||
assertEquals(plains.climateSettings, empty.climateSettings);
|
||||
assertEquals(climate(plains), climate(empty));
|
||||
assertEquals(effects(plains), effects(empty));
|
||||
assertEquals(environment(plains), environment(empty));
|
||||
|
||||
parents.beginLoad(CONTEXT);
|
||||
PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report);
|
||||
assertSame(PackAttributeTable.EMPTY, bare.table());
|
||||
TestBiome biome = new TestBiome(CONFIG, 0, Biomes.PLAINS.identifier());
|
||||
biome.platform().setParentEntries(parents.biomeEntries(bare, Biomes.PLAINS, plains));
|
||||
MinecraftBiomeFactory.Built withoutAttributes = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome,
|
||||
bare, report, plains.getGenerationSettings());
|
||||
assertMatches(plains, withoutAttributes.biome());
|
||||
assertNotSame(plains, withoutAttributes.biome());
|
||||
assertEquals(VillagerType.PLAINS, withoutAttributes.villagerType());
|
||||
assertEquals(List.of(), warnings);
|
||||
assertEquals(List.of(), debugs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void equivalentInputMatchesVanilla() {
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
Biome desert = biome(Biomes.DESERT);
|
||||
PackAttributeTable table = PackAttributeTable.of(REGISTRY);
|
||||
AttributeSlots desertSlots = new VanillaParentReader(HANDLE, CONTEXT).biome(Biomes.DESERT, desert, table, FAIL);
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
List<Attribute<?>> attributes = new ArrayList<>();
|
||||
table.environment().forEach(bound -> attributes.add(bound.attribute()));
|
||||
table.climate().forEach(field -> attributes.add(field.attribute()));
|
||||
table.effects().forEach(field -> attributes.add(field.attribute()));
|
||||
for(Attribute<?> attribute : attributes) {
|
||||
AttributeEntry<?> entry = desertSlots.get(attribute);
|
||||
if(entry != null) entries.put(attribute, entry);
|
||||
}
|
||||
assertTrue(entries.size() > 5, "desert has few entries: " + entries.size());
|
||||
|
||||
Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome();
|
||||
|
||||
assertEquals(desert.climateSettings, built.climateSettings);
|
||||
assertEquals(climate(desert), climate(built));
|
||||
assertEquals(effects(desert), effects(built));
|
||||
Map<?, ?> expected = environment(desert);
|
||||
Map<?, ?> parent = environment(plains);
|
||||
Map<?, ?> actual = environment(built);
|
||||
for(PackAttributeTable.Bound bound : table.environment()) {
|
||||
String id = bound.attribute().getRegistryKey().toString();
|
||||
if(desert.getAttributes().contains(bound.vanilla())) {
|
||||
assertEquals(expected.get(id), actual.get(id), id);
|
||||
} else {
|
||||
assertEquals(parent.get(id), actual.get(id), id + ": a key desert lacks keeps the plains parent's value");
|
||||
}
|
||||
}
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void desertParentKeepsNoPrecipitation() {
|
||||
Biome desert = biome(Biomes.DESERT);
|
||||
assertFalse(desert.hasPrecipitation());
|
||||
Biome built = fixture(Biomes.DESERT, desert, entries(FOG_COLOR, "#123456")).create(report).biome();
|
||||
|
||||
assertFalse(built.hasPrecipitation());
|
||||
assertEquals(desert.climateSettings, built.climateSettings);
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void spawnProbabilityIsApplied() {
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
Biome built = fixture(Biomes.PLAINS, plains, entries(SPAWN_PROBABILITY, 0.2)).create(report).biome();
|
||||
|
||||
assertTrue(built.getAttributes().contains(EnvironmentAttributes.CREATURE_WORLD_GEN_SPAWN_PROBABILITY));
|
||||
assertEquals(0.2f, built.getAttributes().applyModifier(EnvironmentAttributes.CREATURE_WORLD_GEN_SPAWN_PROBABILITY, 0.5f));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonComposableFallsBackToResolved() throws DecodeException {
|
||||
Attribute<Color> fog = attribute(FOG_COLOR);
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
AttributeEntry<Color> blend = HANDLE.decodeEntry(fog, Map.of("modifier", "alpha_blend", "argument", "#80ff0000"), PLAIN);
|
||||
Biome parent = new Biome.BiomeBuilder()
|
||||
.hasPrecipitation(true)
|
||||
.temperature(0.8f)
|
||||
.downfall(0.4f)
|
||||
.putAttributes(MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(fog, blend), true, FAIL))
|
||||
.specialEffects(plains.getSpecialEffects())
|
||||
.generationSettings(plains.getGenerationSettings())
|
||||
.build();
|
||||
ResourceKey<Biome> parentKey = ResourceKey.create(Registries.BIOME, Identifier.fromNamespaceAndPath("test", "blended"));
|
||||
AttributeEntry<?> multiply = decoded(FOG_COLOR, Map.of("modifier", "multiply", "argument", "#808080"));
|
||||
|
||||
Fixture fixture = fixture(parentKey, parent, Map.of(fog, multiply));
|
||||
assertEquals(blend, fixture.biome().platform().parentEntries().get(fog), "the parent's modifier is read");
|
||||
assertTrue(composed(fog, blend, multiply).isEmpty(), "alpha_blend then multiply has no single entry");
|
||||
Biome built = fixture.create(report).biome();
|
||||
|
||||
Color resolved = fixture.attributes().resolve(fog, fixture.biome());
|
||||
assertNotNull(resolved);
|
||||
EnvironmentAttributeMap expected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(fog, AttributeEntry.override(resolved)),
|
||||
true, FAIL);
|
||||
assertEquals(expected.get(EnvironmentAttributes.FOG_COLOR), built.getAttributes().get(EnvironmentAttributes.FOG_COLOR));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> Optional<AttributeEntry<T>> composed(Attribute<T> attribute, AttributeEntry<?> lower, AttributeEntry<?> upper) {
|
||||
return HANDLE.compose(attribute, (AttributeEntry<T>) lower, (AttributeEntry<T>) upper);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedEntriesAreSkippedAlone() {
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand"));
|
||||
PackAttributeTable.Bound nonPositional = PackAttributeTable.of(REGISTRY).environment().stream()
|
||||
.filter(b -> !b.vanilla().isPositional() && b.attribute().defaultValue() != null)
|
||||
.findFirst().orElseThrow();
|
||||
String nonPositionalId = nonPositional.attribute().getRegistryKey().toString();
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>(entries(
|
||||
AMBIENT_PARTICLES, List.of(Map.of("particle", oldParticle, "probability", 0.01)),
|
||||
FOG_COLOR, "#123456"));
|
||||
entries.put(nonPositional.attribute(), AttributeEntry.override(nonPositional.attribute().defaultValue()));
|
||||
|
||||
Biome built = fixture(Biomes.PLAINS, plains, entries).create(report).biome();
|
||||
|
||||
List<String> expected = new ArrayList<>();
|
||||
for(PackAttributeTable.Bound bound : PackAttributeTable.of(REGISTRY).environment()) {
|
||||
String id = bound.attribute().getRegistryKey().toString();
|
||||
if(id.equals(AMBIENT_PARTICLES) || id.equals(nonPositionalId)) {
|
||||
expected.add("Pack \"test\", config \"BIOME\": attribute \"" + id + "\" skipped: "
|
||||
+ rejection(id, entries.get(bound.attribute())));
|
||||
}
|
||||
}
|
||||
assertEquals(expected, warnings);
|
||||
assertEquals(plains.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES),
|
||||
built.getAttributes().contains(EnvironmentAttributes.AMBIENT_PARTICLES));
|
||||
assertFalse(built.getAttributes().contains(nonPositional.vanilla()));
|
||||
assertFogApplied(entries.get(attribute(FOG_COLOR)), built);
|
||||
}
|
||||
|
||||
private static void assertFogApplied(AttributeEntry<?> fog, Biome built) {
|
||||
EnvironmentAttributeMap expected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(attribute(FOG_COLOR), fog), true, FAIL);
|
||||
assertEquals(expected.get(EnvironmentAttributes.FOG_COLOR), built.getAttributes().get(EnvironmentAttributes.FOG_COLOR));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static String rejection(String id, AttributeEntry<?> entry) {
|
||||
Attribute<Object> attribute = attribute(id);
|
||||
Object raw = HANDLE.encodeEntry(attribute, (AttributeEntry<Object>) entry);
|
||||
DecodeException e = assertThrows(DecodeException.class,
|
||||
() -> VanillaCodecs.parse(EnvironmentAttributeMap.CODEC_ONLY_POSITIONAL, Map.of(id, raw), OPS));
|
||||
assertFalse(e.getMessage().isBlank());
|
||||
return e.getMessage();
|
||||
}
|
||||
|
||||
@Test
|
||||
void badFieldIsSkippedAlone() {
|
||||
Attribute<RegistryKey> downfall = HANDLE.attributeBuilder(AttributeKey.<RegistryKey>parse("terra:biome/downfall"),
|
||||
HANDLE.types().identifier("minecraft"),
|
||||
RegistryKey.parse("minecraft:none")).build();
|
||||
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
|
||||
for(Attribute<?> attribute : ATTRIBUTES) {
|
||||
if(!attribute.getRegistryKey().equals(downfall.getRegistryKey())) registry.register(attribute.getRegistryKey(), attribute);
|
||||
}
|
||||
registry.register(downfall.getRegistryKey(), downfall);
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>(entries("terra:biome/temperature", 0.3));
|
||||
entries.put(downfall, AttributeEntry.override(RegistryKey.parse("minecraft:wet")));
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
|
||||
Biome built = fixture(CONTEXT, MinecraftAttributeParentsTest.pack("test", registry), Biomes.PLAINS, plains, entries)
|
||||
.create(report).biome();
|
||||
|
||||
assertEquals(2, warnings.size(), warnings.toString());
|
||||
assertTrue(warnings.get(0).startsWith("Pack \"test\", config \"pack.yml\": attribute \"terra:biome/downfall\" "
|
||||
+ "skipped: vanilla parent \"minecraft:plains\": "), warnings.get(0));
|
||||
assertTrue(warnings.get(1).startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/downfall\" skipped: "),
|
||||
warnings.get(1));
|
||||
assertEquals(0.3f, built.getBaseTemperature());
|
||||
assertEquals(plains.climateSettings.downfall(), built.climateSettings.downfall());
|
||||
assertEquals(plains.hasPrecipitation(), built.hasPrecipitation());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownParentAttributeIsKept() {
|
||||
OpenRegistryImpl<Attribute<?>> withoutSky = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
|
||||
for(Attribute<?> attribute : ATTRIBUTES) {
|
||||
if(!attribute.getRegistryKey().toString().equals(SKY_COLOR)) withoutSky.register(attribute.getRegistryKey(), attribute);
|
||||
}
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
EnvironmentAttribute<?> sky = vanilla(SKY_COLOR);
|
||||
assertTrue(plains.getAttributes().contains(sky));
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = entries(FOG_COLOR, "#123456");
|
||||
|
||||
Fixture fixture = fixture(CONTEXT, MinecraftAttributeParentsTest.pack("nosky", withoutSky), Biomes.PLAINS, plains, entries);
|
||||
assertNull(fixture.biome().platform().parentEntries().get(attribute(SKY_COLOR)), "the pack does not know sky colour");
|
||||
Biome built = fixture.create(report).biome();
|
||||
|
||||
assertSame(plains.getAttributes().get(sky), built.getAttributes().get(sky));
|
||||
assertFogApplied(entries.get(attribute(FOG_COLOR)), built);
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void addonAttributeIsDebugLogged() {
|
||||
Attribute<Float> custom = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:custom"), HANDLE.types().floatType(), 0f)
|
||||
.build();
|
||||
Attribute<Float> unset = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:unset"), HANDLE.types().floatType(), 0f)
|
||||
.build();
|
||||
ConfigPack pack = MinecraftAttributeParentsTest.pack("test", registry(custom, unset));
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
|
||||
Biome built = fixture(CONTEXT, pack, Biomes.PLAINS, plains, Map.of(custom, AttributeEntry.override(1f))).create(report).biome();
|
||||
|
||||
assertEquals(List.of("Pack \"test\": attribute \"test:custom\" is not applied on this platform"), debugs);
|
||||
assertEquals(List.of(), warnings);
|
||||
assertMatches(plains, built);
|
||||
}
|
||||
|
||||
@Test
|
||||
void villagerTypeFallsBackToParent() {
|
||||
VanillaContext villagers = VanillaContext.of(REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null);
|
||||
Biome desert = biome(Biomes.DESERT);
|
||||
|
||||
assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, Map.of()).create(report).villagerType());
|
||||
assertEquals(VillagerType.SNOW, fixture(villagers, PACK, Biomes.DESERT, desert, entries(VILLAGER_TYPE, "minecraft:snow"))
|
||||
.create(report).villagerType());
|
||||
assertEquals(List.of(), warnings);
|
||||
|
||||
assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, entries(VILLAGER_TYPE, "minecraft:nope"))
|
||||
.create(report).villagerType());
|
||||
assertEquals(List.of("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: "
|
||||
+ "no such villager type \"minecraft:nope\""), warnings);
|
||||
warnings.clear();
|
||||
|
||||
Map<Attribute<?>, AttributeEntry<?>> upper = Map.of(attribute(VILLAGER_TYPE),
|
||||
AttributeEntry.override(RegistryKey.of("minecraft", "Snow")));
|
||||
assertEquals(VillagerType.DESERT, fixture(villagers, PACK, Biomes.DESERT, desert, upper).create(report).villagerType());
|
||||
assertEquals(1, warnings.size(), warnings.toString());
|
||||
assertTrue(warnings.getFirst().startsWith("Pack \"test\", config \"BIOME\": attribute \"terra:biome/villager_type\" skipped: "
|
||||
+ "invalid ID \"minecraft:Snow\""), warnings.getFirst());
|
||||
warnings.clear();
|
||||
|
||||
assertEquals(VillagerType.PLAINS, fixture(villagers, PACK, Biomes.PLAINS, biome(Biomes.PLAINS), Map.of())
|
||||
.create(report).villagerType());
|
||||
parents.beginLoad(villagers);
|
||||
PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report);
|
||||
TestBiome biome = new TestBiome(CONFIG, 0, Biomes.DESERT.identifier());
|
||||
biome.platform().setParentEntries(parents.biomeEntries(bare, Biomes.DESERT, desert));
|
||||
assertEquals(VillagerType.DESERT,
|
||||
new MinecraftBiomeFactory(HANDLE, villagers).create(Biomes.DESERT, desert, biome, bare, report,
|
||||
desert.getGenerationSettings()).villagerType());
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadBuildsEqualBiome() {
|
||||
Biome plains = biome(Biomes.PLAINS);
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = entries(FOG_COLOR, "#123456", "terra:biome/temperature", 0.3);
|
||||
Fixture before = fixture(Biomes.PLAINS, plains, entries);
|
||||
Biome first = before.create(report).biome();
|
||||
|
||||
parents.clearPacks();
|
||||
assertNull(parents.packOrNull(before.attributes(), attribute(FOG_COLOR)));
|
||||
TestBiome biome = new TestBiome(CONFIG, 0, Biomes.PLAINS.identifier());
|
||||
AttributeMap.Builder builder = AttributeMap.builder();
|
||||
entries.forEach((attribute, entry) -> put(builder, attribute, entry));
|
||||
FakePackAttributes reloaded = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(),
|
||||
Map.of(biome, builder.build()));
|
||||
PackParents again = parents.prepare(PACK, Optional.of(reloaded), report);
|
||||
assertNotSame(before.pack(), again);
|
||||
biome.platform().setParentEntries(parents.biomeEntries(again, Biomes.PLAINS, plains));
|
||||
Biome second = new MinecraftBiomeFactory(HANDLE, CONTEXT).create(Biomes.PLAINS, plains, biome, again, report,
|
||||
plains.getGenerationSettings()).biome();
|
||||
|
||||
assertEquals(0.3f, second.getBaseTemperature());
|
||||
assertEquals(climate(first), climate(second));
|
||||
assertEquals(effects(first), effects(second));
|
||||
assertEquals(environment(first), environment(second));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
}
|
||||
+292
@@ -0,0 +1,292 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.RegistrationInfo;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeMap;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.timeline.Timeline;
|
||||
import net.minecraft.world.timeline.Timelines;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.registry.OpenRegistryImpl;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
|
||||
class MinecraftDimensionFactoryTest {
|
||||
private static final Registry<Attribute<?>> REGISTRY = registry();
|
||||
private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY);
|
||||
private static final RegistryOps<Object> OPS = CONTEXT.ops();
|
||||
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
|
||||
|
||||
private final List<String> warnings = new ArrayList<>();
|
||||
private final List<String> debugs = new ArrayList<>();
|
||||
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
|
||||
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
|
||||
private final MinecraftDimensionFactory factory = new MinecraftDimensionFactory(HANDLE, CONTEXT);
|
||||
|
||||
private static DimensionType dimensionType(ResourceKey<DimensionType> key) {
|
||||
return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(key).value();
|
||||
}
|
||||
|
||||
private static Map<?, ?> environment(EnvironmentAttributeMap map) {
|
||||
return (Map<?, ?>) VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, OPS);
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, AttributeEntry<?> entry) {
|
||||
builder.put(attribute.key(), (AttributeEntry<T>) entry);
|
||||
}
|
||||
|
||||
private static AttributeEntry<?> decoded(String id, Object raw) {
|
||||
try {
|
||||
return HANDLE.decodeEntry(attribute(id), raw, HANDLE.plainContext());
|
||||
} catch(DecodeException e) {
|
||||
throw new AssertionError(id + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private PackParents prepare(ConfigPack pack, Map<Attribute<?>, AttributeEntry<?>> entries, Map<String, RegistryKey> parentIds) {
|
||||
AttributeMap.Builder builder = AttributeMap.builder();
|
||||
entries.forEach((attribute, entry) -> put(builder, attribute, entry));
|
||||
FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, builder.build(), parentIds, Map.of());
|
||||
parents.beginLoad(CONTEXT);
|
||||
return parents.prepare(pack, Optional.of(attributes), report);
|
||||
}
|
||||
|
||||
private PackParents prepare(Map<Attribute<?>, AttributeEntry<?>> entries) {
|
||||
return prepare(PACK, entries, Map.of());
|
||||
}
|
||||
|
||||
private PackParents bare() {
|
||||
parents.beginLoad(CONTEXT);
|
||||
return parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report);
|
||||
}
|
||||
|
||||
@Test
|
||||
void typeIdFollowsFilledDimension() {
|
||||
Identifier plain = Identifier.parse("terra:test");
|
||||
Identifier nether = Identifier.parse("terra:test/minecraft/the_nether");
|
||||
|
||||
assertEquals(plain, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.OVERWORLD, false));
|
||||
assertEquals(nether, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.NETHER, false));
|
||||
assertEquals(nether, MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.NETHER, true));
|
||||
assertEquals(Identifier.parse("terra:test/minecraft/overworld"),
|
||||
MinecraftDimensionFactory.typeId(PACK, BuiltinDimensionTypes.OVERWORLD, true));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noEntriesMatchesParent() {
|
||||
assertRegistersBesideParent(BuiltinDimensionTypes.OVERWORLD, factory.create(prepare(Map.of()), null));
|
||||
assertRegistersBesideParent(BuiltinDimensionTypes.OVERWORLD, factory.create(bare(), null));
|
||||
assertRegistersBesideParent(BuiltinDimensionTypes.NETHER, factory.create(
|
||||
prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether"))), null));
|
||||
assertEquals(List.of(), warnings);
|
||||
assertEquals(List.of(), debugs);
|
||||
}
|
||||
|
||||
private static void assertRegistersBesideParent(ResourceKey<DimensionType> parentKey, DimensionType built) {
|
||||
DimensionType parent = dimensionType(parentKey);
|
||||
assertEquals(parent, built, parentKey.toString());
|
||||
MappedRegistry<DimensionType> registry = new MappedRegistry<>(Registries.DIMENSION_TYPE, Lifecycle.stable());
|
||||
registry.register(parentKey, parent, RegistrationInfo.BUILT_IN);
|
||||
ResourceKey<DimensionType> key = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.fromNamespaceAndPath("terra", "test"));
|
||||
assertDoesNotThrow(() -> registry.register(key, built, RegistrationInfo.BUILT_IN), parentKey.toString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void equivalentInputMatchesVanilla() {
|
||||
DimensionType nether = dimensionType(BuiltinDimensionTypes.NETHER);
|
||||
PackAttributeTable table = PackAttributeTable.of(REGISTRY);
|
||||
AttributeSlots netherSlots = new VanillaParentReader(HANDLE, CONTEXT).dimension(nether, table, FAIL);
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
List<Attribute<?>> attributes = new ArrayList<>();
|
||||
table.environment().forEach(bound -> attributes.add(bound.attribute()));
|
||||
table.dimension().forEach(field -> attributes.add(field.attribute()));
|
||||
for(Attribute<?> attribute : attributes) {
|
||||
AttributeEntry<?> entry = netherSlots.get(attribute);
|
||||
if(entry != null) entries.put(attribute, entry);
|
||||
}
|
||||
assertTrue(entries.size() > 5, "the nether has few entries: " + entries.size());
|
||||
|
||||
DimensionType built = factory.create(prepare(entries), null);
|
||||
|
||||
assertEquals(nether.hasFixedTime(), built.hasFixedTime());
|
||||
assertEquals(nether.hasSkyLight(), built.hasSkyLight());
|
||||
assertEquals(nether.hasCeiling(), built.hasCeiling());
|
||||
assertEquals(nether.hasEnderDragonFight(), built.hasEnderDragonFight());
|
||||
assertEquals(nether.coordinateScale(), built.coordinateScale());
|
||||
assertEquals(nether.minY(), built.minY());
|
||||
assertEquals(nether.height(), built.height());
|
||||
assertEquals(nether.logicalHeight(), built.logicalHeight());
|
||||
assertEquals(nether.infiniburn().unwrapKey(), built.infiniburn().unwrapKey());
|
||||
assertEquals(nether.ambientLight(), built.ambientLight());
|
||||
assertEquals(nether.monsterSettings(), built.monsterSettings());
|
||||
assertEquals(nether.skybox(), built.skybox());
|
||||
assertEquals(nether.cardinalLightType(), built.cardinalLightType());
|
||||
assertEquals(Optional.empty(), built.defaultClock());
|
||||
assertEquals(nether.defaultClock(), built.defaultClock());
|
||||
|
||||
Map<?, ?> expected = environment(nether.attributes());
|
||||
Map<?, ?> actual = environment(built.attributes());
|
||||
for(Object key : expected.keySet()) assertEquals(expected.get(key), actual.get(key), String.valueOf(key));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidHeightIsSkippedAlone() {
|
||||
String fastLava = "minecraft:gameplay/fast_lava";
|
||||
String height = "terra:dimension/height";
|
||||
String ambientLight = "terra:dimension/ambient_light";
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
entries.put(attribute(height), AttributeEntry.override(100));
|
||||
entries.put(attribute(fastLava), decoded(fastLava, true));
|
||||
entries.put(attribute(ambientLight), decoded(ambientLight, 0.5));
|
||||
PackParents pack = prepare(entries);
|
||||
DimensionType built = assertInvalidHeightKeepsFastLava(pack, fastLava);
|
||||
assertEquals(0.5f, built.ambientLight());
|
||||
assertEquals(384, factory.worldSettings(pack, built).height());
|
||||
|
||||
warnings.clear();
|
||||
OpenRegistryImpl<Attribute<?>> narrow = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
|
||||
narrow.register(attribute(height).getRegistryKey(), attribute(height));
|
||||
narrow.register(attribute(fastLava).getRegistryKey(), attribute(fastLava));
|
||||
entries.remove(attribute(ambientLight));
|
||||
assertInvalidHeightKeepsFastLava(prepare(MinecraftAttributeParentsTest.pack("test", narrow), entries, Map.of()), fastLava);
|
||||
}
|
||||
|
||||
private DimensionType assertInvalidHeightKeepsFastLava(PackParents pack, String fastLava) {
|
||||
DimensionType built = factory.create(pack, null);
|
||||
|
||||
assertEquals(List.of("Pack \"test\", config \"pack.yml\": attribute \"terra:dimension/height\" skipped: "
|
||||
+ "logical_height cannot be higher than height"), warnings);
|
||||
assertEquals(384, built.height());
|
||||
assertTrue(built.attributes().contains(vanilla(fastLava)));
|
||||
assertEquals(true, environment(built.attributes()).get(fastLava));
|
||||
return built;
|
||||
}
|
||||
|
||||
@Test
|
||||
void timelinesAreUsed() {
|
||||
TagKey<Timeline> tag = TagKey.create(Registries.TIMELINE, Identifier.parse("minecraft:in_overworld"));
|
||||
DimensionType nether = dimensionType(BuiltinDimensionTypes.NETHER);
|
||||
assertNotEquals(Optional.of(tag), nether.timelines().unwrapKey());
|
||||
PackParents netherPack = prepare(PACK, Map.of(), Map.of("vanilla", RegistryKey.parse("minecraft:the_nether")));
|
||||
DimensionType tagged = factory.create(netherPack, new TimelineRef.Tag(tag));
|
||||
|
||||
assertTrue(tagged.timelines() instanceof HolderSet.Named<?>, String.valueOf(tagged.timelines()));
|
||||
assertEquals(Optional.of(tag), tagged.timelines().unwrapKey());
|
||||
|
||||
List<ResourceKey<Timeline>> keys = List.of(Timelines.OVERWORLD_DAY, Timelines.MOON);
|
||||
DimensionType direct = factory.create(prepare(Map.of()), new TimelineRef.Direct(keys));
|
||||
|
||||
assertTrue(direct.timelines() instanceof HolderSet.Direct<?>, String.valueOf(direct.timelines()));
|
||||
assertEquals(keys.stream().map(Optional::of).toList(), direct.timelines().stream().map(Holder::unwrapKey).toList());
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectedTimelineTag() {
|
||||
TagKey<Timeline> tag = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:nope"));
|
||||
HolderLookup.RegistryLookup<Timeline> timelines = REGISTRIES.lookupOrThrow(Registries.TIMELINE);
|
||||
HolderLookup.RegistryLookup<Timeline> withoutTag = new HolderLookup.RegistryLookup.Delegate<>() {
|
||||
@Override
|
||||
public HolderLookup.RegistryLookup<Timeline> parent() {
|
||||
return timelines;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<HolderSet.Named<Timeline>> get(TagKey<Timeline> key) {
|
||||
return key.equals(tag) ? Optional.empty() : timelines.get(key);
|
||||
}
|
||||
};
|
||||
HolderLookup.Provider registries = HolderLookup.Provider.create(REGISTRIES.listRegistries()
|
||||
.map(lookup -> lookup.key().equals(Registries.TIMELINE) ? withoutTag : lookup));
|
||||
MinecraftDimensionFactory strict = new MinecraftDimensionFactory(HANDLE, VanillaContext.of(registries, key -> null));
|
||||
|
||||
DimensionType built = strict.create(prepare(Map.of()), new TimelineRef.Tag(tag));
|
||||
|
||||
assertEquals(1, warnings.size(), String.valueOf(warnings));
|
||||
String prefix = "Pack \"test\", config \"pack.yml\": \"schedules\" ignored: ";
|
||||
assertTrue(warnings.getFirst().startsWith(prefix), warnings.getFirst());
|
||||
assertTrue(Character.isLowerCase(warnings.getFirst().charAt(prefix.length())), warnings.getFirst());
|
||||
assertEquals(dimensionType(BuiltinDimensionTypes.OVERWORLD).timelines().unwrapKey(), built.timelines().unwrapKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unappliedPackEntriesAreDebugLogged() {
|
||||
Attribute<Integer> own = HANDLE.attributeBuilder(AttributeKey.<Integer>parse("addon:own"),
|
||||
HANDLE.types().integer(), 0).build();
|
||||
Registry<Attribute<?>> registry = registry(own);
|
||||
PackParents pack = prepare(MinecraftAttributeParentsTest.pack("test", registry), Map.of(own, AttributeEntry.override(3)),
|
||||
Map.of());
|
||||
factory.create(pack, null);
|
||||
|
||||
assertEquals(List.of("Pack \"test\": attribute \"addon:own\" is not applied on this platform"), debugs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void worldSettingsFromAttributes() {
|
||||
OpenRegistryImpl<Attribute<?>> noWorld = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
|
||||
ATTRIBUTES.stream()
|
||||
.filter(attribute -> !attribute.getRegistryKey().toString().startsWith("terra:world/"))
|
||||
.forEach(attribute -> noWorld.register(attribute.getRegistryKey(), attribute));
|
||||
PackParents noWorldPack = prepare(MinecraftAttributeParentsTest.pack("noworld", noWorld), Map.of(), Map.of());
|
||||
assertNull(noWorldPack.table().seaLevel());
|
||||
for(PackParents pack : List.of(noWorldPack, prepare(Map.of()), bare())) {
|
||||
assertEquals(new WorldSettings(-64, 384, 63, true, 64), factory.worldSettings(pack, factory.create(pack, null)));
|
||||
}
|
||||
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
for(Map.Entry<String, Object> entry : Map.<String, Object>of("terra:dimension/min_y", -128, "terra:dimension/height", 512,
|
||||
"terra:world/sea_level", 40, "terra:world/spawn_height", 90,
|
||||
"terra:world/mob_generation", false).entrySet()) {
|
||||
entries.put(attribute(entry.getKey()), decoded(entry.getKey(), entry.getValue()));
|
||||
}
|
||||
PackParents pack = prepare(entries);
|
||||
DimensionType built = factory.create(pack, null);
|
||||
assertEquals(-128, built.minY());
|
||||
assertEquals(512, built.height());
|
||||
assertEquals(new WorldSettings(-128, 512, 40, false, 90), factory.worldSettings(pack, built));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
}
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.HolderSet;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.tags.TagLoader.LoadResult;
|
||||
import net.minecraft.tags.TimelineTags;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.clock.WorldClock;
|
||||
import net.minecraft.world.timeline.Timeline;
|
||||
import net.minecraft.world.timeline.Timelines;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.config.ConfigPack;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Easing;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Keyframe;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeReport;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla;
|
||||
import static com.dfsek.terra.minecraft.attribute.VanillaContextTest.copy;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
class MinecraftTimelinesTest {
|
||||
private static final com.dfsek.terra.api.registry.Registry<Attribute<?>> REGISTRY = registry();
|
||||
private static final ConfigPack PACK = MinecraftAttributeParentsTest.pack("test", REGISTRY);
|
||||
private static final PackAttributeTable TABLE = PackAttributeTable.of(REGISTRY);
|
||||
private static final RegistryKey SEASONS = RegistryKey.parse("mypack:seasons");
|
||||
private static final RegistryKey OVERWORLD = RegistryKey.parse("minecraft:overworld");
|
||||
private static final String SKY_COLOR = "minecraft:visual/sky_color";
|
||||
private static final TagKey<Timeline> TERRA_TEST = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:test"));
|
||||
|
||||
private final List<String> warnings = new ArrayList<>();
|
||||
private final List<String> debugs = new ArrayList<>();
|
||||
private final AttributeReport report = new AttributeReport("test", warnings::add, debugs::add);
|
||||
private final MinecraftAttributeParents parents = new MinecraftAttributeParents(HANDLE);
|
||||
|
||||
private static Object argument(Attribute<?> attribute, Object raw) {
|
||||
try {
|
||||
return attribute.type().decodeArgument(Operation.OVERRIDE, raw, HANDLE.plainContext());
|
||||
} catch(DecodeException e) {
|
||||
throw new AssertionError(attribute.getRegistryKey() + ": " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static ScheduleTrack<?> track(Attribute<?> attribute, Object first, Object second) {
|
||||
return new ScheduleTrack<>(Operation.OVERRIDE, List.of(new Keyframe(0, argument(attribute, first)),
|
||||
new Keyframe(12000, argument(attribute, second))),
|
||||
new Easing.Named("linear"));
|
||||
}
|
||||
|
||||
private static AttributeSchedule schedule(RegistryKey clock, Map<RegistryKey, TimeMarker> markers) {
|
||||
Attribute<?> sky = attribute(SKY_COLOR);
|
||||
return new AttributeSchedule(clock, OptionalInt.of(24000), Map.of(sky, track(sky, "#78a7ff", "#000000")), markers);
|
||||
}
|
||||
|
||||
private static AttributeSchedule skySchedule() {
|
||||
return schedule(OVERWORLD, Map.of());
|
||||
}
|
||||
|
||||
private record Load(MappedRegistry<Timeline> timelines, MappedRegistry<WorldClock> clocks, VanillaContext context) {
|
||||
static Load create() {
|
||||
MappedRegistry<WorldClock> clocks = bound(copy(Registries.WORLD_CLOCK));
|
||||
MappedRegistry<Timeline> timelines = bound(copy(Registries.TIMELINE));
|
||||
VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS),
|
||||
copy(Registries.BIOME), clocks, timelines),
|
||||
MinecraftTestSupport.loadContext(), key -> null);
|
||||
timelines.bindTags(Map.of(TimelineTags.IN_OVERWORLD, List.of(timelines.get(Timelines.OVERWORLD_DAY).orElseThrow(),
|
||||
timelines.get(Timelines.MOON).orElseThrow()),
|
||||
TimelineTags.UNIVERSAL, List.of()));
|
||||
return new Load(timelines, clocks, context);
|
||||
}
|
||||
|
||||
private static <T> MappedRegistry<T> bound(MappedRegistry<T> registry) {
|
||||
try {
|
||||
Method bind = Holder.Reference.class.getDeclaredMethod("bindValue", Object.class);
|
||||
bind.setAccessible(true);
|
||||
for(Map.Entry<ResourceKey<T>, T> entry : registered(registry).entrySet()) {
|
||||
bind.invoke(registry.get(entry.getKey()).orElseThrow(), entry.getValue());
|
||||
}
|
||||
} catch(ReflectiveOperationException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> Map<ResourceKey<T>, T> registered(MappedRegistry<T> registry) throws ReflectiveOperationException {
|
||||
java.lang.reflect.Field byValue = MappedRegistry.class.getDeclaredField("byValue");
|
||||
byValue.setAccessible(true);
|
||||
Map<ResourceKey<T>, T> values = new LinkedHashMap<>();
|
||||
((Map<T, Holder.Reference<T>>) byValue.get(registry)).forEach((value, holder) -> values.put(holder.key(), value));
|
||||
return values;
|
||||
}
|
||||
|
||||
Holder.Reference<Timeline> timeline(ResourceKey<Timeline> key) {
|
||||
return timelines.get(key).orElseThrow();
|
||||
}
|
||||
}
|
||||
|
||||
private PackParents prepare(List<Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey>> refs,
|
||||
Map<RegistryKey, AttributeSchedule> definitions) {
|
||||
FakePackAttributes attributes = new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of(), refs,
|
||||
definitions);
|
||||
parents.beginLoad(CONTEXT);
|
||||
return parents.prepare(PACK, Optional.of(attributes), report);
|
||||
}
|
||||
|
||||
private static Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> id(String id) {
|
||||
return Either.left(RegistryKey.parse(id));
|
||||
}
|
||||
|
||||
private static Either<RegistryKey, com.dfsek.terra.api.registry.key.TagKey> tag(String namespace, String id) {
|
||||
return Either.right(com.dfsek.terra.api.registry.key.TagKey.of(RegistryKey.of(namespace, id)));
|
||||
}
|
||||
|
||||
private static String skipped(String schedule, String reason) {
|
||||
return "Pack \"test\": schedule \"" + schedule + "\" skipped: " + reason;
|
||||
}
|
||||
|
||||
private void assertOneWarningStartingWith(String prefix) {
|
||||
assertEquals(1, warnings.size(), String.valueOf(warnings));
|
||||
assertTrue(warnings.getFirst().startsWith(prefix), warnings.getFirst());
|
||||
}
|
||||
|
||||
@Test
|
||||
void definitionParses() {
|
||||
Attribute<?> sky = attribute(SKY_COLOR);
|
||||
Attribute<?> temperature = attribute("terra:biome/temperature");
|
||||
Map<Attribute<?>, ScheduleTrack<?>> tracks = new LinkedHashMap<>();
|
||||
tracks.put(sky, track(sky, "#78a7ff", "#000000"));
|
||||
tracks.put(temperature, track(temperature, 0.5, 1.0));
|
||||
AttributeSchedule schedule = new AttributeSchedule(OVERWORLD, OptionalInt.of(24000), tracks, Map.of());
|
||||
|
||||
Timeline timeline = MinecraftTimelines.create(SEASONS, schedule, TABLE, HANDLE, CONTEXT, report);
|
||||
|
||||
assertNotNull(timeline, String.valueOf(warnings));
|
||||
assertEquals(Optional.of(24000), timeline.periodTicks());
|
||||
assertEquals(Set.of(vanilla(SKY_COLOR)), timeline.attributes());
|
||||
assertEquals(Optional.of(ResourceKey.create(Registries.WORLD_CLOCK, Identifier.parse("minecraft:overworld"))),
|
||||
timeline.clock().unwrapKey());
|
||||
assertEquals(List.of(), warnings);
|
||||
assertEquals(List.of("Pack \"test\": attribute \"terra:biome/temperature\" is not applied on this platform"), debugs);
|
||||
}
|
||||
|
||||
@Test
|
||||
void badIdsSkipSchedule() {
|
||||
Map<String, Runnable> cases = new LinkedHashMap<>();
|
||||
cases.put(skipped("mypack:Seasons", "invalid ID \"mypack:Seasons\""),
|
||||
() -> assertNull(MinecraftTimelines.create(RegistryKey.parse("mypack:Seasons"), skySchedule(), TABLE, HANDLE, CONTEXT,
|
||||
report)));
|
||||
cases.put(skipped("mypack:seasons", "invalid ID \"minecraft:Overworld\""),
|
||||
() -> assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("minecraft:Overworld"), Map.of()), TABLE,
|
||||
HANDLE, CONTEXT, report)));
|
||||
cases.put(skipped("mypack:seasons", "invalid ID \"mypack:Noon\""),
|
||||
() -> assertNull(MinecraftTimelines.create(SEASONS, schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:Noon"),
|
||||
new TimeMarker(6000, false))),
|
||||
TABLE, HANDLE, CONTEXT, report)));
|
||||
cases.put(skipped("mypack:seasons", "no such clock \"test:nope\""),
|
||||
() -> assertNull(MinecraftTimelines.create(SEASONS, schedule(RegistryKey.parse("test:nope"), Map.of()), TABLE, HANDLE,
|
||||
CONTEXT, report)));
|
||||
cases.forEach((prefix, create) -> {
|
||||
warnings.clear();
|
||||
assertDoesNotThrow(create::run, prefix);
|
||||
assertOneWarningStartingWith(prefix);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
void definitionsAreRegistered() {
|
||||
Load load = Load.create();
|
||||
int before = load.timelines().size();
|
||||
PackParents pack = prepare(List.of(), Map.of(SEASONS, skySchedule()));
|
||||
|
||||
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
|
||||
|
||||
assertEquals(List.of(), warnings);
|
||||
assertEquals(before + 1, load.timelines().size());
|
||||
assertDoesNotThrow(load.timelines()::freeze);
|
||||
Timeline seasons = load.timelines().getValue(Identifier.parse("mypack:seasons"));
|
||||
assertNotNull(seasons);
|
||||
assertEquals(Set.of(vanilla(SKY_COLOR)), seasons.attributes());
|
||||
assertSame(load.clocks().get(Identifier.parse("minecraft:overworld")).orElseThrow(), seasons.clock());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingIdIsNotReplaced() {
|
||||
Load load = Load.create();
|
||||
int before = load.timelines().size();
|
||||
PackParents pack = prepare(List.of(), Map.of(RegistryKey.parse("minecraft:day"), skySchedule()));
|
||||
|
||||
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
|
||||
|
||||
assertEquals(List.of(skipped("minecraft:day", "a timeline with this ID already exists")), warnings);
|
||||
assertEquals(before, load.timelines().size());
|
||||
load.timelines().freeze();
|
||||
assertSame(REGISTRIES.lookupOrThrow(Registries.TIMELINE).getOrThrow(Timelines.OVERWORLD_DAY).value(),
|
||||
load.timelines().getValue(Timelines.OVERWORLD_DAY));
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateTimeMarkerIsDropped() {
|
||||
Load load = Load.create();
|
||||
int before = load.timelines().size();
|
||||
Map<RegistryKey, TimeMarker> seasonsMarkers = new LinkedHashMap<>();
|
||||
seasonsMarkers.put(RegistryKey.parse("minecraft:noon"), new TimeMarker(6000, true));
|
||||
seasonsMarkers.put(RegistryKey.parse("mypack:dawn"), new TimeMarker(0, false));
|
||||
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
|
||||
definitions.put(SEASONS, schedule(OVERWORLD, seasonsMarkers));
|
||||
definitions.put(RegistryKey.parse("mypack:first"), schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:dusk"),
|
||||
new TimeMarker(13000, false))));
|
||||
definitions.put(RegistryKey.parse("mypack:second"), schedule(OVERWORLD, Map.of(RegistryKey.parse("mypack:dusk"),
|
||||
new TimeMarker(14000, false))));
|
||||
PackParents pack = prepare(List.of(), definitions);
|
||||
|
||||
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
|
||||
|
||||
assertEquals(List.of(markerDropped("mypack:seasons", "minecraft:noon"), markerDropped("mypack:second", "mypack:dusk")),
|
||||
warnings);
|
||||
assertEquals(before + 3, load.timelines().size());
|
||||
load.timelines().freeze();
|
||||
Map<ResourceKey<?>, Exception> errors = new HashMap<>();
|
||||
Timeline.validateRegistry(load.timelines(), errors);
|
||||
assertEquals(Map.of(), errors);
|
||||
assertEquals(Set.of("mypack:dawn"), markers(load.timelines().getValue(Identifier.parse("mypack:seasons"))));
|
||||
assertEquals(Set.of("mypack:dusk"), markers(load.timelines().getValue(Identifier.parse("mypack:first"))));
|
||||
Timeline second = load.timelines().getValue(Identifier.parse("mypack:second"));
|
||||
assertEquals(Set.of(), markers(second));
|
||||
assertEquals(Set.of(vanilla(SKY_COLOR)), second.attributes(), "the tracks stay");
|
||||
}
|
||||
|
||||
private static String markerDropped(String schedule, String marker) {
|
||||
return "Pack \"test\": schedule \"" + schedule + "\" time marker \"" + marker
|
||||
+ "\" dropped: already defined for clock \"minecraft:overworld\"";
|
||||
}
|
||||
|
||||
private static Set<String> markers(Timeline timeline) {
|
||||
Set<String> markers = new HashSet<>();
|
||||
timeline.registerTimeMarkers((key, marker) -> markers.add(key.identifier().toString()));
|
||||
return markers;
|
||||
}
|
||||
|
||||
@Test
|
||||
void noRefsMeansNoTag() {
|
||||
PackParents empty = prepare(List.of(), Map.of());
|
||||
assertNull(MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, empty));
|
||||
assertNull(MinecraftTimelines.pending(PACK, empty));
|
||||
parents.beginLoad(CONTEXT);
|
||||
PackParents bare = parents.prepare(MinecraftAttributeParentsTest.pack("bare", null), Optional.empty(), report);
|
||||
assertNull(MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, bare));
|
||||
assertNull(MinecraftTimelines.pending(PACK, bare));
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsAreFilled() {
|
||||
Load load = Load.create();
|
||||
Holder.Reference<Timeline> day = load.timeline(Timelines.OVERWORLD_DAY);
|
||||
Holder.Reference<Timeline> moon = load.timeline(Timelines.MOON);
|
||||
Holder.Reference<Timeline> villagers = load.timeline(Timelines.VILLAGER_SCHEDULE);
|
||||
PackParents pack = prepare(List.of(id("minecraft:day"), tag("minecraft", "in_overworld"), id("minecraft:nope"),
|
||||
tag("minecraft", "nope")), Map.of());
|
||||
assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack));
|
||||
assertEquals(List.of(), warnings);
|
||||
|
||||
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
|
||||
collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon, villagers));
|
||||
MinecraftTimelines.fillTags(collect, load.timelines());
|
||||
|
||||
assertEquals(List.of(day, moon, villagers), collect.get(TERRA_TEST));
|
||||
assertEquals(List.of(day, moon, villagers), collect.get(TimelineTags.IN_OVERWORLD));
|
||||
assertEquals(List.of(skipped("minecraft:nope", "no such timeline"), skipped("#minecraft:nope", "no such timeline tag")),
|
||||
warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidRefsKeepParentTimelines() {
|
||||
Load load = Load.create();
|
||||
Holder.Reference<Timeline> day = load.timeline(Timelines.OVERWORLD_DAY);
|
||||
Holder.Reference<Timeline> moon = load.timeline(Timelines.MOON);
|
||||
PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:nope"), tag("minecraft", "nope")), Map.of());
|
||||
assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack));
|
||||
assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\""));
|
||||
warnings.clear();
|
||||
|
||||
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
|
||||
collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon));
|
||||
MinecraftTimelines.fillTags(collect, load.timelines());
|
||||
|
||||
assertEquals(List.of(day, moon), collect.get(TERRA_TEST));
|
||||
assertTrue(collect.get(TERRA_TEST).contains(day), "the day cycle");
|
||||
assertEquals(List.of(skipped("minecraft:nope", "no such timeline"), skipped("#minecraft:nope", "no such timeline tag"),
|
||||
"Pack \"test\", config \"pack.yml\": \"schedules\" ignored: no valid schedule; "
|
||||
+ "the parent's timelines are kept"),
|
||||
warnings);
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagPerDimensionType() {
|
||||
Load load = Load.create();
|
||||
Holder.Reference<Timeline> day = load.timeline(Timelines.OVERWORLD_DAY);
|
||||
Holder.Reference<Timeline> moon = load.timeline(Timelines.MOON);
|
||||
PackParents overworld = prepare(List.of(id("minecraft:nope")), Map.of());
|
||||
PackParents nether = parents.prepare(PACK, Optional.ofNullable(overworld.attributes()), report, BuiltinDimensionTypes.NETHER);
|
||||
TagKey<Timeline> netherTag = TagKey.create(Registries.TIMELINE, Identifier.parse("terra:test/minecraft/the_nether"));
|
||||
assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, overworld));
|
||||
assertEquals(netherTag, MinecraftTimelines.tagFor(netherTag.location(), PACK, nether));
|
||||
|
||||
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
|
||||
collect.put(TimelineTags.IN_OVERWORLD, List.of(day, moon));
|
||||
MinecraftTimelines.fillTags(collect, load.timelines());
|
||||
|
||||
assertEquals(List.of(day, moon), collect.get(TERRA_TEST));
|
||||
assertFalse(collect.get(netherTag).contains(day), "the nether has no day cycle: " + collect.get(netherTag));
|
||||
}
|
||||
|
||||
@Test
|
||||
void pendingSkipsBadRefs() {
|
||||
Load load = Load.create();
|
||||
PackParents pack = prepare(List.of(tag("Mypack", "Tag"), id("minecraft:day")), Map.of());
|
||||
|
||||
MinecraftTimelines.Pending pending = assertDoesNotThrow(() -> MinecraftTimelines.pending(PACK, pack));
|
||||
|
||||
assertNotNull(pending);
|
||||
assertEquals(List.of(com.mojang.datafixers.util.Either.left(Identifier.parse("minecraft:day"))), pending.refs());
|
||||
assertOneWarningStartingWith(skipped("#Mypack:Tag", "invalid ID \"Mypack:Tag\""));
|
||||
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
|
||||
MinecraftTimelines.fillTags(collect, load.timelines());
|
||||
assertEquals(Map.of(), collect, "nothing recorded");
|
||||
assertEquals(1, warnings.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagRefillsOnReload() {
|
||||
Load load = Load.create();
|
||||
Registry<Timeline> timelines = load.timelines();
|
||||
Holder.Reference<Timeline> day = load.timeline(Timelines.OVERWORLD_DAY);
|
||||
Holder.Reference<Timeline> moon = load.timeline(Timelines.MOON);
|
||||
PackParents pack = prepare(List.of(id("mypack:seasons"), tag("minecraft", "in_overworld")),
|
||||
Map.of(SEASONS, skySchedule()));
|
||||
|
||||
MinecraftTimelines.register(PACK, pack, load.timelines(), HANDLE, load.context());
|
||||
TagKey<Timeline> tag = MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack);
|
||||
assertEquals(TERRA_TEST, tag);
|
||||
HolderSet.Named<Timeline> dimensionTimelines = load.context().ops().getter(Registries.TIMELINE).orElseThrow().get(tag)
|
||||
.orElseThrow();
|
||||
assertFalse(dimensionTimelines.isBound());
|
||||
MinecraftTimelines.bindPendingTags(load.timelines());
|
||||
assertDoesNotThrow(load.timelines()::freeze);
|
||||
Map<ResourceKey<?>, Exception> errors = new HashMap<>();
|
||||
Timeline.validateRegistry(timelines, errors);
|
||||
assertEquals(Map.of(), errors);
|
||||
|
||||
registerTimelineTags(timelines);
|
||||
Holder.Reference<Timeline> seasons = timelines.get(Identifier.parse("mypack:seasons")).orElseThrow();
|
||||
assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList());
|
||||
assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow());
|
||||
assertEquals(List.of(day, moon), timelines.get(TimelineTags.IN_OVERWORLD).orElseThrow().stream().toList());
|
||||
assertTrue(seasons.is(TERRA_TEST));
|
||||
|
||||
int tagsBefore = frozenTags(load.timelines()).size();
|
||||
parents.beginPackReload();
|
||||
parents.prepare(PACK, Optional.of(new FakePackAttributes(HANDLE, parents, AttributeMap.empty(), Map.of(), Map.of(),
|
||||
List.of(id("mypack:seasons"), tag("minecraft", "in_overworld")),
|
||||
Map.of(SEASONS, skySchedule()))), report);
|
||||
registerTimelineTags(timelines);
|
||||
parents.endPackReload();
|
||||
assertSame(dimensionTimelines, timelines.get(TERRA_TEST).orElseThrow());
|
||||
assertEquals(List.of(seasons, day, moon), dimensionTimelines.stream().toList());
|
||||
assertEquals(tagsBefore, frozenTags(load.timelines()).size(), "the reload created no tag");
|
||||
assertEquals(List.of(), warnings);
|
||||
}
|
||||
|
||||
private static void registerTimelineTags(Registry<Timeline> registry) {
|
||||
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
|
||||
registry.getTags().forEach(tag -> collect.put(tag.key(), new ArrayList<>(tag.stream().toList())));
|
||||
MinecraftTimelines.fillTags(collect, registry);
|
||||
registry.prepareTagReload(new LoadResult<>(registry.key(), collect)).apply();
|
||||
}
|
||||
|
||||
private static Map<?, ?> frozenTags(MappedRegistry<Timeline> registry) {
|
||||
try {
|
||||
java.lang.reflect.Field field = MappedRegistry.class.getDeclaredField("frozenTags");
|
||||
field.setAccessible(true);
|
||||
return (Map<?, ?>) field.get(registry);
|
||||
} catch(ReflectiveOperationException e) {
|
||||
throw new AssertionError(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void beginLoadDropsPendingTags() {
|
||||
Load load = Load.create();
|
||||
PackParents pack = prepare(List.of(id("minecraft:day")), Map.of());
|
||||
assertEquals(TERRA_TEST, MinecraftTimelines.tagFor(TERRA_TEST.location(), PACK, pack));
|
||||
|
||||
parents.beginLoad(CONTEXT);
|
||||
Map<TagKey<Timeline>, List<Holder<Timeline>>> collect = new HashMap<>();
|
||||
MinecraftTimelines.fillTags(collect, load.timelines());
|
||||
assertFalse(collect.containsKey(TERRA_TEST));
|
||||
}
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.util.ARGB;
|
||||
import net.minecraft.world.attribute.EnvironmentAttribute;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeMap;
|
||||
import net.minecraft.world.timeline.Timeline;
|
||||
import org.joml.Vector3f;
|
||||
import org.joml.Vector3fc;
|
||||
import org.joml.Vector4f;
|
||||
import org.joml.Vector4fc;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.Operation;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Easing;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.Keyframe;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.ScheduleTrack;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.TimeMarker;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.api.world.attribute.value.TriState;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.LOOKUP;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.vanilla;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
class VanillaCodecHarnessTest {
|
||||
private static final RegistryOps<Object> OPS = CONTEXT.ops();
|
||||
private static final DecodeContext PLAIN = HANDLE.plainContext();
|
||||
|
||||
private static final String FOG_COLOR = "minecraft:visual/fog_color";
|
||||
private static final String CLOUD_COLOR = "minecraft:visual/cloud_color";
|
||||
private static final String SKY_COLOR = "minecraft:visual/sky_color";
|
||||
private static final String STAR_BRIGHTNESS = "minecraft:visual/star_brightness";
|
||||
private static final String WATER_FOG_END = "minecraft:visual/water_fog_end_distance";
|
||||
private static final String EYEBLOSSOM_OPEN = "minecraft:gameplay/eyeblossom_open";
|
||||
private static final String SURFACE_SLIME_SPAWN_CHANCE = "minecraft:gameplay/surface_slime_spawn_chance";
|
||||
|
||||
private static final RegistryKey OVERWORLD = RegistryKey.parse("minecraft:overworld");
|
||||
private static final RegistryKey NOON = RegistryKey.parse("mypack:noon");
|
||||
private static final RegistryKey DUSK = RegistryKey.parse("mypack:dusk");
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <V> Codec<V> codec(String id) {
|
||||
return (Codec<V>) vanilla(id).valueCodec();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> asMap(Object raw) {
|
||||
return (Map<String, Object>) assertInstanceOf(Map.class, raw);
|
||||
}
|
||||
|
||||
private static float c(int n) {
|
||||
return (n + 0.25f) / 255f;
|
||||
}
|
||||
|
||||
private static <T> Object argument(Attribute<T> attribute, Operation operation, Object raw) throws DecodeException {
|
||||
return attribute.type().decodeArgument(operation, raw, PLAIN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void hexColorsMatchVanilla() throws DecodeException {
|
||||
Attribute<Color> fog = attribute(FOG_COLOR);
|
||||
Object fogForm = fog.type().encode(fog.type().decode("#c0d8ff", PLAIN));
|
||||
assertEquals("#c0d8ff", fogForm);
|
||||
Codec<Vector3fc> fogCodec = codec(FOG_COLOR);
|
||||
assertEquals(ARGB.vector3fFromRGB24(0xc0d8ff), VanillaCodecs.parse(fogCodec, fogForm, OPS));
|
||||
|
||||
Attribute<Color> cloud = attribute(CLOUD_COLOR);
|
||||
Object cloudForm = cloud.type().encode(cloud.type().decode("#80ff0000", PLAIN));
|
||||
assertEquals("#80ff0000", cloudForm);
|
||||
Codec<Vector4fc> cloudCodec = codec(CLOUD_COLOR);
|
||||
assertEquals(ARGB.vector4fFromARGB32(0x80ff0000), VanillaCodecs.parse(cloudCodec, cloudForm, OPS));
|
||||
|
||||
assertEquals(Color.rgb(0xc0d8ff), fog.type().decode(VanillaCodecs.encode(fogCodec, ARGB.vector3fFromRGB24(0xc0d8ff), OPS), PLAIN));
|
||||
assertEquals(Color.argb(0x80ff0000),
|
||||
cloud.type().decode(VanillaCodecs.encode(cloudCodec, ARGB.vector4fFromARGB32(0x80ff0000), OPS), PLAIN));
|
||||
}
|
||||
|
||||
@Test
|
||||
void floatListColorsMatchVanilla() throws DecodeException {
|
||||
Attribute<Color> fog = attribute(FOG_COLOR);
|
||||
Object fogForm = fog.type().encode(new Color(c(51), c(102), c(153), 1f));
|
||||
assertEquals(3, assertInstanceOf(List.class, fogForm).size());
|
||||
Vector3fc fogValue = VanillaCodecs.parse(VanillaCodecHarnessTest.<Vector3fc>codec(FOG_COLOR), fogForm, OPS);
|
||||
assertEquals(0x336699, ARGB.colorFromVector3f(fogValue) & 0xFFFFFF);
|
||||
assertEquals(new Vector3f(c(51), c(102), c(153)), fogValue, "vanilla keeps the float channels exactly");
|
||||
|
||||
Attribute<Color> cloud = attribute(CLOUD_COLOR);
|
||||
Object cloudForm = cloud.type().encode(new Color(c(51), c(102), c(153), c(204)));
|
||||
List<?> cloudList = assertInstanceOf(List.class, cloudForm);
|
||||
assertEquals(4, cloudList.size());
|
||||
assertEquals(c(204), cloudList.get(3), "alpha is last");
|
||||
Vector4fc cloudValue = VanillaCodecs.parse(VanillaCodecHarnessTest.<Vector4fc>codec(CLOUD_COLOR), cloudForm, OPS);
|
||||
assertEquals(0xcc336699, ARGB.colorFromVector4f(cloudValue));
|
||||
assertEquals(new Vector4f(c(51), c(102), c(153), c(204)), cloudValue, "vanilla keeps the float channels exactly");
|
||||
}
|
||||
|
||||
@Test
|
||||
void triStateMatchesVanilla() throws DecodeException {
|
||||
Attribute<TriState> eyeblossom = attribute(EYEBLOSSOM_OPEN);
|
||||
Codec<net.minecraft.util.TriState> codec = codec(EYEBLOSSOM_OPEN);
|
||||
Map<TriState, Object> forms = Map.of(TriState.TRUE, true, TriState.FALSE, false, TriState.DEFAULT, "default");
|
||||
Map<TriState, net.minecraft.util.TriState> vanillaValues = Map.of(
|
||||
TriState.TRUE, net.minecraft.util.TriState.TRUE,
|
||||
TriState.FALSE, net.minecraft.util.TriState.FALSE,
|
||||
TriState.DEFAULT, net.minecraft.util.TriState.DEFAULT);
|
||||
for(TriState value : TriState.values()) {
|
||||
Object form = eyeblossom.type().encode(value);
|
||||
assertEquals(forms.get(value), form, value.name());
|
||||
assertEquals(vanillaValues.get(value), VanillaCodecs.parse(codec, form, OPS), value.name());
|
||||
assertEquals(value, eyeblossom.type().decode(VanillaCodecs.encode(codec, vanillaValues.get(value), OPS), PLAIN),
|
||||
value.name());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyDefaultMatchesVanilla() {
|
||||
List<String> mismatches = new ArrayList<>();
|
||||
Set<String> checked = new TreeSet<>();
|
||||
for(AttributeKey<?> key : MinecraftAttributes.all()) {
|
||||
if(!key.getRegistryKey().getNamespace().equals("minecraft")) continue;
|
||||
String id = key.toString();
|
||||
String mismatch = defaultMismatch(attribute(id), vanilla(id));
|
||||
if(mismatch != null) mismatches.add(id + ": " + mismatch);
|
||||
checked.add(id);
|
||||
}
|
||||
assertEquals(List.of(), mismatches);
|
||||
Set<String> vanillaIds = new TreeSet<>();
|
||||
BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.keySet().forEach(id -> vanillaIds.add(id.toString()));
|
||||
assertEquals(vanillaIds, checked, "every vanilla attribute has a Terra key in the minecraft namespace");
|
||||
}
|
||||
|
||||
private static <T, V> String defaultMismatch(Attribute<T> attribute, EnvironmentAttribute<V> vanilla) {
|
||||
if(attribute.defaultValue() == null) return "Terra has no default";
|
||||
Object terraForm = attribute.type().encode(attribute.defaultValue());
|
||||
Codec<V> codec = vanilla.valueCodec();
|
||||
Object expected = VanillaCodecs.encode(codec, vanilla.defaultValue(), OPS);
|
||||
Object actual;
|
||||
try {
|
||||
actual = VanillaCodecs.encode(codec, VanillaCodecs.parse(codec, terraForm, OPS), OPS);
|
||||
} catch(DecodeException e) {
|
||||
return "vanilla rejects " + terraForm + ": " + e.getMessage();
|
||||
}
|
||||
return expected.equals(actual) ? null : "Terra " + terraForm + " reads as " + actual + ", vanilla default is " + expected;
|
||||
}
|
||||
|
||||
@Test
|
||||
void modifierEntriesParse() throws DecodeException {
|
||||
Attribute<Float> water = attribute(WATER_FOG_END);
|
||||
Object multiply = HANDLE.encodeEntry(water, AttributeEntry.of(Operation.MULTIPLY, argument(water, Operation.MULTIPLY, 0.85)));
|
||||
EnvironmentAttributeMap waterMap = VanillaCodecs.parse(EnvironmentAttributeMap.CODEC, Map.of(WATER_FOG_END, multiply), OPS);
|
||||
@SuppressWarnings("unchecked")
|
||||
EnvironmentAttribute<Float> vanillaWater = (EnvironmentAttribute<Float>) vanilla(WATER_FOG_END);
|
||||
assertTrue(waterMap.contains(vanillaWater));
|
||||
assertEquals(85f, waterMap.applyModifier(vanillaWater, 100f), 1e-4f);
|
||||
|
||||
Attribute<Color> fog = attribute(FOG_COLOR);
|
||||
Object blend = HANDLE.encodeEntry(fog, AttributeEntry.of(Operation.ALPHA_BLEND, argument(fog, Operation.ALPHA_BLEND, "#80ff0000")));
|
||||
EnvironmentAttributeMap fogMap = VanillaCodecs.parse(EnvironmentAttributeMap.CODEC, Map.of(FOG_COLOR, blend), OPS);
|
||||
@SuppressWarnings("unchecked")
|
||||
EnvironmentAttribute<Vector3fc> vanillaFog = (EnvironmentAttribute<Vector3fc>) vanilla(FOG_COLOR);
|
||||
assertTrue(fogMap.contains(vanillaFog));
|
||||
float alpha = 128 / 255f;
|
||||
Vector3fc blended = fogMap.applyModifier(vanillaFog, new Vector3f(0, 0, 1));
|
||||
assertEquals(alpha, blended.x(), 1e-3f, blended.toString());
|
||||
assertEquals(0, blended.y(), 1e-3f, blended.toString());
|
||||
assertEquals(1 - alpha, blended.z(), 1e-3f, blended.toString());
|
||||
}
|
||||
|
||||
private static AttributeSchedule clockOnly() {
|
||||
return new AttributeSchedule(OVERWORLD, OptionalInt.empty(), Map.of(), Map.of());
|
||||
}
|
||||
|
||||
private static AttributeSchedule periodic(Map<Attribute<?>, ScheduleTrack<?>> tracks, Map<RegistryKey, TimeMarker> markers) {
|
||||
return new AttributeSchedule(OVERWORLD, OptionalInt.of(24000), tracks, markers);
|
||||
}
|
||||
|
||||
private static AttributeSchedule withMarkers() {
|
||||
Map<RegistryKey, TimeMarker> markers = new LinkedHashMap<>();
|
||||
markers.put(NOON, new TimeMarker(12000, false));
|
||||
markers.put(DUSK, new TimeMarker(13000, true));
|
||||
return periodic(Map.of(), markers);
|
||||
}
|
||||
|
||||
private static AttributeSchedule withTrack(String id, Operation operation, Easing ease, Object first, Object second)
|
||||
throws DecodeException {
|
||||
Attribute<?> attribute = attribute(id);
|
||||
List<Keyframe> keyframes = List.of(new Keyframe(0, argument(attribute, operation, first)),
|
||||
new Keyframe(12000, argument(attribute, operation, second)));
|
||||
return periodic(Map.of(attribute, new ScheduleTrack<>(operation, keyframes, ease)), Map.of());
|
||||
}
|
||||
|
||||
private static AttributeSchedule skyColorTrack() throws DecodeException {
|
||||
return withTrack(SKY_COLOR, Operation.OVERRIDE, new Easing.Named("linear"), "#78a7ff", "#000000");
|
||||
}
|
||||
|
||||
private static Map<String, AttributeSchedule> schedules() throws DecodeException {
|
||||
Map<String, AttributeSchedule> schedules = new LinkedHashMap<>();
|
||||
schedules.put("a: clock only", clockOnly());
|
||||
schedules.put("b: period", periodic(Map.of(), Map.of()));
|
||||
schedules.put("c: time markers", withMarkers());
|
||||
schedules.put("d: override, linear", skyColorTrack());
|
||||
schedules.put("e: maximum, constant", withTrack(SURFACE_SLIME_SPAWN_CHANCE, Operation.MAXIMUM, new Easing.Named("constant"),
|
||||
0.25, 0.75));
|
||||
schedules.put("f: cubic bezier", withTrack(STAR_BRIGHTNESS, Operation.OVERRIDE, new Easing.CubicBezier(0.25f, 0.1f, 0.25f, 1f),
|
||||
1.0, 0.0));
|
||||
return schedules;
|
||||
}
|
||||
|
||||
@Test
|
||||
void schedulesParseAsTimelines() throws DecodeException {
|
||||
for(Map.Entry<String, AttributeSchedule> entry : schedules().entrySet()) {
|
||||
String name = entry.getKey();
|
||||
AttributeSchedule schedule = entry.getValue();
|
||||
Timeline timeline = VanillaCodecs.parse(Timeline.DIRECT_CODEC, HANDLE.encodeSchedule(schedule), OPS);
|
||||
Object vanillaForm = VanillaCodecs.encode(Timeline.DIRECT_CODEC, timeline, OPS);
|
||||
ScheduleDecodeResult result = HANDLE.decodeSchedule(RegistryKey.parse("mypack:schedule"), asMap(vanillaForm), LOOKUP,
|
||||
PLAIN);
|
||||
assertEquals(List.of(), result.droppedTracks(), name);
|
||||
assertEquals(Optional.empty(), result.skipped(), name);
|
||||
assertEquals(Optional.of(schedule), result.schedule(), name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void encodedSchedulesOmitDefaults() throws DecodeException {
|
||||
Map<String, Object> clockOnly = HANDLE.encodeSchedule(clockOnly());
|
||||
assertEquals(Map.of("clock", "minecraft:overworld"), clockOnly);
|
||||
VanillaCodecs.parse(Timeline.DIRECT_CODEC, clockOnly, OPS);
|
||||
|
||||
Map<String, Object> markers = HANDLE.encodeSchedule(withMarkers());
|
||||
Map<String, Object> encodedMarkers = asMap(markers.get("time_markers"));
|
||||
assertFalse(asMap(encodedMarkers.get("mypack:noon")).containsKey("show_in_commands"));
|
||||
assertEquals(true, asMap(encodedMarkers.get("mypack:dusk")).get("show_in_commands"));
|
||||
VanillaCodecs.parse(Timeline.DIRECT_CODEC, markers, OPS);
|
||||
|
||||
Map<String, Object> track = HANDLE.encodeSchedule(skyColorTrack());
|
||||
Map<String, Object> encodedTrack = asMap(asMap(track.get("tracks")).get(SKY_COLOR));
|
||||
assertFalse(encodedTrack.containsKey("modifier"));
|
||||
assertFalse(encodedTrack.containsKey("ease"));
|
||||
VanillaCodecs.parse(Timeline.DIRECT_CODEC, track, OPS);
|
||||
}
|
||||
|
||||
@Test
|
||||
void vanillaTimelinesRoundTrip() throws DecodeException {
|
||||
List<Holder.Reference<Timeline>> timelines = REGISTRIES.lookupOrThrow(Registries.TIMELINE).listElements().toList();
|
||||
assertFalse(timelines.isEmpty());
|
||||
for(Holder.Reference<Timeline> holder : timelines) {
|
||||
String name = holder.key().identifier().toString();
|
||||
Object first = VanillaCodecs.encode(Timeline.DIRECT_CODEC, holder.value(), OPS);
|
||||
ScheduleDecodeResult result = HANDLE.decodeSchedule(RegistryKey.parse(name), asMap(first), LOOKUP, PLAIN);
|
||||
assertEquals(List.of(), result.droppedTracks(), name);
|
||||
assertEquals(Optional.empty(), result.skipped(), name);
|
||||
Map<String, Object> terraForm = HANDLE.encodeSchedule(result.schedule().orElseThrow());
|
||||
Timeline reparsed = VanillaCodecs.parse(Timeline.DIRECT_CODEC, terraForm, OPS);
|
||||
assertEquals(first, VanillaCodecs.encode(Timeline.DIRECT_CODEC, reparsed, OPS), name);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void reasonsStartLowerCase() {
|
||||
DecodeException e = assertThrows(DecodeException.class, () -> VanillaCodecs.parse(Codec.INT, "x", OPS));
|
||||
assertEquals("not a number: x", e.getMessage());
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Lifecycle;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.MappedRegistry;
|
||||
import net.minecraft.core.RegistrationInfo;
|
||||
import net.minecraft.core.Registry;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.tags.BlockTags;
|
||||
import net.minecraft.tags.TagKey;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
|
||||
class VanillaContextTest {
|
||||
static <T> MappedRegistry<T> copy(ResourceKey<? extends Registry<T>> key) {
|
||||
MappedRegistry<T> registry = new MappedRegistry<>(key, Lifecycle.stable());
|
||||
REGISTRIES.lookupOrThrow(key).listElements()
|
||||
.forEach(holder -> registry.register(holder.key(), holder.value(), RegistrationInfo.BUILT_IN));
|
||||
return registry;
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownIdsKeepLoadFreezable() {
|
||||
MappedRegistry<DimensionType> dimensionTypes = copy(Registries.DIMENSION_TYPE);
|
||||
MappedRegistry<NoiseGeneratorSettings> noiseSettings = copy(Registries.NOISE_SETTINGS);
|
||||
MappedRegistry<Biome> biomes = copy(Registries.BIOME);
|
||||
VanillaContext context = VanillaContext.ofLoad(List.of(dimensionTypes, noiseSettings, biomes), MinecraftTestSupport.loadContext(),
|
||||
key -> null);
|
||||
|
||||
ResourceKey<DimensionType> nope = ResourceKey.create(Registries.DIMENSION_TYPE, Identifier.parse("minecraft:nope"));
|
||||
assertFalse(context.dimensionTypes().get(nope).isPresent());
|
||||
assertFalse(context.noiseSettings().get(ResourceKey.create(Registries.NOISE_SETTINGS, Identifier.parse("minecraft:nope")))
|
||||
.isPresent());
|
||||
assertFalse(context.biomes().get(ResourceKey.create(Registries.BIOME, Identifier.parse("minecraft:nope"))).isPresent());
|
||||
assertFalse(context.ops().getter(Registries.DIMENSION_TYPE).orElseThrow().get(nope).isPresent());
|
||||
|
||||
Holder.Reference<DimensionType> overworld = context.dimensionTypes().getOrThrow(BuiltinDimensionTypes.OVERWORLD);
|
||||
assertSame(dimensionTypes.get(BuiltinDimensionTypes.OVERWORLD).orElseThrow(), overworld);
|
||||
assertTrue(overworld.canSerializeIn(context.dimensionTypes()));
|
||||
assertTrue(overworld.canSerializeIn(context.ops().getter(Registries.DIMENSION_TYPE).orElseThrow()));
|
||||
|
||||
assertDoesNotThrow(dimensionTypes::freeze);
|
||||
assertDoesNotThrow(noiseSettings::freeze);
|
||||
assertDoesNotThrow(biomes::freeze);
|
||||
assertEquals(REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElementIds().count(), dimensionTypes.size());
|
||||
assertSame(REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD).value(),
|
||||
overworld.value());
|
||||
}
|
||||
|
||||
@Test
|
||||
void tagsAreCreatedOnDemand() {
|
||||
VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS),
|
||||
copy(Registries.BIOME)), MinecraftTestSupport.loadContext(),
|
||||
key -> null);
|
||||
TagKey<Biome> tag = TagKey.create(Registries.BIOME, Identifier.parse("terra:pack"));
|
||||
assertTrue(context.ops().getter(Registries.BIOME).orElseThrow().get(tag).isPresent());
|
||||
}
|
||||
|
||||
@Test
|
||||
void staticTagsResolveThroughLoadContext() {
|
||||
DimensionType overworld = REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(BuiltinDimensionTypes.OVERWORLD).value();
|
||||
TagKey<Block> infiniburn = BlockTags.INFINIBURN_OVERWORLD;
|
||||
assertTrue(BuiltInRegistries.BLOCK.get(infiniburn).isEmpty(), "the built-in registry already has the tag");
|
||||
Registry.PendingTags<Block> pending = BuiltInRegistries.BLOCK.prepareTagReload(
|
||||
new TagLoader.LoadResult<>(Registries.BLOCK, Map.of(infiniburn, List.of(Blocks.NETHERRACK.builtInRegistryHolder()))));
|
||||
VanillaContext context = VanillaContext.ofLoad(List.of(copy(Registries.DIMENSION_TYPE), copy(Registries.NOISE_SETTINGS),
|
||||
copy(Registries.BIOME), copy(Registries.WORLD_CLOCK),
|
||||
copy(Registries.TIMELINE)),
|
||||
MinecraftTestSupport.loadContext(pending), key -> null);
|
||||
Map<?, ?> encoded = (Map<?, ?>) VanillaCodecs.encode(DimensionType.DIRECT_CODEC, overworld, CONTEXT.ops());
|
||||
assertEquals("#minecraft:infiniburn_overworld", encoded.get("infiniburn"));
|
||||
|
||||
DimensionType parsed = assertDoesNotThrow(() -> VanillaCodecs.parse(DimensionType.DIRECT_CODEC, encoded, context.ops()));
|
||||
assertEquals(infiniburn, parsed.infiniburn().unwrapKey().orElseThrow());
|
||||
}
|
||||
}
|
||||
+356
@@ -0,0 +1,356 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import com.mojang.serialization.Codec;
|
||||
import net.minecraft.core.Holder;
|
||||
import net.minecraft.core.particles.BlockParticleOption;
|
||||
import net.minecraft.core.particles.ParticleOptions;
|
||||
import net.minecraft.core.particles.ParticleTypes;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.core.registries.Registries;
|
||||
import net.minecraft.resources.RegistryOps;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.world.attribute.EnvironmentAttribute;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributeMap;
|
||||
import net.minecraft.world.attribute.EnvironmentAttributes;
|
||||
import net.minecraft.world.entity.npc.villager.VillagerType;
|
||||
import net.minecraft.world.level.biome.Biome;
|
||||
import net.minecraft.world.level.biome.BiomeSpecialEffects;
|
||||
import net.minecraft.world.level.biome.Biomes;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.dimension.BuiltinDimensionTypes;
|
||||
import net.minecraft.world.level.dimension.DimensionType;
|
||||
import net.minecraft.world.level.levelgen.NoiseGeneratorSettings;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.BiConsumer;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeScope;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeContext;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.api.world.attribute.value.Color;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.ATTRIBUTES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.CONTEXT;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.HANDLE;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.REGISTRIES;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.attribute;
|
||||
import static com.dfsek.terra.minecraft.attribute.MinecraftTestSupport.registry;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertSame;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
|
||||
class VanillaParentReaderTest {
|
||||
private static final RegistryOps<Object> OPS = CONTEXT.ops();
|
||||
private static final DecodeContext PLAIN = HANDLE.plainContext();
|
||||
private static final PackAttributeTable TABLE = PackAttributeTable.of(registry());
|
||||
private static final VanillaAttributeMaps MAPS = new VanillaAttributeMaps(HANDLE, CONTEXT);
|
||||
private static final VanillaParentReader READER = new VanillaParentReader(HANDLE, CONTEXT);
|
||||
|
||||
private static final String AMBIENT_PARTICLES = "minecraft:visual/ambient_particles";
|
||||
private static final String FOG_COLOR = "minecraft:visual/fog_color";
|
||||
private static final String DEFAULT_CLOCK = "default_clock";
|
||||
|
||||
private static final BiConsumer<Attribute<?>, String> FAIL = (attribute, reason) -> fail(attribute.getRegistryKey() + ": " + reason);
|
||||
|
||||
private static Biome biome(ResourceKey<Biome> key) {
|
||||
return REGISTRIES.lookupOrThrow(Registries.BIOME).getOrThrow(key).value();
|
||||
}
|
||||
|
||||
private static DimensionType dimensionType(ResourceKey<DimensionType> key) {
|
||||
return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).getOrThrow(key).value();
|
||||
}
|
||||
|
||||
private static List<Holder.Reference<Biome>> biomes() {
|
||||
return REGISTRIES.lookupOrThrow(Registries.BIOME).listElements().toList();
|
||||
}
|
||||
|
||||
private static List<Holder.Reference<DimensionType>> dimensionTypes() {
|
||||
return REGISTRIES.lookupOrThrow(Registries.DIMENSION_TYPE).listElements().toList();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static Map<String, Object> encodeMap(Codec<?> codec, Object value) {
|
||||
Object raw = VanillaCodecs.encode((Codec<Object>) codec, value, OPS);
|
||||
return new LinkedHashMap<>((Map<String, Object>) assertInstanceOf(Map.class, raw));
|
||||
}
|
||||
|
||||
private static Map<String, Object> climate(Biome biome) {
|
||||
return encodeMap(Biome.ClimateSettings.CODEC.codec(), biome.climateSettings);
|
||||
}
|
||||
|
||||
private static Map<String, Object> effects(Biome biome) {
|
||||
return encodeMap(BiomeSpecialEffects.CODEC, biome.getSpecialEffects());
|
||||
}
|
||||
|
||||
private static void assertNoEntries(AttributeSlots slots, String what) {
|
||||
for(Attribute<?> attribute : ATTRIBUTES) assertNull(slots.get(attribute), what + ": " + attribute.getRegistryKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyVanillaAttributeInTable() {
|
||||
Set<EnvironmentAttribute<?>> bound = new HashSet<>();
|
||||
for(PackAttributeTable.Bound b : TABLE.environment()) {
|
||||
assertEquals(String.valueOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getKey(b.vanilla())),
|
||||
b.attribute().getRegistryKey().toString());
|
||||
bound.add(b.vanilla());
|
||||
}
|
||||
assertEquals(Set.copyOf(BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.stream().toList()), bound);
|
||||
assertEquals(bound.size(), TABLE.environment().size(), "each vanilla attribute is bound once");
|
||||
assertEquals(List.of(), TABLE.unapplied());
|
||||
|
||||
assertEquals(4, TABLE.climate().size());
|
||||
assertEquals(5, TABLE.effects().size());
|
||||
assertEquals(15, TABLE.dimension().size());
|
||||
assertEquals(attribute("terra:biome/villager_type"), TABLE.villagerType());
|
||||
assertEquals(attribute("terra:world/sea_level"), TABLE.seaLevel());
|
||||
assertEquals(attribute("terra:world/spawn_height"), TABLE.spawnHeight());
|
||||
assertEquals(attribute("terra:world/mob_generation"), TABLE.mobGeneration());
|
||||
}
|
||||
|
||||
@Test
|
||||
void terraScopeMatchesVanillaPositional() {
|
||||
List<String> mismatches = new ArrayList<>();
|
||||
for(PackAttributeTable.Bound b : TABLE.environment()) {
|
||||
boolean anywhere = b.attribute().scope() == AttributeScope.ANYWHERE;
|
||||
if(anywhere != b.vanilla().isPositional()) {
|
||||
mismatches.add(b.attribute().getRegistryKey() + ": Terra " + b.attribute().scope() + ", vanilla positional "
|
||||
+ b.vanilla().isPositional());
|
||||
}
|
||||
}
|
||||
assertEquals(List.of(), mismatches);
|
||||
}
|
||||
|
||||
@Test
|
||||
void noRegistryMeansEmptyTable() {
|
||||
PackAttributeTable table = PackAttributeTable.of(null);
|
||||
assertSame(PackAttributeTable.EMPTY, table);
|
||||
|
||||
VanillaParentReader reader = new VanillaParentReader(HANDLE, VanillaContext.of(REGISTRIES, key -> VillagerType.DESERT));
|
||||
assertNoEntries(reader.biome(Biomes.PLAINS, biome(Biomes.PLAINS), table, FAIL), "biome");
|
||||
assertNoEntries(reader.dimension(dimensionType(BuiltinDimensionTypes.NETHER), table, FAIL), "dimension");
|
||||
assertNoEntries(reader.generation(REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS)
|
||||
.getOrThrow(NoiseGeneratorSettings.OVERWORLD).value(), table), "generation");
|
||||
}
|
||||
|
||||
@Test
|
||||
void addonAttributeIsUnapplied() {
|
||||
Attribute<Float> custom = HANDLE.attributeBuilder(AttributeKey.<Float>parse("test:custom"), HANDLE.types().floatType(), 0f)
|
||||
.build();
|
||||
PackAttributeTable table = PackAttributeTable.of(registry(custom));
|
||||
assertEquals(List.of(custom), table.unapplied());
|
||||
assertEquals(TABLE.environment(), table.environment());
|
||||
assertNull(READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(custom));
|
||||
}
|
||||
|
||||
@Test
|
||||
void vanillaMapsRoundTrip() {
|
||||
int nonEmpty = 0;
|
||||
for(Holder.Reference<Biome> holder : biomes()) {
|
||||
if(roundTrip(holder.key().identifier().toString(), holder.value().getAttributes(), true)) nonEmpty++;
|
||||
}
|
||||
for(Holder.Reference<DimensionType> holder : dimensionTypes()) {
|
||||
if(roundTrip(holder.key().identifier().toString(), holder.value().attributes(), false)) nonEmpty++;
|
||||
}
|
||||
assertTrue(nonEmpty > 10, "few vanilla maps had entries: " + nonEmpty);
|
||||
}
|
||||
|
||||
private static boolean roundTrip(String name, EnvironmentAttributeMap map, boolean positional) {
|
||||
AttributeEntry<?>[] into = new AttributeEntry<?>[HANDLE.attributeCount()];
|
||||
MAPS.toTerra(map, TABLE, into, (attribute, reason) -> fail(name + ": " + attribute.getRegistryKey() + " unreadable: " + reason));
|
||||
Map<Attribute<?>, AttributeEntry<?>> entries = new LinkedHashMap<>();
|
||||
for(Attribute<?> attribute : ATTRIBUTES) {
|
||||
if(into[attribute.index()] != null) entries.put(attribute, into[attribute.index()]);
|
||||
}
|
||||
assertEquals(map.keySet().size(), entries.size(), name);
|
||||
EnvironmentAttributeMap back = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, entries, positional,
|
||||
(attribute, reason) -> fail(name + ": " + attribute.getRegistryKey()
|
||||
+ " skipped: " + reason));
|
||||
assertEquals(map.keySet(), back.keySet(), name);
|
||||
assertEquals(VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, map, OPS),
|
||||
VanillaCodecs.encode(EnvironmentAttributeMap.CODEC, back, OPS), name);
|
||||
return !entries.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void oldParticleFormIsRejected() throws DecodeException {
|
||||
Attribute<Object> particles = attribute(AMBIENT_PARTICLES);
|
||||
Object oldParticle = Map.of("type", "minecraft:falling_dust", "block_state", Map.of("Name", "minecraft:sand"));
|
||||
Object newParticle = VanillaCodecs.encode(ParticleTypes.CODEC,
|
||||
new BlockParticleOption(ParticleTypes.FALLING_DUST, Blocks.SAND.defaultBlockState()),
|
||||
OPS);
|
||||
|
||||
AttributeEntry<Object> old = HANDLE.decodeEntry(particles, List.of(Map.of("particle", oldParticle, "probability", 0.01)), PLAIN);
|
||||
List<String> skipped = new ArrayList<>();
|
||||
EnvironmentAttributeMap rejected = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(particles, old), true,
|
||||
(attribute, reason) -> {
|
||||
assertEquals(particles, attribute);
|
||||
skipped.add(reason);
|
||||
});
|
||||
assertEquals(1, skipped.size());
|
||||
assertFalse(skipped.getFirst().isBlank());
|
||||
assertFalse(rejected.contains(EnvironmentAttributes.AMBIENT_PARTICLES));
|
||||
|
||||
AttributeEntry<Object> accepted = HANDLE.decodeEntry(particles, List.of(Map.of("particle", newParticle, "probability", 0.01)),
|
||||
PLAIN);
|
||||
EnvironmentAttributeMap map = MAPS.toVanilla(EnvironmentAttributeMap.EMPTY, Map.of(particles, accepted), true, FAIL);
|
||||
List<net.minecraft.world.attribute.AmbientParticle> value = map.applyModifier(EnvironmentAttributes.AMBIENT_PARTICLES,
|
||||
List.of());
|
||||
assertEquals(1, value.size());
|
||||
ParticleOptions particle = value.getFirst().particle();
|
||||
BlockParticleOption block = assertInstanceOf(BlockParticleOption.class, particle);
|
||||
assertEquals(Blocks.SAND.defaultBlockState(), block.getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullOverrideKeepsBase() {
|
||||
Attribute<Color> fog = attribute(FOG_COLOR);
|
||||
EnvironmentAttributeMap base = biome(Biomes.PLAINS).getAttributes();
|
||||
EnvironmentAttributeMap result = MAPS.toVanilla(base, Map.of(fog, AttributeEntry.override(null)), true, FAIL);
|
||||
assertEquals(base, result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsBiomeFieldsAndEnvironment() {
|
||||
Attribute<?> temperature = attribute("terra:biome/temperature");
|
||||
Attribute<?> precipitation = attribute("terra:biome/has_precipitation");
|
||||
Attribute<?> villager = attribute("terra:biome/villager_type");
|
||||
|
||||
AttributeSlots plains = READER.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL);
|
||||
assertEquals(AttributeEntry.override(0.8f), plains.get(temperature));
|
||||
assertEquals(AttributeEntry.override(true), plains.get(precipitation));
|
||||
assertNull(plains.get(villager), "the test context has no villager types");
|
||||
|
||||
AttributeSlots desert = READER.biome(Biomes.DESERT, biome(Biomes.DESERT), TABLE, FAIL);
|
||||
assertEquals(AttributeEntry.override(false), desert.get(precipitation));
|
||||
|
||||
assertEquals(AttributeEntry.override(Color.rgb(0x3f76e4)), plains.get(attribute("terra:biome/water_color")));
|
||||
assertNull(plains.get(attribute("terra:biome/grass_color")));
|
||||
|
||||
VanillaParentReader withVillagers = new VanillaParentReader(HANDLE, VanillaContext.of(
|
||||
REGISTRIES, key -> key == Biomes.DESERT ? VillagerType.DESERT : null));
|
||||
assertEquals(AttributeEntry.override(RegistryKey.parse("minecraft:desert")),
|
||||
withVillagers.biome(Biomes.DESERT, biome(Biomes.DESERT), TABLE, FAIL).get(villager));
|
||||
assertNull(withVillagers.biome(Biomes.PLAINS, biome(Biomes.PLAINS), TABLE, FAIL).get(villager));
|
||||
|
||||
int present = 0;
|
||||
for(PackAttributeTable.Bound b : TABLE.environment()) {
|
||||
if(biome(Biomes.PLAINS).getAttributes().contains(b.vanilla())) {
|
||||
assertNotNull(plains.get(b.attribute()), b.attribute().getRegistryKey().toString());
|
||||
present++;
|
||||
} else {
|
||||
assertNull(plains.get(b.attribute()), b.attribute().getRegistryKey().toString());
|
||||
}
|
||||
}
|
||||
assertTrue(present > 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyTerraPathIsVanillaField() {
|
||||
Set<String> dimensionKeys = new HashSet<>();
|
||||
List<Holder.Reference<DimensionType>> types = dimensionTypes();
|
||||
assertEquals(4, types.size());
|
||||
for(Holder.Reference<DimensionType> holder : types) {
|
||||
dimensionKeys.addAll(encodeMap(DimensionType.DIRECT_CODEC, holder.value()).keySet());
|
||||
}
|
||||
for(PackAttributeTable.Field field : TABLE.dimension()) {
|
||||
assertTrue(dimensionKeys.contains(field.name()), field.name() + " is not a dimension type field: " + dimensionKeys);
|
||||
}
|
||||
|
||||
Set<String> biomeKeys = new HashSet<>();
|
||||
for(Holder.Reference<Biome> holder : biomes()) {
|
||||
biomeKeys.addAll(climate(holder.value()).keySet());
|
||||
biomeKeys.addAll(effects(holder.value()).keySet());
|
||||
}
|
||||
for(PackAttributeTable.Field field : TABLE.climate()) {
|
||||
assertTrue(biomeKeys.contains(field.name()), field.name() + " is not a biome field: " + biomeKeys);
|
||||
}
|
||||
for(PackAttributeTable.Field field : TABLE.effects()) {
|
||||
assertTrue(biomeKeys.contains(field.name()), field.name() + " is not a biome field: " + biomeKeys);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void absentFieldsMatchTerraDefaults() {
|
||||
List<String> mismatches = new ArrayList<>();
|
||||
for(Holder.Reference<DimensionType> holder : dimensionTypes()) {
|
||||
absentFields(holder.key().identifier().toString(), DimensionType.DIRECT_CODEC, holder.value(), TABLE.dimension(), mismatches);
|
||||
}
|
||||
for(ResourceKey<Biome> key : List.of(Biomes.PLAINS, Biomes.SWAMP, Biomes.PALE_GARDEN)) {
|
||||
Biome biome = biome(key);
|
||||
absentFields(key.identifier().toString(), Biome.ClimateSettings.CODEC.codec(), biome.climateSettings, TABLE.climate(),
|
||||
mismatches);
|
||||
absentFields(key.identifier().toString(), BiomeSpecialEffects.CODEC, biome.getSpecialEffects(), TABLE.effects(), mismatches);
|
||||
}
|
||||
assertEquals(List.of(), mismatches);
|
||||
}
|
||||
|
||||
private static <V> void absentFields(String name, Codec<V> codec, V original, List<PackAttributeTable.Field> fields,
|
||||
List<String> mismatches) {
|
||||
Map<String, Object> json = encodeMap(codec, original);
|
||||
for(PackAttributeTable.Field field : fields) {
|
||||
if(field.name().equals(DEFAULT_CLOCK) || json.containsKey(field.name())) continue;
|
||||
Map<String, Object> withDefault = new LinkedHashMap<>(json);
|
||||
Object terraDefault = encodedDefault(field.attribute());
|
||||
if(terraDefault != null) withDefault.put(field.name(), terraDefault);
|
||||
try {
|
||||
Map<String, Object> parsed = encodeMap(codec, VanillaCodecs.parse(codec, withDefault, OPS));
|
||||
if(!json.equals(parsed)) {
|
||||
mismatches.add(name + " " + field.name() + ": Terra default " + terraDefault + " reads as " + parsed.get(field.name()));
|
||||
}
|
||||
} catch(DecodeException e) {
|
||||
mismatches.add(name + " " + field.name() + ": vanilla rejects Terra default " + terraDefault + ": " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Object encodedDefault(Attribute<T> attribute) {
|
||||
T value = attribute.defaultValue();
|
||||
return value == null ? null : attribute.type().encode(value);
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsDimensionFields() {
|
||||
AttributeSlots overworld = READER.dimension(dimensionType(BuiltinDimensionTypes.OVERWORLD), TABLE, FAIL);
|
||||
assertEquals(AttributeEntry.override(-64), overworld.get(attribute("terra:dimension/min_y")));
|
||||
assertEquals(AttributeEntry.override(384), overworld.get(attribute("terra:dimension/height")));
|
||||
assertEquals(AttributeEntry.override(true), overworld.get(attribute("terra:dimension/has_skylight")));
|
||||
assertEquals(AttributeEntry.override(RegistryKey.parse("minecraft:overworld")),
|
||||
overworld.get(attribute("terra:dimension/default_clock")));
|
||||
|
||||
AttributeSlots nether = READER.dimension(dimensionType(BuiltinDimensionTypes.NETHER), TABLE, FAIL);
|
||||
assertEquals(AttributeEntry.override(null), nether.get(attribute("terra:dimension/default_clock")));
|
||||
assertEquals(AttributeEntry.override(true), nether.get(attribute("terra:dimension/has_ceiling")));
|
||||
assertEquals(AttributeEntry.override(4f), nether.get(attribute("minecraft:gameplay/sky_light_level")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void readsGeneration() {
|
||||
NoiseGeneratorSettings overworld = REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS)
|
||||
.getOrThrow(NoiseGeneratorSettings.OVERWORLD).value();
|
||||
AttributeSlots slots = READER.generation(overworld, TABLE);
|
||||
assertEquals(AttributeEntry.override(63), slots.get(attribute("terra:world/sea_level")));
|
||||
assertEquals(AttributeEntry.override(true), slots.get(attribute("terra:world/mob_generation")));
|
||||
assertNull(slots.get(attribute("terra:world/spawn_height")));
|
||||
|
||||
NoiseGeneratorSettings nether = REGISTRIES.lookupOrThrow(Registries.NOISE_SETTINGS)
|
||||
.getOrThrow(NoiseGeneratorSettings.NETHER).value();
|
||||
assertEquals(AttributeEntry.override(32), READER.generation(nether, TABLE).get(attribute("terra:world/sea_level")));
|
||||
}
|
||||
}
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.registry.key.TagKey;
|
||||
import com.dfsek.terra.api.util.generic.either.Either;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeEntry;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeMap;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeParents;
|
||||
import com.dfsek.terra.api.world.attribute.PackAttributes;
|
||||
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
|
||||
import com.dfsek.terra.api.world.biome.Biome;
|
||||
|
||||
|
||||
public final class FakePackAttributes implements PackAttributes {
|
||||
private static final AttributeEntry<?> UNREAD = AttributeEntry.override(new Object());
|
||||
|
||||
private final AttributeHandle handle;
|
||||
private final AttributeParents platformParents;
|
||||
private final AttributeMap pack;
|
||||
private final Map<String, RegistryKey> parents;
|
||||
private final Map<Biome, AttributeMap> biomes;
|
||||
private final List<Either<RegistryKey, TagKey>> scheduleRefs;
|
||||
private final Map<RegistryKey, AttributeSchedule> scheduleDefinitions;
|
||||
private final AttributeEntry<?>[] packSlots;
|
||||
private final IdentityHashMap<Biome, AttributeEntry<?>[]> biomeSlots = new IdentityHashMap<>();
|
||||
|
||||
public FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map<String, RegistryKey> parents,
|
||||
Map<Biome, AttributeMap> biomes) {
|
||||
this(handle, platformParents, pack, parents, biomes, List.of(), Map.of());
|
||||
}
|
||||
|
||||
public FakePackAttributes(AttributeHandle handle, AttributeParents platformParents, AttributeMap pack, Map<String, RegistryKey> parents,
|
||||
Map<Biome, AttributeMap> biomes, List<Either<RegistryKey, TagKey>> scheduleRefs,
|
||||
Map<RegistryKey, AttributeSchedule> scheduleDefinitions) {
|
||||
this.handle = handle;
|
||||
this.platformParents = platformParents;
|
||||
this.pack = pack;
|
||||
this.parents = Map.copyOf(parents);
|
||||
this.biomes = Map.copyOf(biomes);
|
||||
this.scheduleRefs = List.copyOf(scheduleRefs);
|
||||
this.scheduleDefinitions = Collections.unmodifiableMap(new LinkedHashMap<>(scheduleDefinitions));
|
||||
this.packSlots = unread();
|
||||
for(Biome biome : biomes.keySet()) biomeSlots.put(biome, unread());
|
||||
}
|
||||
|
||||
private AttributeEntry<?>[] unread() {
|
||||
AttributeEntry<?>[] slots = new AttributeEntry<?>[handle.attributeCount()];
|
||||
Arrays.fill(slots, UNREAD);
|
||||
return slots;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static <T> @Nullable AttributeEntry<T> slot(AttributeEntry<?>[] slots, AttributeMap map, Attribute<T> attribute) {
|
||||
int index = attribute.index();
|
||||
if(index >= slots.length) return map.get(attribute.key()).orElse(null);
|
||||
AttributeEntry<?> entry = slots[index];
|
||||
if(entry == UNREAD) {
|
||||
entry = map.get(attribute.key()).orElse(null);
|
||||
slots[index] = entry;
|
||||
}
|
||||
return (AttributeEntry<T>) entry;
|
||||
}
|
||||
|
||||
private <T> @Nullable AttributeEntry<T> packEntryOrNull(Attribute<T> attribute) {
|
||||
return slot(packSlots, pack, attribute);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeMap entries() {
|
||||
return pack;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, RegistryKey> parents() {
|
||||
return parents;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Either<RegistryKey, TagKey>> scheduleRefs() {
|
||||
return scheduleRefs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<RegistryKey, AttributeSchedule> scheduleDefinitions() {
|
||||
return scheduleDefinitions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable AttributeEntry<T> biomeEntryOrNull(Attribute<T> attribute, Biome biome) {
|
||||
AttributeEntry<?>[] slots = biomeSlots.get(biome);
|
||||
return slots == null ? null : slot(slots, biomes.get(biome), attribute);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeMap biomeEntries(Biome biome) {
|
||||
return biomes.getOrDefault(biome, AttributeMap.empty());
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T resolve(Attribute<T> attribute, Biome biome) {
|
||||
return handle.resolve(attribute, platformParents.packOrNull(this, attribute), packEntryOrNull(attribute),
|
||||
platformParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome));
|
||||
}
|
||||
|
||||
@Override
|
||||
public <T> @Nullable T resolvePack(Attribute<T> attribute) {
|
||||
return handle.resolve(attribute, platformParents.packOrNull(this, attribute), packEntryOrNull(attribute), null);
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.SharedConstants;
|
||||
import net.minecraft.core.HolderLookup;
|
||||
import net.minecraft.core.RegistryAccess;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.data.registries.VanillaRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.server.Bootstrap;
|
||||
import net.minecraft.tags.TagLoader;
|
||||
import net.minecraft.world.attribute.EnvironmentAttribute;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable;
|
||||
import com.dfsek.terra.api.registry.Registry;
|
||||
import com.dfsek.terra.api.registry.key.RegistryKey;
|
||||
import com.dfsek.terra.api.world.attribute.Attribute;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeHandle;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeKey;
|
||||
import com.dfsek.terra.api.world.attribute.AttributeLookup;
|
||||
import com.dfsek.terra.api.world.attribute.DecodeException;
|
||||
import com.dfsek.terra.registry.OpenRegistryImpl;
|
||||
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
|
||||
|
||||
|
||||
public final class MinecraftTestSupport {
|
||||
static {
|
||||
SharedConstants.tryDetectVersion();
|
||||
Bootstrap.bootStrap();
|
||||
}
|
||||
|
||||
public static final HolderLookup.Provider REGISTRIES = VanillaRegistries.createWorldLookup();
|
||||
public static final VanillaContext CONTEXT = VanillaContext.of(REGISTRIES, key -> null);
|
||||
public static final AttributeHandle HANDLE = new AttributeHandleImpl();
|
||||
public static final List<Attribute<?>> ATTRIBUTES = MinecraftAttributeTable.create(HANDLE);
|
||||
|
||||
private static final Registry<Attribute<?>> TABLE = registry();
|
||||
|
||||
public static final AttributeLookup LOOKUP = key -> {
|
||||
RegistryKey id;
|
||||
try {
|
||||
id = RegistryKey.parseNamespaced(key);
|
||||
} catch(IllegalArgumentException e) {
|
||||
throw new DecodeException("unknown attribute", e);
|
||||
}
|
||||
return TABLE.get(id).orElseThrow(() -> new DecodeException("unknown attribute"));
|
||||
};
|
||||
|
||||
private MinecraftTestSupport() { }
|
||||
|
||||
public static List<HolderLookup.RegistryLookup<?>> loadContext(net.minecraft.core.Registry.PendingTags<?>... pending) {
|
||||
return TagLoader.buildUpdatedLookups(RegistryAccess.fromRegistryOfRegistries(BuiltInRegistries.REGISTRY), List.of(pending));
|
||||
}
|
||||
|
||||
public static Registry<Attribute<?>> registry(Attribute<?>... extra) {
|
||||
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
|
||||
ATTRIBUTES.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute));
|
||||
for(Attribute<?> attribute : extra) registry.register(attribute.getRegistryKey(), attribute);
|
||||
return registry;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Attribute<T> attribute(String id) {
|
||||
AttributeKey<T> key = AttributeKey.parse(id);
|
||||
return (Attribute<T>) TABLE.get(key.getRegistryKey()).orElseThrow(() -> new IllegalArgumentException("no attribute " + id));
|
||||
}
|
||||
|
||||
public static EnvironmentAttribute<?> vanilla(String id) {
|
||||
return BuiltInRegistries.ENVIRONMENT_ATTRIBUTE.getOptional(Identifier.parse(id))
|
||||
.orElseThrow(() -> new IllegalArgumentException("no vanilla attribute " + id));
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
import com.dfsek.terra.api.properties.Context;
|
||||
import com.dfsek.terra.api.world.biome.Biome;
|
||||
import com.dfsek.terra.api.world.biome.PlatformBiome;
|
||||
|
||||
|
||||
public final class TestBiome implements Biome {
|
||||
private final String id;
|
||||
private final int intId;
|
||||
private final PlatformBiome platformBiome;
|
||||
private final Context context = new Context();
|
||||
|
||||
public TestBiome(String id, int intId, Identifier parent) {
|
||||
this(id, intId, new TestPlatformBiome(parent));
|
||||
}
|
||||
|
||||
public TestBiome(String id, int intId, PlatformBiome platformBiome) {
|
||||
this.id = id;
|
||||
this.intId = intId;
|
||||
this.platformBiome = platformBiome;
|
||||
}
|
||||
|
||||
public TestPlatformBiome platform() {
|
||||
return (TestPlatformBiome) platformBiome;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformBiome getPlatformBiome() {
|
||||
return platformBiome;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getColor() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> getTags() {
|
||||
return Set.of();
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getIntID() {
|
||||
return intId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getID() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Context getContext() {
|
||||
return context;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "TestBiome[" + id + "]";
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package com.dfsek.terra.minecraft.attribute;
|
||||
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import com.dfsek.terra.api.world.biome.PlatformBiome;
|
||||
import com.dfsek.terra.world.attribute.platform.AttributeSlots;
|
||||
import com.dfsek.terra.world.attribute.platform.ParentEntryHolder;
|
||||
|
||||
|
||||
public final class TestPlatformBiome implements PlatformBiome, ParentEntryHolder {
|
||||
private final Identifier parent;
|
||||
private AttributeSlots parentEntries = AttributeSlots.EMPTY;
|
||||
|
||||
public TestPlatformBiome(Identifier parent) {
|
||||
this.parent = Objects.requireNonNull(parent);
|
||||
}
|
||||
|
||||
public Identifier parent() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Identifier getHandle() {
|
||||
return parent;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttributeSlots parentEntries() {
|
||||
return parentEntries;
|
||||
}
|
||||
|
||||
public void setParentEntries(AttributeSlots parentEntries) {
|
||||
this.parentEntries = Objects.requireNonNull(parentEntries);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user