ChunkGenerator .java

net.minecraft.world.level.chunk.ChunkGenerator (class): members: getBiomeGenerationSettings, generationSettingsGetter, getTypeNameForDataFixer, getMobsAt.

net.minecraft.world.level.chunkclass683 linescommon27.6 KB

API Surface (15)

void validate()
ChunkPos getOrigin(final RandomState randomState)
ChunkGeneratorStructureState createState(final HolderLookup<StructureSet> structureSets, final RandomState randomState, final long legacyLevelSeed)
Optional<Identifier> getTypeNameForDataFixer()
CompletableFuture<ChunkAccess> createBiomes(final RandomState randomState, final Blender blender, final StructureManager structureManager, final ChunkAccess protoChunk)
BiomeResolver decorateBiomeResolver(final Blender blender, final ChunkAccess protoChunk, final BiomeResolver biomeResolver)
void applyBiomeDecoration(final WorldGenLevel level, final ChunkAccess chunk, final StructureManager structureManager)
int getSpawnHeight(final LevelHeightAccessor heightAccessor)
BiomeSource getBiomeSource()
WeightedList<MobSpawnSettings.SpawnerData> getMobsAt(final Level level, final StructureManager structureManager, final MobCategory mobCategory, final BlockPos pos)
void createStructures(final RegistryAccess registryAccess, final ChunkGeneratorStructureState state, final StructureManager structureManager, final ChunkAccess centerChunk, final StructureTemplateManager structureTemplateManager, final ResourceKey<Level> level)
void createReferences(final WorldGenLevel level, final StructureManager structureManager, final ChunkAccess centerChunk)
int getFirstFreeHeight(final int x, final int z, final Heightmap.Types type, final LevelHeightAccessor heightAccessor, final RandomState randomState)
int getFirstOccupiedHeight(final int x, final int z, final Heightmap.Types type, final LevelHeightAccessor heightAccessor, final RandomState randomState)
BiomeGenerationSettings getBiomeGenerationSettings(final Holder<Biome> biome)

Fields & Constants (28)

CODEC
biomeSource
featuresPerStep
generationSettingsGetter
structureManager
maxSearchRadius
structures
level
pos
createReference
chunkOriginX
chunkOriginZ
radius
seed
config
mobCategory
registryAccess
state
centerChunk
structureTemplateManager
selected
randomState
sourceChunkPos
chunk
blender

…and 3 more (see full source).

String literals (13)

"createBiomes"
"Feature placement"
"Feature"
"Description"
"Biome decoration"
"Generation"
"CenterX"
"CenterZ"
"Decoration Seed"
"Generating structure reference"
"Structure"
"UNKNOWN"
"Class"

Code Graph: Dependencies (63)

Edges (calls / imports / inherits / references) resolved by graphify from the AST. Every chip opens the class source.

Full Source

