Minestom/src/main/java/net/minestom/server/instance/block/BlockImpl.java

89 lines
2.8 KiB
Java
Raw Normal View History

package net.minestom.server.instance.block;
2021-07-10 18:42:02 +02:00
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
2021-06-23 17:41:46 +02:00
import net.minestom.server.registry.Registry;
import net.minestom.server.tag.Tag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jglrxavpok.hephaistos.nbt.NBTCompound;
2021-06-23 17:41:46 +02:00
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
2021-06-26 20:23:56 +02:00
import java.util.Objects;
2021-07-10 18:42:02 +02:00
import java.util.concurrent.TimeUnit;
2021-06-23 17:41:46 +02:00
class BlockImpl implements Block {
2021-07-10 18:42:02 +02:00
private static final Cache<NBTCompound, NBTCompound> NBT_CACHE = Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.weakValues()
.build();
2021-06-23 17:41:46 +02:00
private final Registry.BlockEntry registry;
private final Map<String, String> properties;
private final NBTCompound nbt;
private final BlockHandler handler;
BlockImpl(@NotNull Registry.BlockEntry registry,
@NotNull Map<String, String> properties,
@Nullable NBTCompound nbt,
@Nullable BlockHandler handler) {
this.registry = registry;
this.properties = Collections.unmodifiableMap(properties);
this.nbt = nbt;
this.handler = handler;
}
BlockImpl(@NotNull Registry.BlockEntry registry,
@NotNull Map<String, String> properties) {
this(registry, properties, null, null);
}
@Override
public @NotNull Block withProperty(@NotNull String property, @NotNull String value) {
var properties = new HashMap<>(this.properties);
properties.put(property, value);
2021-06-23 18:29:19 +02:00
Block block = BlockLoader.getProperties(name(), properties);
2021-06-23 17:41:46 +02:00
if (block == null)
throw new IllegalArgumentException("Invalid property: " + property + ":" + value);
if (nbt != null || handler != null)
return new BlockImpl(block.registry(), block.properties(), nbt, handler);
return block;
}
@Override
2021-06-26 20:23:56 +02:00
public @NotNull <T> Block withTag(@NotNull Tag<T> tag, @Nullable T value) {
var compound = Objects.requireNonNullElseGet(nbt(), NBTCompound::new);
tag.write(compound, value);
2021-07-10 18:42:02 +02:00
return new BlockImpl(registry, properties, NBT_CACHE.get(compound, c -> compound), handler);
2021-06-23 17:41:46 +02:00
}
@Override
public @NotNull Block withHandler(@Nullable BlockHandler handler) {
return new BlockImpl(registry, properties, nbt, handler);
}
@Override
public @Nullable BlockHandler handler() {
return handler;
}
@Override
public @NotNull Map<String, String> properties() {
return properties;
}
@Override
public @NotNull Registry.BlockEntry registry() {
return registry;
}
@Override
public <T> @Nullable T getTag(@NotNull Tag<T> tag) {
if (nbt == null)
return null;
return tag.read(nbt);
}
2021-06-23 17:41:46 +02:00
}