feat: add environment attribute system

This commit is contained in:
Zoe Gidiere committed 2026-11-09 16:34:50 -07:00
1 parent 8a940f7e1f
commit 4e37c361ea
127 files changed
+9022 -19

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,10 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation(project(":common:implementation:base"))
testImplementation(project(":common:addons:minecraft-attributes"))
testImplementation(project(":common:addons:manifest-addon-loader"))
testImplementation("com.dfsek", "paralithic", Versions.Libraries.paralithic)
}
@@ -0,0 +1,194 @@
package com.dfsek.terra.addons.attribute;
import org.slf4j.Logger;
import org.slf4j.helpers.MessageFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.dfsek.terra.addons.attribute.AttributeReader.Problem;
import com.dfsek.terra.addons.attribute.AttributeReader.Result;
import com.dfsek.terra.addons.attribute.AttributeReader.Scope;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.events.config.ConfigurationLoadEvent;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPostLoadEvent;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.properties.Context;
import com.dfsek.terra.api.properties.PropertyKey;
import com.dfsek.terra.api.registry.Registry;
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.AttributeHandle;
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.PackAttributes;
import com.dfsek.terra.api.world.attribute.schedule.AttributeSchedule;
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
import com.dfsek.terra.api.world.biome.Biome;
/**
* Biome configs load in parallel: the biome handler may only read shared immutable state and write to its own biome.
*/
public class AttributeAddon implements AddonInitializer {
private static final String ATTRIBUTE_WARNING = "Pack \"{}\", config \"{}\": attribute \"{}\" skipped: {}";
private static final String SCHEDULE_SKIPPED = "Pack \"{}\": schedule \"{}\" skipped: {}";
private static final String TRACK_DROPPED = "Pack \"{}\": schedule \"{}\" track \"{}\" dropped: {}";
private static final String PARENT_WARNING = "Pack \"{}\", config \"{}\": \"{}\" ignored: {}";
private static final String PACK_CONFIG = "pack.yml";
private static final String VANILLA = "vanilla";
private static final String VANILLA_GENERATION = "vanilla-generation";
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Inject
private Logger logger;
@Override
public void initialize() {
AttributeHandle handle = platform.getAttributeHandle();
// Before any parallel load: Context.create is not thread safe.
PropertyKey<BiomeAttributeEntries> biomeKey = Context.create(BiomeAttributeEntries.class);
PropertyKey<PackAttributes> packKey = Context.create(PackAttributes.class);
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPreLoadEvent.class)
.then(event -> {
for(Class<?> type : ConfigDecodeContext.CAPTURED_TYPES) event.getPack().applyLoader(type, LazyConfigValue.LOADER);
})
.failThrough();
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigurationLoadEvent.class)
.then(event -> {
if(!event.is(Biome.class)) return;
Map<String, LazyConfigValue> raw = event.load(new BiomeAttributesTemplate()).getAttributes();
AttributeReader reader = new AttributeReader(event.getPack().getRegistry(Attribute.REGISTRY_TYPE), handle);
Result result = reader.readConfig(raw, Scope.BIOME);
List<String> warnings = new ArrayList<>();
for(Problem problem : result.problems()) {
warnings.add(warn(ATTRIBUTE_WARNING, event.getPack(), event.getConfiguration().getID(), problem.key(),
problem.reason()));
}
event.getLoadedObject(Biome.class).getContext().put(biomeKey, new BiomeAttributeEntries(result.map(), warnings));
})
.failThrough();
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPostLoadEvent.class)
.then(event -> {
ConfigPack pack = event.getPack();
Registry<Attribute<?>> attributes = pack.getRegistry(Attribute.REGISTRY_TYPE);
PackAttributesTemplate template = event.loadTemplate(new PackAttributesTemplate());
List<String> warnings = new ArrayList<>();
Result result = new AttributeReader(attributes, handle).readConfig(template.getAttributes(), Scope.PACK);
for(Problem problem : result.problems()) {
warnings.add(warn(ATTRIBUTE_WARNING, pack, PACK_CONFIG, problem.key(), problem.reason()));
}
Map<String, RegistryKey> parents = new LinkedHashMap<>();
parent(parents, VANILLA, template.getVanilla(), pack, warnings);
parent(parents, VANILLA_GENERATION, template.getVanillaGeneration(), pack, warnings);
List<Either<RegistryKey, TagKey>> schedules = new ArrayList<>();
for(String schedule : template.getSchedules()) {
try {
schedules.add(ScheduleIds.reference(schedule));
} catch(IllegalArgumentException e) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, schedule, e.getMessage()));
}
}
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
Set<RegistryKey> claimed = new HashSet<>();
RegistryAttributeLookup lookup = new RegistryAttributeLookup(attributes);
template.getScheduleDefinitions().forEach((idString, lazy) -> {
RegistryKey id;
try {
id = ScheduleIds.claim(idString, claimed);
} catch(IllegalArgumentException e) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage()));
return;
}
DecodeContext context;
Object value;
try {
context = lazy == null ? handle.plainContext() : lazy.context(handle.plainContext());
value = lazy == null ? null : context.resolve(lazy.raw());
} catch(DecodeException e) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, e.getMessage()));
return;
}
if(!(value instanceof Map<?, ?> map) || !map.keySet().stream().allMatch(String.class::isInstance)) {
warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, "a schedule must be a map"));
return;
}
@SuppressWarnings("unchecked")
Map<String, Object> raw = (Map<String, Object>) map;
ScheduleDecodeResult schedule = handle.decodeSchedule(id, raw, lookup, context);
for(ScheduleDecodeResult.Problem problem : schedule.droppedTracks()) {
warnings.add(warn(TRACK_DROPPED, pack, idString, problem.key(), problem.reason()));
}
schedule.skipped().ifPresent(problem -> warnings.add(warn(SCHEDULE_SKIPPED, pack, idString, problem.reason())));
schedule.schedule().ifPresent(definition -> definitions.put(id, definition));
});
pack.getContext().put(packKey, new PackAttributesImpl(handle, platform.getAttributeParents(), attributes,
result.map(),
parents,
schedules,
definitions,
biomeEntries(pack, biomeKey),
warnings));
})
.failThrough();
}
private static AttributeMap[] biomeEntries(ConfigPack pack, PropertyKey<BiomeAttributeEntries> biomeKey) {
Registry<Biome> biomes = pack.getRegistry(Biome.class);
if(biomes == null) return new AttributeMap[0];
AttributeMap[] entries = new AttributeMap[pack.getBiomeTagIndex().size()];
biomes.forEach(biome -> {
if(biome.getContext().has(biomeKey)) entries[biome.getIntID()] = biome.getContext().get(biomeKey).entries();
});
return entries;
}
private void parent(Map<String, RegistryKey> parents, String key, Optional<String> value, ConfigPack pack, List<String> warnings) {
if(value.isEmpty()) return;
try {
parents.put(key, RegistryKey.parseNamespaced(value.get()));
} catch(IllegalArgumentException e) {
warnings.add(warn(PARENT_WARNING, pack, PACK_CONFIG, key, e.getMessage()));
}
}
private String warn(String format, ConfigPack pack, Object... args) {
Object[] all = new Object[args.length + 1];
all[0] = pack.getID();
System.arraycopy(args, 0, all, 1, args.length);
logger.warn(format, all);
return MessageFormatter.arrayFormat(format, all).getMessage();
}
}
@@ -0,0 +1,86 @@
package com.dfsek.terra.addons.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.Registry;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.AttributeScope;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
public final class AttributeReader {
private final RegistryAttributeLookup lookup;
private final AttributeHandle handle;
public AttributeReader(@Nullable Registry<Attribute<?>> registry, AttributeHandle handle) {
this.lookup = new RegistryAttributeLookup(registry);
this.handle = handle;
}
public enum Scope { BIOME, PACK }
public record Result(AttributeMap map, List<Problem> problems) { }
public record Problem(String key, String reason) { }
private record Value(Object raw, DecodeContext context) { }
public Result read(Map<String, Object> raw, Scope scope) {
DecodeContext plain = handle.plainContext();
Map<String, Value> values = new LinkedHashMap<>();
raw.forEach((key, value) -> values.put(key, new Value(value, plain)));
return readValues(values, scope);
}
Result readConfig(Map<String, LazyConfigValue> config, Scope scope) {
DecodeContext plain = handle.plainContext();
Map<String, Value> values = new LinkedHashMap<>();
config.forEach((key, value) -> values.put(key, value == null
? new Value(null, plain)
: new Value(value.raw(), value.context(plain))));
return readValues(values, scope);
}
private Result readValues(Map<String, Value> raw, Scope scope) {
AttributeMap.Builder builder = AttributeMap.builder();
List<Problem> problems = new ArrayList<>();
for(Map.Entry<String, Value> entry : raw.entrySet()) {
String keyString = entry.getKey();
Attribute<?> attribute;
try {
attribute = lookup.find(keyString);
} catch(DecodeException e) {
problems.add(new Problem(keyString, e.getMessage()));
continue;
}
if(scope == Scope.BIOME && attribute.scope() == AttributeScope.PACK_ONLY) {
problems.add(new Problem(keyString, "not allowed in a biome"));
continue;
}
// Explicit null un-sets an inherited value.
if(entry.getValue().raw() == null) continue;
try {
put(builder, attribute, entry.getValue().raw(), entry.getValue().context());
} catch(DecodeException | RuntimeException e) {
problems.add(new Problem(keyString, e.getMessage() == null ? "unexpected error" : e.getMessage()));
}
}
return new Result(builder.build(), problems);
}
private <T> void put(AttributeMap.Builder builder, Attribute<T> attribute, Object value, DecodeContext context)
throws DecodeException {
builder.put(attribute.key(), handle.decodeEntry(attribute, value, context));
}
}
@@ -0,0 +1,13 @@
package com.dfsek.terra.addons.attribute;
import java.util.List;
import com.dfsek.terra.api.properties.Properties;
import com.dfsek.terra.api.world.attribute.AttributeMap;
record BiomeAttributeEntries(AttributeMap entries, List<String> warnings) implements Properties {
BiomeAttributeEntries {
warnings = List.copyOf(warnings);
}
}
@@ -0,0 +1,23 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Merge;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import java.util.Collections;
import java.util.Map;
import com.dfsek.terra.api.config.meta.Meta;
public class BiomeAttributesTemplate implements ConfigTemplate {
@Value("attributes")
@Merge
@Default
private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of();
Map<String, LazyConfigValue> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
}
@@ -0,0 +1,135 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.exception.ConfigException;
import com.dfsek.tectonic.api.exception.LoadException;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Type;
import java.util.AbstractList;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
/**
* Tectonic picks preprocessors by declared type.
* <p>
* Not thread safe: include preprocessors mutate the {@link DepthTracker}.
*/
final class ConfigDecodeContext implements DecodeContext {
static final List<Class<?>> CAPTURED_TYPES = List.of(LazyConfigValue.class, MapShape.class, ListShape.class);
private static final AnnotatedType WHOLE_VALUE = new TypeKey<@Meta LazyConfigValue>() { }.getAnnotatedType();
private static final AnnotatedType MAP = new TypeKey<@Meta MapShape<String, LazyConfigValue>>() { }.getAnnotatedType();
private static final AnnotatedType LIST = new TypeKey<@Meta ListShape<LazyConfigValue>>() { }.getAnnotatedType();
private static final AnnotatedType STRING = new TypeKey<@Meta String>() { }.getAnnotatedType();
private static final AnnotatedType NUMBER = new TypeKey<@Meta Double>() { }.getAnnotatedType();
private final ConfigLoader loader;
private final DepthTracker tracker;
private final DecodeContext plain;
private final Set<Object> resolved = Collections.newSetFromMap(new IdentityHashMap<>());
ConfigDecodeContext(ConfigLoader loader, DepthTracker tracker, DecodeContext plain) {
this.loader = loader;
this.tracker = tracker;
this.plain = plain;
}
private static boolean numeric(Type type) {
return type instanceof Class<?> c && Number.class.isAssignableFrom(c);
}
private static DecodeException failure(RuntimeException e) {
String message = e instanceof ConfigException && e.getMessage() != null ? e.getMessage().strip() : "config preprocessing failed";
// Tectonic leaves some details only in the cause.
Throwable cause = e.getCause();
boolean readable = cause instanceof ConfigException
|| cause != null && !(cause instanceof RuntimeException || cause instanceof Error);
if(readable && cause.getMessage() != null && !message.contains(cause.getMessage().strip())) {
message += "\n\tCaused by: " + cause.getMessage().strip();
}
return new DecodeException(message, e);
}
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
Object value = resolve(raw);
if(value instanceof String expression && numeric(type)) {
try {
value = loadType(NUMBER, expression, tracker);
} catch(RuntimeException e) {
throw failure(e);
}
}
return plain.load(type, value);
}
@Override
public Object resolve(Object raw) throws DecodeException {
try {
return resolve(raw, tracker);
} catch(RuntimeException e) {
throw failure(e);
}
}
private Object resolve(Object raw, DepthTracker at) {
if(raw == null || raw instanceof Number || raw instanceof Boolean || resolved.contains(raw)) return raw;
LazyConfigValue whole = capture(WHOLE_VALUE, raw, at);
Object value = whole.raw();
Object out;
if(value instanceof String) {
out = loadType(STRING, raw, at);
} else if(value instanceof Map<?, ?>) {
LazyConfigValue included = capture(MAP, value, whole.tracker());
Map<Object, Object> map = new LinkedHashMap<>();
for(Map.Entry<?, ?> entry : ((Map<?, ?>) included.raw()).entrySet()) {
map.put(entry.getKey(), resolve(entry.getValue(), included.tracker().entry(String.valueOf(entry.getKey()))));
}
out = Collections.unmodifiableMap(map);
} else if(value instanceof List<?>) {
LazyConfigValue included = capture(LIST, value, whole.tracker());
List<?> elements = (List<?>) included.raw();
List<Object> list = new ArrayList<>(elements.size());
for(int i = 0; i < elements.size(); i++) list.add(resolve(elements.get(i), included.tracker().index(i)));
out = Collections.unmodifiableList(list);
} else {
out = value;
}
if(out != null) resolved.add(out);
return out;
}
private LazyConfigValue capture(AnnotatedType type, Object raw, DepthTracker at) {
return (LazyConfigValue) loadType(type, raw, at);
}
private Object loadType(AnnotatedType type, Object raw, DepthTracker at) {
try {
return loader.loadType(type, raw, at);
} catch(ConfigException e) {
throw e;
} catch(RuntimeException e) {
throw new LoadException("config preprocessing failed", e, at);
}
}
private abstract static class MapShape<K, V> extends AbstractMap<K, V> { }
private abstract static class ListShape<E> extends AbstractList<E> { }
}
@@ -0,0 +1,19 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.api.loader.type.TypeLoader;
import com.dfsek.terra.api.world.attribute.DecodeContext;
/**
* Use only on the thread that loaded it: the {@link DepthTracker} is mutable.
*/
record LazyConfigValue(Object raw, ConfigLoader loader, DepthTracker tracker) {
static final TypeLoader<LazyConfigValue> LOADER = (type, o, loader, depthTracker) -> new LazyConfigValue(o, loader, depthTracker);
DecodeContext context(DecodeContext plain) {
return new ConfigDecodeContext(loader, tracker, plain);
}
}
@@ -0,0 +1,133 @@
package com.dfsek.terra.addons.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.Registry;
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.AttributeKey;
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;
/**
* {@link #biomeEntryOrNull}, {@link #resolve} and {@link #resolvePack} must not allocate.
*/
public final class PackAttributesImpl implements PackAttributes {
private final AttributeHandle handle;
private final AttributeParents attributeParents;
private final AttributeMap entries;
private final AttributeEntry<?>[] packEntries;
private final AttributeEntry<?>[][] columns;
private final AttributeMap[] biomeEntries;
private final Map<String, RegistryKey> parents;
private final List<Either<RegistryKey, TagKey>> scheduleRefs;
private final Map<RegistryKey, AttributeSchedule> scheduleDefinitions;
private final List<String> warnings;
public PackAttributesImpl(AttributeHandle handle, AttributeParents attributeParents, @Nullable Registry<Attribute<?>> attributes,
AttributeMap entries, Map<String, RegistryKey> parents,
List<Either<RegistryKey, TagKey>> scheduleRefs, Map<RegistryKey, AttributeSchedule> scheduleDefinitions,
AttributeMap[] biomeEntries, List<String> warnings) {
this.handle = handle;
this.attributeParents = attributeParents;
this.entries = entries;
this.packEntries = new AttributeEntry<?>[handle.attributeCount()];
for(AttributeKey<?> key : entries.keys()) {
packEntries[attribute(attributes, key).index()] = entries.get(key).orElseThrow();
}
this.columns = new AttributeEntry<?>[handle.attributeCount()][];
for(int id = 0; id < biomeEntries.length; id++) {
AttributeMap declared = biomeEntries[id];
if(declared == null) continue;
for(AttributeKey<?> key : declared.keys()) {
int index = attribute(attributes, key).index();
if(columns[index] == null) columns[index] = new AttributeEntry<?>[biomeEntries.length];
columns[index][id] = declared.get(key).orElseThrow();
}
}
this.biomeEntries = biomeEntries;
this.parents = Collections.unmodifiableMap(new LinkedHashMap<>(parents));
this.scheduleRefs = List.copyOf(scheduleRefs);
this.scheduleDefinitions = Collections.unmodifiableMap(new LinkedHashMap<>(scheduleDefinitions));
this.warnings = List.copyOf(warnings);
}
private static Attribute<?> attribute(@Nullable Registry<Attribute<?>> attributes, AttributeKey<?> key) {
if(attributes == null) throw new IllegalArgumentException("entry " + key + " given for a pack without attributes");
return attributes.get(key.getRegistryKey())
.orElseThrow(() -> new IllegalArgumentException("entry " + key + " names no attribute of the pack"));
}
@Override
public AttributeMap entries() {
return entries;
}
@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
@SuppressWarnings("unchecked")
public <T> @Nullable AttributeEntry<T> biomeEntryOrNull(Attribute<T> attribute, Biome biome) {
int index = attribute.index();
if(index >= columns.length) return null;
AttributeEntry<?>[] column = columns[index];
if(column == null) return null;
int id = biome.getIntID();
if(id < 0 || id >= column.length) return null;
return (AttributeEntry<T>) column[id];
}
@Override
public AttributeMap biomeEntries(Biome biome) {
int id = biome.getIntID();
if(id < 0 || id >= biomeEntries.length || biomeEntries[id] == null) return AttributeMap.empty();
return biomeEntries[id];
}
@SuppressWarnings("unchecked")
private <T> @Nullable AttributeEntry<T> packEntryOrNull(Attribute<T> attribute) {
int index = attribute.index();
return index < packEntries.length ? (AttributeEntry<T>) packEntries[index] : null;
}
@Override
public <T> @Nullable T resolve(Attribute<T> attribute, Biome biome) {
return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute),
attributeParents.biomeOrNull(biome, attribute), biomeEntryOrNull(attribute, biome));
}
@Override
public <T> @Nullable T resolvePack(Attribute<T> attribute) {
return handle.resolve(attribute, attributeParents.packOrNull(this, attribute), packEntryOrNull(attribute), null);
}
public List<String> warnings() {
return warnings;
}
}
@@ -0,0 +1,60 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.tectonic.api.config.template.ConfigTemplate;
import com.dfsek.tectonic.api.config.template.annotations.Default;
import com.dfsek.tectonic.api.config.template.annotations.Value;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.dfsek.terra.api.config.meta.Meta;
public class PackAttributesTemplate implements ConfigTemplate {
@Value("attributes")
@Default
private @Meta Map<@Meta String, LazyConfigValue> attributes = Map.of();
@Value("schedules")
@Default
private @Meta List<@Meta String> schedules = List.of();
@Value("schedule-definitions")
@Default
private @Meta Map<@Meta String, LazyConfigValue> scheduleDefinitions = Map.of();
// May be a map (vanilla.mobs); only a string names a parent.
@Value("vanilla")
@Default
private @Meta LazyConfigValue vanilla = null;
@Value("vanilla-generation")
@Default
private @Meta LazyConfigValue vanillaGeneration = null;
Map<String, LazyConfigValue> getAttributes() {
return Collections.unmodifiableMap(attributes);
}
public List<String> getSchedules() {
return schedules;
}
Map<String, LazyConfigValue> getScheduleDefinitions() {
return Collections.unmodifiableMap(scheduleDefinitions);
}
public Optional<String> getVanilla() {
return string(vanilla);
}
public Optional<String> getVanillaGeneration() {
return string(vanillaGeneration);
}
private static Optional<String> string(LazyConfigValue value) {
return value != null && value.raw() instanceof String s ? Optional.of(s) : Optional.empty();
}
}
@@ -0,0 +1,60 @@
package com.dfsek.terra.addons.attribute;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
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;
import com.dfsek.terra.api.world.attribute.AttributeLookup;
import com.dfsek.terra.api.world.attribute.DecodeException;
/**
* Keys must be fully namespaced: inheritance merges config maps by raw key text.
*/
public final class RegistryAttributeLookup implements AttributeLookup {
private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\"";
private static final String UNKNOWN = "unknown attribute";
private static final Map<String, String> NAMESPACE_ADDONS = Map.of(
"minecraft", "minecraft-attributes",
"terra", "minecraft-attributes");
private final @Nullable Registry<Attribute<?>> registry;
public RegistryAttributeLookup(@Nullable Registry<Attribute<?>> registry) {
this.registry = registry;
}
@Override
public Attribute<?> find(String key) throws DecodeException {
AttributeKey<?> parsed;
try {
parsed = AttributeKey.parse(key);
} catch(IllegalArgumentException e) {
if(key.indexOf(':') < 0) throw new DecodeException(NAMESPACE_REQUIRED, e);
throw new DecodeException(invalidKey(e), e);
}
Attribute<?> attribute = registry == null ? null : registry.get(parsed.getRegistryKey()).orElse(null);
if(attribute == null) throw new DecodeException(unknownAttribute(parsed.getRegistryKey()));
return attribute;
}
private static String invalidKey(IllegalArgumentException e) {
Throwable cause = e.getCause() == null ? e : e.getCause();
String message = cause.getMessage();
return message == null ? "invalid attribute key" : "invalid attribute key: " + message;
}
private String unknownAttribute(RegistryKey key) {
String namespace = key.getNamespace();
String addon = NAMESPACE_ADDONS.get(namespace);
if(addon == null) return UNKNOWN;
if(registry != null && registry.keys().stream().anyMatch(registered -> registered.getNamespace().equals(namespace))) {
return UNKNOWN;
}
return UNKNOWN + ": no \"" + namespace + "\" attributes are registered; add the \"" + addon + "\" addon to the pack's addons";
}
}
@@ -0,0 +1,30 @@
package com.dfsek.terra.addons.attribute;
import java.util.Set;
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;
final class ScheduleIds {
private ScheduleIds() { }
static RegistryKey claim(String id, Set<RegistryKey> claimed) {
if(id.startsWith("#")) throw new IllegalArgumentException("schedule IDs must not be tags");
RegistryKey key;
try {
key = RegistryKey.parseNamespaced(id);
} catch(IllegalArgumentException e) {
if(id.indexOf(':') < 0) throw new IllegalArgumentException("schedule IDs must include a namespace, e.g. \"mypack:seasons\"", e);
throw e;
}
if(!claimed.add(key)) throw new IllegalArgumentException("duplicate schedule ID");
return key;
}
static Either<RegistryKey, TagKey> reference(String value) {
if(value.startsWith("#")) return Either.right(TagKey.parse(value));
return Either.left(RegistryKey.parseNamespaced(value));
}
}
@@ -0,0 +1,122 @@
{
"id": "config-attributes",
"docVersion": 1,
"description": "Environment attributes for biomes and packs. Contributes the attributes key to biome configurations, and attributes, schedules, schedule-definitions and vanilla-generation to pack.yml, and reads pack.yml's vanilla key when it is a string. The pack must list this addon under addons: in pack.yml, along with the addon that registers the attributes it uses (minecraft-attributes for the minecraft: and terra: ones); an unknown key's warning names that addon when none of its attributes are registered. Attribute keys must be fully namespaced (minecraft:visual/fog_color); a bad entry logs a warning and is skipped without affecting the rest of the pack.",
"types": {
"terra:AttributeEntry": {
"kind": "oneOf",
"options": [
{
"kind": "object",
"fields": {
"modifier": {
"schema": {
"kind": "string"
},
"required": true,
"summary": "Modifier name. The modifier form is exactly the two keys modifier and argument. Examples: override, add, subtract, multiply, minimum, maximum, overlay, alpha_blend or blend_to_gray. Which modifiers are valid depends on the attribute's value type."
},
"argument": {
"schema": {
"kind": "any"
},
"required": true,
"summary": "Modifier argument, in the attribute's value format or the modifier's own argument format. Range validation applies to plain values and override arguments; other modifier arguments are clamped when the value is resolved."
}
},
"description": "Modifier form. Any map containing a modifier key is read as this form, never as a plain value."
},
{
"kind": "any"
}
],
"description": "A plain value in the attribute's vanilla format (for example \"#c0d8ff\", 0.5, true, or a list or map for complex types), or a modifier object. Particle options and text components are kept as opaque raw values for platforms to decode, with meta resolved."
},
"terra:Biome": {
"kind": "object",
"fields": {
"attributes": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "string"
},
"values": {
"kind": "type",
"target": "terra:AttributeEntry"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Maps namespaced attribute IDs (for example minecraft:visual/fog_color) to a value or a {modifier, argument} object. Merged per key through extends, nearest config winning, and << meta includes work at every layer. A key without a namespace, an unknown key, a value that does not decode, or a non-biome attribute logs a warning and is skipped. Attributes not set here are inherited, not defaulted. An explicit null value for a known attribute that is allowed in biomes clears the inherited entry without a warning, so the attribute falls back to the lower layers (the platform's biome parent, the pack, the platform's pack parent, the default). Setting attributes: null on a child does not clear what it inherits, because inheritance merges per key and skips a null layer; clear entries one key at a time instead. Meta features work inside values at any depth: $file:key references, ${file:key} interpolation, << includes in maps and lists, and number expressions wherever a number is expected. A meta error inside a value logs a warning and skips that entry."
}
}
}
},
"files": {
"BIOME": {
"kind": "object",
"fields": {},
"extends": [
"terra:Biome"
]
},
"pack.yml": {
"kind": "object",
"fields": {
"attributes": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "string"
},
"values": {
"kind": "type",
"target": "terra:AttributeEntry"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Pack-level (dimension) attribute values, keyed by namespaced attribute ID. They layer over the platform's pack parent, which it may take from the IDs in vanilla: and vanilla-generation:, and biome values layer on top of them. Bad entries warn and are skipped. An explicit null value for a known attribute sets no entry, without a warning."
},
"schedules": {
"schema": {
"kind": "list",
"element": {
"kind": "string"
},
"nullable": true
},
"required": false,
"default": [],
"summary": "Schedule IDs or #tags to attach to the pack's dimension, each with a namespace (mypack:seasons, #mypack:in_overworld); an entry without one logs a warning and is skipped. Entries are resolved by the platform; they may also name schedules declared in schedule-definitions. A single string is accepted as a one-entry list. Platforms map schedules to Minecraft timelines."
},
"schedule-definitions": {
"schema": {
"kind": "keyMap",
"keys": {
"kind": "string"
},
"values": {
"kind": "any"
},
"nullable": true
},
"required": false,
"default": {},
"summary": "Maps schedule IDs to schedule objects in vanilla's format (clock, period_ticks, time_markers, tracks of keyframes). IDs must include a namespace (mypack:seasons), must not be tags, and must be unique; the first definition with an ID wins. Clock and time-marker IDs must include a namespace too; one without skips the whole definition. A shape error skips the whole definition; an unknown attribute, a modifier invalid for the attribute's type, or a bad keyframe value drops only that track. An unknown modifier name skips the whole definition."
},
"vanilla-generation": {
"schema": {
"kind": "string",
"nullable": true
},
"required": false,
"summary": "Parent ID for the platform's generation settings (for example minecraft:overworld). Like pack.yml's vanilla: key, which this addon reads only when it is a string ID (a map there is for other settings and is ignored here), it must include a namespace. An ID without one, or an invalid ID, in either key logs a warning and is ignored. The platform decides what each parent supplies and to which attributes; without platform support these layers are empty."
}
}
}
}
}
@@ -0,0 +1,14 @@
schema-version: 1
contributors:
- Terra contributors
id: config-attributes
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.attribute.AttributeAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
depends:
config-biome: "1.+"
@@ -0,0 +1,193 @@
package attribute;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.stream.Stream;
import com.dfsek.terra.addons.attribute.AttributeReader;
import com.dfsek.terra.addons.attribute.AttributeReader.Problem;
import com.dfsek.terra.addons.attribute.AttributeReader.Result;
import com.dfsek.terra.addons.attribute.AttributeReader.Scope;
import com.dfsek.terra.addons.attribute.RegistryAttributeLookup;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.schedule.ScheduleDecodeResult;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class AttributeReaderTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final Registry<Attribute<?>> REGISTRY = registry();
private static final AttributeReader READER = new AttributeReader(REGISTRY, HANDLE);
private static final String LIGHT = "terra:dimension/monster_spawn_light_level";
private static final String NAMESPACE_REQUIRED = "attribute keys must include a namespace, e.g. \"minecraft:visual/fog_color\"";
private static Registry<Attribute<?>> registry() {
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : MinecraftAttributeTable.create(HANDLE)) registry.register(attribute.getRegistryKey(), attribute);
return registry;
}
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
private static void assertExactProblem(Result result, String key, String reason) {
assertEquals(List.of(new Problem(key, reason)), result.problems());
}
static Stream<Arguments> accepted() {
return Stream.of(
Arguments.of(Scope.BIOME, "minecraft:visual/fog_color", "#c0d8ff", Operation.OVERRIDE),
Arguments.of(Scope.BIOME, "minecraft:visual/water_fog_end_distance", map("modifier", "multiply", "argument", 0.85),
Operation.MULTIPLY),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "multiply", "argument", 5), Operation.MULTIPLY),
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", map("modifier", "append",
"argument", List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025))), Operation.APPEND),
Arguments.of(Scope.BIOME, "minecraft:gameplay/natural_mob_spawns", map("modifier", "overlay", "argument", map(
"spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15)),
"spawns_by_category", map("creature", List.of(
map("type", "minecraft:sheep", "count", 4, "weight", 12),
map("type", "minecraft:horse", "weight", 5,
"count", map("type", "minecraft:uniform", "max_inclusive", 6, "min_inclusive", 2)))))), Operation.OVERLAY),
Arguments.of(Scope.PACK, "minecraft:gameplay/fast_lava", true, Operation.OVERRIDE),
Arguments.of(Scope.PACK, LIGHT, map("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7), Operation.OVERRIDE));
}
@ParameterizedTest(name = "{1}")
@MethodSource("accepted")
void accepts(Scope scope, String key, Object value, Operation operation) {
Result r = READER.read(Map.of(key, value), scope);
assertTrue(r.problems().isEmpty(), r.problems().toString());
assertEquals(operation, r.map().get(AttributeKey.parse(key)).orElseThrow().operation());
}
@Test
void intProviderModifierForm() {
Result r = READER.read(Map.of(LIGHT, Map.of("modifier", "override", "argument", 7)), Scope.PACK);
assertTrue(r.problems().isEmpty(), r.problems().toString());
AttributeEntry<?> e = r.map().get(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL).orElseThrow();
assertEquals(Operation.OVERRIDE, e.operation());
assertEquals(new IntProviderValue(OptionalInt.of(7), Optional.empty()), e.argument());
}
static Stream<Arguments> problems() {
return Stream.of(
Arguments.of(Scope.BIOME, "minecraft:nope", 1, "unknown attribute"),
Arguments.of(Scope.BIOME, "minecraft:Visual/Sky_Color", "#123456", "unknown attribute"),
Arguments.of(Scope.BIOME, "visual/sky_color", "#123456", NAMESPACE_REQUIRED),
Arguments.of(Scope.BIOME, "minecraft:Bad Key!", 1, "invalid attribute key..."),
Arguments.of(Scope.BIOME, "minecraft:visual/sky_color", true, "expected..."),
Arguments.of(Scope.BIOME, "minecraft:audio/ambient_sounds", map("loop", "minecraft:Music.Game"),
"\"loop\" of ambient sounds: expected an identifier like \"minecraft:id\", got \"minecraft:Music.Game\""),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", 2, "value 2.0 is outside [0, 1]"),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "override", "argument", 2),
"value 2.0 is outside [0, 1]"),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "and", "argument", true),
"modifier and is not valid for minecraft:visual/star_brightness"),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "frobnicate", "argument", 1),
"unknown modifier \"frobnicate\""),
Arguments.of(Scope.BIOME, "minecraft:visual/star_brightness", map("modifier", "add", "argument", null),
"expected a number, got nothing"),
Arguments.of(Scope.PACK, LIGHT, map("modifier", "frobnicate", "argument", 7), "unknown modifier \"frobnicate\""),
Arguments.of(Scope.PACK, LIGHT, map("min_inclusive", 0, "max_inclusive", 7), "int provider object is missing \"type\""),
Arguments.of(Scope.PACK, "terra:dimension/height", 100, "value 100 is not a multiple of 16"),
Arguments.of(Scope.BIOME, "minecraft:gameplay/fast_lava", true, "not allowed in a biome"),
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", Arrays.asList((Object) null),
"element 0: expected an object for ambient particle, got nothing"),
Arguments.of(Scope.BIOME, "minecraft:visual/ambient_particles", List.of(map("particle", null, "probability", 0.1)),
"element 0: \"particle\" of ambient particle: expected a particle object with a \"type\" key, got nothing"));
}
@ParameterizedTest(name = "{1}: {3}")
@MethodSource("problems")
void badEntryIsolated(Scope scope, String key, Object value, String reason) {
Result r = READER.read(map(key, value, "minecraft:visual/fog_color", "#c0d8ff"), scope);
assertEquals(1, r.problems().size(), r.problems().toString());
assertEquals(key, r.problems().get(0).key());
if(reason.endsWith("...")) {
String prefix = reason.substring(0, reason.length() - 3);
assertTrue(r.problems().get(0).reason().startsWith(prefix), r.problems().get(0).reason());
} else {
assertEquals(reason, r.problems().get(0).reason());
}
assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isPresent());
assertEquals(1, r.map().keys().size());
}
@Test
void nullUnsetsKnownKeys() {
for(Scope scope : Scope.values()) {
Result r = READER.read(map("minecraft:visual/fog_color", null, "minecraft:visual/sky_color", "#405060"), scope);
assertTrue(r.problems().isEmpty(), r.problems().toString());
assertTrue(r.map().get(MinecraftAttributes.VISUAL_FOG_COLOR).isEmpty());
assertEquals(1, r.map().keys().size());
}
Map<String, Object> raw = map("minecraft:nope", null, "minecraft:Bad Key!", null, "visual/sky_color", null,
"terra:world/sea_level", null, "minecraft:visual/fog_color", null);
Result r = READER.read(raw, Scope.BIOME);
assertEquals(List.of(
new Problem("minecraft:nope", "unknown attribute"),
new Problem("minecraft:Bad Key!", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"Bad Key!\" is not a valid ID."),
new Problem("visual/sky_color", NAMESPACE_REQUIRED),
new Problem("terra:world/sea_level", "not allowed in a biome")),
r.problems());
assertTrue(r.map().isEmpty());
assertTrue(READER.read(map("terra:world/sea_level", null), Scope.PACK).problems().isEmpty());
}
@Test
void unknownKeyHint() {
AttributeReader empty = new AttributeReader(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE), HANDLE);
for(String key : List.of("minecraft:visual/fog_color", "terra:biome/temperature")) {
String namespace = key.substring(0, key.indexOf(':'));
assertExactProblem(empty.read(Map.of(key, "#ffffff"), Scope.BIOME), key,
"unknown attribute: no \"" + namespace + "\" attributes are registered; add the \"minecraft-attributes\" addon "
+ "to the pack's addons");
}
Result none = new AttributeReader(null, HANDLE).read(Map.of("minecraft:visual/fog_color", "#ffffff"), Scope.PACK);
assertExactProblem(none, "minecraft:visual/fog_color", "unknown attribute: no \"minecraft\" attributes are registered; add the "
+ "\"minecraft-attributes\" addon to the pack's addons");
assertExactProblem(empty.read(Map.of("mypack:thing", 1), Scope.BIOME), "mypack:thing", "unknown attribute");
assertExactProblem(READER.read(Map.of("minecraft:visual/fog_colour", "#ffffff"), Scope.BIOME), "minecraft:visual/fog_colour",
"unknown attribute");
}
@Test
void scheduleTrackKeys() {
Map<String, Object> track = Map.of("keyframes", List.of(Map.of("ticks", 0, "value", 10.0)));
Map<String, Object> raw = map("clock", "minecraft:overworld", "tracks", map(
"visual/sun_angle", track,
"minecraft:visual/sun angle", track,
"minecraft:visual/moon_angle", track));
ScheduleDecodeResult r = HANDLE.decodeSchedule(RegistryKey.parse("terra:test"), raw, new RegistryAttributeLookup(REGISTRY),
HANDLE.plainContext());
assertEquals(List.of(
new ScheduleDecodeResult.Problem("visual/sun_angle", NAMESPACE_REQUIRED),
new ScheduleDecodeResult.Problem("minecraft:visual/sun angle", "invalid attribute key: ID must only contain alphanumeric characters, hyphens, underscores, periods, and slashes. \"visual/sun angle\" is not a valid ID.")),
r.droppedTracks());
assertEquals(1, r.schedule().orElseThrow().tracks().size());
}
}
@@ -0,0 +1,160 @@
package attribute;
import org.jetbrains.annotations.Nullable;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
import com.dfsek.terra.addons.attribute.PackAttributesImpl;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeMap;
import com.dfsek.terra.api.world.attribute.AttributeParents;
import com.dfsek.terra.api.world.attribute.Operation;
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;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
class PackAttributesImplTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final Attribute<Integer> COUNT = HANDLE.attributeBuilder(AttributeKey.parse("test:count"), HANDLE.types().integer(),
10).build();
private static final Attribute<Integer> OTHER = HANDLE.attributeBuilder(AttributeKey.parse("test:other"), HANDLE.types().integer(),
0).build();
private static final Registry<Attribute<?>> REGISTRY = registry(COUNT, OTHER);
private static Registry<Attribute<?>> registry(Attribute<?>... attributes) {
OpenRegistryImpl<Attribute<?>> registry = new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : attributes) registry.register(attribute.getRegistryKey(), attribute);
return registry;
}
private static Biome withId(int id) {
return (Biome) Proxy.newProxyInstance(Biome.class.getClassLoader(), new Class<?>[]{ Biome.class }, (proxy, method, args) ->
switch(method.getName()) {
case "getIntID" -> id;
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static PackAttributesImpl pack(AttributeParents parents, AttributeMap entries, AttributeMap... biomeEntries) {
return new PackAttributesImpl(HANDLE, parents, REGISTRY, entries, Map.of(), List.of(), Map.of(), biomeEntries, List.of());
}
private static AttributeMap map(Attribute<Integer> attribute, AttributeEntry<Integer> entry) {
return AttributeMap.builder().put(attribute.key(), entry).build();
}
@Test
void resolveUsesParents() {
AttributeParents parents = new AttributeParents() {
@Override
@SuppressWarnings("unchecked")
public <T> @Nullable AttributeEntry<T> biomeOrNull(Biome biome, Attribute<T> attribute) {
return attribute == COUNT ? (AttributeEntry<T>) AttributeEntry.override(5) : null;
}
@Override
@SuppressWarnings("unchecked")
public <T> @Nullable AttributeEntry<T> packOrNull(PackAttributes pack, Attribute<T> attribute) {
return attribute == COUNT ? (AttributeEntry<T>) AttributeEntry.of(Operation.ADD, 1) : null;
}
};
PackAttributesImpl pack = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), new AttributeMap[2]);
assertEquals(5, pack.resolve(COUNT, withId(1)));
assertEquals(COUNT.defaultValue() + 3, pack.resolvePack(COUNT));
PackAttributesImpl withBiome = pack(parents, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null,
map(COUNT, AttributeEntry.of(Operation.ADD, 100)));
assertEquals(105, withBiome.resolve(COUNT, withId(1)));
assertEquals(0, pack.resolve(OTHER, withId(1)));
assertEquals(0, pack.resolvePack(OTHER));
}
@Test
void parentsNone() {
PackAttributesImpl pack = pack(AttributeParents.NONE, map(COUNT, AttributeEntry.of(Operation.ADD, 2)), null,
map(COUNT, AttributeEntry.of(Operation.MULTIPLY, 3)));
assertEquals(36, pack.resolve(COUNT, withId(1)));
assertEquals(12, pack.resolve(COUNT, withId(0)));
assertEquals(12, pack.resolvePack(COUNT));
}
@Test
void twoPacksIndependentColumns() {
AttributeEntry<Integer> small1 = AttributeEntry.override(1);
AttributeEntry<Integer> large1 = AttributeEntry.override(2);
AttributeEntry<Integer> large2 = AttributeEntry.override(3);
PackAttributesImpl small = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, small1));
PackAttributesImpl large = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, large1), map(COUNT, large2));
assertSame(small1, small.biomeEntryOrNull(COUNT, withId(1)));
assertSame(large1, large.biomeEntryOrNull(COUNT, withId(1)));
assertSame(large2, large.biomeEntryOrNull(COUNT, withId(2)));
assertNull(small.biomeEntryOrNull(COUNT, withId(2)));
assertEquals(10, small.resolve(COUNT, withId(2)));
assertEquals(3, large.resolve(COUNT, withId(2)));
}
@Test
void storedBiomeEntry() {
AttributeEntry<Integer> stored = AttributeEntry.override(7);
PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, map(COUNT, stored), null);
assertSame(stored, pack.biomeEntryOrNull(COUNT, withId(1)));
assertNull(pack.biomeEntryOrNull(COUNT, withId(0)));
assertNull(pack.biomeEntryOrNull(COUNT, withId(-1)));
assertNull(pack.biomeEntryOrNull(COUNT, withId(3)));
assertNull(pack.biomeEntryOrNull(OTHER, withId(1)));
Attribute<Integer> later = HANDLE.attributeBuilder(AttributeKey.parse("test:later"), HANDLE.types().integer(), 4).build();
assertNull(pack.biomeEntryOrNull(later, withId(1)));
assertEquals(4, pack.resolve(later, withId(1)));
assertEquals(4, pack.resolvePack(later));
}
@Test
void biomeEntriesCold() {
AttributeMap declared = AttributeMap.builder()
.put(COUNT.key(), AttributeEntry.override(1))
.put(OTHER.key(), AttributeEntry.of(Operation.ADD, 2))
.build();
PackAttributesImpl pack = pack(AttributeParents.NONE, AttributeMap.empty(), null, declared);
assertSame(declared, pack.biomeEntries(withId(1)));
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(0)));
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(2)));
assertSame(AttributeMap.empty(), pack.biomeEntries(withId(-1)));
}
@Test
void configOrder() {
Map<String, RegistryKey> parents = new LinkedHashMap<>();
parents.put("vanilla-generation", RegistryKey.parse("test:generation"));
parents.put("vanilla", RegistryKey.parse("test:dimension"));
List<String> ids = List.of("terra:z", "terra:a", "terra:m", "terra:b", "terra:y", "terra:c", "terra:x", "terra:d");
Map<RegistryKey, AttributeSchedule> definitions = new LinkedHashMap<>();
for(String id : ids) {
definitions.put(RegistryKey.parse(id), new AttributeSchedule(RegistryKey.parse("test:clock"), OptionalInt.empty(),
Map.of(), Map.of()));
}
PackAttributesImpl pack = new PackAttributesImpl(HANDLE, AttributeParents.NONE, REGISTRY, AttributeMap.empty(), parents,
List.of(), definitions, new AttributeMap[0], List.of());
assertEquals(List.of("vanilla-generation", "vanilla"), List.copyOf(pack.parents().keySet()));
assertEquals(ids, pack.scheduleDefinitions().keySet().stream().map(RegistryKey::toString).toList());
}
}
@@ -0,0 +1,186 @@
package com.dfsek.terra.addons.attribute;
import com.dfsek.paralithic.eval.parser.Parser.ParseOptions;
import com.dfsek.tectonic.api.config.Configuration;
import com.dfsek.tectonic.api.depth.DepthTracker;
import com.dfsek.tectonic.api.loader.ConfigLoader;
import com.dfsek.tectonic.api.preprocessor.Result;
import com.dfsek.tectonic.api.preprocessor.ValuePreprocessor;
import com.dfsek.tectonic.impl.MapConfiguration;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.Test;
import java.lang.reflect.AnnotatedType;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.config.meta.Meta;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.config.preprocessor.MetaListLikePreprocessor;
import com.dfsek.terra.config.preprocessor.MetaMapPreprocessor;
import com.dfsek.terra.config.preprocessor.MetaNumberPreprocessor;
import com.dfsek.terra.config.preprocessor.MetaStringPreprocessor;
import com.dfsek.terra.config.preprocessor.MetaValuePreprocessor;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class ConfigDecodeContextTest {
private static final Map<String, Object> META = map(
"n", 3,
"s", "two",
"chain", "$meta.yml:s",
"obj", map("x", 1, "y", "$meta.yml:s"),
"list", List.of("a", "b"));
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
private static DecodeContext context() {
return context(Map.of("meta.yml", new MapConfiguration(META, "meta.yml")));
}
private static DecodeContext context(Map<String, Configuration> configs) {
ConfigLoader loader = new ConfigLoader();
loader.registerPreprocessor(Meta.class, new MetaStringPreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaListLikePreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaMapPreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaValuePreprocessor(configs));
loader.registerPreprocessor(Meta.class, new MetaNumberPreprocessor(configs, new ParseOptions()));
return context(loader);
}
private static DecodeContext context(ConfigLoader loader) {
for(Class<?> type : ConfigDecodeContext.CAPTURED_TYPES) loader.registerLoader(type, LazyConfigValue.LOADER);
DepthTracker tracker = new DepthTracker(List.of(), new MapConfiguration(Map.of(), "biome.yml"));
return new LazyConfigValue(null, loader, tracker).context(new AttributeHandleImpl().plainContext());
}
@Test
void numberExpressions() throws DecodeException {
DecodeContext context = context();
assertEquals("2 * 6000", context.resolve("2 * 6000"));
assertEquals(12000, context.<Integer>load(Integer.class, "2 * 6000"));
assertEquals(1.5f, context.<Float>load(Float.class, "${meta.yml:n} / 2"));
assertEquals(3.0, context.<Double>load(Double.class, "$meta.yml:n"));
assertEquals(0.5f, context.<Float>load(Float.class, 0.5));
}
@Test
void plainConversion() {
DecodeContext context = context();
assertTrue(assertThrows(DecodeException.class, () -> context.load(Integer.class, "5 / 2")).getMessage()
.startsWith("expected an integer"));
assertEquals("expected a string, got 3",
assertThrows(DecodeException.class, () -> context.load(String.class, "$meta.yml:n")).getMessage());
assertEquals("expected a boolean (true or false), got \"two\"",
assertThrows(DecodeException.class, () -> context.load(Boolean.class, "$meta.yml:s")).getMessage());
}
@Test
void nestedResolve() throws DecodeException {
Map<String, Object> raw = map(
"null", null,
"ref", "$meta.yml:obj",
"list", List.of("<< meta.yml:list", "c", "${meta.yml:s}"),
"include", map("<<", List.of("meta.yml:obj"), "x", 2),
"string", "one-${meta.yml:s}",
"deep", map("a", List.of(map("b", "$meta.yml:n"))));
Map<?, ?> resolved = (Map<?, ?>) context().resolve(raw);
assertEquals(map(
"null", null,
"ref", map("x", 1, "y", "two"),
"list", List.of("a", "b", "c", "two"),
"include", map("x", 2, "y", "two"),
"string", "one-two",
"deep", map("a", List.of(map("b", 3)))), resolved);
assertEquals(List.copyOf(raw.keySet()), List.copyOf(resolved.keySet()));
}
@Test
void resolveTwice() throws DecodeException {
DecodeContext context = context();
Object once = context.resolve(map("a", "$meta.yml:chain"));
assertEquals(map("a", "$meta.yml:s"), once);
assertSame(once, context.resolve(once));
Object chained = ((Map<?, ?>) once).get("a");
assertSame(chained, context.resolve(chained));
assertEquals("$meta.yml:s", context.load(String.class, chained));
}
@Test
void preprocessingErrors() {
DecodeContext context = context();
String missing = assertThrows(DecodeException.class, () -> context.resolve(map("a", "${meta.yml:missing}"))).getMessage();
assertTrue(missing.contains("No such key missing"), missing);
assertTrue(missing.contains("Path: a"), missing);
String malformed = assertThrows(DecodeException.class, () -> context.resolve(List.of("${2 * 6000}"))).getMessage();
assertTrue(malformed.contains("meta reference \"2 * 6000\" must have the form file:key"), malformed);
assertTrue(malformed.contains("Path: [0]"), malformed);
assertReadable(malformed);
String escape = assertThrows(DecodeException.class, () -> context.resolve(map("a", "$meta.yml:bad\\q"))).getMessage();
assertTrue(escape.contains("meta reference \"meta.yml:bad\\q\" has an invalid key path"), escape);
assertReadable(escape);
String expression = assertThrows(DecodeException.class, () -> context.load(Float.class, "1 +")).getMessage();
assertTrue(expression.contains("Invalid expression"), expression);
String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("meta.yml:list")))).getMessage();
assertTrue(include.contains("MetaMap injection candidate must be map, is type java.util."), include);
}
@Test
void nullMetaTargets() {
Configuration nulls = new Configuration() {
@Override
public Object get(@NotNull String key) {
return null;
}
@Override
public boolean contains(@NotNull String key) {
return true;
}
@Override
public String getName() {
return "null.yml";
}
};
DecodeContext context = context(Map.of("null.yml", nulls));
String string = assertThrows(DecodeException.class, () -> context.resolve("${null.yml:x}")).getMessage();
assertTrue(string.contains("must be string or primitive, is null"), string);
String list = assertThrows(DecodeException.class, () -> context.resolve(List.of("<< null.yml:x"))).getMessage();
assertTrue(list.contains("'null.yml:x' points to null"), list);
String include = assertThrows(DecodeException.class, () -> context.resolve(map("<<", List.of("null.yml:x")))).getMessage();
assertTrue(include.contains("must be map, is null"), include);
}
@Test
void preprocessorRuntimeExceptions() {
ConfigLoader loader = new ConfigLoader();
loader.registerPreprocessor(Meta.class, new ValuePreprocessor<Meta>() {
@Override
public @NotNull <T> Result<T> process(AnnotatedType t, T c, ConfigLoader l, Meta annotation, DepthTracker depthTracker) {
throw new IllegalStateException("java.lang.Boom");
}
});
DecodeContext context = context(loader);
String message = assertThrows(DecodeException.class, () -> context.resolve("x")).getMessage();
assertTrue(message.contains("config preprocessing failed"), message);
assertReadable(message);
}
private static void assertReadable(String message) {
assertFalse(message.contains("java."), message);
assertFalse(message.contains("Exception"), message);
}
}
@@ -0,0 +1,40 @@
package com.dfsek.terra.addons.attribute;
import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
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 static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class ScheduleIdsTest {
@Test
void referenceNamespace() {
assertEquals(Either.left(RegistryKey.parse("mypack:seasons")), ScheduleIds.reference("mypack:seasons"));
assertEquals(Either.right(TagKey.parse("#mypack:in_overworld")), ScheduleIds.reference("#mypack:in_overworld"));
assertEquals("a namespace is required, as in \"namespace:seasons\"",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("seasons")).getMessage());
assertEquals("invalid tag \"#in_overworld\": a namespace is required, as in \"#namespace:in_overworld\"",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.reference("#in_overworld")).getMessage());
}
@Test
void claim() {
Set<RegistryKey> claimed = new HashSet<>();
assertEquals(RegistryKey.parse("mypack:seasons"), ScheduleIds.claim("mypack:seasons", claimed));
assertEquals("duplicate schedule ID",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:seasons", claimed)).getMessage());
assertEquals(RegistryKey.parse("MyPack:Seasons"), ScheduleIds.claim("MyPack:Seasons", claimed));
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("mypack:", claimed));
assertEquals("schedule IDs must include a namespace, e.g. \"mypack:seasons\"",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("seasons", claimed)).getMessage());
assertEquals("schedule IDs must not be tags",
assertThrows(IllegalArgumentException.class, () -> ScheduleIds.claim("#mypack:seasons", claimed)).getMessage());
}
}
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020-2025 Polyhedral Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,8 @@
version = version("1.0.0")
dependencies {
compileOnlyApi(project(":common:addons:manifest-addon-loader"))
testImplementation(project(":common:implementation:base"))
testImplementation(project(":common:addons:manifest-addon-loader"))
}
@@ -0,0 +1,6 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.world.attribute.RawValue;
public record AmbientParticle(RawValue particle, float probability) { }
@@ -0,0 +1,18 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
import java.util.Optional;
public record AmbientSounds(Optional<SoundRef> loop, Optional<Mood> mood, List<Additions> additions) {
public static final AmbientSounds EMPTY = new AmbientSounds(Optional.empty(), Optional.empty(), List.of());
public AmbientSounds {
additions = List.copyOf(additions);
}
public record Mood(SoundRef sound, int tickDelay, int blockSearchExtent, double offset) { }
public record Additions(SoundRef sound, double tickChance) { }
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
public record BackgroundMusic(Optional<Music> defaultMusic, Optional<Music> creative, Optional<Music> underwater) {
public static final BackgroundMusic EMPTY = new BackgroundMusic(Optional.empty(), Optional.empty(), Optional.empty());
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
import com.dfsek.terra.api.world.attribute.RawValue;
public record BedRule(Rule canSleep, Rule canSetSpawn, boolean destroyOnUse, boolean destroyOnLeave, Optional<RawValue> errorMessage) {
public enum Rule implements StringIdentifiable {
ALWAYS("always"),
WHEN_DARK("when_dark"),
NEVER("never");
private final String id;
Rule(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
}
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum CardinalLight implements StringIdentifiable {
DEFAULT("default"),
NETHER("nether");
private final String id;
CardinalLight(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum GrassColorModifier implements StringIdentifiable {
NONE("none"),
DARK_FOREST("dark_forest"),
SWAMP("swamp");
private final String id;
GrassColorModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,15 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Optional;
import java.util.OptionalInt;
import com.dfsek.terra.api.world.attribute.RawValue;
public record IntProviderValue(OptionalInt constant, Optional<RawValue> provider) {
public IntProviderValue {
if(constant.isPresent() == provider.isPresent()) {
throw new IllegalArgumentException("an int provider value needs exactly one of a constant and a provider");
}
}
}
@@ -0,0 +1,159 @@
package com.dfsek.terra.addons.attribute.minecraft;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalInt;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.AttributeTypes;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributeTable {
private static final RawValue NO_SLEEP_MESSAGE = new RawValue(Map.of("translate", "block.minecraft.bed.no_sleep"));
private static final BedRule CAN_SLEEP_WHEN_DARK = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.ALWAYS, false, false,
Optional.of(NO_SLEEP_MESSAGE));
private static final BedRule DESTROY_ON_LEAVE = new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, false, true,
Optional.of(NO_SLEEP_MESSAGE));
private static final IntProviderValue MONSTER_SPAWN_LIGHT_LEVEL = new IntProviderValue(OptionalInt.empty(), Optional.of(
new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))));
private MinecraftAttributeTable() { }
public static List<Attribute<?>> create(AttributeHandle handle) {
AttributeTypes t = handle.types();
MinecraftAttributeTypes m = new MinecraftAttributeTypes(handle);
AttributeType<TemperatureModifier> temperatureModifier = t.enumType("temperature_modifier", TemperatureModifier.class);
AttributeType<GrassColorModifier> grassColorModifier = t.enumType("grass_color_modifier", GrassColorModifier.class);
AttributeType<Skybox> skybox = t.enumType("skybox", Skybox.class);
AttributeType<CardinalLight> cardinalLight = t.enumType("cardinal_light", CardinalLight.class);
Table table = new Table(handle);
table.row(MinecraftAttributes.VISUAL_FOG_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_FOG_START_DISTANCE, t.floatType(), 0f);
table.row(MinecraftAttributes.VISUAL_FOG_END_DISTANCE, t.floatType(), 1024f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_FOG_END_DISTANCE, t.floatType(), 512f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_CLOUD_FOG_END_DISTANCE, t.floatType(), 2048f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_COLOR, t.rgbColor(), Color.rgb(0x050533));
table.row(MinecraftAttributes.VISUAL_WATER_FOG_START_DISTANCE, t.floatType(), -8f);
table.row(MinecraftAttributes.VISUAL_WATER_FOG_END_DISTANCE, t.floatType(), 96f).range(0, Double.POSITIVE_INFINITY);
table.row(MinecraftAttributes.VISUAL_SKY_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_SUNRISE_SUNSET_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_COLOR, t.argbColor(), Color.argb(0));
table.row(MinecraftAttributes.VISUAL_CLOUD_HEIGHT, t.floatType(), 192.33f);
table.row(MinecraftAttributes.VISUAL_SUN_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_STAR_ANGLE, t.angleDegrees(), 0f);
table.row(MinecraftAttributes.VISUAL_MOON_PHASE, m.moonPhase(), MoonPhase.FULL_MOON);
table.row(MinecraftAttributes.VISUAL_STAR_BRIGHTNESS, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_BLOCK_LIGHT_TINT, t.rgbColor(), Color.rgb(0xffd88c));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_COLOR, t.rgbColor(), Color.rgb(0xffffff));
table.row(MinecraftAttributes.VISUAL_SKY_LIGHT_FACTOR, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.VISUAL_NIGHT_VISION_COLOR, t.rgbColor(), Color.rgb(0x999999));
table.row(MinecraftAttributes.VISUAL_AMBIENT_LIGHT_COLOR, t.rgbColor(), Color.rgb(0x000000));
table.row(MinecraftAttributes.VISUAL_DEFAULT_DRIPSTONE_PARTICLE, m.particle(),
new RawValue(Map.of("type", "minecraft:dripping_dripstone_water")));
table.row(MinecraftAttributes.VISUAL_AMBIENT_PARTICLES, m.ambientParticles(), List.of());
table.row(MinecraftAttributes.AUDIO_BACKGROUND_MUSIC, m.backgroundMusic(), BackgroundMusic.EMPTY);
table.row(MinecraftAttributes.AUDIO_MUSIC_VOLUME, t.floatType(), 1f).range(0, 1);
table.row(MinecraftAttributes.AUDIO_AMBIENT_SOUNDS, m.ambientSounds(), AmbientSounds.EMPTY);
table.row(MinecraftAttributes.AUDIO_FIREFLY_BUSH_SOUNDS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SKY_LIGHT_LEVEL, t.floatType(), 15f).range(0, 15).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_CAN_START_RAID, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_WATER_EVAPORATES, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_BED_RULE, m.bedRule(), CAN_SLEEP_WHEN_DARK);
table.row(MinecraftAttributes.GAMEPLAY_STRAW_BED_RULE, m.bedRule(), DESTROY_ON_LEAVE);
table.row(MinecraftAttributes.GAMEPLAY_RESPAWN_ANCHOR_WORKS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_FAST_LAVA, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.GAMEPLAY_INCREASED_FIRE_BURNOUT, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_EYEBLOSSOM_OPEN, t.triState(), TriState.DEFAULT);
table.row(MinecraftAttributes.GAMEPLAY_TURTLE_EGG_HATCH_CHANCE, t.floatType(), 0.002f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_PIGLINS_ZOMBIFY, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_SNOW_GOLEM_MELTS, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CREAKING_ACTIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE, t.floatType(), 0f).range(0, 1);
table.row(MinecraftAttributes.GAMEPLAY_BEES_STAY_IN_HIVE, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_MONSTERS_BURN, t.booleanType(), false);
table.row(MinecraftAttributes.GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN, t.booleanType(), true);
table.row(MinecraftAttributes.GAMEPLAY_NATURAL_MOB_SPAWNS, m.mobSpawnSettings(), MobSpawnSettings.EMPTY);
table.row(MinecraftAttributes.GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY, t.floatType(), 0.1f).range(0, 0.9999999);
table.row(MinecraftAttributes.GAMEPLAY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.GAMEPLAY_BABY_VILLAGER_ACTIVITY, m.identifier(), RegistryKey.parse("minecraft:idle"));
table.row(MinecraftAttributes.BIOME_HAS_PRECIPITATION, t.booleanType(), true);
table.row(MinecraftAttributes.BIOME_TEMPERATURE, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_TEMPERATURE_MODIFIER, temperatureModifier, TemperatureModifier.NONE);
table.row(MinecraftAttributes.BIOME_DOWNFALL, t.floatType(), 0.5f);
table.row(MinecraftAttributes.BIOME_WATER_COLOR, t.rgbColor(), Color.rgb(0x3f76e4));
table.row(MinecraftAttributes.BIOME_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_DRY_FOLIAGE_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR, t.rgbColor(), null);
table.row(MinecraftAttributes.BIOME_GRASS_COLOR_MODIFIER, grassColorModifier, GrassColorModifier.NONE);
table.row(MinecraftAttributes.BIOME_VILLAGER_TYPE, m.identifier(), RegistryKey.parse("minecraft:plains"));
table.row(MinecraftAttributes.DIMENSION_HAS_FIXED_TIME, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_SKYLIGHT, t.booleanType(), true).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_CEILING, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_HAS_ENDER_DRAGON_FIGHT, t.booleanType(), false).packOnly();
table.row(MinecraftAttributes.DIMENSION_COORDINATE_SCALE, t.floatType(), 1f).packOnly().range(1e-5, 3e7);
table.row(MinecraftAttributes.DIMENSION_MIN_Y, t.integerOverrideOnly(), -64).packOnly().range(-2032, 2031).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(16, 4064).multipleOf(16);
table.row(MinecraftAttributes.DIMENSION_LOGICAL_HEIGHT, t.integerOverrideOnly(), 384).packOnly().range(0, 4064);
table.row(MinecraftAttributes.DIMENSION_INFINIBURN, m.identifierOrTag(),
Either.right(TagKey.parse("#minecraft:infiniburn_overworld"))).packOnly();
table.row(MinecraftAttributes.DIMENSION_AMBIENT_LIGHT, t.floatType(), 0f).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL, m.intProvider(), MONSTER_SPAWN_LIGHT_LEVEL).packOnly();
table.row(MinecraftAttributes.DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT, t.integer(), 0).packOnly().range(0, 15);
table.row(MinecraftAttributes.DIMENSION_SKYBOX, skybox, Skybox.OVERWORLD).packOnly();
table.row(MinecraftAttributes.DIMENSION_CARDINAL_LIGHT, cardinalLight, CardinalLight.DEFAULT).packOnly();
table.row(MinecraftAttributes.DIMENSION_DEFAULT_CLOCK, m.identifier(), RegistryKey.parse("minecraft:overworld")).packOnly();
table.row(MinecraftAttributes.WORLD_SEA_LEVEL, t.integer(), 63).packOnly();
table.row(MinecraftAttributes.WORLD_SPAWN_HEIGHT, t.integer(), 64).packOnly();
table.row(MinecraftAttributes.WORLD_MOB_GENERATION, t.booleanType(), true).packOnly();
List<Attribute<?>> attributes = table.build();
if(!attributes.stream().map(Attribute::key).toList().equals(MinecraftAttributes.all())) {
throw new IllegalStateException("the Minecraft attribute table does not match MinecraftAttributes.all()");
}
return attributes;
}
private static final class Table {
private final AttributeHandle handle;
private final List<Attribute.Builder<?>> rows = new ArrayList<>();
private Table(AttributeHandle handle) {
this.handle = handle;
}
private <T> Attribute.Builder<T> row(AttributeKey<T> key, AttributeType<T> type, @Nullable T defaultValue) {
MinecraftIds.requireLowerCase(key.getRegistryKey());
Attribute.Builder<T> builder = handle.attributeBuilder(key, type, defaultValue);
rows.add(builder);
return builder;
}
private List<Attribute<?>> build() {
List<Attribute<?>> built = new ArrayList<>(rows.size());
for(Attribute.Builder<?> row : rows) built.add(row.build());
return List.copyOf(built);
}
}
}
@@ -0,0 +1,109 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.ArrayList;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftAttributeTypes {
private final AttributeType<MoonPhase> moonPhase;
private final AttributeType<BedRule> bedRule;
private final AttributeType<RawValue> particle;
private final AttributeType<List<AmbientParticle>> ambientParticles;
private final AttributeType<BackgroundMusic> backgroundMusic;
private final AttributeType<AmbientSounds> ambientSounds;
private final AttributeType<MobSpawnSettings> mobSpawnSettings;
private final AttributeType<RegistryKey> identifier;
private final AttributeType<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeType<IntProviderValue> intProvider;
public MinecraftAttributeTypes(AttributeHandle handle) {
MinecraftCodecs codecs = new MinecraftCodecs(handle);
this.moonPhase = handle.typeBuilder("moon_phase", codecs.moonPhase()).build();
this.bedRule = handle.typeBuilder("bed_rule", codecs.bedRule()).build();
this.particle = handle.typeBuilder("particle", codecs.particle()).build();
this.ambientParticles = handle.typeBuilder("ambient_particles", codecs.ambientParticles())
.op(Operation.APPEND, codecs.ambientParticles(), MinecraftAttributeTypes::append)
.build();
this.backgroundMusic = handle.typeBuilder("background_music", codecs.backgroundMusic()).build();
this.ambientSounds = handle.typeBuilder("ambient_sounds", codecs.ambientSounds()).build();
this.mobSpawnSettings = handle.typeBuilder("mob_spawn_settings", codecs.mobSpawnSettings())
.op(Operation.OVERLAY, codecs.mobSpawnSettings(), MinecraftAttributeTypes::overlay)
.build();
this.identifier = handle.typeBuilder("identifier", codecs.identifier()).build();
this.identifierOrTag = handle.typeBuilder("identifier_or_tag", codecs.identifierOrTag()).build();
this.intProvider = handle.typeBuilder("int_provider", codecs.intProvider()).build();
}
public AttributeType<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeType<BedRule> bedRule() {
return bedRule;
}
public AttributeType<RawValue> particle() {
return particle;
}
public AttributeType<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeType<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeType<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeType<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
public AttributeType<RegistryKey> identifier() {
return identifier;
}
public AttributeType<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeType<IntProviderValue> intProvider() {
return intProvider;
}
private static List<AmbientParticle> append(List<AmbientParticle> s, List<AmbientParticle> a) {
if(a.isEmpty()) return s;
if(s.isEmpty()) return a;
List<AmbientParticle> out = new ArrayList<>(s.size() + a.size());
out.addAll(s);
out.addAll(a);
return List.copyOf(out);
}
private static MobSpawnSettings overlay(MobSpawnSettings first, MobSpawnSettings second) {
if(first.spawnsByCategory().isEmpty() && first.spawnCosts().isEmpty()) return second;
if(second.spawnsByCategory().isEmpty() && second.spawnCosts().isEmpty()) return first;
if(second.spawnsByCategory().keySet().containsAll(first.spawnsByCategory().keySet())
&& second.spawnCosts().keySet().containsAll(first.spawnCosts().keySet())) {
return second;
}
Map<String, List<MobSpawnSettings.Spawner>> categories = new LinkedHashMap<>(first.spawnsByCategory());
categories.putAll(second.spawnsByCategory());
Map<RegistryKey, MobSpawnSettings.Cost> costs = new LinkedHashMap<>(first.spawnCosts());
costs.putAll(second.spawnCosts());
return new MobSpawnSettings(categories, costs);
}
}
@@ -0,0 +1,128 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.ArrayList;
import java.util.List;
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.AttributeKey;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.api.world.attribute.value.TriState;
public final class MinecraftAttributes {
private static List<AttributeKey<?>> building = new ArrayList<>();
public static final AttributeKey<Color> VISUAL_FOG_COLOR = vanilla("visual/fog_color");
public static final AttributeKey<Float> VISUAL_FOG_START_DISTANCE = vanilla("visual/fog_start_distance");
public static final AttributeKey<Float> VISUAL_FOG_END_DISTANCE = vanilla("visual/fog_end_distance");
public static final AttributeKey<Float> VISUAL_SKY_FOG_END_DISTANCE = vanilla("visual/sky_fog_end_distance");
public static final AttributeKey<Float> VISUAL_CLOUD_FOG_END_DISTANCE = vanilla("visual/cloud_fog_end_distance");
public static final AttributeKey<Color> VISUAL_WATER_FOG_COLOR = vanilla("visual/water_fog_color");
public static final AttributeKey<Float> VISUAL_WATER_FOG_START_DISTANCE = vanilla("visual/water_fog_start_distance");
public static final AttributeKey<Float> VISUAL_WATER_FOG_END_DISTANCE = vanilla("visual/water_fog_end_distance");
public static final AttributeKey<Color> VISUAL_SKY_COLOR = vanilla("visual/sky_color");
public static final AttributeKey<Color> VISUAL_SUNRISE_SUNSET_COLOR = vanilla("visual/sunrise_sunset_color");
public static final AttributeKey<Color> VISUAL_CLOUD_COLOR = vanilla("visual/cloud_color");
public static final AttributeKey<Float> VISUAL_CLOUD_HEIGHT = vanilla("visual/cloud_height");
public static final AttributeKey<Float> VISUAL_SUN_ANGLE = vanilla("visual/sun_angle");
public static final AttributeKey<Float> VISUAL_MOON_ANGLE = vanilla("visual/moon_angle");
public static final AttributeKey<Float> VISUAL_STAR_ANGLE = vanilla("visual/star_angle");
public static final AttributeKey<MoonPhase> VISUAL_MOON_PHASE = vanilla("visual/moon_phase");
public static final AttributeKey<Float> VISUAL_STAR_BRIGHTNESS = vanilla("visual/star_brightness");
public static final AttributeKey<Color> VISUAL_BLOCK_LIGHT_TINT = vanilla("visual/block_light_tint");
public static final AttributeKey<Color> VISUAL_SKY_LIGHT_COLOR = vanilla("visual/sky_light_color");
public static final AttributeKey<Float> VISUAL_SKY_LIGHT_FACTOR = vanilla("visual/sky_light_factor");
public static final AttributeKey<Color> VISUAL_NIGHT_VISION_COLOR = vanilla("visual/night_vision_color");
public static final AttributeKey<Color> VISUAL_AMBIENT_LIGHT_COLOR = vanilla("visual/ambient_light_color");
public static final AttributeKey<RawValue> VISUAL_DEFAULT_DRIPSTONE_PARTICLE = vanilla("visual/default_dripstone_particle");
public static final AttributeKey<List<AmbientParticle>> VISUAL_AMBIENT_PARTICLES = vanilla("visual/ambient_particles");
public static final AttributeKey<BackgroundMusic> AUDIO_BACKGROUND_MUSIC = vanilla("audio/background_music");
public static final AttributeKey<Float> AUDIO_MUSIC_VOLUME = vanilla("audio/music_volume");
public static final AttributeKey<AmbientSounds> AUDIO_AMBIENT_SOUNDS = vanilla("audio/ambient_sounds");
public static final AttributeKey<Boolean> AUDIO_FIREFLY_BUSH_SOUNDS = vanilla("audio/firefly_bush_sounds");
public static final AttributeKey<Float> GAMEPLAY_SKY_LIGHT_LEVEL = vanilla("gameplay/sky_light_level");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_START_RAID = vanilla("gameplay/can_start_raid");
public static final AttributeKey<Boolean> GAMEPLAY_WATER_EVAPORATES = vanilla("gameplay/water_evaporates");
public static final AttributeKey<BedRule> GAMEPLAY_BED_RULE = vanilla("gameplay/bed_rule");
public static final AttributeKey<BedRule> GAMEPLAY_STRAW_BED_RULE = vanilla("gameplay/straw_bed_rule");
public static final AttributeKey<Boolean> GAMEPLAY_RESPAWN_ANCHOR_WORKS = vanilla("gameplay/respawn_anchor_works");
public static final AttributeKey<Boolean> GAMEPLAY_NETHER_PORTAL_SPAWNS_PIGLIN = vanilla("gameplay/nether_portal_spawns_piglin");
public static final AttributeKey<Boolean> GAMEPLAY_FAST_LAVA = vanilla("gameplay/fast_lava");
public static final AttributeKey<Boolean> GAMEPLAY_INCREASED_FIRE_BURNOUT = vanilla("gameplay/increased_fire_burnout");
public static final AttributeKey<TriState> GAMEPLAY_EYEBLOSSOM_OPEN = vanilla("gameplay/eyeblossom_open");
public static final AttributeKey<Float> GAMEPLAY_TURTLE_EGG_HATCH_CHANCE = vanilla("gameplay/turtle_egg_hatch_chance");
public static final AttributeKey<Boolean> GAMEPLAY_PIGLINS_ZOMBIFY = vanilla("gameplay/piglins_zombify");
public static final AttributeKey<Boolean> GAMEPLAY_SNOW_GOLEM_MELTS = vanilla("gameplay/snow_golem_melts");
public static final AttributeKey<Boolean> GAMEPLAY_CREAKING_ACTIVE = vanilla("gameplay/creaking_active");
public static final AttributeKey<Float> GAMEPLAY_SURFACE_SLIME_SPAWN_CHANCE = vanilla("gameplay/surface_slime_spawn_chance");
public static final AttributeKey<Float> GAMEPLAY_CAT_WAKING_UP_GIFT_CHANCE = vanilla("gameplay/cat_waking_up_gift_chance");
public static final AttributeKey<Boolean> GAMEPLAY_BEES_STAY_IN_HIVE = vanilla("gameplay/bees_stay_in_hive");
public static final AttributeKey<Boolean> GAMEPLAY_MONSTERS_BURN = vanilla("gameplay/monsters_burn");
public static final AttributeKey<Boolean> GAMEPLAY_CAN_PILLAGER_PATROL_SPAWN = vanilla("gameplay/can_pillager_patrol_spawn");
public static final AttributeKey<MobSpawnSettings> GAMEPLAY_NATURAL_MOB_SPAWNS = vanilla("gameplay/natural_mob_spawns");
public static final AttributeKey<Float> GAMEPLAY_CREATURE_WORLD_GEN_SPAWN_PROBABILITY =
vanilla("gameplay/creature_world_gen_spawn_probability");
public static final AttributeKey<RegistryKey> GAMEPLAY_VILLAGER_ACTIVITY = vanilla("gameplay/villager_activity");
public static final AttributeKey<RegistryKey> GAMEPLAY_BABY_VILLAGER_ACTIVITY = vanilla("gameplay/baby_villager_activity");
public static final AttributeKey<Boolean> BIOME_HAS_PRECIPITATION = terra("biome/has_precipitation");
public static final AttributeKey<Float> BIOME_TEMPERATURE = terra("biome/temperature");
public static final AttributeKey<TemperatureModifier> BIOME_TEMPERATURE_MODIFIER = terra("biome/temperature_modifier");
public static final AttributeKey<Float> BIOME_DOWNFALL = terra("biome/downfall");
public static final AttributeKey<Color> BIOME_WATER_COLOR = terra("biome/water_color");
public static final AttributeKey<Color> BIOME_FOLIAGE_COLOR = terra("biome/foliage_color");
public static final AttributeKey<Color> BIOME_DRY_FOLIAGE_COLOR = terra("biome/dry_foliage_color");
public static final AttributeKey<Color> BIOME_GRASS_COLOR = terra("biome/grass_color");
public static final AttributeKey<GrassColorModifier> BIOME_GRASS_COLOR_MODIFIER = terra("biome/grass_color_modifier");
public static final AttributeKey<RegistryKey> BIOME_VILLAGER_TYPE = terra("biome/villager_type");
public static final AttributeKey<Boolean> DIMENSION_HAS_FIXED_TIME = terra("dimension/has_fixed_time");
public static final AttributeKey<Boolean> DIMENSION_HAS_SKYLIGHT = terra("dimension/has_skylight");
public static final AttributeKey<Boolean> DIMENSION_HAS_CEILING = terra("dimension/has_ceiling");
public static final AttributeKey<Boolean> DIMENSION_HAS_ENDER_DRAGON_FIGHT = terra("dimension/has_ender_dragon_fight");
public static final AttributeKey<Float> DIMENSION_COORDINATE_SCALE = terra("dimension/coordinate_scale");
public static final AttributeKey<Integer> DIMENSION_MIN_Y = terra("dimension/min_y");
public static final AttributeKey<Integer> DIMENSION_HEIGHT = terra("dimension/height");
public static final AttributeKey<Integer> DIMENSION_LOGICAL_HEIGHT = terra("dimension/logical_height");
public static final AttributeKey<Either<RegistryKey, TagKey>> DIMENSION_INFINIBURN = terra("dimension/infiniburn");
public static final AttributeKey<Float> DIMENSION_AMBIENT_LIGHT = terra("dimension/ambient_light");
public static final AttributeKey<IntProviderValue> DIMENSION_MONSTER_SPAWN_LIGHT_LEVEL = terra("dimension/monster_spawn_light_level");
public static final AttributeKey<Integer> DIMENSION_MONSTER_SPAWN_BLOCK_LIGHT_LIMIT =
terra("dimension/monster_spawn_block_light_limit");
public static final AttributeKey<Skybox> DIMENSION_SKYBOX = terra("dimension/skybox");
public static final AttributeKey<CardinalLight> DIMENSION_CARDINAL_LIGHT = terra("dimension/cardinal_light");
public static final AttributeKey<RegistryKey> DIMENSION_DEFAULT_CLOCK = terra("dimension/default_clock");
public static final AttributeKey<Integer> WORLD_SEA_LEVEL = terra("world/sea_level");
public static final AttributeKey<Integer> WORLD_SPAWN_HEIGHT = terra("world/spawn_height");
public static final AttributeKey<Boolean> WORLD_MOB_GENERATION = terra("world/mob_generation");
private static final List<AttributeKey<?>> VIEW = seal();
private MinecraftAttributes() { }
public static List<AttributeKey<?>> all() {
return VIEW;
}
private static List<AttributeKey<?>> seal() {
List<AttributeKey<?>> view = List.copyOf(building);
building = null;
return view;
}
private static <T> AttributeKey<T> vanilla(String path) {
return add(RegistryKey.of("minecraft", path));
}
private static <T> AttributeKey<T> terra(String path) {
return add(RegistryKey.of("terra", path));
}
private static <T> AttributeKey<T> add(RegistryKey key) {
AttributeKey<T> attributeKey = AttributeKey.of(key);
building.add(attributeKey);
return attributeKey;
}
}
@@ -0,0 +1,35 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.List;
import com.dfsek.terra.addons.manifest.api.AddonInitializer;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.event.functional.FunctionalEventHandler;
import com.dfsek.terra.api.inject.annotations.Inject;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.world.attribute.Attribute;
public class MinecraftAttributesAddon implements AddonInitializer {
@Inject
private Platform platform;
@Inject
private BaseAddon addon;
@Override
public void initialize() {
List<Attribute<?>> attributes = MinecraftAttributeTable.create(platform.getAttributeHandle());
platform.getEventManager()
.getHandler(FunctionalEventHandler.class)
.register(addon, ConfigPackPreLoadEvent.class)
.then(event -> {
CheckedRegistry<Attribute<?>> registry = event.getPack().getOrCreateRegistry(Attribute.REGISTRY_TYPE);
for(Attribute<?> attribute : attributes) registry.register(attribute.getRegistryKey(), attribute);
})
.failThrough();
}
}
@@ -0,0 +1,349 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalDouble;
import java.util.OptionalInt;
import java.util.Set;
import java.util.TreeSet;
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.AttributeCodec;
import com.dfsek.terra.api.world.attribute.AttributeCodecs;
import com.dfsek.terra.api.world.attribute.AttributeCodecs.ObjectReader;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.api.world.attribute.DecodeContext;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.RawValue;
public final class MinecraftCodecs {
public static final String NAMESPACE = "minecraft";
// Same wording as the core identifier codec.
private static final String EXPECTED_IDENTIFIER = "expected an identifier like \"" + NAMESPACE + ":id\"";
private static final Set<String> MOB_CATEGORIES = Set.of("monster", "creature", "ambient", "axolotls", "underground_water_creature",
"water_creature", "water_ambient", "misc");
private final AttributeCodecs codecs;
private final DecodeContext plain;
private final AttributeCodec<String> idString;
private final AttributeCodec<RegistryKey> identifier;
private final AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag;
private final AttributeCodec<MoonPhase> moonPhase;
private final AttributeCodec<RawValue> particle;
private final AttributeCodec<AmbientParticle> ambientParticle;
private final AttributeCodec<List<AmbientParticle>> ambientParticles;
private final AttributeCodec<IntProviderValue> intProvider;
private final AttributeCodec<SoundRef> soundRef;
private final AttributeCodec<Music> music;
private final AttributeCodec<BackgroundMusic> backgroundMusic;
private final AttributeCodec<AmbientSounds.Mood> mood;
private final AttributeCodec<List<AmbientSounds.Additions>> additions;
private final AttributeCodec<AmbientSounds> ambientSounds;
private final AttributeCodec<BedRule.Rule> bedRuleRule;
private final AttributeCodec<BedRule> bedRule;
private final AttributeCodec<List<MobSpawnSettings.Spawner>> spawners;
private final AttributeCodec<MobSpawnSettings.Cost> spawnCost;
private final AttributeCodec<Map<String, List<MobSpawnSettings.Spawner>>> spawnsByCategory;
private final AttributeCodec<Map<RegistryKey, MobSpawnSettings.Cost>> spawnCosts;
private final AttributeCodec<MobSpawnSettings> mobSpawnSettings;
public MinecraftCodecs(AttributeHandle handle) {
AttributeCodecs c = handle.codecs();
this.codecs = c;
this.plain = handle.plainContext();
this.idString = c.string(EXPECTED_IDENTIFIER);
AttributeCodec<RegistryKey> coreIdentifier = c.identifier(NAMESPACE);
this.identifier = c.of((raw, context) -> {
String s = idString.decode(raw, context);
return lowerCase(coreIdentifier.decode(s, plain), s);
}, coreIdentifier::encode);
AttributeCodec<Either<RegistryKey, TagKey>> coreIdentifierOrTag = c.identifierOrTag(NAMESPACE);
this.identifierOrTag = c.of((raw, context) -> {
String s = idString.decode(raw, context);
Either<RegistryKey, TagKey> id = coreIdentifierOrTag.decode(s, plain);
lowerCase(id.hasLeft() ? id.getLeft().orElseThrow() : id.getRight().orElseThrow().key(), s);
return id;
}, coreIdentifierOrTag::encode);
this.moonPhase = c.enumCodec("moon phase", MoonPhase.class);
this.particle = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(!(value instanceof Map<?, ?> map) || !map.containsKey("type")) {
throw new DecodeException("expected a particle object with a \"type\" key, got " + c.describe(value));
}
if(map.get("type") instanceof String type) {
try {
identifier.decode(type, plain);
} catch(DecodeException e) {
throw new DecodeException("\"type\" of particle: " + e.getMessage(), e);
}
}
return c.raw().decode(value, context);
}, RawValue::value);
this.ambientParticle = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient particle", raw, context);
RawValue value = f.required("particle", this.particle);
float probability = f.required("probability", c.unitFloat());
f.finish();
return new AmbientParticle(value, probability);
}, value -> c.writer()
.put("particle", particle, value.particle())
.put("probability", c.unitFloat(), value.probability())
.map());
this.ambientParticles = c.list(ambientParticle);
this.intProvider = c.of((raw, context) -> {
String expected = "expected an integer or an int provider object";
Object value = context.resolve(raw);
if(value instanceof Map<?, ?> map) {
if(!map.containsKey("type")) throw new DecodeException("int provider object is missing \"type\"");
return new IntProviderValue(OptionalInt.empty(), Optional.of(c.raw().decode(value, context)));
}
if(value instanceof Number) return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
if(value instanceof String) {
try {
return new IntProviderValue(OptionalInt.of(c.intCodec().decode(value, context)), Optional.empty());
} catch(DecodeException e) {
throw new DecodeException(expected + ", got " + c.describe(value), e);
}
}
throw new DecodeException(expected + ", got " + c.describe(value));
}, value -> value.constant().isPresent() ? (Object) value.constant().getAsInt() : value.provider().orElseThrow().value());
this.soundRef = c.of((raw, context) -> {
Object value = context.resolve(raw);
if(value instanceof String) return new SoundRef(identifier.decode(value, context), OptionalDouble.empty());
if(value instanceof Map<?, ?>) {
ObjectReader f = c.reader("sound", value, context);
RegistryKey id = f.required("sound_id", identifier);
Optional<Double> range = f.optional("range", c.doubleCodec());
f.finish();
return new SoundRef(id, range.map(OptionalDouble::of).orElse(OptionalDouble.empty()));
}
throw new DecodeException("expected a sound ID or a {sound_id, range} object, got " + c.describe(value));
}, value -> {
if(value.range().isEmpty()) return identifier.encode(value.id());
return c.writer()
.put("sound_id", identifier, value.id())
.put("range", c.doubleCodec(), value.range().getAsDouble())
.map();
});
this.music = c.of((raw, context) -> {
ObjectReader f = c.reader("music", raw, context);
SoundRef sound = f.required("sound", soundRef);
int min = f.required("min_delay", c.nonNegativeInt());
int max = f.required("max_delay", c.nonNegativeInt());
boolean replace = f.orDefault("replace_current_music", c.booleanCodec(), false);
f.finish();
return new Music(sound, min, max, replace);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("min_delay", c.nonNegativeInt(), value.minDelay())
.put("max_delay", c.nonNegativeInt(), value.maxDelay())
.put("replace_current_music", c.booleanCodec(), value.replaceCurrentMusic())
.map());
this.backgroundMusic = c.of((raw, context) -> {
ObjectReader f = c.reader("background music", raw, context);
Optional<Music> def = f.optional("default", music);
Optional<Music> creative = f.optional("creative", music);
Optional<Music> underwater = f.optional("underwater", music);
f.finish();
return new BackgroundMusic(def, creative, underwater);
}, value -> c.writer()
.optional("default", music, value.defaultMusic())
.optional("creative", music, value.creative())
.optional("underwater", music, value.underwater())
.map());
this.mood = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient mood", raw, context);
SoundRef sound = f.required("sound", soundRef);
int tickDelay = f.required("tick_delay", c.intCodec());
int extent = f.required("block_search_extent", c.intCodec());
double offset = f.required("offset", c.doubleCodec());
f.finish();
return new AmbientSounds.Mood(sound, tickDelay, extent, offset);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_delay", c.intCodec(), value.tickDelay())
.put("block_search_extent", c.intCodec(), value.blockSearchExtent())
.put("offset", c.doubleCodec(), value.offset())
.map());
this.additions = c.compactList(c.of((raw, context) -> {
ObjectReader f = c.reader("ambient additions", raw, context);
SoundRef sound = f.required("sound", soundRef);
double chance = f.required("tick_chance", c.doubleCodec());
f.finish();
return new AmbientSounds.Additions(sound, chance);
}, value -> c.writer()
.put("sound", soundRef, value.sound())
.put("tick_chance", c.doubleCodec(), value.tickChance())
.map()));
this.ambientSounds = c.of((raw, context) -> {
ObjectReader f = c.reader("ambient sounds", raw, context);
Optional<SoundRef> loop = f.optional("loop", soundRef);
Optional<AmbientSounds.Mood> moodValue = f.optional("mood", mood);
List<AmbientSounds.Additions> additionsValue = f.orDefault("additions", additions, List.of());
f.finish();
return new AmbientSounds(loop, moodValue, additionsValue);
}, value -> c.writer()
.optional("loop", soundRef, value.loop())
.optional("mood", mood, value.mood())
.put("additions", additions, value.additions())
.map());
this.bedRuleRule = c.enumCodec("bed rule", BedRule.Rule.class);
this.bedRule = c.of((raw, context) -> {
ObjectReader f = c.reader("bed rule", raw, context);
BedRule.Rule canSleep = f.required("can_sleep", bedRuleRule);
BedRule.Rule canSetSpawn = f.required("can_set_spawn", bedRuleRule);
boolean onUse = f.orDefault("destroy_on_use", c.booleanCodec(), false);
boolean onLeave = f.orDefault("destroy_on_leave", c.booleanCodec(), false);
Optional<RawValue> message = f.optional("error_message", c.raw());
f.finish();
return new BedRule(canSleep, canSetSpawn, onUse, onLeave, message);
}, value -> c.writer()
.put("can_sleep", bedRuleRule, value.canSleep())
.put("can_set_spawn", bedRuleRule, value.canSetSpawn())
.put("destroy_on_use", c.booleanCodec(), value.destroyOnUse())
.put("destroy_on_leave", c.booleanCodec(), value.destroyOnLeave())
.optional("error_message", c.raw(), value.errorMessage())
.map());
this.spawners = c.list(c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawner", raw, context);
RegistryKey type = f.required("type", identifier);
int weight = f.required("weight", c.nonNegativeInt());
IntProviderValue count = f.required("count", intProvider);
f.finish();
return new MobSpawnSettings.Spawner(type, weight, count);
}, value -> c.writer()
.put("type", identifier, value.type())
.put("weight", c.nonNegativeInt(), value.weight())
.put("count", intProvider, value.count())
.map()));
this.spawnCost = c.of((raw, context) -> {
ObjectReader f = c.reader("spawn cost", raw, context);
double budget = f.required("energy_budget", c.doubleCodec());
double charge = f.required("charge", c.doubleCodec());
f.finish();
return new MobSpawnSettings.Cost(budget, charge);
}, value -> c.writer()
.put("energy_budget", c.doubleCodec(), value.energyBudget())
.put("charge", c.doubleCodec(), value.charge())
.map());
this.spawnsByCategory = c.of((raw, context) -> {
ObjectReader categories = c.reader("spawns_by_category", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> out = new LinkedHashMap<>();
for(String key : categories.keys()) {
if(!MOB_CATEGORIES.contains(key)) {
throw new DecodeException("unknown mob category \"" + key + "\", expected one of " + new TreeSet<>(MOB_CATEGORIES));
}
out.put(key, categories.required(key, spawners));
}
categories.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((category, list) -> out.put(category, spawners.encode(list)));
return out;
});
// Map keys are never preprocessed.
this.spawnCosts = c.of((raw, context) -> {
ObjectReader costs = c.reader("spawn_costs", raw, context);
Map<RegistryKey, MobSpawnSettings.Cost> out = new LinkedHashMap<>();
for(String key : costs.keys()) {
out.put(identifier.decode(key, plain), costs.required(key, spawnCost));
}
costs.finish();
return out;
}, value -> {
Map<String, Object> out = new LinkedHashMap<>();
value.forEach((entity, cost) -> out.put((String) identifier.encode(entity), spawnCost.encode(cost)));
return out;
});
this.mobSpawnSettings = c.of((raw, context) -> {
ObjectReader f = c.reader("mob spawn settings", raw, context);
Map<String, List<MobSpawnSettings.Spawner>> byCategory = f.required("spawns_by_category", spawnsByCategory);
Map<RegistryKey, MobSpawnSettings.Cost> costs = f.required("spawn_costs", spawnCosts);
f.finish();
return new MobSpawnSettings(byCategory, costs);
}, value -> c.writer()
.put("spawns_by_category", spawnsByCategory, value.spawnsByCategory())
.put("spawn_costs", spawnCosts, value.spawnCosts())
.map());
}
private RegistryKey lowerCase(RegistryKey key, String written) throws DecodeException {
try {
return MinecraftIds.requireLowerCase(key, written);
} catch(IllegalArgumentException e) {
throw new DecodeException(EXPECTED_IDENTIFIER + ", got " + codecs.describe(written), e);
}
}
public AttributeCodec<RegistryKey> identifier() {
return identifier;
}
public AttributeCodec<Either<RegistryKey, TagKey>> identifierOrTag() {
return identifierOrTag;
}
public AttributeCodec<MoonPhase> moonPhase() {
return moonPhase;
}
public AttributeCodec<RawValue> particle() {
return particle;
}
public AttributeCodec<List<AmbientParticle>> ambientParticles() {
return ambientParticles;
}
public AttributeCodec<IntProviderValue> intProvider() {
return intProvider;
}
public AttributeCodec<SoundRef> soundRef() {
return soundRef;
}
public AttributeCodec<BackgroundMusic> backgroundMusic() {
return backgroundMusic;
}
public AttributeCodec<AmbientSounds> ambientSounds() {
return ambientSounds;
}
public AttributeCodec<BedRule> bedRule() {
return bedRule;
}
public AttributeCodec<MobSpawnSettings> mobSpawnSettings() {
return mobSpawnSettings;
}
}
@@ -0,0 +1,29 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.regex.Pattern;
import com.dfsek.terra.api.registry.key.RegistryKey;
public final class MinecraftIds {
private static final Pattern NAMESPACE = Pattern.compile("[a-z0-9_.-]+");
private static final Pattern PATH = Pattern.compile("[a-z0-9_./-]+");
private MinecraftIds() { }
public static RegistryKey requireLowerCase(RegistryKey key) {
return requireLowerCase(key, key.toString());
}
public static RegistryKey requireLowerCase(RegistryKey key, String written) {
if(!NAMESPACE.matcher(key.getNamespace()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -");
}
if(!PATH.matcher(key.getID()).matches()) {
throw new IllegalArgumentException(
"invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -");
}
return key;
}
}
@@ -0,0 +1,25 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record MobSpawnSettings(Map<String, List<Spawner>> spawnsByCategory, Map<RegistryKey, Cost> spawnCosts) {
public static final MobSpawnSettings EMPTY = new MobSpawnSettings(Map.of(), Map.of());
public MobSpawnSettings {
Map<String, List<Spawner>> copy = new LinkedHashMap<>();
spawnsByCategory.forEach((k, v) -> copy.put(k, List.copyOf(v)));
spawnsByCategory = Collections.unmodifiableMap(copy);
spawnCosts = Collections.unmodifiableMap(new LinkedHashMap<>(spawnCosts));
}
public record Spawner(RegistryKey type, int weight, IntProviderValue count) { }
public record Cost(double energyBudget, double charge) { }
}
@@ -0,0 +1,26 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum MoonPhase implements StringIdentifiable {
FULL_MOON("full_moon"),
WANING_GIBBOUS("waning_gibbous"),
THIRD_QUARTER("third_quarter"),
WANING_CRESCENT("waning_crescent"),
NEW_MOON("new_moon"),
WAXING_CRESCENT("waxing_crescent"),
FIRST_QUARTER("first_quarter"),
WAXING_GIBBOUS("waxing_gibbous");
private final String id;
MoonPhase(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,3 @@
package com.dfsek.terra.addons.attribute.minecraft;
public record Music(SoundRef sound, int minDelay, int maxDelay, boolean replaceCurrentMusic) { }
@@ -0,0 +1,21 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum Skybox implements StringIdentifiable {
NONE("none"),
OVERWORLD("overworld"),
END("end");
private final String id;
Skybox(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,8 @@
package com.dfsek.terra.addons.attribute.minecraft;
import java.util.OptionalDouble;
import com.dfsek.terra.api.registry.key.RegistryKey;
public record SoundRef(RegistryKey id, OptionalDouble range) { }
@@ -0,0 +1,20 @@
package com.dfsek.terra.addons.attribute.minecraft;
import com.dfsek.terra.api.registry.key.StringIdentifiable;
public enum TemperatureModifier implements StringIdentifiable {
NONE("none"),
FROZEN("frozen");
private final String id;
TemperatureModifier(String id) {
this.id = id;
}
@Override
public String getID() {
return id;
}
}
@@ -0,0 +1,12 @@
schema-version: 1
contributors:
- Terra contributors
id: minecraft-attributes
version: @VERSION@
entrypoints:
- "com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon"
website:
issues: https://github.com/PolyhedralDev/Terra/issues
source: https://github.com/PolyhedralDev/Terra
docs: https://terra.polydev.org
license: MIT License
@@ -0,0 +1,450 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle;
import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds;
import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic;
import com.dfsek.terra.addons.attribute.minecraft.BedRule;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftCodecs;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftIds;
import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings;
import com.dfsek.terra.addons.attribute.minecraft.MoonPhase;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
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.RawValue;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.*;
class MinecraftAttributeTypesTest {
private static final float EPS = 1e-6f;
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE);
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final MinecraftCodecs CODECS = new MinecraftCodecs(HANDLE);
private static <T> T mod(AttributeType<T> type, Operation op, T subject, Object rawArg) throws DecodeException {
return type.apply(op, subject, type.decodeArgument(op, rawArg, PLAIN));
}
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
@Test
void everyTypeSupportsOverride() {
List<AttributeType<?>> all = List.of(TYPES.moonPhase(), TYPES.bedRule(), TYPES.particle(), TYPES.ambientParticles(),
TYPES.backgroundMusic(), TYPES.ambientSounds(), TYPES.mobSpawnSettings(), TYPES.identifier(), TYPES.identifierOrTag(),
TYPES.intProvider());
for(AttributeType<?> t : all) assertTrue(t.operations().contains(Operation.OVERRIDE), t.id());
}
@Test
void operationSets() {
assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifier().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE), TYPES.identifierOrTag().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.APPEND), TYPES.ambientParticles().operations());
assertEquals(EnumSet.of(Operation.OVERRIDE, Operation.OVERLAY), TYPES.mobSpawnSettings().operations());
}
@Test
void idsAreVanillaTypeIds() {
assertEquals("moon_phase", TYPES.moonPhase().id());
assertEquals("bed_rule", TYPES.bedRule().id());
assertEquals("particle", TYPES.particle().id());
assertEquals("ambient_particles", TYPES.ambientParticles().id());
assertEquals("background_music", TYPES.backgroundMusic().id());
assertEquals("ambient_sounds", TYPES.ambientSounds().id());
assertEquals("mob_spawn_settings", TYPES.mobSpawnSettings().id());
assertEquals("identifier", TYPES.identifier().id());
assertEquals("identifier_or_tag", TYPES.identifierOrTag().id());
assertEquals("int_provider", TYPES.intProvider().id());
}
@Test
void decodeFailuresReadTheSameEverywhere() {
String bedRule = assertThrows(DecodeException.class,
() -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN)).getMessage();
assertEquals("\"can_sleep\" of bed rule: unknown bed rule \"sometimes\", expected one of [always, when_dark, never]", bedRule);
String moonPhase = assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("x", PLAIN)).getMessage();
assertTrue(moonPhase.startsWith("unknown moon phase \"x\", expected one of [full_moon, "), moonPhase);
}
@Test
void enumsAreStringIdentifiable() {
assertEquals("waxing_gibbous", MoonPhase.WAXING_GIBBOUS.getID());
assertEquals("when_dark", BedRule.Rule.WHEN_DARK.getID());
assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON));
}
@Test
void ambientParticlesAppend() throws DecodeException {
AttributeType<List<AmbientParticle>> t = TYPES.ambientParticles();
List<AmbientParticle> one = t.decode(List.of(map("particle", map("type", "minecraft:crimson_spore"), "probability", 0.025)), PLAIN);
List<AmbientParticle> two = t.decode(List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1)), PLAIN);
assertEquals(1, one.size());
assertEquals(0.025f, one.get(0).probability(), EPS);
assertEquals(new RawValue(map("type", "minecraft:crimson_spore")), one.get(0).particle());
assertEquals(one, t.apply(Operation.APPEND, one, List.of()));
assertEquals(two, t.apply(Operation.APPEND, List.of(), two));
assertEquals(List.of(one.get(0), two.get(0)), t.apply(Operation.APPEND, one, two));
assertEquals(List.of(one.get(0), two.get(0)),
mod(t, Operation.APPEND, one, List.of(map("particle", map("type", "minecraft:white_ash"), "probability", 0.1))));
}
@Test
void ambientParticleValidation() {
AttributeType<List<AmbientParticle>> t = TYPES.ambientParticles();
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"), "probability", 1.5)), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", map("type", "x"))), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(List.of(map("particle", "x", "probability", 0.5)), PLAIN));
assertThrows(DecodeException.class,
() -> t.decode(List.of(map("particle", map("type", "x"), "probability", 0.5, "extra", 1)), PLAIN));
assertThrows(DecodeException.class, () -> t.decode(map("particle", map("type", "x"), "probability", 0.5), PLAIN));
}
private static MobSpawnSettings spawns(Map<String, Object> raw) throws DecodeException {
return TYPES.mobSpawnSettings().decode(raw, PLAIN);
}
private static Map<String, Object> spawner(String type, int weight, int count) {
return map("type", type, "weight", weight, "count", count);
}
@Test
void mobSpawnDecode() throws DecodeException {
MobSpawnSettings s = spawns(map(
"spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 10, 8))),
"spawn_costs", map("minecraft:enderman", map("energy_budget", 0.7, "charge", 0.15))));
MobSpawnSettings.Spawner sp = s.spawnsByCategory().get("ambient").get(0);
assertEquals(RegistryKey.parse("minecraft:bat"), sp.type());
assertEquals(10, sp.weight());
assertEquals(8, sp.count().constant().getAsInt());
assertEquals(0.7, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).energyBudget(), 1e-9);
assertEquals(0.15, s.spawnCosts().get(RegistryKey.parse("minecraft:enderman")).charge(), 1e-9);
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map("bogus", List.of()), "spawn_costs", map())));
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map())));
assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category", map(), "spawn_costs", map(), "x", 1)));
}
@Test
void mobSpawnCountMapIsKeptRaw() throws DecodeException {
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(
map("type", "minecraft:zombie", "weight", 5,
"count", map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3)))),
"spawn_costs", map()));
IntProviderValue c = s.spawnsByCategory().get("monster").get(0).count();
assertTrue(c.constant().isEmpty());
assertTrue(c.provider().isPresent());
}
@Test
void mobSpawnOverlayRules() throws DecodeException {
AttributeType<MobSpawnSettings> t = TYPES.mobSpawnSettings();
MobSpawnSettings empty = MobSpawnSettings.EMPTY;
MobSpawnSettings a = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1))),
"spawn_costs", map()));
assertSame(a, t.apply(Operation.OVERLAY, empty, a));
assertSame(a, t.apply(Operation.OVERLAY, a, empty));
MobSpawnSettings sup = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:husk", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))), "spawn_costs", map()));
assertSame(sup, t.apply(Operation.OVERLAY, a, sup));
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)),
"creature", List.of(spawner("minecraft:cow", 1, 1))),
"spawn_costs", map("minecraft:a", map("energy_budget", 1, "charge", 1))));
MobSpawnSettings arg = spawns(map("spawns_by_category", map("ambient", List.of(spawner("minecraft:bat", 1, 1)),
"creature", List.of(spawner("minecraft:pig", 1, 1))),
"spawn_costs", map("minecraft:b", map("energy_budget", 2, "charge", 2))));
MobSpawnSettings r = t.apply(Operation.OVERLAY, s, arg);
assertEquals(RegistryKey.parse("minecraft:zombie"), r.spawnsByCategory().get("monster").get(0).type());
assertEquals(RegistryKey.parse("minecraft:pig"), r.spawnsByCategory().get("creature").get(0).type());
assertEquals(RegistryKey.parse("minecraft:bat"), r.spawnsByCategory().get("ambient").get(0).type());
assertEquals(Set.of(RegistryKey.parse("minecraft:a"), RegistryKey.parse("minecraft:b")), r.spawnCosts().keySet());
}
@Test
void mobSpawnOverlayEmptyCategoryClears() throws DecodeException {
AttributeType<MobSpawnSettings> t = TYPES.mobSpawnSettings();
MobSpawnSettings s = spawns(map("spawns_by_category", map("monster", List.of(spawner("minecraft:zombie", 1, 1)),
"creature", List.of(spawner("minecraft:cow", 1, 1))), "spawn_costs", map()));
MobSpawnSettings arg = spawns(map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()));
MobSpawnSettings r = mod(t, Operation.OVERLAY, s, map("spawns_by_category", map("monster", List.of()), "spawn_costs", map()));
assertTrue(r.spawnsByCategory().get("monster").isEmpty());
assertEquals(1, r.spawnsByCategory().get("creature").size());
assertEquals(r, t.apply(Operation.OVERLAY, s, arg));
}
@Test
void ambientSoundsDecode() throws DecodeException {
AmbientSounds a = TYPES.ambientSounds().decode(map(
"additions", map("sound", "minecraft:ambient.crimson_forest.additions", "tick_chance", 0.0111),
"loop", "minecraft:ambient.crimson_forest.loop",
"mood", map("block_search_extent", 8, "offset", 2.0, "sound", "minecraft:ambient.crimson_forest.mood", "tick_delay", 6000)),
PLAIN);
assertEquals(1, a.additions().size());
assertEquals(0.0111, a.additions().get(0).tickChance(), 1e-9);
assertEquals(RegistryKey.parse("minecraft:ambient.crimson_forest.loop"), a.loop().orElseThrow().id());
assertEquals(6000, a.mood().orElseThrow().tickDelay());
assertEquals(8, a.mood().orElseThrow().blockSearchExtent());
assertEquals(2.0, a.mood().orElseThrow().offset(), 1e-9);
AmbientSounds list = TYPES.ambientSounds().decode(map(
"additions", List.of(map("sound", "a:b", "tick_chance", 0.1), map("sound", "a:c", "tick_chance", 0.2))), PLAIN);
assertEquals(2, list.additions().size());
assertTrue(list.loop().isEmpty());
assertEquals(AmbientSounds.EMPTY, TYPES.ambientSounds().decode(map(), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("looop", "a:b"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("mood", map("sound", "a:b")), PLAIN));
}
@Test
void soundRefForms() throws DecodeException {
AmbientSounds a = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b", "range", 16)), PLAIN);
assertEquals(RegistryKey.parse("a:b"), a.loop().orElseThrow().id());
assertEquals(16.0, a.loop().orElseThrow().range().getAsDouble(), 1e-9);
AmbientSounds b = TYPES.ambientSounds().decode(map("loop", map("sound_id", "a:b")), PLAIN);
assertTrue(b.loop().orElseThrow().range().isEmpty());
assertEquals(RegistryKey.parse("minecraft:ambient.cave"),
TYPES.ambientSounds().decode(map("loop", "ambient.cave"), PLAIN).loop().orElseThrow().id());
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", 5), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", "Not Valid"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.ambientSounds().decode(map("loop", map("range", 1)), PLAIN));
}
@Test
void upperCaseIdRejected() {
DecodeException e = assertThrows(DecodeException.class, () -> CODECS.soundRef().decode("minecraft:Ambient.Cave", PLAIN));
assertEquals("expected an identifier like \"minecraft:id\", got \"minecraft:Ambient.Cave\"", e.getMessage());
assertEquals(path("minecraft:Ambient.Cave"), e.getCause().getMessage());
assertEquals(namespace("Minecraft:x"), lowerCaseFailure(() -> CODECS.soundRef().decode("Minecraft:x", PLAIN)));
}
private static String path(String written) {
return "invalid ID \"" + written + "\": the path must be non-empty and use only a-z, 0-9, _, ., / and -";
}
private static String namespace(String written) {
return "invalid ID \"" + written + "\": the namespace must be non-empty and use only a-z, 0-9, _, . and -";
}
private static String lowerCaseFailure(Executable decode) {
Throwable t = assertThrows(DecodeException.class, decode);
while(t != null && !(t instanceof IllegalArgumentException)) t = t.getCause();
assertNotNull(t, "no lower-case rule failure in the cause chain");
return t.getMessage();
}
@Test
void lowerCaseIds() {
assertEquals(path("minecraft:Music.Game"),
lowerCaseFailure(() -> TYPES.ambientSounds().decode(Map.of("loop", "minecraft:Music.Game"), PLAIN)));
assertEquals(path("Music.Game"), lowerCaseFailure(() -> TYPES.backgroundMusic().decode(
map("default", map("sound", "Music.Game", "min_delay", 1, "max_delay", 2)), PLAIN)));
assertEquals(path("minecraft:Flame"), lowerCaseFailure(() -> TYPES.particle().decode(map("type", "minecraft:Flame"), PLAIN)));
assertEquals(path("Idle"), lowerCaseFailure(() -> TYPES.identifier().decode("Idle", PLAIN)));
assertEquals(path("#minecraft:Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#minecraft:Logs", PLAIN)));
assertEquals(path("#Logs"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("#Logs", PLAIN)));
assertEquals(namespace("Minecraft:stone"), lowerCaseFailure(() -> TYPES.identifierOrTag().decode("Minecraft:stone", PLAIN)));
assertEquals(path("minecraft:Zombie"), lowerCaseFailure(() -> spawns(map(
"spawns_by_category", map("monster", List.of(spawner("minecraft:Zombie", 1, 1))), "spawn_costs", map()))));
assertEquals(namespace("Minecraft:enderman"), lowerCaseFailure(() -> spawns(map("spawns_by_category", map(),
"spawn_costs", map("Minecraft:enderman", map("energy_budget", 1, "charge", 1))))));
}
@Test
void requireLowerCase() {
RegistryKey key = RegistryKey.parse("minecraft:visual/fog_color");
assertSame(key, MinecraftIds.requireLowerCase(key));
assertSame(key, MinecraftIds.requireLowerCase(key, "visual/fog_color"));
assertEquals(namespace("Mod:thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("Mod:thing"))).getMessage());
assertEquals(path("mod:Thing"),
assertThrows(IllegalArgumentException.class, () -> MinecraftIds.requireLowerCase(RegistryKey.parse("mod:Thing"))).getMessage());
assertEquals(path("Thing"), assertThrows(IllegalArgumentException.class,
() -> MinecraftIds.requireLowerCase(RegistryKey.parse("minecraft:Thing"), "Thing")).getMessage());
}
@Test
void integersFollowTheCoreRule() {
String weight = assertThrows(DecodeException.class, () -> spawns(map("spawns_by_category",
map("monster", List.of(map("type", "minecraft:zombie", "weight", 1.5, "count", 1))), "spawn_costs", map()))).getMessage();
assertTrue(weight.endsWith("\"weight\" of mob spawner: expected an integer, got 1.5"), weight);
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(99999999999L, PLAIN));
}
@Test
void backgroundMusicDecode() throws DecodeException {
BackgroundMusic m = TYPES.backgroundMusic().decode(map(
"default", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.game", "replace_current_music", true),
"underwater", map("max_delay", 24000, "min_delay", 12000, "sound", "minecraft:music.under_water")), PLAIN);
assertTrue(m.defaultMusic().orElseThrow().replaceCurrentMusic());
assertFalse(m.underwater().orElseThrow().replaceCurrentMusic());
assertEquals(12000, m.underwater().orElseThrow().minDelay());
assertEquals(24000, m.underwater().orElseThrow().maxDelay());
assertTrue(m.creative().isEmpty());
assertEquals(BackgroundMusic.EMPTY, TYPES.backgroundMusic().decode(map(), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("bogus", 1), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", 1)), PLAIN));
assertThrows(DecodeException.class,
() -> TYPES.backgroundMusic().decode(map("default", map("sound", "a:b", "min_delay", -1, "max_delay", 1)), PLAIN));
}
@Test
void bedRuleDecode() throws DecodeException {
BedRule r = TYPES.bedRule().decode(map("can_set_spawn", "never", "can_sleep", "when_dark", "destroy_on_leave", true,
"error_message", map("translate", "block.minecraft.bed.no_sleep")), PLAIN);
assertEquals(BedRule.Rule.WHEN_DARK, r.canSleep());
assertEquals(BedRule.Rule.NEVER, r.canSetSpawn());
assertFalse(r.destroyOnUse());
assertTrue(r.destroyOnLeave());
assertTrue(r.errorMessage().isPresent());
BedRule plain = TYPES.bedRule().decode(map("can_set_spawn", "always", "can_sleep", "always"), PLAIN);
assertTrue(plain.errorMessage().isEmpty());
assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "always"), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.bedRule().decode(map("can_sleep", "sometimes", "can_set_spawn", "always"), PLAIN));
assertThrows(DecodeException.class,
() -> TYPES.bedRule().decode(map("can_sleep", "always", "can_set_spawn", "always", "nope", 1), PLAIN));
}
@Test
void simpleTypesDecode() throws DecodeException {
assertEquals(MoonPhase.NEW_MOON, TYPES.moonPhase().decode("new_moon", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.moonPhase().decode("blue_moon", PLAIN));
assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("minecraft:idle", PLAIN));
assertEquals(RegistryKey.parse("minecraft:idle"), TYPES.identifier().decode("idle", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifier().decode("Not Valid", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifier().decode(3, PLAIN));
assertEquals("expected an identifier, not a tag, got \"#minecraft:logs\"",
assertThrows(DecodeException.class, () -> TYPES.identifier().decode("#minecraft:logs", PLAIN)).getMessage());
assertEquals(Either.left(RegistryKey.parse("minecraft:stone")), TYPES.identifierOrTag().decode("stone", PLAIN));
assertEquals(Either.right(TagKey.parse("#minecraft:logs")), TYPES.identifierOrTag().decode("#logs", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.identifierOrTag().decode("#", PLAIN));
}
@Test
void particleDecode() throws DecodeException {
RawValue p = TYPES.particle().decode(map("type", "minecraft:dripping_dripstone_lava"), PLAIN);
assertEquals(new RawValue(map("type", "minecraft:dripping_dripstone_lava")), p);
assertThrows(DecodeException.class, () -> TYPES.particle().decode(map("color", 1), PLAIN));
assertThrows(DecodeException.class, () -> TYPES.particle().decode("minecraft:flame", PLAIN));
}
@Test
void intProviderDecode() throws DecodeException {
IntProviderValue c = TYPES.intProvider().decode(7, PLAIN);
assertEquals(7, c.constant().getAsInt());
assertTrue(c.provider().isEmpty());
IntProviderValue p = TYPES.intProvider().decode(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3), PLAIN);
assertTrue(p.constant().isEmpty());
assertTrue(p.provider().isPresent());
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode("x", PLAIN));
assertThrows(DecodeException.class, () -> TYPES.intProvider().decode(1.5, PLAIN));
}
@Test
void overrideArgumentDecodesWithValueDecoder() throws DecodeException {
assertEquals(MoonPhase.NEW_MOON, mod(TYPES.moonPhase(), Operation.OVERRIDE, MoonPhase.FULL_MOON, "new_moon"));
}
@Test
void nestedDecodeContext() throws DecodeException {
List<Object> seen = new ArrayList<>();
DecodeContext recording = new DecodeContext() {
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
seen.add(raw);
return PLAIN.load(type, raw);
}
@Override
public Object resolve(Object raw) {
return raw;
}
};
Map<String, Object> music = map("sound", "minecraft:music.game", "min_delay", 1, "max_delay", 2);
TYPES.backgroundMusic().decode(map("default", music), recording);
assertTrue(seen.contains("minecraft:music.game"), seen.toString());
assertTrue(seen.contains(1), seen.toString());
assertTrue(seen.contains(2), seen.toString());
assertTrue(seen.contains(music), seen.toString());
}
private static DecodeContext referencing(Map<String, Object> targets) {
return new DecodeContext() {
@Override
public <V> V load(Type type, Object raw) throws DecodeException {
return PLAIN.load(type, raw);
}
@Override
public Object resolve(Object raw) {
if(raw instanceof String s && targets.containsKey(s)) return resolve(targets.get(s));
if(raw instanceof Map<?, ?> m) {
Map<String, Object> out = new LinkedHashMap<>();
m.forEach((k, v) -> out.put((String) k, resolve(v)));
return out;
}
if(raw instanceof List<?> l) return l.stream().map(this::resolve).toList();
return raw;
}
};
}
@Test
void resolveBeforeShape() throws DecodeException {
DecodeContext context = referencing(map(
"@sound", map("sound_id", "minecraft:ambient.cave", "range", 4.0),
"@additions", List.of(map("sound", "minecraft:a", "tick_chance", 0.5), map("sound", "minecraft:b", "tick_chance", 0.25)),
"@provider", map("type", "minecraft:uniform", "min_inclusive", "@min", "max_inclusive", 4),
"@min", 1,
"@flame", "minecraft:flame",
"@message", map("translate", "@key"),
"@key", "block.minecraft.bed.no_sleep"));
AmbientSounds sounds = TYPES.ambientSounds().decode(map("loop", "@sound", "additions", "@additions"), context);
assertEquals(4.0, sounds.loop().orElseThrow().range().orElseThrow());
assertEquals(2, sounds.additions().size());
IntProviderValue provider = TYPES.intProvider().decode("@provider", context);
assertEquals(new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 4)),
provider.provider().orElseThrow());
List<AmbientParticle> particles = TYPES.ambientParticles().decode(
List.of(map("particle", map("type", "@flame"), "probability", 0.5)), context);
assertEquals(new RawValue(map("type", "minecraft:flame")), particles.get(0).particle());
BedRule rule = TYPES.bedRule().decode(map("can_sleep", "never", "can_set_spawn", "never", "error_message", "@message"),
context);
assertEquals(new RawValue(map("translate", "block.minecraft.bed.no_sleep")), rule.errorMessage().orElseThrow());
}
@Test
void mapKeysInsideValuesAreNotPreprocessed() throws DecodeException {
DecodeContext context = referencing(map("minecraft:zombie", "minecraft:cow"));
MobSpawnSettings settings = TYPES.mobSpawnSettings().decode(map(
"spawns_by_category", map(),
"spawn_costs", map("minecraft:zombie", map("energy_budget", 1.0, "charge", 0.5))), context);
assertEquals(List.of(RegistryKey.parse("minecraft:zombie")), List.copyOf(settings.spawnCosts().keySet()));
}
}
@@ -0,0 +1,99 @@
package attribute.minecraft;
import ca.solostudios.strata.Versions;
import ca.solostudios.strata.version.Version;
import ca.solostudios.strata.version.VersionRange;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributesAddon;
import com.dfsek.terra.api.Platform;
import com.dfsek.terra.api.addon.BaseAddon;
import com.dfsek.terra.api.config.ConfigPack;
import com.dfsek.terra.api.event.EventManager;
import com.dfsek.terra.api.event.events.config.pack.ConfigPackPreLoadEvent;
import com.dfsek.terra.api.inject.Injector;
import com.dfsek.terra.api.registry.CheckedRegistry;
import com.dfsek.terra.api.util.reflection.TypeKey;
import com.dfsek.terra.api.world.attribute.Attribute;
import com.dfsek.terra.api.world.attribute.AttributeHandle;
import com.dfsek.terra.event.EventManagerImpl;
import com.dfsek.terra.registry.CheckedRegistryImpl;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
class MinecraftAttributesAddonTest {
private static final BaseAddon ADDON = new BaseAddon() {
@Override
public String getID() {
return "minecraft-attributes";
}
@Override
public Version getVersion() {
return null;
}
};
private static final VersionRange ONE = Versions.getVersionRange(Versions.getVersion(1, 0, 0), true, Versions.getVersion(2, 0, 0),
false);
private static Platform platform(EventManager events, AttributeHandle handle) {
return (Platform) Proxy.newProxyInstance(Platform.class.getClassLoader(), new Class<?>[]{ Platform.class },
(proxy, method, args) -> switch(method.getName()) {
case "getEventManager" -> events;
case "getAttributeHandle" -> handle;
default -> throw new UnsupportedOperationException(method.getName());
});
}
private static ConfigPack pack(Map<BaseAddon, VersionRange> addons) {
Map<TypeKey<?>, CheckedRegistry<?>> registries = new HashMap<>();
return (ConfigPack) Proxy.newProxyInstance(ConfigPack.class.getClassLoader(), new Class<?>[]{ ConfigPack.class },
(proxy, method, args) -> switch(method.getName()) {
case "addons" -> addons;
case "getOrCreateRegistry" -> registries.computeIfAbsent((TypeKey<?>) args[0],
type -> new CheckedRegistryImpl<>(new OpenRegistryImpl<>(type)));
default -> throw new UnsupportedOperationException(method.getName());
});
}
@Test
void dependentPacksOnly() {
EventManager events = new EventManagerImpl();
AttributeHandle handle = new AttributeHandleImpl();
MinecraftAttributesAddon initializer = new MinecraftAttributesAddon();
Injector<Platform> platformInjector = Injector.get(platform(events, handle));
platformInjector.addExplicitTarget(Platform.class);
platformInjector.inject(initializer);
Injector<BaseAddon> addonInjector = Injector.get(ADDON);
addonInjector.addExplicitTarget(BaseAddon.class);
addonInjector.inject(initializer);
initializer.initialize();
ConfigPack dependent = pack(Map.of(ADDON, ONE));
ConfigPack other = pack(Map.of());
events.callEvent(new ConfigPackPreLoadEvent(dependent, template -> { }));
events.callEvent(new ConfigPackPreLoadEvent(other, template -> { }));
CheckedRegistry<Attribute<?>> registered = dependent.getOrCreateRegistry(Attribute.REGISTRY_TYPE);
assertEquals(79, registered.entries().size());
assertTrue(other.getOrCreateRegistry(Attribute.REGISTRY_TYPE).entries().isEmpty());
Attribute<?> fog = MinecraftAttributes.VISUAL_FOG_COLOR.lookup(registered).orElseThrow();
assertSame(fog, registered.get(fog.getRegistryKey()).orElseThrow());
ConfigPack second = pack(Map.of(ADDON, ONE));
events.callEvent(new ConfigPackPreLoadEvent(second, template -> { }));
assertSame(fog, MinecraftAttributes.VISUAL_FOG_COLOR.lookup(second.getOrCreateRegistry(Attribute.REGISTRY_TYPE)).orElseThrow());
assertEquals(79, handle.attributeCount());
}
}
@@ -0,0 +1,194 @@
package attribute.minecraft;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTable;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributes;
import com.dfsek.terra.api.registry.CheckedRegistry;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeKey;
import com.dfsek.terra.api.world.attribute.AttributeScope;
import com.dfsek.terra.api.world.attribute.DecodeException;
import com.dfsek.terra.api.world.attribute.Operation;
import com.dfsek.terra.api.world.attribute.RawValue;
import com.dfsek.terra.api.world.attribute.value.Color;
import com.dfsek.terra.registry.CheckedRegistryImpl;
import com.dfsek.terra.registry.OpenRegistryImpl;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
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;
class MinecraftAttributesTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final List<Attribute<?>> ALL = MinecraftAttributeTable.create(HANDLE);
private static final CheckedRegistry<Attribute<?>> REGISTRY = registry();
private static CheckedRegistry<Attribute<?>> registry() {
CheckedRegistry<Attribute<?>> registry = new CheckedRegistryImpl<>(new OpenRegistryImpl<>(Attribute.REGISTRY_TYPE));
ALL.forEach(attribute -> registry.register(attribute.getRegistryKey(), attribute));
return registry;
}
private static Attribute<?> byId(String id) {
return REGISTRY.get(RegistryKey.parse(id)).orElseThrow();
}
@SuppressWarnings("unchecked")
private static <T> Attribute<T> typed(String id) {
return (Attribute<T>) byId(id);
}
@Test
void tableOrder() {
assertEquals(MinecraftAttributes.all(), ALL.stream().map(Attribute::key).toList());
int first = ALL.get(0).index();
for(int i = 0; i < ALL.size(); i++) {
assertEquals(first + i, ALL.get(i).index(), ALL.get(i).key().toString());
assertSame(ALL.get(i), REGISTRY.get(ALL.get(i).getRegistryKey()).orElseThrow());
}
assertTrue(HANDLE.attributeCount() >= first + ALL.size());
}
@Test
void scopes() {
Set<String> packOnly = ALL.stream().filter(a -> a.key().getNamespace().equals("minecraft"))
.filter(a -> a.scope() == AttributeScope.PACK_ONLY).map(a -> a.key().toString()).collect(Collectors.toSet());
assertEquals(Set.of("minecraft:gameplay/sky_light_level", "minecraft:gameplay/fast_lava"), packOnly);
for(Attribute<?> a : ALL) {
if(!a.key().getNamespace().equals("terra")) continue;
boolean packWide = a.key().getID().startsWith("dimension/") || a.key().getID().startsWith("world/");
assertEquals(packWide ? AttributeScope.PACK_ONLY : AttributeScope.ANYWHERE, a.scope(), a.key().toString());
}
}
@Test
void terraDefaults() {
assertNull(byId("terra:biome/foliage_color").defaultValue());
assertNull(byId("terra:biome/dry_foliage_color").defaultValue());
assertNull(byId("terra:biome/grass_color").defaultValue());
assertEquals(Color.rgb(0x3f76e4), byId("terra:biome/water_color").defaultValue());
assertEquals(-64, byId("terra:dimension/min_y").defaultValue());
assertEquals(384, byId("terra:dimension/height").defaultValue());
assertEquals(Either.right(TagKey.parse("#minecraft:infiniburn_overworld")),
byId("terra:dimension/infiniburn").defaultValue());
assertEquals(RegistryKey.parse("minecraft:plains"), byId("terra:biome/villager_type").defaultValue());
assertEquals(RegistryKey.parse("minecraft:overworld"), byId("terra:dimension/default_clock").defaultValue());
IntProviderValue light = (IntProviderValue) byId("terra:dimension/monster_spawn_light_level").defaultValue();
assertEquals(Optional.of(new RawValue(Map.of("type", "minecraft:uniform", "min_inclusive", 0, "max_inclusive", 7))),
light.provider());
}
@Test
void rangeValidation() throws Exception {
Attribute<Float> spawn = typed("minecraft:gameplay/creature_world_gen_spawn_probability");
assertEquals(0.5f, spawn.validate(0.5f));
assertThrows(DecodeException.class, () -> spawn.validate(1.0f));
assertThrows(DecodeException.class, () -> spawn.validate(-0.1f));
assertThrows(DecodeException.class, () -> spawn.validate(Float.NaN));
Attribute<Float> unit = typed("minecraft:audio/music_volume");
assertEquals("value 2.0 is outside [0, 1]", assertThrows(DecodeException.class, () -> unit.validate(2f)).getMessage());
Attribute<Float> fogEnd = typed("minecraft:visual/fog_end_distance");
assertThrows(DecodeException.class, () -> fogEnd.validate(-1f));
assertEquals(1e9f, fogEnd.validate(1e9f));
assertEquals(-5f, typed("minecraft:visual/fog_start_distance").validate(-5f));
Attribute<Float> scale = typed("terra:dimension/coordinate_scale");
assertEquals(1f, scale.validate(1f));
assertThrows(DecodeException.class, () -> scale.validate(0f));
Attribute<Integer> light = typed("terra:dimension/monster_spawn_block_light_limit");
assertThrows(DecodeException.class, () -> light.validate(16));
}
@Test
void dimensionGeometry() throws Exception {
for(String id : List.of("terra:dimension/min_y", "terra:dimension/height", "terra:dimension/logical_height")) {
assertEquals(EnumSet.of(Operation.OVERRIDE), byId(id).type().operations(), id);
}
Attribute<Integer> minY = typed("terra:dimension/min_y");
assertEquals(-2032, minY.validate(-2032));
assertThrows(DecodeException.class, () -> minY.validate(-2048));
assertThrows(DecodeException.class, () -> minY.validate(2032));
assertThrows(DecodeException.class, () -> minY.validate(-60));
Attribute<Integer> height = typed("terra:dimension/height");
assertEquals(16, height.validate(16));
assertThrows(DecodeException.class, () -> height.validate(0));
assertEquals("value 100 is not a multiple of 16", assertThrows(DecodeException.class, () -> height.validate(100)).getMessage());
assertEquals(37, typed("terra:dimension/logical_height").validate(37));
}
@Test
void sanitizeClamps() {
Attribute<Float> sky = typed("minecraft:gameplay/sky_light_level");
assertEquals(15f, sky.sanitize(20f));
assertEquals(0f, sky.sanitize(-3f));
assertEquals(7f, sky.sanitize(7f));
Attribute<Boolean> flag = typed("minecraft:gameplay/can_start_raid");
assertEquals(true, flag.sanitize(true));
Attribute<Integer> height = typed("terra:dimension/height");
assertEquals(4064, height.sanitize(9999));
}
@Test
void typedKeys() throws ReflectiveOperationException {
Set<AttributeKey<?>> constants = new HashSet<>();
for(Field field : MinecraftAttributes.class.getFields()) {
if(!Modifier.isStatic(field.getModifiers()) || field.getType() != AttributeKey.class) continue;
AttributeKey<?> key = (AttributeKey<?>) field.get(null);
Type argument = ((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0];
Class<?> valueClass = (Class<?>) (argument instanceof ParameterizedType p ? p.getRawType() : argument);
Attribute<?> attribute = key.lookup(REGISTRY).orElseThrow(() -> new AssertionError("Not registered: " + key));
assertSame(key, attribute.key(), field.getName());
Object defaultValue = attribute.defaultValue();
if(defaultValue != null) {
assertTrue(valueClass.isInstance(defaultValue),
field.getName() + ": " + defaultValue.getClass() + " is not a " + valueClass);
}
constants.add(key);
}
assertEquals(79, constants.size());
assertEquals(Set.copyOf(MinecraftAttributes.all()), constants);
assertEquals(79, ALL.size());
}
@Test
void typedLookup() {
AttributeKey<Float> lookalike = AttributeKey.parse("minecraft:visual/fog_color");
assertEquals(MinecraftAttributes.VISUAL_FOG_COLOR, lookalike);
assertTrue(lookalike.lookup(REGISTRY).isEmpty());
assertTrue(REGISTRY.get(lookalike.getRegistryKey()).isPresent());
}
@Test
void keyIds() {
for(AttributeKey<?> key : MinecraftAttributes.all()) {
String namespace = key.getRegistryKey().getNamespace();
String path = key.getRegistryKey().getID();
assertTrue(namespace.matches("[a-z0-9_.-]+") && path.matches("[a-z0-9_./-]+"), key.toString());
}
}
}
@@ -0,0 +1,177 @@
package attribute.minecraft;
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.OptionalDouble;
import java.util.OptionalInt;
import com.dfsek.terra.addons.attribute.minecraft.AmbientParticle;
import com.dfsek.terra.addons.attribute.minecraft.AmbientSounds;
import com.dfsek.terra.addons.attribute.minecraft.BackgroundMusic;
import com.dfsek.terra.addons.attribute.minecraft.BedRule;
import com.dfsek.terra.addons.attribute.minecraft.CardinalLight;
import com.dfsek.terra.addons.attribute.minecraft.GrassColorModifier;
import com.dfsek.terra.addons.attribute.minecraft.IntProviderValue;
import com.dfsek.terra.addons.attribute.minecraft.MinecraftAttributeTypes;
import com.dfsek.terra.addons.attribute.minecraft.MobSpawnSettings;
import com.dfsek.terra.addons.attribute.minecraft.MoonPhase;
import com.dfsek.terra.addons.attribute.minecraft.Music;
import com.dfsek.terra.addons.attribute.minecraft.Skybox;
import com.dfsek.terra.addons.attribute.minecraft.SoundRef;
import com.dfsek.terra.addons.attribute.minecraft.TemperatureModifier;
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.AttributeHandle;
import com.dfsek.terra.api.world.attribute.AttributeType;
import com.dfsek.terra.api.world.attribute.AttributeTypes;
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.RawValue;
import com.dfsek.terra.world.attribute.AttributeHandleImpl;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
class MinecraftCodecRoundTripTest {
private static final AttributeHandle HANDLE = new AttributeHandleImpl();
private static final AttributeTypes CORE = HANDLE.types();
private static final MinecraftAttributeTypes TYPES = new MinecraftAttributeTypes(HANDLE);
private static final DecodeContext PLAIN = HANDLE.plainContext();
private static final RawValue FLAME = new RawValue(map("type", "minecraft:flame"));
private static final RawValue UNIFORM = new RawValue(map("type", "minecraft:uniform", "min_inclusive", 1, "max_inclusive", 3));
private static final SoundRef SOUND = new SoundRef(RegistryKey.parse("minecraft:music.game"), OptionalDouble.empty());
private static final SoundRef RANGED_SOUND = new SoundRef(RegistryKey.parse("minecraft:ambient.cave"), OptionalDouble.of(16));
private static Map<String, Object> map(Object... kv) {
Map<String, Object> m = new LinkedHashMap<>();
for(int i = 0; i < kv.length; i += 2) m.put((String) kv[i], kv[i + 1]);
return m;
}
private record Case<T>(AttributeType<T> type, List<T> values, Map<Operation, List<?>> arguments) { }
private static <T> Case<T> of(AttributeType<T> type, List<T> values, Object... opArgs) {
Map<Operation, List<?>> arguments = new LinkedHashMap<>();
for(int i = 0; i < opArgs.length; i += 2) arguments.put((Operation) opArgs[i], (List<?>) opArgs[i + 1]);
return new Case<>(type, values, arguments);
}
private static List<Case<?>> cases() {
MobSpawnSettings spawns = new MobSpawnSettings(
Map.of("monster", List.of(
new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:zombie"), 95,
new IntProviderValue(OptionalInt.of(4), Optional.empty())),
new MobSpawnSettings.Spawner(RegistryKey.parse("minecraft:husk"), 5,
new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))),
"ambient", List.of()),
Map.of(RegistryKey.parse("minecraft:enderman"), new MobSpawnSettings.Cost(0.7, 0.15)));
return List.of(
of(TYPES.moonPhase(), List.of(MoonPhase.values())),
of(TYPES.bedRule(), List.of(
new BedRule(BedRule.Rule.WHEN_DARK, BedRule.Rule.NEVER, true, false,
Optional.of(new RawValue(map("translate", "block.minecraft.bed.no_sleep")))),
new BedRule(BedRule.Rule.ALWAYS, BedRule.Rule.ALWAYS, false, true, Optional.empty()))),
of(TYPES.particle(), List.of(FLAME, new RawValue(map("type", "minecraft:dust", "color", List.of(1.0, 0.5, 0.0), "scale", 2)))),
of(TYPES.ambientParticles(), List.of(List.of(), List.of(new AmbientParticle(FLAME, 0.025f))),
Operation.APPEND, List.of(List.of(new AmbientParticle(FLAME, 0.5f), new AmbientParticle(FLAME, 1f)))),
of(TYPES.backgroundMusic(), List.of(BackgroundMusic.EMPTY,
new BackgroundMusic(Optional.of(new Music(SOUND, 12000, 24000, true)), Optional.empty(),
Optional.of(new Music(RANGED_SOUND, 0, 1, false))))),
of(TYPES.ambientSounds(), List.of(AmbientSounds.EMPTY,
new AmbientSounds(Optional.of(RANGED_SOUND), Optional.of(new AmbientSounds.Mood(SOUND, 6000, 8, 2.0)),
List.of(new AmbientSounds.Additions(SOUND, 0.0111), new AmbientSounds.Additions(RANGED_SOUND, 0.5))))),
of(TYPES.mobSpawnSettings(), List.of(MobSpawnSettings.EMPTY, spawns),
Operation.OVERLAY, List.of(MobSpawnSettings.EMPTY, spawns)),
of(TYPES.identifier(), List.of(RegistryKey.parse("minecraft:stone"), RegistryKey.parse("my.pack:a/b"))),
of(TYPES.identifierOrTag(), List.<Either<RegistryKey, TagKey>>of(
Either.left(RegistryKey.parse("minecraft:stone")), Either.right(TagKey.parse("#my.pack:logs")))),
of(TYPES.intProvider(), List.of(new IntProviderValue(OptionalInt.of(-4), Optional.empty()),
new IntProviderValue(OptionalInt.empty(), Optional.of(UNIFORM)))),
of(CORE.enumType("skybox", Skybox.class), List.of(Skybox.values())),
of(CORE.enumType("cardinal_light", CardinalLight.class), List.of(CardinalLight.values())),
of(CORE.enumType("grass_color_modifier", GrassColorModifier.class), List.of(GrassColorModifier.values())),
of(CORE.enumType("temperature_modifier", TemperatureModifier.class), List.of(TemperatureModifier.values())));
}
private static void assertPlain(Object encoded, String where) {
if(encoded == null || encoded instanceof Number || encoded instanceof Boolean || encoded instanceof String) return;
if(encoded instanceof List<?> list) {
for(Object element : list) assertPlain(element, where);
return;
}
if(encoded instanceof Map<?, ?> m) {
m.forEach((k, v) -> {
assertTrue(k instanceof String, where + ": map key " + k + " is not a string");
assertPlain(v, where);
});
return;
}
fail(where + ": encoded a " + encoded.getClass().getName() + ": " + encoded);
}
private static <T> void assertValuesRoundTrip(Case<T> c) throws DecodeException {
for(T value : c.values()) {
Object encoded = c.type().encode(value);
assertPlain(encoded, c.type().id());
assertEquals(value, c.type().decode(encoded, PLAIN), c.type().id() + " via " + encoded);
}
}
@Test
void everyMinecraftType() throws DecodeException {
for(Case<?> c : cases()) assertValuesRoundTrip(c);
}
@Test
void everyArgument() throws DecodeException {
for(Case<?> c : cases()) {
AttributeType<?> type = c.type();
List<Operation> unsampled = new ArrayList<>(type.operations());
unsampled.remove(Operation.OVERRIDE);
unsampled.removeAll(c.arguments().keySet());
assertTrue(unsampled.isEmpty(), type.id() + " has no sample argument for " + unsampled);
Map<Operation, List<?>> arguments = new LinkedHashMap<>(c.arguments());
arguments.put(Operation.OVERRIDE, c.values());
for(Map.Entry<Operation, List<?>> e : arguments.entrySet()) {
for(Object argument : e.getValue()) {
Object encoded = type.encodeArgument(e.getKey(), argument);
assertPlain(encoded, type.id() + " " + e.getKey().getID());
assertEquals(argument, type.decodeArgument(e.getKey(), encoded, PLAIN),
type.id() + " " + e.getKey().getID() + " via " + encoded);
}
}
}
}
@Test
void canonicalForms() {
assertEquals("minecraft:stone", TYPES.identifier().encode(RegistryKey.parse("minecraft:stone")));
assertEquals("#minecraft:logs", TYPES.identifierOrTag().encode(Either.right(TagKey.parse("#minecraft:logs"))));
assertEquals("minecraft:stone", TYPES.identifierOrTag().encode(Either.left(RegistryKey.parse("minecraft:stone"))));
assertEquals("new_moon", TYPES.moonPhase().encode(MoonPhase.NEW_MOON));
assertEquals("end", CORE.enumType("skybox", Skybox.class).encode(Skybox.END));
assertEquals(map("type", "minecraft:flame"), TYPES.particle().encode(FLAME));
assertEquals(7, TYPES.intProvider().encode(new IntProviderValue(OptionalInt.of(7), Optional.empty())));
Map<?, ?> plainLoop = (Map<?, ?>) TYPES.ambientSounds().encode(new AmbientSounds(Optional.of(SOUND), Optional.empty(), List.of()));
assertEquals("minecraft:music.game", plainLoop.get("loop"));
Map<?, ?> rangedLoop = (Map<?, ?>) TYPES.ambientSounds().encode(
new AmbientSounds(Optional.of(RANGED_SOUND), Optional.empty(), List.of()));
assertEquals(map("sound_id", "minecraft:ambient.cave", "range", 16.0), rangedLoop.get("loop"));
Map<?, ?> bedRule = (Map<?, ?>) TYPES.bedRule().encode(
new BedRule(BedRule.Rule.NEVER, BedRule.Rule.NEVER, false, false, Optional.empty()));
assertFalse(bedRule.containsKey("error_message"));
}
}