BlockEntity .java

net.minecraft.world.level.block.entity.BlockEntity (class): members: applyComponentsFromItemStack, BlockEntityPathElement, saveWithFullMetadata, hasLevel.

net.minecraft.world.level.block.entityclass345 linescommon11.5 KB

Implements

API Surface (43)

boolean isValidBlockState(final BlockState blockState)
BlockPos getPosFromTag(final ChunkPos base, final CompoundTag entityTag)
void setLevel(final Level level)
boolean hasLevel()
void loadAdditional(final ValueInput input)
void loadWithComponents(final ValueInput input)
void loadCustomOnly(final ValueInput input)
void saveAdditional(final ValueOutput output)
CompoundTag saveWithFullMetadata(final HolderLookup.Provider registries)
void saveWithFullMetadata(final ValueOutput output)
void saveWithId(final ValueOutput output)
CompoundTag saveWithoutMetadata(final HolderLookup.Provider registries)
void saveWithoutMetadata(final ValueOutput output)
CompoundTag saveCustomOnly(final HolderLookup.Provider registries)
void saveCustomOnly(final ValueOutput output)
void addEntityType(final ValueOutput output, final BlockEntityType<?> type)
void setChanged()
void setChanged(final Level level, final BlockPos worldPosition, final BlockState blockState)
BlockPos getBlockPos()
BlockState getBlockState()
CompoundTag getUpdateTag(final HolderLookup.Provider registries)
boolean isRemoved()
void setRemoved()
void clearRemoved()
void preRemoveSideEffects(final BlockPos pos, final BlockState state)
boolean triggerEvent(final int b0, final int b1)
void fillCrashReportCategory(final CrashReportCategory category)
String getNameForReporting()
BlockEntityType<?> getType()
Holder<BlockEntityType<?>> typeHolder()
void setBlockState(final BlockState blockState)
void applyImplicitComponents(final DataComponentGetter components)
void applyComponentsFromItemStack(final ItemStack stack)
void applyComponents(final DataComponentMap prototype, final DataComponentPatch patch)
<T> T getOrDefault(final DataComponentType<? extends T> type, final T defaultValue)
void collectImplicitComponents(final DataComponentMap.Builder components)
void removeComponentsFromTag(final ValueOutput output)
DataComponentMap collectComponents()
DataComponentMap components()
void setComponents(final DataComponentMap components)
ProblemReporter.PathElement problemPath()
void registerDebugValues(final ServerLevel level, final DebugValueSource.Registration registration)
String get()

Fields & Constants (8)

TYPE_CODEC
LOGGER
type
level
worldPosition
remove
blockState
components

String literals (8)

"Invalid block entity "
" state at "
", got "
"components"
"Cached block"
"Block location"
" (world missing)"
"Actual block"

Full Source