ChunkGenerator.java683 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level.chunk;
2
3
import com.google.common.base.Suppliers;
4
import com.mojang.datafixers.util.Pair;
5
import com.mojang.serialization.Codec;
6
import com.mojang.serialization.MapCodec;
7
import it.unimi.dsi.fastutil.ints.IntArraySet;
8
import it.unimi.dsi.fastutil.ints.IntSet;
9
import it.unimi.dsi.fastutil.longs.LongSet;
10
import it.unimi.dsi.fastutil.objects.Object2ObjectArrayMap;
11
import it.unimi.dsi.fastutil.objects.ObjectArraySet;
12
import java.util.ArrayList;
13
import java.util.Arrays;
14
import java.util.Collections;
15
import java.util.List;
16
import java.util.Map;
17
import java.util.Optional;
18
import java.util.Set;
19
import java.util.Map.Entry;
20
import java.util.concurrent.CompletableFuture;
21
import java.util.function.Function;
22
import java.util.function.Predicate;
23
import java.util.function.Supplier;
24
import java.util.stream.Collectors;
25
import net.minecraft.CrashReport;
26
import net.minecraft.CrashReportCategory;
27
import net.minecraft.ReportedException;
28
import net.minecraft.SharedConstants;
29
import net.minecraft.core.BlockPos;
30
import net.minecraft.core.Holder;
31
import net.minecraft.core.HolderLookup;
32
import net.minecraft.core.HolderSet;
33
import net.minecraft.core.QuartPos;
34
import net.minecraft.core.Registry;
35
import net.minecraft.core.RegistryAccess;
36
import net.minecraft.core.SectionPos;
37
import net.minecraft.core.registries.BuiltInRegistries;
38
import net.minecraft.core.registries.Registries;
39
import net.minecraft.resources.Identifier;
40
import net.minecraft.resources.ResourceKey;
41
import net.minecraft.server.level.ServerLevel;
42
import net.minecraft.server.level.WorldGenRegion;
43
import net.minecraft.util.Util;
44
import net.minecraft.util.random.WeightedList;
45
import net.minecraft.world.attribute.EnvironmentAttributes;
46
import net.minecraft.world.entity.MobCategory;
47
import net.minecraft.world.level.ChunkPos;
48
import net.minecraft.world.level.Level;
49
import net.minecraft.world.level.LevelHeightAccessor;
50
import net.minecraft.world.level.LevelReader;
51
import net.minecraft.world.level.NoiseColumn;
52
import net.minecraft.world.level.StructureManager;
53
import net.minecraft.world.level.WorldGenLevel;
54
import net.minecraft.world.level.biome.Biome;
55
import net.minecraft.world.level.biome.BiomeGenerationSettings;
56
import net.minecraft.world.level.biome.BiomeManager;
57
import net.minecraft.world.level.biome.BiomeResolver;
58
import net.minecraft.world.level.biome.BiomeSource;
59
import net.minecraft.world.level.biome.Climate;
60
import net.minecraft.world.level.biome.FeatureSorter;
61
import net.minecraft.world.level.biome.MobSpawnSettings;
62
import net.minecraft.world.level.chunk.status.ChunkStatus;
63
import net.minecraft.world.level.levelgen.GenerationStep;
64
import net.minecraft.world.level.levelgen.Heightmap;
65
import net.minecraft.world.level.levelgen.LegacyRandomSource;
66
import net.minecraft.world.level.levelgen.RandomState;
67
import net.minecraft.world.level.levelgen.RandomSupport;
68
import net.minecraft.world.level.levelgen.WorldgenRandom;
69
import net.minecraft.world.level.levelgen.XoroshiroRandomSource;
70
import net.minecraft.world.level.levelgen.blending.Blender;
71
import net.minecraft.world.level.levelgen.densityfunction.DensityBufferPool;
72
import net.minecraft.world.level.levelgen.densityfunction.SamplerContext;
73
import net.minecraft.world.level.levelgen.feature.FeatureCountTracker;
74
import net.minecraft.world.level.levelgen.placement.FeaturePlacer;
75
import net.minecraft.world.level.levelgen.placement.PlacedFeature;
76
import net.minecraft.world.level.levelgen.structure.BoundingBox;
77
import net.minecraft.world.level.levelgen.structure.Structure;
78
import net.minecraft.world.level.levelgen.structure.StructureCheckResult;
79
import net.minecraft.world.level.levelgen.structure.StructureSet;
80
import net.minecraft.world.level.levelgen.structure.StructureSpawnOverride;
81
import net.minecraft.world.level.levelgen.structure.StructureStart;
82
import net.minecraft.world.level.levelgen.structure.placement.ConcentricRingsStructurePlacement;
83
import net.minecraft.world.level.levelgen.structure.placement.RandomSpreadStructurePlacement;
84
import net.minecraft.world.level.levelgen.structure.placement.StructurePlacement;
85
import net.minecraft.world.level.levelgen.structure.templatesystem.StructureTemplateManager;
86
import org.apache.commons.lang3.mutable.MutableBoolean;
87
import org.jspecify.annotations.Nullable;
88
89
public abstract class ChunkGenerator {
90
	public static final Codec<ChunkGenerator> CODEC = BuiltInRegistries.CHUNK_GENERATOR.byNameCodec().dispatchStable(ChunkGenerator::codec, Function.identity());
91
	protected final BiomeSource biomeSource;
92
	private final Supplier<List<FeatureSorter.StepFeatureData>> featuresPerStep;
93
	private final Function<Holder<Biome>, BiomeGenerationSettings> generationSettingsGetter;
94
95
	public ChunkGenerator(final BiomeSource biomeSource) {
96
		this(biomeSource, biome -> biome.value().getGenerationSettings());
97
	}
98
99
	public ChunkGenerator(final BiomeSource biomeSource, final Function<Holder<Biome>, BiomeGenerationSettings> generationSettingsGetter) {
100
		this.biomeSource = biomeSource;
101
		this.generationSettingsGetter = generationSettingsGetter;
102
		this.featuresPerStep = Suppliers.memoize(
103
			() -> FeatureSorter.buildFeaturesPerStep(List.copyOf(biomeSource.possibleBiomes()), b -> generationSettingsGetter.apply(b).features(), true)
104
		);
105
	}
106
107
	public void validate() {
108
		this.featuresPerStep.get();
109
	}
110
111
	public ChunkPos getOrigin(final RandomState randomState) {
112
		return ChunkPos.ZERO;
113
	}
114
115
	protected abstract MapCodec<? extends ChunkGenerator> codec();
116
117
	public ChunkGeneratorStructureState createState(final HolderLookup<StructureSet> structureSets, final RandomState randomState, final long legacyLevelSeed) {
118
		return ChunkGeneratorStructureState.createForNormal(randomState, legacyLevelSeed, this.getOrigin(randomState), this.biomeSource, structureSets);
119
	}
120
121
	public Optional<Identifier> getTypeNameForDataFixer() {
122
		return BuiltInRegistries.CHUNK_GENERATOR.getResourceKey(this.codec()).map(ResourceKey::identifier);
123
	}
124
125
	public CompletableFuture<ChunkAccess> createBiomes(
126
		final RandomState randomState, final Blender blender, final StructureManager structureManager, final ChunkAccess protoChunk
127
	) {
128
		return CompletableFuture.supplyAsync(() -> {
129
			this.doCreateBiomes(blender, randomState, protoChunk);
130
			return protoChunk;
131
		}, Util.backgroundExecutor().forName("createBiomes"));
132
	}
133
134
	private void doCreateBiomes(final Blender blender, final RandomState randomState, final ChunkAccess protoChunk) {
135
		DensityBufferPool bufferPool = randomState.acquireDensityBufferPool();
136
137
		try {
138
			Climate.Sampler climateSampler = randomState.createClimateSampler(SamplerContext.builder().enableCaches().useBufferArena(bufferPool).build());
139
			ChunkPos pos = protoChunk.getPos();
140
			BiomeResolver biomeResolver = this.biomeSource
141
				.createResolverForChunk(
142
					climateSampler,
143
					QuartPos.fromBlock(pos.getMinBlockX()),
144
					QuartPos.fromBlock(protoChunk.getMinY()),
145
					QuartPos.fromBlock(pos.getMinBlockZ()),
146
					QuartPos.fromBlock(16),
147
					QuartPos.fromBlock(protoChunk.getHeight()),
148
					QuartPos.fromBlock(16)
149
				);
150
			protoChunk.fillBiomesFromNoise(this.decorateBiomeResolver(blender, protoChunk, biomeResolver));
151
		} finally {
152
			randomState.releaseDensityBufferPool(bufferPool);
153
		}
154
	}
155
156
	protected BiomeResolver decorateBiomeResolver(final Blender blender, final ChunkAccess protoChunk, final BiomeResolver biomeResolver) {
157
		return biomeResolver;
158
	}
159
160
	public @Nullable Pair<BlockPos, Holder<Structure>> findNearestMapStructure(
161
		final ServerLevel level, final HolderSet<Structure> wantedStructures, final BlockPos pos, final int maxSearchRadius, final boolean createReference
162
	) {
163
		if (SharedConstants.DEBUG_DISABLE_FEATURES) {
164
			return null;
165
		}
166
167
		if (!level.getServer().getWorldGenSettings().options().generateStructures()) {
168
			return null;
169
		}
170
171
		ChunkGeneratorStructureState generatorState = level.getChunkSource().getGeneratorState();
172
		Map<StructurePlacement, Set<Holder<Structure>>> placementScans = new Object2ObjectArrayMap<>();
173
174
		for (Holder<Structure> structure : wantedStructures) {
175
			for (StructurePlacement placement : generatorState.getPlacementsForStructure(structure)) {
176
				placementScans.computeIfAbsent(placement, p -> new ObjectArraySet<>()).add(structure);
177
			}
178
		}
179
180
		if (placementScans.isEmpty()) {
181
			return null;
182
		}
183
184
		Pair<BlockPos, Holder<Structure>> nearest = null;
185
		double distanceSqr = Double.MAX_VALUE;
186
		StructureManager structureManager = level.structureManager();
187
		List<Entry<StructurePlacement, Set<Holder<Structure>>>> randomSpreadEntries = new ArrayList<>(placementScans.size());
188
189
		for (Entry<StructurePlacement, Set<Holder<Structure>>> entry : placementScans.entrySet()) {
190
			StructurePlacement placement = entry.getKey();
191
			if (placement instanceof ConcentricRingsStructurePlacement rings) {
192
				Pair<BlockPos, Holder<Structure>> generating = this.getNearestGeneratedStructure(entry.getValue(), level, structureManager, pos, createReference, rings);
193
				if (generating != null) {
194
					BlockPos structurePos = generating.getFirst();
195
					double newDistanceSqr = pos.distSqr(structurePos);
196
					if (newDistanceSqr < distanceSqr) {
197
						distanceSqr = newDistanceSqr;
198
						nearest = generating;
199
					}
200
				}
201
			} else if (placement instanceof RandomSpreadStructurePlacement) {
202
				randomSpreadEntries.add(entry);
203
			}
204
		}
205
206
		if (!randomSpreadEntries.isEmpty()) {
207
			int chunkOriginX = SectionPos.blockToSectionCoord(pos.getX());
208
			int chunkOriginZ = SectionPos.blockToSectionCoord(pos.getZ());
209
210
			for (int radius = 0; radius <= maxSearchRadius; radius++) {
211
				boolean foundSomething = false;
212
213
				for (Entry<StructurePlacement, Set<Holder<Structure>>> entry : randomSpreadEntries) {
214
					RandomSpreadStructurePlacement randomPlacement = (RandomSpreadStructurePlacement)entry.getKey();
215
					Pair<BlockPos, Holder<Structure>> structurePos = getNearestGeneratedStructure(
216
						entry.getValue(), level, structureManager, chunkOriginX, chunkOriginZ, radius, createReference, generatorState.getLevelSeed(), randomPlacement
217
					);
218
					if (structurePos != null) {
219
						foundSomething = true;
220
						double newDistanceSqr = pos.distSqr(structurePos.getFirst());
221
						if (newDistanceSqr < distanceSqr) {
222
							distanceSqr = newDistanceSqr;
223
							nearest = structurePos;
224
						}
225
					}
226
				}
227
228
				if (foundSomething) {
229
					return nearest;
230
				}
231
			}
232
		}
233
234
		return nearest;
235
	}
236
237
	private @Nullable Pair<BlockPos, Holder<Structure>> getNearestGeneratedStructure(
238
		final Set<Holder<Structure>> structures,
239
		final ServerLevel level,
240
		final StructureManager structureManager,
241
		final BlockPos pos,
242
		final boolean createReference,
243
		final ConcentricRingsStructurePlacement rings
244
	) {
245
		List<ChunkPos> positions = level.getChunkSource().getGeneratorState().getRingPositionsFor(rings);
246
		if (positions == null) {
247
			throw new IllegalStateException("Somehow tried to find structures for a placement that doesn't exist");
248
		}
249
250
		Pair<BlockPos, Holder<Structure>> closestPos = null;
251
		double closest = Double.MAX_VALUE;
252
		BlockPos.MutableBlockPos structurePos = new BlockPos.MutableBlockPos();
253
254
		for (ChunkPos chunkPos : positions) {
255
			structurePos.set(SectionPos.sectionToBlockCoord(chunkPos.x(), 8), 32, SectionPos.sectionToBlockCoord(chunkPos.z(), 8));
256
			double distSqr = structurePos.distSqr(pos);
257
			boolean isClosest = closestPos == null || distSqr < closest;
258
			if (isClosest) {
259
				Pair<BlockPos, Holder<Structure>> generating = getStructureGeneratingAt(structures, level, structureManager, createReference, rings, chunkPos);
260
				if (generating != null) {
261
					closestPos = generating;
262
					closest = distSqr;
263
				}
264
			}
265
		}
266
267
		return closestPos;
268
	}
269
270
	private static @Nullable Pair<BlockPos, Holder<Structure>> getNearestGeneratedStructure(
271
		final Set<Holder<Structure>> structures,
272
		final LevelReader level,
273
		final StructureManager structureManager,
274
		final int chunkOriginX,
275
		final int chunkOriginZ,
276
		final int radius,
277
		final boolean createReference,
278
		final long seed,
279
		final RandomSpreadStructurePlacement config
280
	) {
281
		int spacing = config.spacing();
282
283
		for (int x = -radius; x <= radius; x++) {
284
			boolean xEdge = x == -radius || x == radius;
285
286
			for (int z = -radius; z <= radius; z++) {
287
				boolean zEdge = z == -radius || z == radius;
288
				if (xEdge || zEdge) {
289
					int sectorX = chunkOriginX + spacing * x;
290
					int sectorZ = chunkOriginZ + spacing * z;
291
					ChunkPos chunkTarget = config.getPotentialStructureChunk(seed, sectorX, sectorZ);
292
					Pair<BlockPos, Holder<Structure>> generating = getStructureGeneratingAt(structures, level, structureManager, createReference, config, chunkTarget);
293
					if (generating != null) {
294
						return generating;
295
					}
296
				}
297
			}
298
		}
299
300
		return null;
301
	}
302
303
	private static @Nullable Pair<BlockPos, Holder<Structure>> getStructureGeneratingAt(
304
		final Set<Holder<Structure>> structures,
305
		final LevelReader level,
306
		final StructureManager structureManager,
307
		final boolean createReference,
308
		final StructurePlacement config,
309
		final ChunkPos chunkTarget
310
	) {
311
		for (Holder<Structure> structure : structures) {
312
			StructureCheckResult fastCheckResult = structureManager.checkStructurePresence(chunkTarget, structure.value(), config, createReference);
313
			if (fastCheckResult != StructureCheckResult.START_NOT_PRESENT) {
314
				if (!createReference && fastCheckResult == StructureCheckResult.START_PRESENT) {
315
					return Pair.of(config.getLocatePos(chunkTarget), structure);
316
				}
317
318
				ChunkAccess chunk = level.getChunk(chunkTarget.x(), chunkTarget.z(), ChunkStatus.STRUCTURE_STARTS);
319
				StructureStart start = structureManager.getStartForStructure(structure.value(), chunk);
320
				if (start != null && start.isValid() && (!createReference || tryAddReference(structureManager, start))) {
321
					return Pair.of(config.getLocatePos(start.getChunkPos()), structure);
322
				}
323
			}
324
		}
325
326
		return null;
327
	}
328
329
	private static boolean tryAddReference(final StructureManager manager, final StructureStart start) {
330
		if (start.canBeReferenced()) {
331
			manager.addReference(start);
332
			return true;
333
		} else {
334
			return false;
335
		}
336
	}
337
338
	public void applyBiomeDecoration(final WorldGenLevel level, final ChunkAccess chunk, final StructureManager structureManager) {
339
		ChunkPos centerPos = chunk.getPos();
340
		if (!SharedConstants.debugVoidTerrain(centerPos)) {
341
			SectionPos sectionPos = SectionPos.of(centerPos, level.getMinSectionY());
342
			BlockPos origin = sectionPos.origin();
343
			Registry<Structure> structuresRegistry = level.registryAccess().lookupOrThrow(Registries.STRUCTURE);
344
			Map<Integer, List<Structure>> structuresByStep = structuresRegistry.stream().collect(Collectors.groupingBy(structure -> structure.step().ordinal()));
345
			List<FeatureSorter.StepFeatureData> featureList = this.featuresPerStep.get();
346
			WorldgenRandom random = new WorldgenRandom(new XoroshiroRandomSource(RandomSupport.generateUniqueSeed()));
347
			long decorationSeed = random.setDecorationSeed(level.getSeed(), origin.getX(), origin.getZ());
348
			Set<Holder<Biome>> possibleBiomes = new ObjectArraySet<>();
349
			ChunkPos.rangeClosed(sectionPos.chunk(), 1).forEach(chunkPos -> {
350
				ChunkAccess chunkInRange = level.getChunk(chunkPos.x(), chunkPos.z());
351
352
				for (LevelChunkSection section : chunkInRange.getSections()) {
353
					section.getBiomes().getAll(possibleBiomes::add);
354
				}
355
			});
356
			possibleBiomes.retainAll(this.biomeSource.possibleBiomes());
357
			int featureStepCount = featureList.size();
358
			FeaturePlacer placer = new FeaturePlacer(level, this);
359
360
			try {
361
				Registry<PlacedFeature> featureRegistry = level.registryAccess().lookupOrThrow(Registries.PLACED_FEATURE);
362
				int generationSteps = Math.max(GenerationStep.Decoration.values().length, featureStepCount);
363
364
				for (int stepIndex = 0; stepIndex < generationSteps; stepIndex++) {
365
					int index = 0;
366
					if (structureManager.shouldGenerateStructures()) {
367
						for (Structure structure : structuresByStep.getOrDefault(stepIndex, Collections.emptyList())) {
368
							random.setFeatureSeed(decorationSeed, index, stepIndex);
369
							Supplier<String> currentlyGenerating = () -> structuresRegistry.getResourceKey(structure).map(Object::toString).orElseGet(structure::toString);
370
371
							try {
372
								level.setCurrentlyGenerating(currentlyGenerating);
373
								structureManager.startsForStructure(sectionPos.x(), sectionPos.z(), structure)
374
									.forEach(start -> start.placeInChunk(level, structureManager, this, random, getWritableArea(chunk), centerPos));
375
							} catch (Exception e) {
376
								CrashReport report = CrashReport.forThrowable(e, "Feature placement");
377
								report.addCategory("Feature").setDetail("Description", currentlyGenerating::get);
378
								throw new ReportedException(report);
379
							}
380
381
							index++;
382
						}
383
					}
384
385
					if (stepIndex < featureStepCount) {
386
						IntSet possibleFeaturesThisStep = new IntArraySet();
387
388
						for (Holder<Biome> biome : possibleBiomes) {
389
							List<HolderSet<PlacedFeature>> featuresInBiome = this.generationSettingsGetter.apply(biome).features();
390
							if (stepIndex < featuresInBiome.size()) {
391
								HolderSet<PlacedFeature> featuresInBiomeThisStep = featuresInBiome.get(stepIndex);
392
								FeatureSorter.StepFeatureData stepFeatureData = featureList.get(stepIndex);
393
								featuresInBiomeThisStep.stream()
394
									.map(Holder::value)
395
									.forEach(featurex -> possibleFeaturesThisStep.add(stepFeatureData.indexMapping().applyAsInt(featurex)));
396
							}
397
						}
398
399
						int numberOfFeaturesInStep = possibleFeaturesThisStep.size();
400
						int[] indexArray = possibleFeaturesThisStep.toIntArray();
401
						Arrays.sort(indexArray);
402
						FeatureSorter.StepFeatureData stepFeatureData = featureList.get(stepIndex);
403
404
						for (int featureIndex = 0; featureIndex < numberOfFeaturesInStep; featureIndex++) {
405
							int globalIndexOfFeature = indexArray[featureIndex];
406
							PlacedFeature feature = stepFeatureData.features().get(globalIndexOfFeature);
407
							Supplier<String> currentlyGenerating = () -> featureRegistry.getResourceKey(feature).map(Object::toString).orElseGet(feature::toString);
408
							random.setFeatureSeed(decorationSeed, globalIndexOfFeature, stepIndex);
409
410
							try {
411
								level.setCurrentlyGenerating(currentlyGenerating);
412
								placer.placeWithBiomeCheck(feature, random, origin);
413
							} catch (Exception e) {
414
								CrashReport report = CrashReport.forThrowable(e, "Feature placement");
415
								report.addCategory("Feature").setDetail("Description", currentlyGenerating::get);
416
								throw new ReportedException(report);
417
							}
418
						}
419
					}
420
				}
421
422
				level.setCurrentlyGenerating(null);
423
				if (SharedConstants.DEBUG_FEATURE_COUNT) {
424
					FeatureCountTracker.chunkDecorated(level.getLevel());
425
				}
426
			} catch (Exception e) {
427
				CrashReport report = CrashReport.forThrowable(e, "Biome decoration");
428
				report.addCategory("Generation").setDetail("CenterX", centerPos.x()).setDetail("CenterZ", centerPos.z()).setDetail("Decoration Seed", decorationSeed);
429
				throw new ReportedException(report);
430
			}
431
		}
432
	}
433
434
	private static BoundingBox getWritableArea(final ChunkAccess chunk) {
435
		ChunkPos chunkPos = chunk.getPos();
436
		int targetBlockX = chunkPos.getMinBlockX();
437
		int targetBlockZ = chunkPos.getMinBlockZ();
438
		LevelHeightAccessor heightAccessor = chunk.getHeightAccessorForGeneration();
439
		int minY = heightAccessor.getMinY() + 1;
440
		int maxY = heightAccessor.getMaxY();
441
		return new BoundingBox(targetBlockX, minY, targetBlockZ, targetBlockX + 15, maxY, targetBlockZ + 15);
442
	}
443
444
	public abstract void spawnOriginalMobs(WorldGenRegion worldGenRegion);
445
446
	public int getSpawnHeight(final LevelHeightAccessor heightAccessor) {
447
		return 64;
448
	}
449
450
	public BiomeSource getBiomeSource() {
451
		return this.biomeSource;
452
	}
453
454
	public abstract int getGenDepth();
455
456
	public WeightedList<MobSpawnSettings.SpawnerData> getMobsAt(
457
		final Level level, final StructureManager structureManager, final MobCategory mobCategory, final BlockPos pos
458
	) {
459
		Map<Structure, LongSet> structures = structureManager.getAllStructuresAt(pos);
460
461
		for (Entry<Structure, LongSet> entry : structures.entrySet()) {
462
			Structure structure = entry.getKey();
463
			StructureSpawnOverride override = structure.spawnOverrides().get(mobCategory);
464
			if (override != null) {
465
				MutableBoolean inOverrideBox = new MutableBoolean(false);
466
				Predicate<StructureStart> check = override.boundingBox() == StructureSpawnOverride.BoundingBoxType.PIECE
467
					? start -> structureManager.structureHasPieceAt(pos, start)
468
					: start -> start.getBoundingBox().isInside(pos);
469
				structureManager.fillStartsForStructure(structure, entry.getValue(), start -> {
470
					if (inOverrideBox.isFalse() && check.test(start)) {
471
						inOverrideBox.setTrue();
472
					}
473
				});
474
				if (inOverrideBox.isTrue()) {
475
					return override.spawns();
476
				}
477
			}
478
		}
479
480
		return level.environmentAttributes().getValue(EnvironmentAttributes.NATURAL_MOB_SPAWNS, pos).getMobsToSpawn(mobCategory);
481
	}
482
483
	public void createStructures(
484
		final RegistryAccess registryAccess,
485
		final ChunkGeneratorStructureState state,
486
		final StructureManager structureManager,
487
		final ChunkAccess centerChunk,
488
		final StructureTemplateManager structureTemplateManager,
489
		final ResourceKey<Level> level
490
	) {
491
		if (!SharedConstants.DEBUG_DISABLE_STRUCTURES) {
492
			ChunkPos sourceChunkPos = centerChunk.getPos();
493
			RandomState randomState = state.randomState();
494
			Climate.Sampler climateSampler = randomState.createClimateSampler(SamplerContext.builder().enableCaches().build());
495
			state.possibleStructureSets()
496
				.forEach(
497
					set -> {
498
						StructurePlacement featurePlacement = set.value().placement();
499
						List<StructureSet.StructureSelectionEntry> structures = set.value().structures();
500
501
						for (StructureSet.StructureSelectionEntry structure : structures) {
502
							StructureStart existingStart = structureManager.getStartForStructure(structure.structure().value(), centerChunk);
503
							if (existingStart != null && existingStart.isValid()) {
504
								return;
505
							}
506
						}
507
508
						if (featurePlacement.isStructureChunk(state, sourceChunkPos.x(), sourceChunkPos.z())) {
509
							if (structures.size() == 1) {
510
								this.tryGenerateStructure(
511
									structures.get(0),
512
									structureManager,
513
									registryAccess,
514
									randomState,
515
									structureTemplateManager,
516
									state.getLevelSeed(),
517
									centerChunk,
518
									sourceChunkPos,
519
									level,
520
									climateSampler
521
								);
522
							} else {
523
								ArrayList<StructureSet.StructureSelectionEntry> options = new ArrayList<>(structures.size());
524
								options.addAll(structures);
525
								WorldgenRandom random = new WorldgenRandom(new LegacyRandomSource(0L));
526
								random.setLargeFeatureSeed(state.getLevelSeed(), sourceChunkPos.x(), sourceChunkPos.z());
527
								int total = 0;
528
529
								for (StructureSet.StructureSelectionEntry option : options) {
530
									total += option.weight();
531
								}
532
533
								while (!options.isEmpty()) {
534
									int choice = random.nextInt(total);
535
									int index = 0;
536
537
									for (StructureSet.StructureSelectionEntry option : options) {
538
										choice -= option.weight();
539
										if (choice < 0) {
540
											break;
541
										}
542
543
										index++;
544
									}
545
546
									StructureSet.StructureSelectionEntry selected = options.get(index);
547
									if (this.tryGenerateStructure(
548
										selected,
549
										structureManager,
550
										registryAccess,
551
										randomState,
552
										structureTemplateManager,
553
										state.getLevelSeed(),
554
										centerChunk,
555
										sourceChunkPos,
556
										level,
557
										climateSampler
558
									)) {
559
										return;
560
									}
561
562
									options.remove(index);
563
									total -= selected.weight();
564
								}
565
							}
566
						}
567
					}
568
				);
569
		}
570
	}
571
572
	private boolean tryGenerateStructure(
573
		final StructureSet.StructureSelectionEntry selected,
574
		final StructureManager structureManager,
575
		final RegistryAccess registryAccess,
576
		final RandomState randomState,
577
		final StructureTemplateManager structureTemplateManager,
578
		final long seed,
579
		final ChunkAccess centerChunk,
580
		final ChunkPos sourceChunkPos,
581
		final ResourceKey<Level> level,
582
		final Climate.Sampler climateSampler
583
	) {
584
		Structure structure = selected.structure().value();
585
		int references = fetchReferences(structureManager, centerChunk, structure);
586
		HolderSet<Biome> biomeAllowedForStructure = structure.biomes();
587
		Predicate<Holder<Biome>> biomePredicate = biomeAllowedForStructure::contains;
588
		StructureStart start = structure.generate(
589
			selected.structure(),
590
			level,
591
			registryAccess,
592
			this,
593
			this.biomeSource,
594
			climateSampler,
595
			randomState,
596
			structureTemplateManager,
597
			seed,
598
			sourceChunkPos,
599
			references,
600
			centerChunk,
601
			biomePredicate
602
		);
603
		if (start.isValid()) {
604
			structureManager.setStartForStructure(structure, start, centerChunk);
605
			return true;
606
		} else {
607
			return false;
608
		}
609
	}
610
611
	private static int fetchReferences(final StructureManager structureManager, final ChunkAccess centerChunk, final Structure structure) {
612
		StructureStart prevEntry = structureManager.getStartForStructure(structure, centerChunk);
613
		return prevEntry != null ? prevEntry.getReferences() : 0;
614
	}
615
616
	public void createReferences(final WorldGenLevel level, final StructureManager structureManager, final ChunkAccess centerChunk) {
617
		int range = 8;
618
		ChunkPos chunkPos = centerChunk.getPos();
619
		int targetX = chunkPos.x();
620
		int targetZ = chunkPos.z();
621
		int targetBlockX = chunkPos.getMinBlockX();
622
		int targetBlockZ = chunkPos.getMinBlockZ();
623
		SectionPos pos = SectionPos.bottomOf(centerChunk);
624
625
		for (int sourceX = targetX - 8; sourceX <= targetX + 8; sourceX++) {
626
			for (int sourceZ = targetZ - 8; sourceZ <= targetZ + 8; sourceZ++) {
627
				long sourceChunkKey = ChunkPos.pack(sourceX, sourceZ);
628
629
				for (StructureStart start : level.getChunk(sourceX, sourceZ).getAllStarts().values()) {
630
					try {
631
						if (start.isValid() && start.getBoundingBox().intersects(targetBlockX, targetBlockZ, targetBlockX + 15, targetBlockZ + 15)) {
632
							structureManager.addReferenceForStructure(start.getStructure(), sourceChunkKey, centerChunk);
633
						}
634
					} catch (Exception e) {
635
						CrashReport report = CrashReport.forThrowable(e, "Generating structure reference");
636
						CrashReportCategory structure = report.addCategory("Structure");
637
						Optional<? extends Registry<Structure>> configuredStructuresRegistry = level.registryAccess().lookup(Registries.STRUCTURE);
638
						structure.setDetail("Id", () -> configuredStructuresRegistry.<String>map(r -> r.getKey(start.getStructure()).toString()).orElse("UNKNOWN"));
639
						structure.setDetail("Name", () -> BuiltInRegistries.STRUCTURE_TYPE.getKey(start.getStructure().type()).toString());
640
						structure.setDetail("Class", () -> start.getStructure().getClass().getCanonicalName());
641
						throw new ReportedException(report);
642
					}
643
				}
644
			}
645
		}
646
	}
647
648
	public abstract CompletableFuture<ChunkAccess> buildTerrain(
649
		ChunkAccess chunk,
650
		Blender blender,
651
		RandomState randomState,
652
		StructureManager structureManager,
653
		BiomeManager biomeManager,
654
		@Nullable WorldGenRegion carverBiomeRegion,
655
		Set<Holder<Biome>> possibleBiomes
656
	);
657
658
	public abstract int getSeaLevel();
659
660
	public abstract int getMinY();
661
662
	public abstract int getBaseHeight(int x, int z, final Heightmap.Types type, final LevelHeightAccessor heightAccessor, final RandomState randomState);
663
664
	public abstract NoiseColumn getBaseColumn(final int x, final int z, final LevelHeightAccessor heightAccessor, final RandomState randomState);
665
666
	public int getFirstFreeHeight(final int x, final int z, final Heightmap.Types type, final LevelHeightAccessor heightAccessor, final RandomState randomState) {
667
		return this.getBaseHeight(x, z, type, heightAccessor, randomState);
668
	}
669
670
	public int getFirstOccupiedHeight(
671
		final int x, final int z, final Heightmap.Types type, final LevelHeightAccessor heightAccessor, final RandomState randomState
672
	) {
673
		return this.getBaseHeight(x, z, type, heightAccessor, randomState) - 1;
674
	}
675
676
	public abstract void addDebugScreenInfo(final List<String> result, final RandomState randomState, final BlockPos feetPos, final SamplerContext samplerContext);
677
678
	@Deprecated
679
	public BiomeGenerationSettings getBiomeGenerationSettings(final Holder<Biome> biome) {
680
		return this.generationSettingsGetter.apply(biome);
681
	}
682
}
683

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