Change Java whitespace handling in .editorconfig (#425)

* Change whitespace handling in .editorconfig

* Reformat code

* fix format error

* Reformat code

---------

Co-authored-by: Zoë Gidiere <duplexsys@protonmail.com>
This commit is contained in:
Astrashh
2023-11-13 11:57:01 +11:00
committed by GitHub
parent a73fda7d04
commit defd775f13
793 changed files with 7579 additions and 7577 deletions

View File

@@ -29,11 +29,11 @@ import com.dfsek.terra.api.tectonic.LoaderRegistrar;
*/
public interface Platform extends LoaderRegistrar {
boolean reload();
@NotNull
@Contract(pure = true)
String platformName();
/**
* Runs a task that may or may not be thread safe, depending on platform.
* <p>
@@ -44,40 +44,40 @@ public interface Platform extends LoaderRegistrar {
default void runPossiblyUnsafeTask(@NotNull Runnable task) {
task.run();
}
@NotNull
@Contract(pure = true)
WorldHandle getWorldHandle();
@NotNull
@Contract(pure = true)
PluginConfig getTerraConfig();
@NotNull
@Contract(pure = true)
File getDataFolder();
@NotNull
@Contract(pure = true)
CheckedRegistry<ConfigPack> getConfigRegistry();
@NotNull
@Contract(pure = true)
Registry<BaseAddon> getAddons();
@NotNull
@Contract(pure = true)
ItemHandle getItemHandle();
@NotNull
@Contract(pure = true)
EventManager getEventManager();
@Contract(pure = true)
default @NotNull String getVersion() {
return "@VERSION@";
}
@NotNull
@Contract(pure = true)
Profiler getProfiler();

View File

@@ -25,7 +25,7 @@ public interface BaseAddon extends StringIdentifiable, Namespaced {
* Initializes the addon. To be implemented by addons, but never manually invoked.
*/
default void initialize() { }
/**
* Gets the dependencies of this addon.
*
@@ -34,14 +34,14 @@ public interface BaseAddon extends StringIdentifiable, Namespaced {
default Map<String, VersionRange> getDependencies() {
return Collections.emptyMap();
}
/**
* Get the version of the addon
*
* @return Version of addon
*/
Version getVersion();
default String getNamespace() {
return getID();
}

View File

@@ -9,23 +9,23 @@ public class BootstrapAddonClassLoader extends URLClassLoader {
public BootstrapAddonClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
public BootstrapAddonClassLoader(URL[] urls) {
super(urls);
}
public BootstrapAddonClassLoader(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(urls, parent, factory);
}
public BootstrapAddonClassLoader(String name, URL[] urls, ClassLoader parent) {
super(name, urls, parent);
}
public BootstrapAddonClassLoader(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(name, urls, parent, factory);
}
@Override
public void addURL(URL url) {
super.addURL(url);

View File

@@ -21,14 +21,14 @@ public interface BlockType extends Handle {
* @return Default block state
*/
BlockState getDefaultState();
/**
* Get whether this block is solid.
*
* @return Whether this block is solid.
*/
boolean isSolid();
/**
* Get whether this block is water.
*

View File

@@ -14,18 +14,18 @@ import com.dfsek.terra.api.util.vector.Vector3;
public interface BlockEntity extends Handle {
boolean update(boolean applyPhysics);
default void applyState(String state) {
// Do nothing by default.
}
Vector3 getPosition();
int getX();
int getY();
int getZ();
BlockState getBlockState();
}

View File

@@ -14,34 +14,34 @@ import com.dfsek.terra.api.entity.EntityType;
public interface MobSpawner extends BlockEntity {
EntityType getSpawnedType();
void setSpawnedType(@NotNull EntityType creatureType);
int getDelay();
void setDelay(int delay);
int getMinSpawnDelay();
void setMinSpawnDelay(int delay);
int getMaxSpawnDelay();
void setMaxSpawnDelay(int delay);
int getSpawnCount();
void setSpawnCount(int spawnCount);
int getMaxNearbyEntities();
void setMaxNearbyEntities(int maxNearbyEntities);
int getRequiredPlayerRange();
void setRequiredPlayerRange(int requiredPlayerRange);
int getSpawnRange();
void setSpawnRange(int spawnRange);
}

View File

@@ -13,10 +13,10 @@ import java.util.Map;
public class SerialState {
protected final Map<String, Property<?>> properties = new HashMap<>();
public SerialState() {
}
public static Map<String, String> parse(String props) {
String[] sep = props.split(",");
Map<String, String> map = new HashMap<>();
@@ -25,7 +25,7 @@ public class SerialState {
}
return map;
}
@SuppressWarnings("unchecked")
public <T> T get(String id, Class<T> clazz) {
checkExists(id);
@@ -33,69 +33,69 @@ public class SerialState {
checkType(clazz, prop.getValue(), id);
return (T) prop.getValue();
}
private void checkExists(String prop) {
if(!properties.containsKey(prop)) throw new IllegalArgumentException("No such property \"" + prop + "\"");
}
private void checkType(Class<?> clazz, Object o, String id) {
if(!clazz.isInstance(o))
throw new IllegalArgumentException("Invalid data for property " + id + ": " + o);
}
public void setProperty(String id, Object value) {
checkExists(id);
Property<?> prop = properties.get(id);
checkType(prop.getValueClass(), value, id);
prop.setValue(value);
}
public int getInteger(String id) {
checkExists(id);
Property<?> prop = properties.get(id);
checkType(Integer.class, prop.getValue(), id);
return (Integer) prop.getValue();
}
public String getString(String id) {
checkExists(id);
Property<?> prop = properties.get(id);
checkType(String.class, prop.getValue(), id);
return (String) prop.getValue();
}
public long getLong(String id) {
checkExists(id);
Property<?> prop = properties.get(id);
checkType(Long.class, prop.getValue(), id);
return (Long) prop.getValue();
}
public boolean getBoolean(String id) {
checkExists(id);
Property<?> prop = properties.get(id);
checkType(Boolean.class, prop.getValue(), id);
return (Boolean) prop.getValue();
}
protected static class Property<T> {
private final Class<T> clazz;
private Object value;
public Property(Class<T> clazz) {
this.clazz = clazz;
}
public Class<T> getValueClass() {
return clazz;
}
@SuppressWarnings("unchecked")
public T getValue() {
return (T) value;
}
public void setValue(Object value) {
this.value = value;
}

View File

@@ -12,8 +12,8 @@ import org.jetbrains.annotations.NotNull;
public interface Sign extends BlockEntity {
void setLine(int index, @NotNull String line) throws IndexOutOfBoundsException;
@NotNull String[] getLines();
@NotNull String getLine(int index) throws IndexOutOfBoundsException;
}

View File

@@ -18,7 +18,7 @@ import com.dfsek.terra.api.block.state.properties.Property;
* Contains basic data about a {@link BlockType} in the world
*/
public interface BlockState extends Handle {
/**
* Whether this {@link BlockState} matches another.
* <p>
@@ -29,7 +29,7 @@ public interface BlockState extends Handle {
* @return Whether this state matches the other
*/
boolean matches(BlockState other);
/**
* Check whether this {@link BlockState} has a {@link Property}.
*
@@ -38,7 +38,7 @@ public interface BlockState extends Handle {
* @return Whether this state has the property.
*/
<T extends Comparable<T>> boolean has(Property<T> property);
/**
* Get the value of a {@link Property} on this state.
*
@@ -47,7 +47,7 @@ public interface BlockState extends Handle {
* @return Value of the property
*/
<T extends Comparable<T>> T get(Property<T> property);
/**
* Return a new {@link BlockState} with a {@link Property} set to a value.
*
@@ -57,7 +57,7 @@ public interface BlockState extends Handle {
* @return New {@link BlockState} with property set.
*/
<T extends Comparable<T>> BlockState set(Property<T> property, T value);
/**
* Perform an action on this {@link BlockState} if it contains a {@link Property}
*
@@ -70,7 +70,7 @@ public interface BlockState extends Handle {
if(has(property)) action.accept(this);
return this;
}
/**
* Set the value of a {@link Property} on this {@link BlockState} if it is present.
*
@@ -83,14 +83,14 @@ public interface BlockState extends Handle {
if(has(property)) set(property, value);
return this;
}
/**
* Get the {@link BlockType} this state applies to.
*
* @return Block type.
*/
BlockType getBlockType();
/**
* Get this state and its properties as a String
*
@@ -99,7 +99,7 @@ public interface BlockState extends Handle {
default String getAsString() {
return getAsString(true);
}
/**
* Get this state and its properties as a String
*
@@ -108,7 +108,7 @@ public interface BlockState extends Handle {
* @return String representation of this state
*/
String getAsString(boolean properties);
/**
* Get whether this BlockState is air
*

View File

@@ -22,7 +22,7 @@ public interface Property<T> extends StringIdentifiable {
* @return All values of this property
*/
Collection<T> values();
/**
* Get the type of this property.
*

View File

@@ -17,19 +17,19 @@ public interface BooleanProperty extends Property<Boolean> {
static BooleanProperty of(String name) {
return new BooleanProperty() {
private static final Collection<Boolean> BOOLEANS = Arrays.asList(true, false);
@Override
public Collection<Boolean> values() {
return BOOLEANS;
}
@Override
public String getID() {
return name;
}
};
}
@Override
default Class<Boolean> getType() {
return Boolean.class;

View File

@@ -18,17 +18,17 @@ public interface EnumProperty<T extends Enum<T>> extends Property<T> {
static <T extends Enum<T>> EnumProperty<T> of(String name, Class<T> clazz) {
return new EnumProperty<>() {
private final Lazy<Collection<T>> constants = Lazy.lazy(() -> Arrays.asList(clazz.getEnumConstants()));
@Override
public Collection<T> values() {
return constants.value();
}
@Override
public Class<T> getType() {
return clazz;
}
@Override
public String getID() {
return name;

View File

@@ -25,19 +25,19 @@ public interface IntProperty extends Property<Integer> {
}
return ints;
});
@Override
public Collection<Integer> values() {
return collection;
}
@Override
public String getID() {
return name;
}
};
}
@Override
default Class<Integer> getType() {
return Integer.class;

View File

@@ -18,29 +18,29 @@ public enum Direction {
WEST(3, -1, 0, 0),
UP(-1, 0, 1, 0),
DOWN(-1, 0, -1, 0);
private static final Direction[] rotations = Construct.construct(() -> new Direction[]{ NORTH, SOUTH, EAST, WEST });
private final int rotation;
private final int modX;
private final int modY;
private final int modZ;
Direction(int rotation, int modX, int modY, int modZ) {
this.rotation = rotation;
this.modX = modX;
this.modY = modY;
this.modZ = modZ;
}
public Direction rotate(Rotation rotation) {
return switch(this) {
case UP, DOWN -> this;
default -> rotations[(this.rotation + rotation.getDegrees() / 90) % 4];
};
}
public Direction opposite() {
return switch(this) {
case DOWN -> UP;
@@ -51,15 +51,15 @@ public enum Direction {
case SOUTH -> NORTH;
};
}
public int getModX() {
return modX;
}
public int getModY() {
return modY;
}
public int getModZ() {
return modZ;
}

View File

@@ -16,7 +16,7 @@ public enum Half {
* The bottom half of the block, normally with the lower y coordinate.
*/
BOTTOM,
/**
* Some blocks, e.g. slabs, can occupy both halves.
*/

View File

@@ -16,8 +16,8 @@ import com.dfsek.terra.api.entity.Player;
public interface CommandSender extends Handle {
void sendMessage(String message);
Optional<Entity> getEntity();
Optional<Player> getPlayer();
}

View File

@@ -24,99 +24,99 @@ import com.dfsek.terra.api.util.reflection.TypeKey;
public class RegistryArgument<T, R> extends CommandArgument<T, R> {
private RegistryArgument(
boolean required,
@NonNull String name,
Function<CommandContext<T>, Registry<R>> registryFunction,
TypeToken<R> typeToken,
@NonNull String defaultValue,
@Nullable BiFunction<CommandContext<T>, String, List<String>> suggestionsProvider,
@NonNull ArgumentDescription description
) {
boolean required,
@NonNull String name,
Function<CommandContext<T>, Registry<R>> registryFunction,
TypeToken<R> typeToken,
@NonNull String defaultValue,
@Nullable BiFunction<CommandContext<T>, String, List<String>> suggestionsProvider,
@NonNull ArgumentDescription description
) {
super(required,
name,
new RegistryArgumentParser<>(registryFunction),
defaultValue,
typeToken,
suggestionsProvider,
description);
name,
new RegistryArgumentParser<>(registryFunction),
defaultValue,
typeToken,
suggestionsProvider,
description);
}
public static <T, R> Builder<T, R> builder(String name, Registry<R> registry) {
return new Builder<>(name, registry);
}
public static <T, R> CommandArgument<T, R> of(String name, Registry<R> registry) {
return RegistryArgument.<T, R>builder(name, registry).build();
}
public static <T, R> CommandArgument<T, R> optional(String name, Registry<R> registry) {
return RegistryArgument.<T, R>builder(name, registry).asOptional().build();
}
public static <T, R> CommandArgument<T, R> optional(String name, Registry<R> registry, String defaultKey) {
return RegistryArgument.<T, R>builder(name, registry).asOptionalWithDefault(defaultKey).build();
}
@SuppressWarnings("unchecked")
public static <T, R> Builder<T, R> builder(String name, Function<CommandContext<T>, Registry<R>> registryFunction,
TypeKey<R> registryType) {
return new Builder<>(name, registryFunction, (TypeToken<R>) TypeToken.get(registryType.getType()));
}
public static <T, R> CommandArgument<T, R> of(String name, Function<CommandContext<T>, Registry<R>> registryFunction,
TypeKey<R> registryType) {
return RegistryArgument.<T, R>builder(name, registryFunction, registryType).build();
}
public static <T, R> CommandArgument<T, R> optional(String name, Function<CommandContext<T>, Registry<R>> registryFunction,
TypeKey<R> registryType) {
return RegistryArgument.builder(name, registryFunction, registryType).asOptional().build();
}
public static <T, R> CommandArgument<T, R> optional(String name, Function<CommandContext<T>, Registry<R>> registryFunction,
TypeKey<R> registryType, String defaultKey) {
return RegistryArgument.builder(name, registryFunction, registryType).asOptionalWithDefault(defaultKey).build();
}
public static final class Builder<T, R> extends CommandArgument.Builder<T, R> {
private final Function<CommandContext<T>, Registry<R>> registryFunction;
private final TypeToken<R> typeToken;
@SuppressWarnings("unchecked")
private Builder(@NonNull String name, Registry<R> registry) {
super((TypeToken<R>) TypeToken.get(registry.getType().getType()), name);
this.registryFunction = commandContext -> registry;
this.typeToken = (TypeToken<R>) TypeToken.get(registry.getType().getType());
}
private Builder(@NonNull String name, Function<CommandContext<T>, Registry<R>> registryFunction, TypeToken<R> typeToken) {
super(typeToken, name);
this.typeToken = typeToken;
this.registryFunction = registryFunction;
}
@Override
public @NonNull RegistryArgument<T, R> build() {
return new RegistryArgument<>(
isRequired(),
getName(),
registryFunction,
typeToken,
getDefaultValue(),
getSuggestionsProvider(),
getDefaultDescription()
isRequired(),
getName(),
registryFunction,
typeToken,
getDefaultValue(),
getSuggestionsProvider(),
getDefaultDescription()
);
}
}
private static final class RegistryArgumentParser<T, R> implements ArgumentParser<T, R> {
private final Function<CommandContext<T>, Registry<R>> registryFunction;
private RegistryArgumentParser(Function<CommandContext<T>, Registry<R>> registryFunction) {
this.registryFunction = registryFunction;
}
@Override
public @NonNull ArgumentParseResult<@NonNull R> parse(@NonNull CommandContext<@NonNull T> commandContext,
@NonNull Queue<@NonNull String> inputQueue) {
@@ -126,9 +126,9 @@ public class RegistryArgument<T, R> extends CommandArgument<T, R> {
input += inputQueue.remove();
input += inputQueue.remove();
}
Registry<R> registry = registryFunction.apply(commandContext);
Optional<R> result;
try {
result = registry.get(RegistryKey.parse(input));
@@ -139,12 +139,12 @@ public class RegistryArgument<T, R> extends CommandArgument<T, R> {
return ArgumentParseResult.failure(e1);
}
}
return result
.map(ArgumentParseResult::success)
.orElse(ArgumentParseResult.failure(new NoSuchEntryException("No such entry: " + input)));
.map(ArgumentParseResult::success)
.orElse(ArgumentParseResult.failure(new NoSuchEntryException("No such entry: " + input)));
}
@Override
public @NonNull List<@NonNull String> suggestions(@NonNull CommandContext<T> commandContext, @NonNull String input) {
return registryFunction.apply(commandContext).keys().stream().map(RegistryKey::toString).sorted().collect(Collectors.toList());

View File

@@ -34,26 +34,26 @@ public interface ConfigPack extends LoaderRegistrar,
RegistryProvider,
Keyed<ConfigPack>,
PropertyHolder {
ConfigPack registerConfigType(ConfigType<?, ?> type, RegistryKey id, int priority);
Map<BaseAddon, VersionRange> addons();
BiomeProvider getBiomeProvider();
List<GenerationStage> getStages();
Loader getLoader();
String getAuthor();
Version getVersion();
<T> ConfigPack registerShortcut(TypeKey<T> clazz, String shortcut, ShortcutLoader<T> loader);
default <T> ConfigPack registerShortcut(Class<T> clazz, String shortcut, ShortcutLoader<T> loader) {
return registerShortcut(TypeKey.of(clazz), shortcut, loader);
}
ChunkGeneratorProvider getGeneratorProvider();
}

View File

@@ -13,8 +13,8 @@ import com.dfsek.terra.api.util.reflection.TypeKey;
public interface ConfigType<T extends AbstractableTemplate, R> {
T getTemplate(ConfigPack pack, Platform platform);
ConfigFactory<T, R> getFactory();
TypeKey<R> getTypeKey();
}

View File

@@ -18,11 +18,11 @@ import java.util.function.Consumer;
public interface Loader {
Loader thenNames(Consumer<List<String>> consumer) throws ConfigException;
Loader thenEntries(Consumer<Set<Map.Entry<String, InputStream>>> consumer) throws ConfigException;
/**
* Get a single file from this Loader.
*
@@ -31,7 +31,7 @@ public interface Loader {
* @return InputStream from file.
*/
InputStream get(String singleFile) throws IOException;
/**
* Open a subdirectory.
*
@@ -39,7 +39,7 @@ public interface Loader {
* @param extension File extension
*/
Loader open(String directory, String extension);
/**
* Close all InputStreams opened.
*/

View File

@@ -12,24 +12,24 @@ import com.dfsek.terra.api.Platform;
public interface PluginConfig {
void load(Platform platform);
boolean dumpDefaultConfig();
boolean isDebugCommands();
boolean isDebugProfiler();
boolean isDebugScript();
boolean isDebugLog();
int getBiomeSearchResolution();
int getStructureCache();
int getSamplerCache();
int getMaxRecursion();
int getProviderCache();
}

View File

@@ -14,10 +14,10 @@ import com.dfsek.terra.api.world.ServerWorld;
public interface Entity extends Handle {
Vector3 position();
void position(Vector3 position);
void world(ServerWorld world);
ServerWorld world();
}

View File

@@ -20,8 +20,8 @@ public interface EventManager {
* @param event Event to pass to all registered EventListeners.
*/
<T extends Event> T callEvent(T event);
<T extends EventHandler> void registerHandler(Class<T> clazz, T handler);
<T extends EventHandler> T getHandler(Class<T> clazz);
}

View File

@@ -15,12 +15,12 @@ import com.dfsek.terra.api.util.mutable.MutableBoolean;
*/
public abstract class AbstractCancellable implements Cancellable {
private final MutableBoolean cancelled = new MutableBoolean(false);
@Override
public boolean isCancelled() {
return cancelled.get();
}
@Override
public void setCancelled(boolean cancelled) {
this.cancelled.set(cancelled);

View File

@@ -19,7 +19,7 @@ public interface Cancellable extends Event {
* @return Whether event is cancelled.
*/
boolean isCancelled();
/**
* Set the cancellation status of the event.
*

View File

@@ -26,24 +26,24 @@ import com.dfsek.terra.api.event.events.PackEvent;
public class ConfigurationDiscoveryEvent implements PackEvent, FailThroughEvent {
private final ConfigPack pack;
private final Loader loader;
private final BiConsumer<String, Configuration> consumer;
public ConfigurationDiscoveryEvent(ConfigPack pack, Loader loader, BiConsumer<String, Configuration> consumer) {
this.pack = pack;
this.loader = loader;
this.consumer = consumer;
}
public void register(String identifier, Configuration config) {
consumer.accept(identifier, config);
}
@Override
public ConfigPack getPack() {
return pack;
}
public Loader getLoader() {
return loader;
}

View File

@@ -30,9 +30,9 @@ public class ConfigurationLoadEvent implements PackEvent, FailThroughEvent {
private final AbstractConfiguration configuration;
private final Consumer<ConfigTemplate> loader;
private final ConfigType<?, ?> type;
private final Object loaded;
public ConfigurationLoadEvent(ConfigPack pack, AbstractConfiguration configuration, Consumer<ConfigTemplate> loader,
ConfigType<?, ?> type, Object loaded) {
this.pack = pack;
@@ -41,38 +41,38 @@ public class ConfigurationLoadEvent implements PackEvent, FailThroughEvent {
this.type = type;
this.loaded = loaded;
}
public <T extends ConfigTemplate> T load(T template) {
loader.accept(template);
return template;
}
public boolean is(Class<?> clazz) {
return clazz.isAssignableFrom(type.getTypeKey().getRawType());
}
@Override
public ConfigPack getPack() {
return pack;
}
public AbstractConfiguration getConfiguration() {
return configuration;
}
public ConfigType<?, ?> getType() {
return type;
}
@SuppressWarnings("unchecked")
public <T> T getLoadedObject(Class<T> clazz) {
if(!clazz.isAssignableFrom(type.getTypeKey().getRawType()))
throw new ClassCastException(
"Cannot assign object from loader of type " + ReflectionUtil.typeToString(type.getTypeKey().getType()) + " to class " +
clazz.getCanonicalName());
"Cannot assign object from loader of type " + ReflectionUtil.typeToString(type.getTypeKey().getType()) + " to class " +
clazz.getCanonicalName());
return (T) loaded;
}
@SuppressWarnings("unchecked")
public <T> T getLoadedObject() {
return (T) loaded;

View File

@@ -21,12 +21,12 @@ import com.dfsek.terra.api.event.events.PackEvent;
public abstract class ConfigPackLoadEvent implements PackEvent, FailThroughEvent {
private final ConfigPack pack;
private final ExceptionalConsumer<ConfigTemplate> configLoader;
public ConfigPackLoadEvent(ConfigPack pack, ExceptionalConsumer<ConfigTemplate> configLoader) {
this.pack = pack;
this.configLoader = configLoader;
}
/**
* Load a custom {@link ConfigTemplate} using the pack manifest.
*
@@ -36,12 +36,12 @@ public abstract class ConfigPackLoadEvent implements PackEvent, FailThroughEvent
configLoader.accept(template);
return template;
}
@Override
public ConfigPack getPack() {
return pack;
}
public interface ExceptionalConsumer<T extends ConfigTemplate> {
void accept(T value) throws ConfigException;
}

View File

@@ -18,30 +18,30 @@ import com.dfsek.terra.api.util.reflection.ReflectionUtil;
public abstract class ConfigTypeLoadEvent implements PackEvent, FailThroughEvent {
private final ConfigType<?, ?> type;
private final CheckedRegistry<?> registry;
private final ConfigPack pack;
public ConfigTypeLoadEvent(ConfigType<?, ?> type, CheckedRegistry<?> registry, ConfigPack pack) {
this.type = type;
this.registry = registry;
this.pack = pack;
}
public boolean is(Class<?> clazz) {
return clazz.isAssignableFrom(type.getTypeKey().getRawType());
}
@Override
public ConfigPack getPack() {
return pack;
}
@SuppressWarnings("unchecked")
public <T> CheckedRegistry<T> getRegistry(Class<T> clazz) {
if(!clazz.isAssignableFrom(type.getTypeKey().getRawType()))
throw new ClassCastException(
"Cannot assign object from loader of type " + ReflectionUtil.typeToString(type.getTypeKey().getType()) + " to class " +
clazz.getCanonicalName());
"Cannot assign object from loader of type " + ReflectionUtil.typeToString(type.getTypeKey().getType()) + " to class " +
clazz.getCanonicalName());
return (CheckedRegistry<T>) registry;
}
}

View File

@@ -8,11 +8,11 @@ import com.dfsek.terra.api.event.events.Event;
public class CommandRegistrationEvent implements Event {
private final CommandManager<CommandSender> commandManager;
public CommandRegistrationEvent(CommandManager<CommandSender> commandManager) {
this.commandManager = commandManager;
}
public CommandManager<CommandSender> getCommandManager() {
return commandManager;
}

View File

@@ -18,17 +18,17 @@ import com.dfsek.terra.api.event.events.PackEvent;
public class EntitySpawnEvent implements PackEvent {
private final ConfigPack pack;
private final Entity entity;
public EntitySpawnEvent(ConfigPack pack, Entity entity) {
this.pack = pack;
this.entity = entity;
}
@Override
public ConfigPack getPack() {
return pack;
}
/**
* Get the entity that triggered the event.
*

View File

@@ -26,23 +26,23 @@ public class LootPopulateEvent extends AbstractCancellable implements PackEvent
private final ConfigPack pack;
private final Structure structure;
private LootTable table;
public LootPopulateEvent(Container container, LootTable table, ConfigPack pack, Structure structure) {
this.container = container;
this.table = table;
this.pack = pack;
this.structure = structure;
}
@Override
public ConfigPack getPack() {
return pack;
}
public Vector3 getPosition() {
return container.getPosition();
}
/**
* Get the {@link Container} representing the inventory.
*
@@ -51,7 +51,7 @@ public class LootPopulateEvent extends AbstractCancellable implements PackEvent
public Container getContainer() {
return container;
}
/**
* Get the loot table to be populated.
*
@@ -60,7 +60,7 @@ public class LootPopulateEvent extends AbstractCancellable implements PackEvent
public LootTable getTable() {
return table;
}
/**
* Set the loot table to be populated.
*
@@ -69,7 +69,7 @@ public class LootPopulateEvent extends AbstractCancellable implements PackEvent
public void setTable(@NotNull LootTable table) {
this.table = table;
}
/**
* Get the script used to generate the structure.
*

View File

@@ -14,10 +14,10 @@ import com.dfsek.terra.api.event.events.Event;
public interface EventContext<T extends Event> {
EventContext<T> then(Consumer<T> action);
EventContext<T> priority(int priority);
EventContext<T> failThrough();
EventContext<T> global();
}

View File

@@ -15,6 +15,6 @@ import com.dfsek.terra.api.util.reflection.TypeKey;
public interface FunctionalEventHandler extends EventHandler {
<T extends Event> EventContext<T> register(BaseAddon addon, Class<T> clazz);
<T extends Event> EventContext<T> register(BaseAddon addon, TypeKey<T> clazz);
}

View File

@@ -14,10 +14,10 @@ import com.dfsek.terra.api.inventory.item.Enchantment;
public interface ItemHandle {
Item createItem(String data);
Enchantment getEnchantment(String id);
Set<Enchantment> getEnchantments();
}

View File

@@ -21,11 +21,11 @@ public interface WorldHandle {
@NotNull
@Contract("_ -> new")
BlockState createBlockState(@NotNull String data);
@NotNull
@Contract(pure = true)
BlockState air();
@NotNull
EntityType getEntity(@NotNull String id);
}

View File

@@ -23,14 +23,14 @@ public interface Injector<T> {
static <T1> Injector<T1> get(T1 value) {
return new InjectorImpl<>(value);
}
/**
* Add an explicit class as a target. Useful for applications where subclasses may cause issues with DI.
*
* @param target Target class type.
*/
void addExplicitTarget(Class<? extends T> target);
/**
* Inject the stored object into an object.
* <p>

View File

@@ -18,11 +18,11 @@ import com.dfsek.terra.api.inject.Injector;
public class InjectionException extends RuntimeException {
@Serial
private static final long serialVersionUID = -6929631447064215387L;
public InjectionException(String message) {
super(message);
}
public InjectionException(String message, Throwable cause) {
super(message, cause);
}

View File

@@ -21,7 +21,7 @@ import com.dfsek.terra.api.util.reflection.ReflectionUtil;
public class InjectorImpl<T> implements Injector<T> {
private final T value;
private final Set<Class<? extends T>> targets = new HashSet<>();
/**
* Instantiate an Injector with a value to inject
*
@@ -30,14 +30,14 @@ public class InjectorImpl<T> implements Injector<T> {
public InjectorImpl(T value) {
this.value = value;
}
@Override
public void addExplicitTarget(Class<? extends T> target) {
targets.add(target);
}
@Override
public void inject(Object object) throws InjectionException {
for(Field field : ReflectionUtil.getFields(object.getClass())) {

View File

@@ -12,8 +12,8 @@ import com.dfsek.terra.api.Handle;
public interface Inventory extends Handle {
void setItem(int slot, ItemStack newStack);
int getSize();
ItemStack getItem(int slot);
}

View File

@@ -15,6 +15,6 @@ import com.dfsek.terra.api.Handle;
*/
public interface Item extends Handle {
ItemStack newItemStack(int amount);
double getMaxDurability();
}

View File

@@ -14,15 +14,15 @@ import com.dfsek.terra.api.inventory.item.ItemMeta;
public interface ItemStack extends Handle {
int getAmount();
void setAmount(int i);
Item getType();
ItemMeta getItemMeta();
void setItemMeta(ItemMeta meta);
default boolean isDamageable() {
return getItemMeta() instanceof Damageable;
}

View File

@@ -12,8 +12,8 @@ import com.dfsek.terra.api.Handle;
public interface Damageable extends Handle {
int getDamage();
void setDamage(int damage);
boolean hasDamage();
}

View File

@@ -13,10 +13,10 @@ import com.dfsek.terra.api.inventory.ItemStack;
public interface Enchantment extends Handle {
boolean canEnchantItem(ItemStack itemStack);
boolean conflictsWith(Enchantment other);
String getID();
int getMaxLevel();
}

View File

@@ -14,6 +14,6 @@ import com.dfsek.terra.api.Handle;
public interface ItemMeta extends Handle {
void addEnchantment(Enchantment enchantment, int level);
Map<Enchantment, Integer> getEnchantments();
}

View File

@@ -21,39 +21,39 @@ public interface NoiseSampler {
public double noise(long seed, double x, double y) {
return 0;
}
@Override
public double noise(long seed, double x, double y, double z) {
return 0;
}
};
}
default double noise(Vector3 vector3, long seed) {
return noise(seed, vector3.getX(), vector3.getY(), vector3.getZ());
}
default double noise(Vector3Int vector3, long seed) {
return noise(seed, vector3.getX(), vector3.getY(), vector3.getZ());
}
default double noise(Vector2 vector2, long seed) {
return noise(seed, vector2.getX(), vector2.getZ());
}
default double noise(Vector2Int vector2, long seed) {
return noise(seed, vector2.getX(), vector2.getZ());
}
double noise(long seed, double x, double y);
default double noise(long seed, int x, int y) {
return noise(seed, (double) x, y);
}
double noise(long seed, double x, double y, double z);
default double noise(long seed, int x, int y, int z) {
return noise(seed, (double) x, y, z);
}

View File

@@ -17,7 +17,7 @@ public interface Profiler {
* @param frame ID of frame.
*/
void push(String frame);
/**
* Pop a frame from this profiler.
*
@@ -25,22 +25,22 @@ public interface Profiler {
* at the top of the profiler stack.
*/
void pop(String frame);
/**
* Start profiling.
*/
void start();
/**
* Stop profiling.
*/
void stop();
/**
* Clear the profiler data.
*/
void reset();
/**
* Get the profiler data.
*

View File

@@ -18,46 +18,46 @@ import java.util.Set;
public class Timings {
private final Map<String, Timings> subItems = new HashMap<>();
private final List<Long> timings = new ArrayList<>();
public void addTime(long time) {
timings.add(time);
}
public double average() {
return (double) timings.stream().reduce(0L, Long::sum) / timings.size();
}
public long max() {
return timings.stream().mapToLong(Long::longValue).max().orElse(0L);
}
public long min() {
return timings.stream().mapToLong(Long::longValue).min().orElse(0L);
}
public double sum() {
return timings.stream().mapToDouble(Long::doubleValue).sum();
}
@Override
public String toString() {
return toString(1, this, Collections.emptySet());
}
private String toString(int indent, Timings parent, Set<Integer> branches) {
StringBuilder builder = new StringBuilder();
builder.append((double) min() / 1000000).append("ms min / ").append(average() / 1000000).append("ms avg / ")
.append((double) max() / 1000000).append("ms max (").append(timings.size()).append(" samples, ")
.append((sum() / parent.sum()) * 100).append("% of parent)");
.append((double) max() / 1000000).append("ms max (").append(timings.size()).append(" samples, ")
.append((sum() / parent.sum()) * 100).append("% of parent)");
List<String> frames = new ArrayList<>();
Set<Integer> newBranches = new HashSet<>(branches);
newBranches.add(indent);
subItems.forEach((id, timings) -> frames.add(id + ": " + timings.toString(indent + 1, this, newBranches)));
for(int i = 0; i < frames.size(); i++) {
builder.append('\n');
for(int j = 0; j < indent; j++) {
@@ -70,11 +70,11 @@ public class Timings {
}
return builder.toString();
}
public List<Long> getTimings() {
return timings;
}
public Timings getSubItem(String id) {
return subItems.computeIfAbsent(id, s -> new Timings());
}

View File

@@ -18,26 +18,26 @@ public class Context {
private static final Map<Class<? extends Properties>, PropertyKey<?>> properties = new HashMap<>();
private final Map<Class<? extends Properties>, Properties> map = new HashMap<>();
private final AtomicReference<Properties[]> list = new AtomicReference<>(new Properties[size.get()]);
@SuppressWarnings("unchecked")
public static <T extends Properties> PropertyKey<T> create(Class<T> clazz) {
return (PropertyKey<T>) properties.computeIfAbsent(clazz, c -> new PropertyKey<>(size.getAndIncrement(), clazz));
}
@SuppressWarnings("unchecked")
public <T extends Properties> T get(Class<T> clazz) {
return (T) map.computeIfAbsent(clazz, k -> {
throw new IllegalArgumentException("No properties registered for class " + clazz.getCanonicalName());
});
}
public Context put(Properties properties) {
if(map.containsKey(properties.getClass())) throw new IllegalArgumentException(
"Property for class " + properties.getClass().getCanonicalName() + " already registered.");
"Property for class " + properties.getClass().getCanonicalName() + " already registered.");
map.put(properties.getClass(), properties);
return this;
}
public <T extends Properties> Context put(PropertyKey<T> key, T properties) {
list.updateAndGet(p -> {
if(p.length == size.get()) return p;
@@ -47,12 +47,12 @@ public class Context {
})[key.key] = properties;
return this;
}
@SuppressWarnings("unchecked")
public <T extends Properties> T get(PropertyKey<T> key) {
return (T) list.get()[key.key];
}
public <T extends Properties> boolean has(Class<T> test) {
return map.containsKey(test);
}

View File

@@ -3,12 +3,12 @@ package com.dfsek.terra.api.properties;
public class PropertyKey<T extends Properties> {
protected final int key;
private final Class<T> clazz;
protected PropertyKey(int key, Class<T> clazz) {
this.key = key;
this.clazz = clazz;
}
public Class<T> getTypeClass() {
return clazz;
}

View File

@@ -24,7 +24,7 @@ public interface CheckedRegistry<T> extends Registry<T> {
* @throws DuplicateEntryException If an entry with the same identifier is already present.
*/
void register(@NotNull RegistryKey identifier, @NotNull T value) throws DuplicateEntryException;
@SuppressWarnings("unchecked")
default void register(@NotNull Keyed<? extends T> value) throws DuplicateEntryException {
register(value.getRegistryKey(), (T) value);

View File

@@ -22,12 +22,12 @@ public interface OpenRegistry<T> extends Registry<T> {
* @param value Value to register.
*/
boolean register(@NotNull RegistryKey identifier, @NotNull T value);
@SuppressWarnings("unchecked")
default boolean register(@NotNull Keyed<? extends T> value) {
return register(value.getRegistryKey(), (T) value);
}
/**
* Add a value to this registry, checking whether it is present first.
*
@@ -37,12 +37,12 @@ public interface OpenRegistry<T> extends Registry<T> {
* @throws DuplicateEntryException If an entry with the same identifier is already present.
*/
void registerChecked(@NotNull RegistryKey identifier, @NotNull T value) throws DuplicateEntryException;
@SuppressWarnings("unchecked")
default void registerChecked(@NotNull Keyed<? extends T> value) {
registerChecked(value.getRegistryKey(), (T) value);
}
/**
* Clears all entries from the registry.
*/

View File

@@ -33,7 +33,7 @@ public interface Registry<T> extends TypeLoader<T> {
*/
@Contract(pure = true)
Optional<T> get(@NotNull RegistryKey key);
/**
* Check if the registry contains a value.
*
@@ -43,21 +43,21 @@ public interface Registry<T> extends TypeLoader<T> {
*/
@Contract(pure = true)
boolean contains(@NotNull RegistryKey key);
/**
* Perform the given action for every value in the registry.
*
* @param consumer Action to perform on value.
*/
void forEach(@NotNull Consumer<T> consumer);
/**
* Perform an action for every key-value pair in the registry.
*
* @param consumer Action to perform on pair.
*/
void forEach(@NotNull BiConsumer<RegistryKey, T> consumer);
/**
* Get the entries of this registry as a {@link Set}.
*
@@ -66,7 +66,7 @@ public interface Registry<T> extends TypeLoader<T> {
@NotNull
@Contract(pure = true)
Collection<T> entries();
/**
* Get all the keys in this registry.
*
@@ -75,13 +75,13 @@ public interface Registry<T> extends TypeLoader<T> {
@NotNull
@Contract(pure = true)
Set<RegistryKey> keys();
TypeKey<T> getType();
default Class<? super T> getRawType() {
return getType().getRawType();
}
default Optional<T> getByID(String id) {
return getByID(id, map -> {
if(map.isEmpty()) return Optional.empty();
@@ -89,19 +89,19 @@ public interface Registry<T> extends TypeLoader<T> {
return map.values().stream().findFirst(); // only one value.
}
throw new IllegalArgumentException("ID \"" + id + "\" is ambiguous; matches: " + map
.keySet()
.stream()
.map(RegistryKey::toString)
.reduce("", (a, b) -> a + "\n - " + b));
.keySet()
.stream()
.map(RegistryKey::toString)
.reduce("", (a, b) -> a + "\n - " + b));
});
}
default Collection<T> getAllWithID(String id) {
return getMatches(id).values();
}
Map<RegistryKey, T> getMatches(String id);
default Optional<T> getByID(String attempt, Function<Map<RegistryKey, T>, Optional<T>> reduction) {
if(attempt.contains(":")) {
return get(RegistryKey.parse(attempt));

View File

@@ -16,11 +16,11 @@ import java.io.Serial;
public class DuplicateEntryException extends RuntimeException {
@Serial
private static final long serialVersionUID = -7199021672428288780L;
public DuplicateEntryException(String message) {
super(message);
}
public DuplicateEntryException(String message, Throwable cause) {
super(message, cause);
}

View File

@@ -4,5 +4,5 @@ public class NoSuchEntryException extends RuntimeException {
public NoSuchEntryException(String message) {
super(message);
}
}

View File

@@ -3,12 +3,12 @@ package com.dfsek.terra.api.registry.key;
@SuppressWarnings("unused")
public interface Keyed<T extends Keyed<T>> extends Namespaced, StringIdentifiable {
RegistryKey getRegistryKey();
@Override
default String getNamespace() {
return getRegistryKey().getNamespace();
}
@Override
default String getID() {
return getRegistryKey().getID();

View File

@@ -2,7 +2,7 @@ package com.dfsek.terra.api.registry.key;
public interface Namespaced {
String getNamespace();
default RegistryKey key(String id) {
return RegistryKey.of(getNamespace(), id);
}

View File

@@ -8,53 +8,53 @@ public final class RegistryKey implements StringIdentifiable, Namespaced {
private static final Pattern ID_PATTERN = Pattern.compile("^[a-zA-Z0-9_-]*$");
private final String namespace;
private final String id;
private RegistryKey(String namespace, String id) {
if(!ID_PATTERN.matcher(namespace).matches()) {
throw new IllegalArgumentException(
"Namespace must only contain alphanumeric characters, hyphens, and underscores. \"" + namespace +
"\" is not a valid namespace.");
"Namespace must only contain alphanumeric characters, hyphens, and underscores. \"" + namespace +
"\" is not a valid namespace.");
}
if(!ID_PATTERN.matcher(id).matches()) {
throw new IllegalArgumentException(
"ID must only contain alphanumeric characters, hyphens, and underscores. \"" + id +
"\" is not a valid ID.");
"ID must only contain alphanumeric characters, hyphens, and underscores. \"" + id +
"\" is not a valid ID.");
}
this.namespace = namespace;
this.id = id;
}
public static RegistryKey parse(String key) {
if(key.chars().filter(c -> c == ':').count() != 1) {
throw new IllegalArgumentException("Malformed RegistryKey: " + key);
}
String namespace = key.substring(0, key.indexOf(":"));
String id = key.substring(key.indexOf(":") + 1);
return new RegistryKey(namespace, id);
}
public static RegistryKey of(String namespace, String id) {
return new RegistryKey(namespace, id);
}
@Override
public String getNamespace() {
return namespace;
}
@Override
public String getID() {
return id;
}
@Override
public int hashCode() {
return Objects.hash(namespace, id);
}
@Override
public boolean equals(Object obj) {
if(obj instanceof RegistryKey that) {
@@ -62,7 +62,7 @@ public final class RegistryKey implements StringIdentifiable, Namespaced {
}
return false;
}
@Override
public String toString() {
return namespace + ":" + id;

View File

@@ -10,10 +10,10 @@ public interface CheckedRegistryHolder extends RegistryHolder {
default <T> CheckedRegistry<T> getCheckedRegistry(Class<T> clazz) throws IllegalStateException {
return getCheckedRegistry((Type) clazz);
}
default <T> CheckedRegistry<T> getCheckedRegistry(TypeKey<T> type) throws IllegalStateException {
return getCheckedRegistry(type.getType());
}
<T> CheckedRegistry<T> getCheckedRegistry(Type type);
}

View File

@@ -17,10 +17,10 @@ public interface RegistryHolder {
default <T> Registry<T> getRegistry(Class<T> clazz) {
return getRegistry((Type) clazz);
}
default <T> Registry<T> getRegistry(TypeKey<T> type) {
return getRegistry(type.getType());
}
<T> Registry<T> getRegistry(Type type);
}

View File

@@ -8,6 +8,6 @@ public interface RegistryProvider {
default <T> CheckedRegistry<T> getOrCreateRegistry(Class<T> clazz) {
return getOrCreateRegistry(TypeKey.of(clazz));
}
<T> CheckedRegistry<T> getOrCreateRegistry(TypeKey<T> type);
}

View File

@@ -25,7 +25,7 @@ public interface LootTable {
* @param r The The Random instance to use.
*/
void fillInventory(Inventory i, Random r);
/**
* Fetches a list of ItemStacks from the loot table using the given Random instance.
*

View File

@@ -19,8 +19,8 @@ import com.dfsek.terra.api.util.collection.ProbabilityCollection;
@Experimental
public interface ConfiguredStructure extends StringIdentifiable {
ProbabilityCollection<Structure> getStructure();
Range getSpawnStart();
StructureSpawn getSpawn();
}

View File

@@ -24,7 +24,7 @@ public class BinaryColumn {
private final int minY;
private final int maxY;
private final Lazy<boolean[]> results;
/**
* Constructs a new {@link BinaryColumn} with all values initiated to {@code false}
*
@@ -44,7 +44,7 @@ public class BinaryColumn {
if(maxY <= minY) throw new IllegalArgumentException("Max y must be greater than min y");
this.data = data;
}
public BinaryColumn(int minY, int maxY, boolean[] data) {
this.minY = minY;
this.maxY = maxY;
@@ -52,15 +52,15 @@ public class BinaryColumn {
if(maxY <= minY) throw new IllegalArgumentException("Max y must be greater than min y");
this.data = y -> data[y - minY];
}
public BinaryColumn(Range y, IntToBooleanFunction data) {
this(y.getMin(), y.getMax(), data);
}
public static BinaryColumn getNull() {
return NULL;
}
/**
* Get the value at a height.
*
@@ -71,12 +71,12 @@ public class BinaryColumn {
public boolean get(int y) {
return data.apply(y);
}
public boolean contains(int y) {
return y >= minY && y < maxY;
}
/**
* Perform an action for all heights which have been set.
*
@@ -90,7 +90,7 @@ public class BinaryColumn {
}
}
}
/**
* Return a {@link BinaryColumn} of equal height with a boolean AND operation applied to each height.
*
@@ -103,12 +103,12 @@ public class BinaryColumn {
public BinaryColumn and(BinaryColumn that) {
int bigMinY = Math.max(this.minY, that.minY); // narrow new column, as areas outside will always be false.
int smallMaxY = Math.min(this.maxY, that.maxY);
if(bigMinY >= smallMaxY) return getNull();
return new BinaryColumn(bigMinY, smallMaxY, y -> this.get(y) && that.get(y));
}
/**
* Return a {@link BinaryColumn} of equal height with a boolean OR operation applied to each height.
*
@@ -121,18 +121,18 @@ public class BinaryColumn {
public BinaryColumn or(BinaryColumn that) {
return or(that, (a, b) -> a.getAsBoolean() || b.getAsBoolean());
}
public BinaryColumn xor(BinaryColumn that) {
return or(that, (a, b) -> a.getAsBoolean() ^ b.getAsBoolean());
}
private BinaryColumn or(BinaryColumn that, BooleanBinaryOperator operator) {
int smallMinY = Math.min(this.minY, that.minY);
int bigMaxY = Math.max(this.maxY, that.maxY);
return new BinaryColumn(smallMinY, bigMaxY, y -> operator.apply(() -> this.get(y), () -> that.get(y)));
}
private interface BooleanBinaryOperator {
boolean apply(BooleanSupplier a, BooleanSupplier b);
}

View File

@@ -11,21 +11,21 @@ public interface Distributor {
static Distributor yes() {
return (x, z, seed) -> true;
}
static Distributor no() {
return (x, z, seed) -> false;
}
boolean matches(int x, int z, long seed);
default Distributor and(Distributor other) {
return (x, z, seed) -> this.matches(x, z, seed) && other.matches(x, z, seed);
}
default Distributor or(Distributor other) {
return (x, z, seed) -> this.matches(x, z, seed) || other.matches(x, z, seed);
}
default Distributor xor(Distributor other) {
return (x, z, seed) -> this.matches(x, z, seed) ^ other.matches(x, z, seed);
}

View File

@@ -14,8 +14,8 @@ import com.dfsek.terra.api.world.WritableWorld;
public interface Feature extends StringIdentifiable {
Structure getStructure(WritableWorld world, int x, int y, int z);
Distributor getDistributor();
Locator getLocator();
}

View File

@@ -14,14 +14,14 @@ public interface Locator {
default Locator and(Locator that) {
return column -> this.getSuitableCoordinates(column).and(that.getSuitableCoordinates(column));
}
default Locator or(Locator that) {
return column -> this.getSuitableCoordinates(column).or(that.getSuitableCoordinates(column));
}
default Locator xor(Locator that) {
return column -> this.getSuitableCoordinates(column).xor(that.getSuitableCoordinates(column));
}
BinaryColumn getSuitableCoordinates(Column<?> column);
}

View File

@@ -16,13 +16,13 @@ import java.util.function.Supplier;
public interface ConfigLoadingDelegate {
<T> ConfigLoadingDelegate applyLoader(Type type, TypeLoader<T> loader);
default <T> ConfigLoadingDelegate applyLoader(Class<? extends T> type, TypeLoader<T> loader) {
return applyLoader((Type) type, loader);
}
<T> ConfigLoadingDelegate applyLoader(Type type, Supplier<ObjectTemplate<T>> loader);
default <T> ConfigLoadingDelegate applyLoader(Class<? extends T> type, Supplier<ObjectTemplate<T>> loader) {
return applyLoader((Type) type, loader);
}

View File

@@ -17,6 +17,6 @@ public interface Validator<T> {
static <T> Validator<T> notNull() {
return Objects::nonNull;
}
boolean validate(T value) throws TransformException;
}

View File

@@ -20,12 +20,12 @@ public class AttemptsFailedException extends RuntimeException {
@Serial
private static final long serialVersionUID = -1160459550006067137L;
private final List<Throwable> causes;
public AttemptsFailedException(String message, List<Throwable> causes) {
super(message);
this.causes = causes;
}
public List<Throwable> getCauses() {
return new ArrayList<>(causes);
}

View File

@@ -13,19 +13,19 @@ import java.io.Serial;
public class TransformException extends Exception {
@Serial
private static final long serialVersionUID = -6661338369581162084L;
public TransformException() {
super();
}
public TransformException(String message) {
super(message);
}
public TransformException(String message, Throwable cause) {
super(message, cause);
}
public TransformException(Throwable cause) {
super(cause);
}

View File

@@ -10,45 +10,45 @@ import com.dfsek.terra.api.util.function.IntObjConsumer;
public interface Column<T> {
int getMinY();
int getMaxY();
int getX();
int getZ();
T get(int y);
default void forEach(Consumer<T> consumer) {
for(int y = getMinY(); y < getMaxY(); y++) {
consumer.accept(get(y));
}
}
default void forEach(IntObjConsumer<T> consumer) {
for(int y = getMinY(); y < getMaxY(); y++) {
consumer.accept(y, get(y));
}
}
default void forRanges(int resolution, IntIntObjConsumer<T> consumer) {
int min = getMinY();
int y = min;
T runningObj = get(y);
int runningMin = min;
int max = getMaxY() - 1;
while(true) {
y += resolution;
if(y > max) {
break;
}
T current = get(y);
if(!current.equals(runningObj)) {
consumer.accept(runningMin, y, runningObj);
runningMin = y;
@@ -57,7 +57,7 @@ public interface Column<T> {
}
consumer.accept(runningMin, getMaxY(), runningObj);
}
default List<? extends T> asList() {
List<T> list = new ArrayList<>();
forEach((Consumer<T>) list::add);

View File

@@ -16,30 +16,30 @@ import java.util.Random;
public class ConstantRange implements Range {
private int min;
private int max;
public ConstantRange(int min, int max) {
if(min >= max) throw new IllegalArgumentException("Minimum must not be greater than or equal to maximum!");
this.max = max;
this.min = min;
}
@Override
public Range multiply(int mult) {
min *= mult;
max *= mult;
return this;
}
@Override
public Range reflect(int pt) {
return new ConstantRange(2 * pt - this.getMax(), 2 * pt - this.getMin());
}
@Override
public int get(Random r) {
return r.nextInt(min, max);
}
@Override
public Range intersects(Range other) {
try {
@@ -48,91 +48,91 @@ public class ConstantRange implements Range {
return null;
}
}
@Override
public Range add(int add) {
this.min += add;
this.max += add;
return this;
}
@Override
public Range sub(int sub) {
this.min -= sub;
this.max -= sub;
return this;
}
@NotNull
@Override
public Iterator<Integer> iterator() {
return new RangeIterator(this);
}
@Override
public boolean isInRange(int test) {
return test >= min && test < max;
}
@Override
public int getMax() {
return max;
}
@Override
public Range setMax(int max) {
this.max = max;
return this;
}
@Override
public int getMin() {
return min;
}
@Override
public Range setMin(int min) {
this.min = min;
return this;
}
@Override
public int getRange() {
return max - min;
}
@Override
public int hashCode() {
return min * 31 + max;
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof ConstantRange)) return false;
Range other = (Range) obj;
return other.getMin() == this.getMin() && other.getMax() == this.getMax();
}
@Override
public String toString() {
return "Min: " + getMin() + ", Max:" + getMax();
}
private static class RangeIterator implements Iterator<Integer> {
private final Range m;
private Integer current;
public RangeIterator(Range m) {
this.m = m;
current = m.getMin();
}
@Override
public boolean hasNext() {
return current < m.getMax();
}
@Override
public Integer next() {
current++;

View File

@@ -9,7 +9,7 @@ public final class GeometryUtil {
private GeometryUtil() {
}
public static void sphere(Vector3Int origin, int radius, Consumer<Vector3Int> action) {
for(int x = -radius; x <= radius; x++) {
for(int y = -radius; y <= radius; y++) {
@@ -21,7 +21,7 @@ public final class GeometryUtil {
}
}
}
public static void cube(Vector3Int origin, int radius, Consumer<Vector3Int> action) {
for(int x = -radius; x <= radius; x++) {
for(int y = -radius; y <= radius; y++) {

View File

@@ -26,39 +26,39 @@ public final class MathUtil {
SIN_BITS = 12;
SIN_MASK = ~(-1 << SIN_BITS);
SIN_COUNT = SIN_MASK + 1;
radFull = Math.PI * 2.0;
degFull = 360.0;
radToIndex = SIN_COUNT / radFull;
degToIndex = SIN_COUNT / degFull;
sin = new double[SIN_COUNT];
cos = new double[SIN_COUNT];
for(int i = 0; i < SIN_COUNT; i++) {
sin[i] = Math.sin((i + 0.5f) / SIN_COUNT * radFull);
cos[i] = Math.cos((i + 0.5f) / SIN_COUNT * radFull);
}
// Four cardinal directions (credits: Nate)
for(int i = 0; i < 360; i += 90) {
sin[(int) (i * degToIndex) & SIN_MASK] = Math.sin(i * Math.PI / 180.0);
cos[(int) (i * degToIndex) & SIN_MASK] = Math.cos(i * Math.PI / 180.0);
}
}
public static double sin(double rad) {
return sin[(int) (rad * radToIndex) & SIN_MASK];
}
public static double cos(double rad) {
return cos[(int) (rad * radToIndex) & SIN_MASK];
}
public static double tan(double rad) {
return sin(rad)/cos(rad);
return sin(rad) / cos(rad);
}
public static double invSqrt(double x) {
double halfX = 0.5d * x;
long i = Double.doubleToLongBits(x); // evil floating point bit level hacking
@@ -66,10 +66,10 @@ public final class MathUtil {
double y = Double.longBitsToDouble(i);
y *= (1.5d - halfX * y * y); // 1st newtonian iteration
// y *= (1.5d - halfX * y * y); // 2nd newtonian iteration, this can be removed
return y;
}
/**
* Gets the standard deviation of an array of doubles.
*
@@ -80,20 +80,20 @@ public final class MathUtil {
public static double standardDeviation(List<Number> numArray) {
double sum = 0.0, standardDeviation = 0.0;
int length = numArray.size();
for(Number num : numArray) {
sum += num.doubleValue();
}
double mean = sum / length;
for(Number num : numArray) {
standardDeviation += Math.pow(num.doubleValue() - mean, 2);
}
return Math.sqrt(standardDeviation / length);
}
public static long hashToLong(String s) {
if(s == null) {
return 0;
@@ -104,7 +104,7 @@ public final class MathUtil {
}
return hash;
}
/**
* Compare 2 floating-point values with epsilon to account for rounding errors
*
@@ -116,15 +116,15 @@ public final class MathUtil {
public static boolean equals(double a, double b) {
return a == b || Math.abs(a - b) < EPSILON;
}
public static int normalizeIndex(double val, int size) {
return Math.max(Math.min((int) Math.floor(((val + 1D) / 2D) * size), size - 1), 0);
}
public static long squash(int first, int last) {
return (((long) first) << 32) | (last & 0xffffffffL);
}
/**
* Clamp value to range of [-1, 1]
*
@@ -135,11 +135,11 @@ public final class MathUtil {
public static double clamp(double in) {
return Math.min(Math.max(in, -1), 1);
}
public static int clamp(int min, int i, int max) {
return Math.max(Math.min(i, max), min);
}
/**
* Compute the value in a normally distributed data set that has probability p.
*
@@ -161,30 +161,30 @@ public final class MathUtil {
if(sigma == 0)
return mu;
double q, r, val;
q = p - 0.5;
if(Math.abs(q) <= .425) {
r = .180625 - q * q;
val =
q * (((((((r * 2509.0809287301226727 +
33430.575583588128105) * r + 67265.770927008700853) * r +
45921.953931549871457) * r + 13731.693765509461125) * r +
1971.5909503065514427) * r + 133.14166789178437745) * r +
3.387132872796366608)
/ (((((((r * 5226.495278852854561 +
28729.085735721942674) * r + 39307.89580009271061) * r +
21213.794301586595867) * r + 5394.1960214247511077) * r +
687.1870074920579083) * r + 42.313330701600911252) * r + 1);
q * (((((((r * 2509.0809287301226727 +
33430.575583588128105) * r + 67265.770927008700853) * r +
45921.953931549871457) * r + 13731.693765509461125) * r +
1971.5909503065514427) * r + 133.14166789178437745) * r +
3.387132872796366608)
/ (((((((r * 5226.495278852854561 +
28729.085735721942674) * r + 39307.89580009271061) * r +
21213.794301586595867) * r + 5394.1960214247511077) * r +
687.1870074920579083) * r + 42.313330701600911252) * r + 1);
} else {
if(q > 0) {
r = 1 - p;
} else {
r = p;
}
r = Math.sqrt(-Math.log(r));
if(r <= 5) {
r -= 1.6;
val = (((((((r * 7.7454501427834140764e-4 +
@@ -214,15 +214,15 @@ public final class MathUtil {
* r + .13692988092273580531) * r +
.59983220655588793769) * r + 1);
}
if(q < 0.0) {
val = -val;
}
}
return mu + sigma * val;
}
/**
* Murmur64 hashing function
*
@@ -238,7 +238,7 @@ public final class MathUtil {
h ^= h >>> 33;
return h;
}
/**
* 1D Linear interpolation between 2 points 1 unit apart.
*
@@ -251,16 +251,16 @@ public final class MathUtil {
public static double lerp(double t, double v0, double v1) {
return v0 + t * (v1 - v0);
}
public static double cubicLerp(double a, double b, double c, double d, double t) {
double p = (d - c) - (a - b);
return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b;
}
public static double interpHermite(double t) {
return t * t * (3 - 2 * t);
}
public static double interpQuintic(double t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}

View File

@@ -7,20 +7,20 @@
package com.dfsek.terra.api.util;
import com.dfsek.terra.api.world.chunk.Chunk;
import java.util.Random;
import com.dfsek.terra.api.world.chunk.Chunk;
public final class PopulationUtil {
public static Random getRandom(Chunk c) {
return getRandom(c, 0);
}
public static Random getRandom(Chunk c, long salt) {
return new Random(getCarverChunkSeed(c.getX(), c.getZ(), c.getWorld().getSeed() + salt));
}
/**
* Gets the carver seed for a chunk.
*

View File

@@ -16,48 +16,48 @@ import java.util.function.Supplier;
public interface Range extends Iterable<Integer> {
Range multiply(int mult);
Range reflect(int pt);
int get(Random r);
Range intersects(Range other);
Range add(int add);
Range sub(int sub);
@NotNull
@Override
Iterator<Integer> iterator();
boolean isInRange(int test);
int getMax();
Range setMax(int max);
int getMin();
Range setMin(int min);
int getRange();
default <T> T ifInRange(int y, T inRange, T notInRange) {
if(isInRange(y)) return inRange;
return notInRange;
}
default <T> T ifInRange(int y, Supplier<T> inRange, Supplier<T> notInRange) {
if(isInRange(y)) return inRange.get();
return notInRange.get();
}
default <T> T ifInRange(int y, Supplier<T> inRange, T notInRange) {
if(isInRange(y)) return inRange.get();
return notInRange;
}
default <T> T ifInRange(int y, T inRange, Supplier<T> notInRange) {
if(isInRange(y)) return inRange;
return notInRange.get();

View File

@@ -8,17 +8,17 @@
package com.dfsek.terra.api.util;
public enum Rotation {
CW_90(90),
CW_180(180),
CCW_90(270),
NONE(0);
private final int degrees;
Rotation(int degrees) {
this.degrees = degrees;
}
public static Rotation fromDegrees(int deg) {
return switch(Math.floorMod(deg, 360)) {
case 0 -> Rotation.NONE;
@@ -28,7 +28,7 @@ public enum Rotation {
default -> throw new IllegalArgumentException();
};
}
public Rotation inverse() {
return switch(this) {
case NONE -> NONE;
@@ -37,15 +37,15 @@ public enum Rotation {
case CW_180 -> CW_180;
};
}
public Rotation rotate(Rotation rotation) {
return fromDegrees(this.getDegrees() + rotation.getDegrees());
}
public int getDegrees() {
return degrees;
}
public enum Axis {
X,
Y,

View File

@@ -29,6 +29,6 @@ public final class RotationUtil {
}
return copy.immutable();
}
}

View File

@@ -24,46 +24,46 @@ import com.dfsek.terra.api.block.state.BlockState;
public class MaterialSet extends HashSet<BlockType> {
@Serial
private static final long serialVersionUID = 3056512763631017301L;
public static MaterialSet singleton(BlockType material) {
return new Singleton(material);
}
public static MaterialSet get(BlockType... materials) {
MaterialSet set = new MaterialSet();
set.addAll(Arrays.asList(materials));
return set;
}
public static MaterialSet get(BlockState... materials) {
MaterialSet set = new MaterialSet();
Arrays.stream(materials).forEach(set::add);
return set;
}
public static MaterialSet empty() {
return new MaterialSet();
}
private void add(BlockState data) {
add(data.getBlockType());
}
private static final class Singleton extends MaterialSet {
private final BlockType element;
Singleton(BlockType e) {
element = e;
}
public Iterator<BlockType> iterator() {
return new Iterator<>() {
private boolean hasNext = true;
public boolean hasNext() {
return hasNext;
}
public BlockType next() {
if(hasNext) {
hasNext = false;
@@ -71,11 +71,11 @@ public class MaterialSet extends HashSet<BlockType> {
}
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void forEachRemaining(Consumer<? super BlockType> action) {
Objects.requireNonNull(action);
@@ -86,31 +86,31 @@ public class MaterialSet extends HashSet<BlockType> {
}
};
}
public int size() {
return 1;
}
public boolean contains(Object o) {
return Objects.equals(o, element);
}
// Override default methods for Collection
@Override
public void forEach(Consumer<? super BlockType> action) {
action.accept(element);
}
@Override
public Spliterator<BlockType> spliterator() {
return new Spliterator<>() {
long est = 1;
@Override
public Spliterator<BlockType> trySplit() {
return null;
}
@Override
public boolean tryAdvance(Consumer<? super BlockType> consumer) {
Objects.requireNonNull(consumer);
@@ -121,32 +121,32 @@ public class MaterialSet extends HashSet<BlockType> {
}
return false;
}
@Override
public void forEachRemaining(Consumer<? super BlockType> consumer) {
tryAdvance(consumer);
}
@Override
public long estimateSize() {
return est;
}
@Override
public int characteristics() {
int value = (element != null) ? Spliterator.NONNULL : 0;
return value | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE |
Spliterator.DISTINCT | Spliterator.ORDERED;
}
};
}
@Override
public boolean removeIf(Predicate<? super BlockType> filter) {
throw new UnsupportedOperationException();
}
@Override
public int hashCode() {
return Objects.hashCode(element);

View File

@@ -30,7 +30,7 @@ public class ProbabilityCollection<E> implements Collection<E> {
protected final Map<E, MutableInteger> cont = new HashMap<>();
private Object[] array = new Object[0];
private int size;
public ProbabilityCollection<E> add(E item, int probability) {
if(!cont.containsKey(item)) size++;
cont.computeIfAbsent(item, i -> new MutableInteger(0)).increment();
@@ -41,94 +41,94 @@ public class ProbabilityCollection<E> implements Collection<E> {
for(int i = oldLength; i < array.length; i++) array[i] = item;
return this;
}
@SuppressWarnings("unchecked")
public E get(Random r) {
if(array.length == 0) return null;
return (E) array[r.nextInt(array.length)];
}
@SuppressWarnings("unchecked")
public E get(NoiseSampler n, double x, double y, double z, long seed) {
if(array.length == 0) return null;
return (E) array[(int) MathUtil.normalizeIndex(n.noise(seed, x, y, z), array.length)];
}
@SuppressWarnings("unchecked")
public E get(NoiseSampler n, Vector3Int vector3Int, long seed) {
if(array.length == 0) return null;
return (E) array[(int) MathUtil.normalizeIndex(n.noise(seed, vector3Int.getX(), vector3Int.getY(), vector3Int.getZ()),
array.length)];
array.length)];
}
@SuppressWarnings("unchecked")
public E get(NoiseSampler n, Vector3 vector3Int, long seed) {
if(array.length == 0) return null;
return (E) array[(int) MathUtil.normalizeIndex(n.noise(seed, vector3Int.getX(), vector3Int.getY(), vector3Int.getZ()),
array.length)];
array.length)];
}
@SuppressWarnings("unchecked")
public E get(NoiseSampler n, double x, double z, long seed) {
if(array.length == 0) return null;
return (E) array[(int) MathUtil.normalizeIndex(n.noise(seed, x, z), array.length)];
}
@SuppressWarnings("unchecked")
public <T> ProbabilityCollection<T> map(Function<E, T> mapper, boolean carryNull) {
ProbabilityCollection<T> newCollection = new ProbabilityCollection<>();
newCollection.array = new Object[array.length];
for(int i = 0; i < array.length; i++) {
if(carryNull && array[i] == null) continue;
newCollection.array[i] = mapper.apply((E) array[i]);
}
return newCollection;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
cont.forEach((item, prob) -> builder.append(item).append(": ").append(prob).append(", "));
return builder.append("]").toString();
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return array.length == 0;
}
@Override
public boolean contains(Object o) {
return cont.containsKey(o);
}
@NotNull
@Override
public Iterator<E> iterator() {
return cont.keySet().iterator();
}
@NotNull
@Override
public Object @NotNull [] toArray() {
return cont.keySet().toArray();
}
@SuppressWarnings("SuspiciousToArrayCall")
@NotNull
@Override
public <T> T @NotNull [] toArray(@NotNull T @NotNull [] a) {
return cont.keySet().toArray(a);
}
/**
* Adds an item with probability of 1.
*/
@@ -137,96 +137,96 @@ public class ProbabilityCollection<E> implements Collection<E> {
add(e, 1);
return true; // Since this adds the item with a probability, the collection will always have changed.
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException("Cannot remove item from ProbabilityCollection!");
}
@Override
public boolean containsAll(@NotNull Collection<?> c) {
return cont.keySet().containsAll(c);
}
@Override
public boolean addAll(@NotNull Collection<? extends E> c) {
c.forEach(this::add);
return true;
}
@Override
public boolean removeAll(@NotNull Collection<?> c) {
throw new UnsupportedOperationException("Cannot remove item from ProbabilityCollection!");
}
@Override
public boolean retainAll(@NotNull Collection<?> c) {
throw new UnsupportedOperationException("Cannot remove item from ProbabilityCollection!");
}
@Override
public void clear() {
cont.clear();
array = new Object[0];
}
public int getTotalProbability() {
return array.length;
}
public int getProbability(E item) {
MutableInteger integer = cont.get(item);
return integer == null ? 0 : integer.get();
}
public Set<E> getContents() {
return new HashSet<>(cont.keySet());
}
public static final class Singleton<T> extends ProbabilityCollection<T> {
private final T single;
public Singleton(T single) {
this.single = single;
cont.put(single, new MutableInteger(1));
}
@Override
public ProbabilityCollection<T> add(T item, int probability) {
throw new UnsupportedOperationException();
}
@Override
public T get(Random r) {
return single;
}
@Override
public T get(NoiseSampler n, double x, double y, double z, long seed) {
return single;
}
@Override
public T get(NoiseSampler n, double x, double z, long seed) {
return single;
}
@Override
public <T1> ProbabilityCollection<T1> map(Function<T, T1> mapper, boolean carryNull) {
if(carryNull && single == null) return new Singleton<>(null);
return new Singleton<>(mapper.apply(single));
}
@Override
public int size() {
return 1;
}
@Override
public int getTotalProbability() {
return 1;
}
@Override
public Set<T> getContents() {
return Collections.singleton(single);

View File

@@ -14,15 +14,15 @@ public final class Lazy<T> {
private final Supplier<T> valueSupplier;
private T value;
private boolean got = false;
private Lazy(Supplier<T> valueSupplier) {
this.valueSupplier = valueSupplier;
}
public static <T> Lazy<T> lazy(Supplier<T> valueSupplier) {
return new Lazy<>(valueSupplier);
}
public T value() {
if(!got && value == null) {
got = true;

View File

@@ -19,68 +19,68 @@ public final class Either<L, R> {
private final L left;
private final R right;
private final boolean leftPresent;
private Either(L left, R right, boolean leftPresent) {
this.left = left;
this.right = right;
this.leftPresent = leftPresent;
}
@NotNull
@Contract("_ -> new")
public static <L1, R1> Either<L1, R1> left(L1 left) {
return new Either<>(Objects.requireNonNull(left), null, true);
}
@NotNull
@Contract("_ -> new")
public static <L1, R1> Either<L1, R1> right(R1 right) {
return new Either<>(null, Objects.requireNonNull(right), false);
}
@NotNull
@Contract("_ -> this")
public Either<L, R> ifLeft(Consumer<L> action) {
if(leftPresent) action.accept(left);
return this;
}
@NotNull
@Contract("_ -> this")
public Either<L, R> ifRight(Consumer<R> action) {
if(!leftPresent) action.accept(right);
return this;
}
@NotNull
public Optional<L> getLeft() {
if(leftPresent) return Optional.of(left);
return Optional.empty();
}
@NotNull
public Optional<R> getRight() {
if(!leftPresent) return Optional.of(right);
return Optional.empty();
}
public boolean hasLeft() {
return leftPresent;
}
public boolean hasRight() {
return !leftPresent;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Either<?, ?> that)) return false;
return (this.leftPresent && that.leftPresent && Objects.equals(this.left, that.left))
|| (!this.leftPresent && !that.leftPresent && Objects.equals(this.right, that.right));
}

View File

@@ -21,137 +21,137 @@ public final class Pair<L, R> {
private static final Pair<?, ?> NULL = new Pair<>(null, null);
private final L left;
private final R right;
private Pair(L left, R right) {
this.left = left;
this.right = right;
}
public static <L, R, T> Function<Pair<L, R>, Pair<T, R>> mapLeft(Function<L, T> function) {
return pair -> of(function.apply(pair.left), pair.right);
}
public static <L, R, T> Function<Pair<L, R>, Pair<L, T>> mapRight(Function<R, T> function) {
return pair -> of(pair.left, function.apply(pair.right));
}
public static <L> Predicate<Pair<L, ?>> testLeft(Predicate<L> predicate) {
return pair -> predicate.test(pair.left);
}
public static <R> Predicate<Pair<?, R>> testRight(Predicate<R> predicate) {
return pair -> predicate.test(pair.right);
}
public static <L> Consumer<Pair<L, ?>> consumeLeft(Consumer<L> consumer) {
return pair -> consumer.accept(pair.left);
}
public static <R> Consumer<Pair<?, R>> consumeRight(Consumer<R> consumer) {
return pair -> consumer.accept(pair.right);
}
public static <R> Function<Pair<?, R>, R> unwrapRight() {
return pair -> pair.right;
}
public static <L> Function<Pair<L, ?>, L> unwrapLeft() {
return pair -> pair.left;
}
@Contract("_, _ -> new")
public static <L1, R1> Pair<L1, R1> of(L1 left, R1 right) {
return new Pair<>(left, right);
}
@Contract("-> new")
@SuppressWarnings("unchecked")
public static <L1, R1> Pair<L1, R1> ofNull() {
return (Pair<L1, R1>) NULL;
}
@NotNull
@Contract("-> new")
public Pair.Mutable<L, R> mutable() {
return Mutable.of(left, right);
}
public R getRight() {
return right;
}
public L getLeft() {
return left;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Pair<?, ?> that)) return false;
return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right);
}
public Pair<L, R> apply(BiConsumer<L, R> consumer) {
consumer.accept(this.left, this.right);
return this;
}
@Override
public String toString() {
return String.format("{%s,%s}", left, right);
}
public static class Mutable<L, R> {
private L left;
private R right;
private Mutable(L left, R right) {
this.left = left;
this.right = right;
}
@NotNull
@Contract("_, _ -> new")
public static <L1, R1> Pair.Mutable<L1, R1> of(L1 left, R1 right) {
return new Mutable<>(left, right);
}
@Contract("-> new")
public Pair<L, R> immutable() {
return Pair.of(left, right);
}
public L getLeft() {
return left;
}
public void setLeft(L left) {
this.left = left;
}
public R getRight() {
return right;
}
public void setRight(R right) {
this.right = right;
}
@Override
public int hashCode() {
return Objects.hash(left, right);
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof Mutable<?, ?> that)) return false;
return Objects.equals(this.left, that.left) && Objects.equals(this.right, that.right);
}
}

View File

@@ -12,30 +12,30 @@ import org.jetbrains.annotations.NotNull;
public class MutableBoolean implements MutablePrimitive<Boolean> {
private boolean value;
public MutableBoolean() {
this.value = false;
}
public MutableBoolean(boolean value) {
this.value = value;
}
@Override
public Boolean get() {
return value;
}
@Override
public void set(Boolean value) {
this.value = value;
}
public boolean invert() {
value = !value;
return value;
}
@Override
public int compareTo(@NotNull Boolean o) {
return Boolean.compare(value, o);

View File

@@ -15,41 +15,41 @@ import java.io.Serial;
public class MutableDouble extends MutableNumber<Double> {
@Serial
private static final long serialVersionUID = -2218110876763640053L;
public MutableDouble(Double value) {
super(value);
}
@Override
public void increment() {
add(1d);
}
@Override
public void decrement() {
subtract(1d);
}
@Override
public void add(Double add) {
value += add;
}
@Override
public void multiply(Double mul) {
value *= mul;
}
@Override
public void subtract(Double sub) {
value -= sub;
}
@Override
public void divide(Double divide) {
value /= divide;
}
@Override
public int compareTo(@NotNull Double o) {
return Double.compare(value, o);

View File

@@ -15,43 +15,43 @@ import java.io.Serial;
public class MutableInteger extends MutableNumber<Integer> {
@Serial
private static final long serialVersionUID = -4427935901819632745L;
public MutableInteger(Integer value) {
super(value);
}
public void increment() {
add(1);
}
public void decrement() {
subtract(1);
}
@Override
public void add(Integer add) {
value += add;
}
@Override
public void multiply(Integer mul) {
value *= mul;
}
@Override
public void subtract(Integer sub) {
value -= sub;
}
@Override
public void divide(Integer divide) {
value /= divide;
}
public void add(int add) {
value += add;
}
@Override
public int compareTo(@NotNull Integer o) {
return Integer.compare(value, o);

View File

@@ -11,52 +11,52 @@ import java.io.Serial;
public abstract class MutableNumber<T extends Number> extends Number implements MutablePrimitive<T> {
@Serial
private static final long serialVersionUID = 8619508342781664393L;
protected T value;
public MutableNumber(T value) {
this.value = value;
}
public abstract void increment();
public abstract void decrement();
public abstract void add(T add);
public abstract void multiply(T mul);
public abstract void subtract(T sub);
public abstract void divide(T divide);
@Override
public T get() {
return value;
}
@Override
public void set(T value) {
this.value = value;
}
@Override
public int intValue() {
return value.intValue();
}
@Override
public long longValue() {
return value.longValue();
}
@Override
public float floatValue() {
return value.floatValue();
}
@Override
public double doubleValue() {
return value.doubleValue();

View File

@@ -9,6 +9,6 @@ package com.dfsek.terra.api.util.mutable;
public interface MutablePrimitive<T> extends Comparable<T> {
T get();
void set(T value);
}

View File

@@ -34,7 +34,7 @@ public final class ReflectionUtil {
}
return result;
}
public static Method[] getMethods(@NotNull Class<?> type) {
Method[] result = type.getDeclaredMethods();
Class<?> parentClass = type.getSuperclass();
@@ -43,13 +43,13 @@ public final class ReflectionUtil {
}
return result;
}
public static <T extends Annotation> void ifAnnotationPresent(AnnotatedElement element, Class<? extends T> annotation,
Consumer<T> operation) {
T a = element.getAnnotation(annotation);
if(a != null) operation.accept(a);
}
public static Class<?> getRawType(Type type) {
if(type instanceof Class<?>) {
return (Class<?>) type;
@@ -69,11 +69,11 @@ public final class ReflectionUtil {
+ "GenericArrayType, but <" + type + "> is of type " + className);
}
}
public static String typeToString(Type type) {
return type instanceof Class ? ((Class<?>) type).getName() : type.toString();
}
public static boolean equals(Type a, Type b) {
if(a == b) {
return true;
@@ -83,7 +83,7 @@ public final class ReflectionUtil {
if(!(b instanceof ParameterizedType pb)) {
return false;
}
return Objects.equals(pa.getOwnerType(), pb.getOwnerType())
&& pa.getRawType().equals(pb.getRawType())
&& Arrays.equals(pa.getActualTypeArguments(), pb.getActualTypeArguments());
@@ -91,13 +91,13 @@ public final class ReflectionUtil {
if(!(b instanceof GenericArrayType gb)) {
return false;
}
return equals(ga.getGenericComponentType(), gb.getGenericComponentType());
} else if(a instanceof WildcardType wa) {
if(!(b instanceof WildcardType wb)) {
return false;
}
return Arrays.equals(wa.getUpperBounds(), wb.getUpperBounds())
&& Arrays.equals(wa.getLowerBounds(), wb.getLowerBounds());
} else if(a instanceof TypeVariable<?> va) {

View File

@@ -18,10 +18,10 @@ import java.lang.reflect.Type;
public class TypeKey<T> {
final Class<? super T> rawType;
final Type type;
final AnnotatedType annotatedType;
final int hashCode;
@SuppressWarnings("unchecked")
protected TypeKey() {
this.type = getSuperclassTypeParameter(getClass());
@@ -29,18 +29,18 @@ public class TypeKey<T> {
this.rawType = (Class<? super T>) ReflectionUtil.getRawType(type);
this.hashCode = type.hashCode();
}
protected TypeKey(Class<T> clazz) {
this.type = clazz;
this.rawType = clazz;
this.annotatedType = new ClassAnnotatedTypeImpl(clazz);
this.hashCode = type.hashCode();
}
public static <T> TypeKey<T> of(Class<T> clazz) {
return new TypeKey<>(clazz);
}
private static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if(superclass instanceof Class) {
@@ -49,7 +49,7 @@ public class TypeKey<T> {
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments()[0];
}
private static AnnotatedType getAnnotatedSuperclassTypeParameter(Class<?> subclass) {
AnnotatedType superclass = subclass.getAnnotatedSuperclass();
if(superclass.getType() instanceof Class) {
@@ -58,36 +58,36 @@ public class TypeKey<T> {
AnnotatedParameterizedType parameterized = (AnnotatedParameterizedType) superclass;
return parameterized.getAnnotatedActualTypeArguments()[0];
}
/**
* Returns the raw (non-generic) type for this type.
*/
public final Class<? super T> getRawType() {
return rawType;
}
/**
* Gets underlying {@code Type} instance.
*/
public final Type getType() {
return type;
}
public final AnnotatedType getAnnotatedType() {
return annotatedType;
}
@Override
public final int hashCode() {
return this.hashCode;
}
@Override
public final boolean equals(Object o) {
return o instanceof TypeKey<?>
&& ReflectionUtil.equals(type, ((TypeKey<?>) o).type);
}
@Override
public final String toString() {
return ReflectionUtil.typeToString(type);

View File

@@ -17,7 +17,7 @@ public class Vector2 {
private static final Vector2 ZERO = new Vector2(0, 0);
private static final Vector2 UNIT = new Vector2(0, 1);
protected double x, z;
/**
* Create a vector with a given X and Z component
*
@@ -28,20 +28,20 @@ public class Vector2 {
this.x = x;
this.z = z;
}
public static Vector2 zero() {
return ZERO;
}
public static Vector2 unit() {
return UNIT;
}
public static Vector2 of(double x, double z) {
return new Vector2(x, z);
}
/**
* Get the length of this Vector
*
@@ -50,7 +50,7 @@ public class Vector2 {
public double length() {
return Math.sqrt(lengthSquared());
}
/**
* Get the squared length of this Vector
*
@@ -59,7 +59,7 @@ public class Vector2 {
public double lengthSquared() {
return x * x + z * z;
}
/**
* Get the distance from this vector to another.
*
@@ -70,7 +70,7 @@ public class Vector2 {
public double distance(Vector2 other) {
return Math.sqrt(distanceSquared(other));
}
/**
* Get the squared distance between 2 vectors.
*
@@ -83,11 +83,11 @@ public class Vector2 {
double dz = other.getZ() - z;
return dx * dx + dz * dz;
}
public Vector3 extrude(double y) {
return Vector3.of(this.x, y, this.z);
}
/**
* Get X component
*
@@ -96,8 +96,8 @@ public class Vector2 {
public double getX() {
return x;
}
/**
* Get Z component
*
@@ -106,16 +106,16 @@ public class Vector2 {
public double getZ() {
return z;
}
public int getBlockX() {
return (int) Math.floor(x);
}
public int getBlockZ() {
return (int) Math.floor(z);
}
@Override
public int hashCode() {
int hash = 17;
@@ -123,50 +123,50 @@ public class Vector2 {
hash = 31 * hash + Double.hashCode(z);
return hash;
}
public boolean equals(Object obj) {
if(!(obj instanceof Vector2 other)) return false;
return MathUtil.equals(this.x, other.x) && MathUtil.equals(this.z, other.z);
}
public Mutable mutable() {
return new Mutable(x, z);
}
@Override
public String toString() {
return "(" + x + ", " + z + ")";
}
public static class Mutable extends Vector2 {
private Mutable(double x, double z) {
super(x, z);
}
public double getX() {
return x;
}
public Mutable setX(double x) {
this.x = x;
return this;
}
public double getZ() {
return z;
}
public Mutable setZ(double z) {
this.z = z;
return this;
}
public Vector2 immutable() {
return Vector2.of(x, z);
}
/**
* Get the length of this Vector
*
@@ -175,7 +175,7 @@ public class Vector2 {
public double length() {
return Math.sqrt(lengthSquared());
}
/**
* Get the squared length of this Vector
*
@@ -184,13 +184,13 @@ public class Vector2 {
public double lengthSquared() {
return x * x + z * z;
}
public Mutable add(double x, double z) {
this.x += x;
this.z += z;
return this;
}
/**
* Multiply X and Z components by a value.
*
@@ -203,7 +203,7 @@ public class Vector2 {
z *= m;
return this;
}
/**
* Add this vector to another.
*
@@ -216,7 +216,7 @@ public class Vector2 {
z += other.getZ();
return this;
}
/**
* Subtract a vector from this vector,
*
@@ -229,7 +229,7 @@ public class Vector2 {
z -= other.getZ();
return this;
}
/**
* Normalize this vector to length 1
*
@@ -239,7 +239,7 @@ public class Vector2 {
divide(length());
return this;
}
/**
* Divide X and Z components by a value.
*

View File

@@ -10,40 +10,40 @@ public class Vector2Int {
private static final Vector2Int ZERO = new Vector2Int(0, 0);
private static final Vector2Int UNIT = new Vector2Int(0, 1);
protected int x, z;
protected Vector2Int(int x, int z) {
this.x = x;
this.z = z;
}
public static Vector2Int zero() {
return ZERO;
}
public static Vector2Int unit() {
return UNIT;
}
public static Vector2Int of(int x, int z) {
return new Vector2Int(x, z);
}
public int getX() {
return x;
}
public int getZ() {
return z;
}
public Vector3Int toVector3(int y) {
return new Vector3Int(x, y, z);
}
public Mutable mutable() {
return new Mutable(x, z);
}
public Vector2Int rotate(Rotation rotation) {
return switch(rotation) {
case CW_90 -> of(z, -x);
@@ -52,12 +52,12 @@ public class Vector2Int {
default -> this;
};
}
@Override
public int hashCode() {
return (31 * x) + z;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Vector2Int that) {
@@ -65,30 +65,30 @@ public class Vector2Int {
}
return false;
}
public static class Mutable extends Vector2Int {
protected Mutable(int x, int z) {
super(x, z);
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public Vector2Int immutable() {
return new Vector2Int(x, z);
}

View File

@@ -16,37 +16,37 @@ public class Vector3 {
private static final Vector3 ZERO = new Vector3(0, 0, 0);
private static final Vector3 UNIT = new Vector3(0, 1, 0);
protected double x, y, z;
private Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public static Vector3 zero() {
return ZERO;
}
public static Vector3 unit() {
return UNIT;
}
public static Vector3 of(double x, double y, double z) {
return new Vector3(x, y, z);
}
public double lengthSquared() {
return x * x + y * y + z * z;
}
public double length() {
return Math.sqrt(lengthSquared());
}
public double inverseLength() {
return MathUtil.invSqrt(lengthSquared());
}
/**
* Get the distance between this vector and another. The value of this
* method is not cached and uses a costly square-root function, so do not
@@ -61,7 +61,7 @@ public class Vector3 {
public double distance(@NotNull Vector3 o) {
return Math.sqrt(Math.pow(x - o.getX(), 2) + Math.pow(y - o.getY(), 2) + Math.pow(z - o.getZ(), 2));
}
/**
* Get the squared distance between this vector and another.
*
@@ -72,7 +72,7 @@ public class Vector3 {
public double distanceSquared(@NotNull Vector3 o) {
return Math.pow(x - o.getX(), 2) + Math.pow(y - o.getY(), 2) + Math.pow(z - o.getZ(), 2);
}
/**
* Calculates the dot product of this vector with another. The dot product
* is defined as x1*x2+y1*y2+z1*z2. The returned value is a scalar.
@@ -84,34 +84,34 @@ public class Vector3 {
public double dot(@NotNull Vector3 other) {
return x * other.getX() + y * other.getY() + z * other.getZ();
}
public double getZ() {
return z;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
public int getBlockX() {
return (int) Math.floor(x);
}
public int getBlockY() {
return (int) Math.floor(y);
}
public int getBlockZ() {
return (int) Math.floor(z);
}
/**
* Returns if a vector is normalized
*
@@ -120,7 +120,7 @@ public class Vector3 {
public boolean isNormalized() {
return MathUtil.equals(this.lengthSquared(), 1);
}
/**
* Returns a hash code for this vector
*
@@ -129,13 +129,13 @@ public class Vector3 {
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32));
hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32));
hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32));
return hash;
}
/**
* Checks to see if two objects are equal.
* <p>
@@ -148,84 +148,84 @@ public class Vector3 {
if(!(obj instanceof Vector3 other)) return false;
return MathUtil.equals(x, other.getX()) && MathUtil.equals(y, other.getY()) && MathUtil.equals(z, other.getZ());
}
public Vector3Int toInt() {
return Vector3Int.of(getBlockX(), getBlockY(), getBlockZ());
}
public Mutable mutable() {
return new Mutable(x, y, z);
}
@Override
public String toString() {
return "(" + getX() + ", " + getY() + ", " + getZ() + ")";
}
public static class Mutable extends Vector3 {
private Mutable(double x, double y, double z) {
super(x, y, z);
}
public static Mutable of(double x, double y, double z) {
return new Mutable(x, y, z);
}
public Vector3 immutable() {
return Vector3.of(x, y, z);
}
public double getZ() {
return z;
}
public Mutable setZ(double z) {
this.z = z;
return this;
}
public double getX() {
return x;
}
public Mutable setX(double x) {
this.x = x;
return this;
}
public double getY() {
return y;
}
public Mutable setY(double y) {
this.y = y;
return this;
}
public double lengthSquared() {
return x * x + y * y + z * z;
}
public double length() {
return Math.sqrt(lengthSquared());
}
public double inverseLength() {
return MathUtil.invSqrt(lengthSquared());
}
public Mutable normalize() {
return this.multiply(this.inverseLength());
}
public Mutable subtract(int x, int y, int z) {
this.x -= x;
this.y -= y;
this.z -= z;
return this;
}
/**
* Calculates the dot product of this vector with another. The dot product
* is defined as x1*x2+y1*y2+z1*z2. The returned value is a scalar.
@@ -237,48 +237,48 @@ public class Vector3 {
public double dot(@NotNull Vector3 other) {
return x * other.getX() + y * other.getY() + z * other.getZ();
}
public Mutable subtract(Vector3 end) {
x -= end.getX();
y -= end.getY();
z -= end.getZ();
return this;
}
public Mutable multiply(double m) {
x *= m;
y *= m;
z *= m;
return this;
}
public Mutable add(double x, double y, double z) {
this.x += x;
this.y += y;
this.z += z;
return this;
}
public Mutable add(Vector3 other) {
this.x += other.getX();
this.y += other.getY();
this.z += other.getZ();
return this;
}
public Mutable add(Vector3Int other) {
this.x += other.getX();
this.y += other.getY();
this.z += other.getZ();
return this;
}
public Mutable add(Vector2 other) {
this.x += other.getX();
this.z += other.getZ();
return this;
}
/**
* Rotates the vector around a given arbitrary axis in 3 dimensional space.
*
@@ -304,7 +304,7 @@ public class Vector3 {
public Mutable rotateAroundAxis(@NotNull Vector3 axis, double angle) throws IllegalArgumentException {
return rotateAroundNonUnitAxis(axis.isNormalized() ? axis : axis.mutable().normalize().immutable(), angle);
}
/**
* Rotates the vector around a given arbitrary axis in 3 dimensional space.
*
@@ -329,11 +329,11 @@ public class Vector3 {
public Mutable rotateAroundNonUnitAxis(@NotNull Vector3 axis, double angle) throws IllegalArgumentException {
double x = getX(), y = getY(), z = getZ();
double x2 = axis.getX(), y2 = axis.getY(), z2 = axis.getZ();
double cosTheta = MathUtil.cos(angle);
double sinTheta = MathUtil.sin(angle);
double dotProduct = this.dot(axis);
double xPrime = x2 * dotProduct * (1d - cosTheta)
+ x * cosTheta
+ (-z2 * y + y2 * z) * sinTheta;
@@ -343,10 +343,10 @@ public class Vector3 {
double zPrime = z2 * dotProduct * (1d - cosTheta)
+ z * cosTheta
+ (-y2 * x + x2 * y) * sinTheta;
return setX(xPrime).setY(yPrime).setZ(zPrime);
}
/**
* Rotates the vector around the x axis.
* <p>
@@ -364,12 +364,12 @@ public class Vector3 {
public Mutable rotateAroundX(double angle) {
double angleCos = MathUtil.cos(angle);
double angleSin = MathUtil.sin(angle);
double y = angleCos * getY() - angleSin * getZ();
double z = angleSin * getY() + angleCos * getZ();
return setY(y).setZ(z);
}
/**
* Rotates the vector around the y axis.
* <p>
@@ -387,12 +387,12 @@ public class Vector3 {
public Mutable rotateAroundY(double angle) {
double angleCos = MathUtil.cos(angle);
double angleSin = MathUtil.sin(angle);
double x = angleCos * getX() + angleSin * getZ();
double z = -angleSin * getX() + angleCos * getZ();
return setX(x).setZ(z);
}
/**
* Rotates the vector around the z axis
* <p>
@@ -410,30 +410,30 @@ public class Vector3 {
public Mutable rotateAroundZ(double angle) {
double angleCos = MathUtil.cos(angle);
double angleSin = MathUtil.sin(angle);
double x = angleCos * getX() - angleSin * getY();
double y = angleSin * getX() + angleCos * getY();
return setX(x).setY(y);
}
@Override
public int hashCode() {
int hash = 13;
hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ (Double.doubleToLongBits(this.x) >>> 32));
hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ (Double.doubleToLongBits(this.y) >>> 32));
hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ (Double.doubleToLongBits(this.z) >>> 32));
return hash;
}
public int getBlockX() {
return (int) Math.floor(x);
}
public int getBlockY() {
return (int) Math.floor(y);
}
public int getBlockZ() {
return (int) Math.floor(z);
}

View File

@@ -5,93 +5,93 @@ public class Vector3Int {
private static final Vector3Int ZERO = new Vector3Int(0, 0, 0);
private static final Vector3Int UNIT = new Vector3Int(0, 1, 0);
protected int x, y, z;
protected Vector3Int(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public static Vector3Int unit() {
return UNIT;
}
public static Vector3Int zero() {
return ZERO;
}
public static Vector3Int of(int x, int y, int z) {
return new Vector3Int(x, y, z);
}
public static Vector3Int of(Vector3Int origin, int x, int y, int z) {
return new Vector3Int(origin.x + x, origin.y + y, origin.z + z);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getZ() {
return z;
}
public Mutable mutable() {
return new Mutable(x, y, z);
}
public Vector3 toVector3() {
return Vector3.of(x, y, z);
}
public Vector3.Mutable toVector3Mutable() {
return Vector3.Mutable.of(x, y, z);
}
public static class Mutable extends Vector3Int {
protected Mutable(int x, int y, int z) {
super(x, y, z);
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public Vector3Int immutable() {
return Vector3Int.of(x, y, z);
}
public Mutable add(int x, int y, int z) {
this.x += x;
this.y += y;
this.z += z;
return this;
}
public Vector3 toVector3() {
return Vector3.of(x, y, z);
}

View File

@@ -22,80 +22,80 @@ import com.dfsek.terra.api.world.util.WriteInterceptor;
public class BufferedWorld implements WritableWorld {
private final WritableWorld delegate;
private final int offsetX, offsetY, offsetZ;
private final ReadInterceptor readInterceptor;
private final WriteInterceptor writeInterceptor;
protected BufferedWorld(WritableWorld delegate, int offsetX, int offsetY, int offsetZ,
ReadInterceptor readInterceptor, WriteInterceptor writeInterceptor) {
this.delegate = delegate;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.offsetZ = offsetZ;
this.readInterceptor = readInterceptor;
this.writeInterceptor = writeInterceptor;
}
protected static Builder builder(WritableWorld world) {
return new Builder(world);
}
@Override
public Object getHandle() {
return delegate.getHandle();
}
@Override
public BlockState getBlockState(int x, int y, int z) {
return readInterceptor.read(x + offsetX, y + offsetY, z + offsetZ, delegate);
}
@Override
public BlockEntity getBlockEntity(int x, int y, int z) {
return delegate.getBlockEntity(x + offsetX, y + offsetY, z + offsetZ);
}
@Override
public long getSeed() {
return delegate.getSeed();
}
@Override
public int getMaxHeight() {
return delegate.getMaxHeight();
}
@Override
public int getMinHeight() {
return delegate.getMinHeight();
}
@Override
public ChunkGenerator getGenerator() {
return delegate.getGenerator();
}
@Override
public BiomeProvider getBiomeProvider() {
return delegate.getBiomeProvider();
}
@Override
public ConfigPack getPack() {
return delegate.getPack();
}
@Override
public void setBlockState(int x, int y, int z, BlockState data, boolean physics) {
writeInterceptor.write(x + offsetX, y + offsetY, z + offsetZ, data, delegate, physics);
}
@Override
public Entity spawnEntity(double x, double y, double z, EntityType entityType) {
return delegate.spawnEntity(x + offsetX, y + offsetY, z + offsetZ, entityType);
}
/**
* Get the world this {@link BufferedWorld} delegates to.
*
@@ -104,60 +104,60 @@ public class BufferedWorld implements WritableWorld {
public WritableWorld getDelegate() {
return delegate;
}
public static final class Builder {
private final WritableWorld delegate;
private ReadInterceptor readInterceptor;
private WriteInterceptor writeInterceptor;
private int x = 0;
private int y = 0;
private int z = 0;
private Builder(WritableWorld delegate) {
this.delegate = delegate;
}
public Builder read(ReadInterceptor interceptor) {
this.readInterceptor = interceptor;
return this;
}
public Builder write(WriteInterceptor interceptor) {
this.writeInterceptor = interceptor;
return this;
}
public Builder offsetX(int x) {
this.x = x;
return this;
}
public Builder offsetY(int y) {
this.y = y;
return this;
}
public Builder offsetZ(int z) {
this.z = z;
return this;
}
public Builder offset(Vector3Int vector) {
this.x = vector.getX();
this.y = vector.getY();
this.z = vector.getZ();
return this;
}
public BufferedWorld build() {
return new BufferedWorld(delegate,
this.x,
this.y,
this.z,
Objects.requireNonNullElse(readInterceptor, Interceptors.readThrough()),
Objects.requireNonNullElse(writeInterceptor, Interceptors.writeThrough()));
this.x,
this.y,
this.z,
Objects.requireNonNullElse(readInterceptor, Interceptors.readThrough()),
Objects.requireNonNullElse(writeInterceptor, Interceptors.writeThrough()));
}
}
}

View File

@@ -20,7 +20,7 @@ public interface ReadableWorld extends World {
* @return {@link BlockState} at coordinates.
*/
BlockState getBlockState(int x, int y, int z);
/**
* Get the {@link BlockState} at a location.
*
@@ -31,7 +31,7 @@ public interface ReadableWorld extends World {
default BlockState getBlockState(Vector3 position) {
return getBlockState(position.getBlockX(), position.getBlockY(), position.getBlockZ());
}
/**
* Get the {@link BlockState} at a location.
*
@@ -42,13 +42,13 @@ public interface ReadableWorld extends World {
default BlockState getBlockState(Vector3Int position) {
return getBlockState(position.getX(), position.getY(), position.getZ());
}
BlockEntity getBlockEntity(int x, int y, int z);
default BlockEntity getBlockEntity(Vector3 position) {
return getBlockEntity(position.getBlockX(), position.getBlockY(), position.getBlockZ());
}
default BlockEntity getBlockEntity(Vector3Int position) {
return getBlockEntity(position.getX(), position.getY(), position.getZ());
}

View File

@@ -13,7 +13,7 @@ import com.dfsek.terra.api.world.chunk.Chunk;
public interface ServerWorld extends WritableWorld {
Chunk getChunkAt(int x, int z);
default Chunk getChunkAt(Vector3 location) {
return getChunkAt(location.getBlockX() >> 4, location.getBlockZ() >> 4);
}

View File

@@ -16,14 +16,14 @@ public interface World extends WorldProperties {
* @return Chunk generator.
*/
ChunkGenerator getGenerator();
/**
* Get the {@link BiomeProvider} this world uses.
*
* @return Biome provider.
*/
BiomeProvider getBiomeProvider();
/**
* Get the {@link ConfigPack} this world uses.
*

View File

@@ -12,61 +12,61 @@ public interface WritableWorld extends ReadableWorld {
default void setBlockState(Vector3 position, BlockState data, boolean physics) {
setBlockState(position.getBlockX(), position.getBlockY(), position.getBlockZ(), data, physics);
}
default void setBlockState(Vector3.Mutable position, BlockState data, boolean physics) {
setBlockState(position.getBlockX(), position.getBlockY(), position.getBlockZ(), data, physics);
}
default void setBlockState(Vector3Int position, BlockState data, boolean physics) {
setBlockState(position.getX(), position.getY(), position.getZ(), data, physics);
}
default void setBlockState(Vector3Int.Mutable position, BlockState data, boolean physics) {
setBlockState(position.getX(), position.getY(), position.getZ(), data, physics);
}
default void setBlockState(Vector3 position, BlockState data) {
setBlockState(position, data, false);
}
default void setBlockState(Vector3.Mutable position, BlockState data) {
setBlockState(position, data, false);
}
default void setBlockState(Vector3Int position, BlockState data) {
setBlockState(position, data, false);
}
default void setBlockState(Vector3Int.Mutable position, BlockState data) {
setBlockState(position, data, false);
}
default void setBlockState(int x, int y, int z, BlockState data) {
setBlockState(x, y, z, data, false);
}
void setBlockState(int x, int y, int z, BlockState data, boolean physics);
default Entity spawnEntity(Vector3 location, EntityType entityType) {
return spawnEntity(location.getX(), location.getY(), location.getZ(), entityType);
}
Entity spawnEntity(double x, double y, double z, EntityType entityType);
default BufferedWorld buffer(int offsetX, int offsetY, int offsetZ) {
return BufferedWorld
.builder(this)
.offsetX(offsetX)
.offsetY(offsetY)
.offsetZ(offsetZ)
.build();
.builder(this)
.offsetX(offsetX)
.offsetY(offsetY)
.offsetZ(offsetZ)
.build();
}
default BufferedWorld.Builder buffer() {
return BufferedWorld.builder(this);
}
default Column<WritableWorld> column(int x, int z) {
return new Column<>(x, z, this);
}

Some files were not shown because too many files have changed in this diff Show More