BlockEntity.java345 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.block.entity;
2
3
import com.mojang.logging.LogUtils;
4
import com.mojang.serialization.Codec;
5
import java.util.HashSet;
6
import java.util.Set;
7
import net.fabricmc.fabric.api.attachment.v1.AttachmentTarget;
8
import net.fabricmc.fabric.api.blockgetter.v2.RenderDataBlockEntity;
9
import net.minecraft.CrashReportCategory;
10
import net.minecraft.core.BlockPos;
11
import net.minecraft.core.Holder;
12
import net.minecraft.core.HolderLookup;
13
import net.minecraft.core.SectionPos;
14
import net.minecraft.core.TypedInstance;
15
import net.minecraft.core.component.DataComponentGetter;
16
import net.minecraft.core.component.DataComponentMap;
17
import net.minecraft.core.component.DataComponentPatch;
18
import net.minecraft.core.component.DataComponentType;
19
import net.minecraft.core.component.DataComponents;
20
import net.minecraft.core.component.PatchedDataComponentMap;
21
import net.minecraft.core.registries.BuiltInRegistries;
22
import net.minecraft.nbt.CompoundTag;
23
import net.minecraft.network.chat.Component;
24
import net.minecraft.network.chat.ComponentSerialization;
25
import net.minecraft.network.protocol.Packet;
26
import net.minecraft.network.protocol.game.ClientGamePacketListener;
27
import net.minecraft.server.level.ServerLevel;
28
import net.minecraft.util.ProblemReporter;
29
import net.minecraft.util.debug.DebugValueSource;
30
import net.minecraft.world.Container;
31
import net.minecraft.world.Containers;
32
import net.minecraft.world.item.ItemStack;
33
import net.minecraft.world.level.ChunkPos;
34
import net.minecraft.world.level.Level;
35
import net.minecraft.world.level.block.state.BlockState;
36
import net.minecraft.world.level.storage.TagValueInput;
37
import net.minecraft.world.level.storage.TagValueOutput;
38
import net.minecraft.world.level.storage.ValueInput;
39
import net.minecraft.world.level.storage.ValueOutput;
40
import org.jspecify.annotations.Nullable;
41
import org.slf4j.Logger;
42
43
public abstract class BlockEntity implements DebugValueSource, TypedInstance<BlockEntityType<?>>, RenderDataBlockEntity, AttachmentTarget {
44
	private static final Codec<BlockEntityType<?>> TYPE_CODEC = BuiltInRegistries.BLOCK_ENTITY_TYPE.byNameCodec();
45
	private static final Logger LOGGER = LogUtils.getLogger();
46
	private final BlockEntityType<?> type;
47
	protected @Nullable Level level;
48
	protected final BlockPos worldPosition;
49
	protected boolean remove;
50
	private BlockState blockState;
51
	private DataComponentMap components = DataComponentMap.EMPTY;
52
53
	public BlockEntity(final BlockEntityType<?> type, final BlockPos worldPosition, final BlockState blockState) {
54
		this.type = type;
55
		this.worldPosition = worldPosition.immutable();
56
		this.validateBlockState(blockState);
57
		this.blockState = blockState;
58
	}
59
60
	private void validateBlockState(final BlockState blockState) {
61
		if (!this.isValidBlockState(blockState)) {
62
			throw new IllegalStateException("Invalid block entity " + this.getNameForReporting() + " state at " + this.worldPosition + ", got " + blockState);
63
		}
64
	}
65
66
	public boolean isValidBlockState(final BlockState blockState) {
67
		return this.type.isValid(blockState);
68
	}
69
70
	public static BlockPos getPosFromTag(final ChunkPos base, final CompoundTag entityTag) {
71
		int x = entityTag.getIntOr("x", 0);
72
		int y = entityTag.getIntOr("y", 0);
73
		int z = entityTag.getIntOr("z", 0);
74
		int sectionX = SectionPos.blockToSectionCoord(x);
75
		int sectionZ = SectionPos.blockToSectionCoord(z);
76
		if (sectionX != base.x() || sectionZ != base.z()) {
77
			LOGGER.warn("Block entity {} found in a wrong chunk, expected position from chunk {}", entityTag, base);
78
			x = base.getBlockX(SectionPos.sectionRelative(x));
79
			z = base.getBlockZ(SectionPos.sectionRelative(z));
80
		}
81
82
		return new BlockPos(x, y, z);
83
	}
84
85
	public @Nullable Level getLevel() {
86
		return this.level;
87
	}
88
89
	public void setLevel(final Level level) {
90
		this.level = level;
91
	}
92
93
	public boolean hasLevel() {
94
		return this.level != null;
95
	}
96
97
	protected void loadAdditional(final ValueInput input) {
98
	}
99
100
	public final void loadWithComponents(final ValueInput input) {
101
		this.loadAdditional(input);
102
		this.components = input.read("components", DataComponentMap.CODEC).orElse(DataComponentMap.EMPTY);
103
	}
104
105
	public final void loadCustomOnly(final ValueInput input) {
106
		this.loadAdditional(input);
107
	}
108
109
	protected void saveAdditional(final ValueOutput output) {
110
	}
111
112
	public final CompoundTag saveWithFullMetadata(final HolderLookup.Provider registries) {
113
		try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(this.problemPath(), LOGGER)) {
114
			TagValueOutput output = TagValueOutput.createWithContext(reporter, registries);
115
			this.saveWithFullMetadata(output);
116
			return output.buildResult();
117
		}
118
	}
119
120
	public void saveWithFullMetadata(final ValueOutput output) {
121
		this.saveWithoutMetadata(output);
122
		this.saveMetadata(output);
123
	}
