minecraft-src/net/minecraft/world/level/block/entity/BlockEntity.java
2025-07-04 03:15:13 +03:00

328 lines
10 KiB
Java

package net.minecraft.world.level.block.entity;
import com.mojang.logging.LogUtils;
import com.mojang.serialization.Codec;
import java.util.HashSet;
import java.util.Set;
import net.minecraft.CrashReportCategory;
import net.minecraft.core.BlockPos;
import net.minecraft.core.HolderLookup.Provider;
import net.minecraft.core.component.DataComponentMap;
import net.minecraft.core.component.DataComponentPatch;
import net.minecraft.core.component.DataComponentType;
import net.minecraft.core.component.DataComponents;
import net.minecraft.core.component.PatchedDataComponentMap;
import net.minecraft.core.component.DataComponentMap.Builder;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.NbtOps;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.Component.Serializer;
import net.minecraft.network.protocol.Packet;
import net.minecraft.network.protocol.game.ClientGamePacketListener;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
public abstract class BlockEntity {
private static final Logger LOGGER = LogUtils.getLogger();
private final BlockEntityType<?> type;
@Nullable
protected Level level;
protected final BlockPos worldPosition;
protected boolean remove;
private BlockState blockState;
private DataComponentMap components = DataComponentMap.EMPTY;
public BlockEntity(BlockEntityType<?> type, BlockPos pos, BlockState blockState) {
this.type = type;
this.worldPosition = pos.immutable();
this.validateBlockState(blockState);
this.blockState = blockState;
}
private void validateBlockState(BlockState state) {
if (!this.isValidBlockState(state)) {
throw new IllegalStateException("Invalid block entity " + this.getNameForReporting() + " state at " + this.worldPosition + ", got " + state);
}
}
public boolean isValidBlockState(BlockState state) {
return this.type.isValid(state);
}
public static BlockPos getPosFromTag(CompoundTag tag) {
return new BlockPos(tag.getInt("x"), tag.getInt("y"), tag.getInt("z"));
}
@Nullable
public Level getLevel() {
return this.level;
}
public void setLevel(Level level) {
this.level = level;
}
/**
* @return whether this BlockEntity's level has been set
*/
public boolean hasLevel() {
return this.level != null;
}
protected void loadAdditional(CompoundTag tag, Provider registries) {
}
public final void loadWithComponents(CompoundTag tag, Provider registries) {
this.loadAdditional(tag, registries);
BlockEntity.ComponentHelper.COMPONENTS_CODEC
.parse(registries.createSerializationContext(NbtOps.INSTANCE), tag)
.resultOrPartial(string -> LOGGER.warn("Failed to load components: {}", string))
.ifPresent(dataComponentMap -> this.components = dataComponentMap);
}
public final void loadCustomOnly(CompoundTag tag, Provider registries) {
this.loadAdditional(tag, registries);
}
protected void saveAdditional(CompoundTag tag, Provider registries) {
}
public final CompoundTag saveWithFullMetadata(Provider registries) {
CompoundTag compoundTag = this.saveWithoutMetadata(registries);
this.saveMetadata(compoundTag);
return compoundTag;
}
public final CompoundTag saveWithId(Provider registries) {
CompoundTag compoundTag = this.saveWithoutMetadata(registries);
this.saveId(compoundTag);
return compoundTag;
}
public final CompoundTag saveWithoutMetadata(Provider registries) {
CompoundTag compoundTag = new CompoundTag();
this.saveAdditional(compoundTag, registries);
BlockEntity.ComponentHelper.COMPONENTS_CODEC
.encodeStart(registries.createSerializationContext(NbtOps.INSTANCE), this.components)
.resultOrPartial(string -> LOGGER.warn("Failed to save components: {}", string))
.ifPresent(tag -> compoundTag.merge((CompoundTag)tag));
return compoundTag;
}
public final CompoundTag saveCustomOnly(Provider registries) {
CompoundTag compoundTag = new CompoundTag();
this.saveAdditional(compoundTag, registries);
return compoundTag;
}
public final CompoundTag saveCustomAndMetadata(Provider registries) {
CompoundTag compoundTag = this.saveCustomOnly(registries);
this.saveMetadata(compoundTag);
return compoundTag;
}
private void saveId(CompoundTag tag) {
ResourceLocation resourceLocation = BlockEntityType.getKey(this.getType());
if (resourceLocation == null) {
throw new RuntimeException(this.getClass() + " is missing a mapping! This is a bug!");
} else {
tag.putString("id", resourceLocation.toString());
}
}
public static void addEntityType(CompoundTag tag, BlockEntityType<?> entityType) {
tag.putString("id", BlockEntityType.getKey(entityType).toString());
}
private void saveMetadata(CompoundTag tag) {
this.saveId(tag);
tag.putInt("x", this.worldPosition.getX());
tag.putInt("y", this.worldPosition.getY());
tag.putInt("z", this.worldPosition.getZ());
}
@Nullable
public static BlockEntity loadStatic(BlockPos pos, BlockState state, CompoundTag tag, Provider registries) {
String string = tag.getString("id");
ResourceLocation resourceLocation = ResourceLocation.tryParse(string);
if (resourceLocation == null) {
LOGGER.error("Block entity has invalid type: {}", string);
return null;
} else {
return (BlockEntity)BuiltInRegistries.BLOCK_ENTITY_TYPE.getOptional(resourceLocation).map(blockEntityType -> {
try {
return blockEntityType.create(pos, state);
} catch (Throwable var5x) {
LOGGER.error("Failed to create block entity {}", string, var5x);
return null;
}
}).map(blockEntity -> {
try {
blockEntity.loadWithComponents(tag, registries);
return blockEntity;
} catch (Throwable var5x) {
LOGGER.error("Failed to load data for block entity {}", string, var5x);
return null;
}
}).orElseGet(() -> {
LOGGER.warn("Skipping BlockEntity with id {}", string);
return null;
});
}
}
public void setChanged() {
if (this.level != null) {
setChanged(this.level, this.worldPosition, this.blockState);
}
}
protected static void setChanged(Level level, BlockPos pos, BlockState state) {
level.blockEntityChanged(pos);
if (!state.isAir()) {
level.updateNeighbourForOutputSignal(pos, state.getBlock());
}
}
public BlockPos getBlockPos() {
return this.worldPosition;
}
public BlockState getBlockState() {
return this.blockState;
}
@Nullable
public Packet<ClientGamePacketListener> getUpdatePacket() {
return null;
}
public CompoundTag getUpdateTag(Provider registries) {
return new CompoundTag();
}
public boolean isRemoved() {
return this.remove;
}
/**
* Marks this {@code BlockEntity} as no longer valid (removed from the level).
*/
public void setRemoved() {
this.remove = true;
}
/**
* Marks this {@code BlockEntity} as valid again (no longer removed from the level).
*/
public void clearRemoved() {
this.remove = false;
}
public boolean triggerEvent(int id, int type) {
return false;
}
public void fillCrashReportCategory(CrashReportCategory reportCategory) {
reportCategory.setDetail("Name", this::getNameForReporting);
if (this.level != null) {
CrashReportCategory.populateBlockDetails(reportCategory, this.level, this.worldPosition, this.getBlockState());
CrashReportCategory.populateBlockDetails(reportCategory, this.level, this.worldPosition, this.level.getBlockState(this.worldPosition));
}
}
private String getNameForReporting() {
return BuiltInRegistries.BLOCK_ENTITY_TYPE.getKey(this.getType()) + " // " + this.getClass().getCanonicalName();
}
public BlockEntityType<?> getType() {
return this.type;
}
@Deprecated
public void setBlockState(BlockState blockState) {
this.validateBlockState(blockState);
this.blockState = blockState;
}
protected void applyImplicitComponents(BlockEntity.DataComponentInput componentInput) {
}
public final void applyComponentsFromItemStack(ItemStack stack) {
this.applyComponents(stack.getPrototype(), stack.getComponentsPatch());
}
public final void applyComponents(DataComponentMap components, DataComponentPatch patch) {
final Set<DataComponentType<?>> set = new HashSet();
set.add(DataComponents.BLOCK_ENTITY_DATA);
set.add(DataComponents.BLOCK_STATE);
final DataComponentMap dataComponentMap = PatchedDataComponentMap.fromPatch(components, patch);
this.applyImplicitComponents(new BlockEntity.DataComponentInput() {
@Nullable
@Override
public <T> T get(DataComponentType<T> component) {
set.add(component);
return dataComponentMap.get(component);
}
@Override
public <T> T getOrDefault(DataComponentType<? extends T> component, T defaultValue) {
set.add(component);
return dataComponentMap.getOrDefault(component, defaultValue);
}
});
DataComponentPatch dataComponentPatch = patch.forget(set::contains);
this.components = dataComponentPatch.split().added();
}
protected void collectImplicitComponents(Builder components) {
}
@Deprecated
public void removeComponentsFromTag(CompoundTag tag) {
}
public final DataComponentMap collectComponents() {
Builder builder = DataComponentMap.builder();
builder.addAll(this.components);
this.collectImplicitComponents(builder);
return builder.build();
}
public DataComponentMap components() {
return this.components;
}
public void setComponents(DataComponentMap components) {
this.components = components;
}
@Nullable
public static Component parseCustomNameSafe(String customName, Provider registries) {
try {
return Serializer.fromJson(customName, registries);
} catch (Exception var3) {
LOGGER.warn("Failed to parse custom name from string '{}', discarding", customName, var3);
return null;
}
}
static class ComponentHelper {
public static final Codec<DataComponentMap> COMPONENTS_CODEC = DataComponentMap.CODEC.optionalFieldOf("components", DataComponentMap.EMPTY).codec();
private ComponentHelper() {
}
}
protected interface DataComponentInput {
@Nullable
<T> T get(DataComponentType<T> component);
<T> T getOrDefault(DataComponentType<? extends T> component, T defaultValue);
}
}