StructureCheck .java

net.minecraft.world.level.levelgen.structure.StructureCheck (class): members: MAX_CHUNKS_WITHOUT_STORED_STARTS, chunksWithoutStartsInStorage, NO_STRUCTURE.

net.minecraft.world.level.levelgen.structureclass244 linescommon9.5 KB

API Surface (3)

StructureCheckResult checkStart(final ChunkPos pos, final Structure structure, final StructurePlacement placement, final boolean requireUnreferenced)
void onStructureLoad(final ChunkPos pos, final Map<Structure, StructureStart> starts)
void incrementReference(final ChunkPos chunkPos, final Structure structure)

Fields & Constants (17)

LOGGER
NO_STRUCTURE
MAX_CHUNKS_WITHOUT_STORED_STARTS
storageAccess
registryAccess
structureTemplateManager
dimension
chunkGenerator
randomState
heightAccessor
climateSampler
biomeSource
seed
fixerUpper
loadedChunks
featureChecks
chunksWithoutStartsInStorage

String literals (8)

"DataVersion"
"Level"
"Structures"
"Starts"
"structures"
"starts"
"INVALID"
"references"

Full Source

StructureCheck.java244 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.levelgen.structure;
2
3
import com.mojang.datafixers.DataFixer;
4
import com.mojang.logging.LogUtils;
5
import it.unimi.dsi.fastutil.longs.Long2BooleanMap;
6
import it.unimi.dsi.fastutil.longs.Long2BooleanOpenHashMap;
7
import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
8
import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
9
import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
10
import it.unimi.dsi.fastutil.longs.LongSet;
11
import it.unimi.dsi.fastutil.objects.Object2IntMap;
12
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
13
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
14
import java.util.HashMap;
15
import java.util.Map;
16
import java.util.Optional;
17
import net.minecraft.core.Registry;
18
import net.minecraft.core.RegistryAccess;
19
import net.minecraft.core.registries.Registries;
20
import net.minecraft.nbt.CompoundTag;
21
import net.minecraft.nbt.IntTag;
22
import net.minecraft.nbt.NbtUtils;
23
import net.minecraft.nbt.visitors.CollectFields;
24
import net.minecraft.nbt.visitors.FieldSelector;
25
import net.minecraft.resources.Identifier;
26
import net.minecraft.resources.ResourceKey;
27
import net.minecraft.server.level.ChunkMap;
28
import net.minecraft.util.datafix.DataFixTypes;
29
import net.minecraft.world.level.ChunkPos;
30
import net.minecraft.world.level.Level;
31
import net.minecraft.world.level.LevelHeightAccessor;
32
import net.minecraft.world.level.biome.BiomeSource;
33
import net.minecraft.world.level.biome.Climate;
34
import net.minecraft.world.level.chunk.ChunkGenerator;
35
import net.minecraft.world.level.chunk.storage.ChunkScanAccess;
36
import net.minecraft.world.level.chunk.storage.SimpleRegionStorage;
37
import net.minecraft.world.level.levelgen.RandomState;
38
import net.minecraft.world.level.levelgen.densityfunction.SamplerContext;
39
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
40
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
41
import org.jspecify.annotations.Nullable;
42
import org.slf4j.Logger;
43
44
public class StructureCheck {
45
	private static final Logger LOGGER = LogUtils.getLogger();
46
	private static final int NO_STRUCTURE = -1;
47
	private static final int MAX_CHUNKS_WITHOUT_STORED_STARTS = 131072;
48
	private final ChunkScanAccess storageAccess;
49
	private final RegistryAccess registryAccess;
50
	private final StructureTemplateManager structureTemplateManager;
51
	private final ResourceKey<Level> dimension;
52
	private final ChunkGenerator chunkGenerator;
53
	private final RandomState randomState;
54
	private final LevelHeightAccessor heightAccessor;
55
	private final Climate.Sampler climateSampler;
56
	private final BiomeSource biomeSource;
57
	private final long seed;
58
	private final DataFixer fixerUpper;
59
	private final Long2ObjectMap<Object2IntMap<Structure>> loadedChunks = new Long2ObjectOpenHashMap<>();
60
	private final Map<Structure, Long2BooleanMap> featureChecks = new HashMap<>();
61
	private final LongSet chunksWithoutStartsInStorage = new LongOpenHashSet();
62
63
	public StructureCheck(
64
		final ChunkScanAccess storageAccess,
65
		final RegistryAccess registryAccess,
66
		final StructureTemplateManager structureTemplateManager,
67
		final ResourceKey<Level> dimension,
68
		final ChunkGenerator chunkGenerator,
69
		final RandomState randomState,
70
		final LevelHeightAccessor heightAccessor,
71
		final BiomeSource biomeSource,
72
		final long seed,
73
		final DataFixer fixerUpper
74
	) {
75
		this.storageAccess = storageAccess;
76
		this.registryAccess = registryAccess;
77
		this.structureTemplateManager = structureTemplateManager;
78
		this.dimension = dimension;
79
		this.chunkGenerator = chunkGenerator;
80
		this.randomState = randomState;
81
		this.heightAccessor = heightAccessor;
82
		this.biomeSource = biomeSource;
83
		this.climateSampler = randomState.createClimateSampler(SamplerContext.builder().enableCaches().build());
84
		this.seed = seed;
85
		this.fixerUpper = fixerUpper;
86
	}
87
88
	public StructureCheckResult checkStart(final ChunkPos pos, final Structure structure, final StructurePlacement placement, final boolean requireUnreferenced) {
89
		long posKey = pos.pack();
90
		Object2IntMap<Structure> cachedResult = this.loadedChunks.get(posKey);
91
		if (cachedResult != null) {
92
			return this.checkStructureInfo(cachedResult, structure, requireUnreferenced);
93
		}
94
95
		if (!this.chunksWithoutStartsInStorage.contains(posKey)) {
96
			StructureCheckResult storageCheckResult = this.tryLoadFromStorage(pos, structure, requireUnreferenced);
97
			if (storageCheckResult != null) {
98
				return storageCheckResult;
99
			}
100
101
			if (this.chunksWithoutStartsInStorage.size() >= 131072) {
102
				this.chunksWithoutStartsInStorage.clear();
103
			}
104
105
			this.chunksWithoutStartsInStorage.add(posKey);
106
		}
107
108
		if (!placement.applyAdditionalChunkRestrictions(pos.x(), pos.z(), this.seed)) {
109
			return StructureCheckResult.START_NOT_PRESENT;
110
		}
111
112
		boolean isFeatureChunk = this.featureChecks
113
			.computeIfAbsent(structure, k -> new Long2BooleanOpenHashMap())
114
			.computeIfAbsent(posKey, k -> this.canCreateStructure(pos, structure));
115
		return !isFeatureChunk ? StructureCheckResult.START_NOT_PRESENT : StructureCheckResult.CHUNK_LOAD_NEEDED;
116
	}
117
118
	private boolean canCreateStructure(final ChunkPos pos, final Structure structure) {
119
		return structure.findValidGenerationPoint(
120
				new Structure.GenerationContext(
121
					this.registryAccess,
122
					this.chunkGenerator,
123
					this.biomeSource,
124
					this.climateSampler,
125
					this.randomState,
126
					this.structureTemplateManager,
127
					this.seed,
128
					pos,
129
					this.heightAccessor,
130
					structure.biomes()::contains
131
				)
132
			)
133
			.isPresent();
134
	}
135
136
	private @Nullable StructureCheckResult tryLoadFromStorage(final ChunkPos pos, final Structure structure, final boolean requireUnreferenced) {
137
		CollectFields collectFields = new CollectFields(
138
			new FieldSelector(IntTag.TYPE, "DataVersion"),
139
			new FieldSelector("Level", "Structures", CompoundTag.TYPE, "Starts"),
140
			new FieldSelector("structures", CompoundTag.TYPE, "starts")
141
		);
142
143
		try {
144
			this.storageAccess.scanChunk(pos, collectFields).join();
145
		} catch (Exception e) {
146
			LOGGER.warn("Failed to read chunk {}", pos, e);
147
			return StructureCheckResult.CHUNK_LOAD_NEEDED;
148
		}
149
150
		if (collectFields.getResult() instanceof CompoundTag chunkTag) {
151
			int version = NbtUtils.getDataVersion(chunkTag);
152
			SimpleRegionStorage.injectDatafixingContext(chunkTag, ChunkMap.getChunkDataFixContextTag(this.dimension, this.chunkGenerator.getTypeNameForDataFixer()));
153
154
			CompoundTag fixedChunkTag;
155
			try {
156
				fixedChunkTag = DataFixTypes.CHUNK.updateToCurrentVersion(this.fixerUpper, chunkTag, version);
157
			} catch (Exception e) {
158
				LOGGER.warn("Failed to partially datafix chunk {}", pos, e);
159
				return StructureCheckResult.CHUNK_LOAD_NEEDED;
160
			}
161
162
			Object2IntMap<Structure> knownStarts = this.loadStructures(fixedChunkTag);
163
			if (knownStarts == null) {
164
				return null;
165
			}
166
167
			this.storeFullResults(pos.pack(), knownStarts);
168
			return this.checkStructureInfo(knownStarts, structure, requireUnreferenced);
169
		} else {
170
			return null;
171
		}
172
	}
173
174
	private @Nullable Object2IntMap<Structure> loadStructures(final CompoundTag chunkTag) {
175
		Optional<CompoundTag> maybeStartsTag = chunkTag.getCompound("structures").flatMap(tag -> tag.getCompound("starts"));
176
		if (maybeStartsTag.isEmpty()) {
177
			return null;
178
		}
179
180
		CompoundTag startsTag = maybeStartsTag.get();
181
		if (startsTag.isEmpty()) {
182
			return Object2IntMaps.emptyMap();
183
		}
184
185
		Object2IntMap<Structure> knownStarts = new Object2IntOpenHashMap<>();
186
		Registry<Structure> structuresRegistry = this.registryAccess.lookupOrThrow(Registries.STRUCTURE);
187
		startsTag.forEach((key, tag) -> {
188
			Identifier id = Identifier.tryParse(key);
189
			if (id != null) {
190
				Structure foundFeature = structuresRegistry.getValue(id);
191
				if (foundFeature != null) {
192
					tag.asCompound().ifPresent(structureData -> {
193
						String pieceId = structureData.getStringOr("id", "");
194
						if (!"INVALID".equals(pieceId)) {
195
							int referenceCount = structureData.getIntOr("references", 0);
196
							knownStarts.put(foundFeature, referenceCount);
197
						}
198
					});
199
				}
200
			}
201
		});
202
		return knownStarts;
203
	}
204
205
	private static Object2IntMap<Structure> deduplicateEmptyMap(final Object2IntMap<Structure> map) {
206
		return map.isEmpty() ? Object2IntMaps.emptyMap() : map;
207
	}
208
209
	private StructureCheckResult checkStructureInfo(final Object2IntMap<Structure> cachedResult, final Structure structure, final boolean requireUnreferenced) {
210
		int referenceCount = cachedResult.getOrDefault(structure, -1);
211
		return referenceCount == -1 || requireUnreferenced && referenceCount != 0 ? StructureCheckResult.START_NOT_PRESENT : StructureCheckResult.START_PRESENT;
212
	}
213
214
	public void onStructureLoad(final ChunkPos pos, final Map<Structure, StructureStart> starts) {
215
		long posKey = pos.pack();
216
		Object2IntMap<Structure> startsToReferences = new Object2IntOpenHashMap<>();
217
		starts.forEach((structure, structureStart) -> {
218
			if (structureStart.isValid()) {
219
				startsToReferences.put(structure, structureStart.getReferences());
220
			}
221
		});
222
		this.storeFullResults(posKey, startsToReferences);
223
	}
224
225
	private void storeFullResults(final long posKey, final Object2IntMap<Structure> starts) {
226
		this.loadedChunks.put(posKey, deduplicateEmptyMap(starts));
227
		this.featureChecks.values().forEach(m -> m.remove(posKey));
228
		this.chunksWithoutStartsInStorage.remove(posKey);
229
	}
230
231
	public void incrementReference(final ChunkPos chunkPos, final Structure structure) {
232
		long posKey = chunkPos.pack();
233
		this.loadedChunks.compute(posKey, (key, counts) -> {
234
			if (counts == null || counts.isEmpty()) {
235
				counts = new Object2IntOpenHashMap<>();
236
			}
237
238
			counts.computeInt(structure, (k, value) -> value == null ? 1 : value + 1);
239
			return counts;
240
		});
241
		this.chunksWithoutStartsInStorage.remove(posKey);
242
	}
243
}
244

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