124
125
	public void saveWithId(final ValueOutput output) {
126
		this.saveWithoutMetadata(output);
127
		this.saveId(output);
128
	}
129
130
	public final CompoundTag saveWithoutMetadata(final HolderLookup.Provider registries) {
131
		try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(this.problemPath(), LOGGER)) {
132
			TagValueOutput output = TagValueOutput.createWithContext(reporter, registries);
133
			this.saveWithoutMetadata(output);
134
			return output.buildResult();
135
		}
136
	}
137
138
	public void saveWithoutMetadata(final ValueOutput output) {
139
		this.saveAdditional(output);
140
		output.store("components", DataComponentMap.CODEC, this.components);
141
	}
142
143
	public final CompoundTag saveCustomOnly(final HolderLookup.Provider registries) {
144
		try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(this.problemPath(), LOGGER)) {
145
			TagValueOutput output = TagValueOutput.createWithContext(reporter, registries);
146
			this.saveCustomOnly(output);
147
			return output.buildResult();
148
		}
149
	}
150
151
	public void saveCustomOnly(final ValueOutput output) {
152
		this.saveAdditional(output);
153
	}
154
155
	private void saveId(final ValueOutput output) {
156
		addEntityType(output, this.getType());
157
	}
158
159
	public static void addEntityType(final ValueOutput output, final BlockEntityType<?> type) {
160
		output.store("id", TYPE_CODEC, type);
161
	}
162
163
	private void saveMetadata(final ValueOutput output) {
164
		this.saveId(output);
165
		output.putInt("x", this.worldPosition.getX());
166
		output.putInt("y", this.worldPosition.getY());
167
		output.putInt("z", this.worldPosition.getZ());
168
	}
169
170
	public static @Nullable BlockEntity loadStatic(final BlockPos pos, final BlockState state, final CompoundTag tag, final HolderLookup.Provider registries) {
171
		BlockEntityType<?> type = tag.read("id", TYPE_CODEC).orElse(null);
172
		if (type == null) {
173
			LOGGER.error("Skipping block entity with invalid type: {}", tag.get("id"));
174
			return null;
175
		}
176
177
		BlockEntity entity;
178
		try {
179
			entity = type.create(pos, state);
180
		} catch (Throwable t) {
181
			LOGGER.error("Failed to create block entity {} for block {} at position {} ", type, state, pos, t);
182
			return null;
183
		}
184
185
		try (ProblemReporter.ScopedCollector reporter = new ProblemReporter.ScopedCollector(entity.problemPath(), LOGGER)) {
186
			entity.loadWithComponents(TagValueInput.create(reporter, registries, tag));
187
			return entity;
188
		} catch (Throwable t) {
189
			LOGGER.error("Failed to load data for block entity {} for block {} at position {}", type, state, pos, t);
190
			return null;
191
		}
192
	}
193
194
	public void setChanged() {
195
		if (this.level != null) {
196
			setChanged(this.level, this.worldPosition, this.blockState);
197
		}
198
	}
199
200
	protected static void setChanged(final Level level, final BlockPos worldPosition, final BlockState blockState) {
201
		level.blockEntityChanged(worldPosition);
202
		if (!blockState.isAir()) {
203
			level.updateNeighbourForOutputSignal(worldPosition, blockState.getBlock());
204
		}
205
	}
206
207
	public BlockPos getBlockPos() {
208
		return this.worldPosition;
209
	}
210
211
	public BlockState getBlockState() {
212
		return this.blockState;
213
	}
214
215
	public @Nullable Packet<ClientGamePacketListener> getUpdatePacket() {
216
		return null;
217
	}
218
219
	public CompoundTag getUpdateTag(final HolderLookup.Provider registries) {
220
		return new CompoundTag();
221
	}
222
223
	public boolean isRemoved() {
224
		return this.remove;
225
	}
226
227
	public void setRemoved() {
228
		this.remove = true;
229
	}
230
231
	public void clearRemoved() {
232
		this.remove = false;
233
	}
234
235
	public void preRemoveSideEffects(final BlockPos pos, final BlockState state) {
236
		if (this instanceof Container container && this.level != null) {
237
			Containers.dropContents(this.level, pos, container);
238
		}
239
	}
240
241
	public boolean triggerEvent(final int b0, final int b1) {
242
		return false;
243
	}
244
245
	public void fillCrashReportCategory(final CrashReportCategory category) {
246
		category.setDetail("Name", this::getNameForReporting);
247
		category.setDetail("Cached block", this.getBlockState()::toString);
248
		if (this.level == null) {
249
			category.setDetail("Block location", () -> this.worldPosition + " (world missing)");
250
		} else {
251
			category.setDetail("Actual block", this.level.getBlockState(this.worldPosition)::toString);
252
			CrashReportCategory.populateBlockLocationDetails(category, this.level, this.worldPosition);
253
		}
254
	}
255
256
	public String getNameForReporting() {
257
		return this.typeHolder().getRegisteredName() + " // " + this.getClass().getCanonicalName();
258
	}
259
260
	public BlockEntityType<?> getType() {
261
		return this.type;
262
	}
263
264
	@Override
265
	public Holder<BlockEntityType<?>> typeHolder() {
266
		return this.type.builtInRegistryHolder();
267
	}
268
269
	@Deprecated
270
	public void setBlockState(final BlockState blockState) {
271
		this.validateBlockState(blockState);
272
		this.blockState = blockState;
273
	}
274
275
	protected void applyImplicitComponents(final DataComponentGetter components) {
276
	}
277
278
	public final void applyComponentsFromItemStack(final ItemStack stack) {
279
		this.applyComponents(stack.getPrototype(), stack.getComponentsPatch());
280
	}
281
282
	public final void applyComponents(final DataComponentMap prototype, final DataComponentPatch patch) {
283
		final Set<DataComponentType<?>> implicitComponents = new HashSet<>();
284
		implicitComponents.add(DataComponents.BLOCK_ENTITY_DATA);
285
		implicitComponents.add(DataComponents.BLOCK_STATE);
286
		final DataComponentMap fullView = PatchedDataComponentMap.fromPatch(prototype, patch);
287
		this.applyImplicitComponents(new DataComponentGetter() {
288
			@Override
289
			public <T> @Nullable T get(final DataComponentType<? extends T> type) {
290
				implicitComponents.add(type);
291
				return fullView.get(type);
292
			}
293
294
			@Override
295
			public <T> T getOrDefault(final DataComponentType<? extends T> type, final T defaultValue) {
296
				implicitComponents.add(type);
297
				return fullView.getOrDefault(type, defaultValue);
298
			}
299
		});
300
		DataComponentPatch newPatch = patch.forget(implicitComponents::contains);
301
		this.components = newPatch.split().added();
302
	}
303
304
	protected void collectImplicitComponents(final DataComponentMap.Builder components) {
305
	}
306
307
	@Deprecated
308
	public void removeComponentsFromTag(final ValueOutput output) {
309
	}
310
311
	public final DataComponentMap collectComponents() {
312
		DataComponentMap.Builder result = DataComponentMap.builder();
313
		result.addAll(this.components);
314
		this.collectImplicitComponents(result);
315
		return result.build();
316
	}
317
318
	public DataComponentMap components() {
319
		return this.components;
320
	}
321
322
	public void setComponents(final DataComponentMap components) {
323
		this.components = components;
324
	}
325
326
	public static @Nullable Component parseCustomNameSafe(final ValueInput input, final String name) {
327
		return input.read(name, ComponentSerialization.CODEC).orElse(null);
328
	}
329
330
	public ProblemReporter.PathElement problemPath() {
331
		return new BlockEntity.BlockEntityPathElement(this);
332
	}
333
334
	@Override
335
	public void registerDebugValues(final ServerLevel level, final DebugValueSource.Registration registration) {
336
	}
337
338
	private record BlockEntityPathElement(BlockEntity blockEntity) implements ProblemReporter.PathElement {
339
		@Override
340
		public String get() {
341
			return this.blockEntity.getNameForReporting() + "@" + this.blockEntity.getBlockPos();
342
		}
343
	}
344
}
345

Decompiled Minecraft 26.3 source of BlockEntity (net/minecraft/world/level/block/entity/BlockEntity.java) with Mojang official mappings, stored verbatim on the site.