CreateWorldScreen .java

net.minecraft.client.gui.screens.worldselection.CreateWorldScreen (class, 797 lines): members: createTempDataPackDirFromExistingWorld, ALLOW_COMMANDS_INFO.

net.minecraft.client.gui.screens.worldselectionclass797 linesclientextends Screen35.9 KB

API Surface (14)

void openFresh(final Minecraft minecraft, final Runnable onClose)
void openFresh(final Minecraft minecraft, final Runnable onClose, final CreateWorldCallback createWorld)
void testWorld(final Minecraft minecraft, final Runnable onClose)
CreateWorldScreen createFromExisting(final Minecraft minecraft, final Runnable onClose, final LevelSettings levelSettings, final WorldCreationContext worldCreationContext, final @Nullable Path newDataPackDir)
WorldCreationUiState getUiState()
void init()
void setInitialFocus()
void repositionElements()
boolean keyPressed(final KeyEvent event)
void onClose()
void popScreen()
void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final float a)
void extractMenuBackground(final GuiGraphicsExtractor graphics)
Path createTempDataPackDirFromExistingWorld(final Path sourcePackDir, final Minecraft minecraft)

Fields & Constants (31)

GROUP_BOTTOM
TAB_COLUMN_WIDTH
LOGGER
TEMP_WORLD_PREFIX
GAME_MODEL_LABEL
NAME_LABEL
EXPERIMENTS_LABEL
ALLOW_COMMANDS_INFO
PREPARING_WORLD_DATA
HORIZONTAL_BUTTON_SPACING
VERTICAL_BUTTON_SPACING
TAB_HEADER_BACKGROUND
layout
uiState
tabManager
recreated
packValidator
createWorldCallback
onClose
tempDataPackDir
tempDataPackRepository
tabNavigationBar
minecraft
worldGenSettings
worldCreationContext
worldPreset
levelSettings
settings
preset
seed
worldDataAndGenSettings

String literals (35)

"mcworld-"
"selectWorld.gameMode"
"selectWorld.enterName"
"selectWorld.experiments"
"selectWorld.allowCommands.info"
"createWorld.preparing"
"textures/gui/tab_header_background.png"
"vanilla"
"tests"
"selectWorld.create"
"Failed to create temporary dir"
"dataPack.title"
"dataPack.validation.working"
"Needs at least one world preset to continue"
"Needs at least one biome continue"
"Failed to validate datapack"
"dataPack.validation.failed"
"dataPack.validation.back"
"dataPack.validation.reset"
"createWorld.tab.game.title"
"selectWorld.allowCommands"
"selectWorld.targetFolder"
"options.difficulty"
"createWorld.tab.more.title"

Code Graph: Dependencies (68)

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

Full Source

CreateWorldScreen.java797 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.gui.screens.worldselection;
2
3
import com.google.common.collect.ImmutableList;
4
import com.google.gson.JsonElement;
5
import com.mojang.datafixers.util.Pair;
6
import com.mojang.logging.LogUtils;
7
import com.mojang.serialization.DataResult;
8
import com.mojang.serialization.DynamicOps;
9
import com.mojang.serialization.JsonOps;
10
import com.mojang.serialization.Lifecycle;
11
import java.io.IOException;
12
import java.io.UncheckedIOException;
13
import java.nio.file.Files;
14
import java.nio.file.Path;
15
import java.util.Comparator;
16
import java.util.List;
17
import java.util.Optional;
18
import java.util.OptionalLong;
19
import java.util.concurrent.CompletableFuture;
20
import java.util.function.Consumer;
21
import java.util.function.Function;
22
import java.util.stream.Stream;
23
import net.fabricmc.api.EnvType;
24
import net.fabricmc.api.Environment;
25
import net.minecraft.ChatFormatting;
26
import net.minecraft.SharedConstants;
27
import net.minecraft.client.Minecraft;
28
import net.minecraft.client.gui.GuiGraphicsExtractor;
29
import net.minecraft.client.gui.components.Button;
30
import net.minecraft.client.gui.components.CycleButton;
31
import net.minecraft.client.gui.components.EditBox;
32
import net.minecraft.client.gui.components.Tooltip;
33
import net.minecraft.client.gui.components.tabs.GridLayoutTab;
34
import net.minecraft.client.gui.components.tabs.MenuTabBar;
35
import net.minecraft.client.gui.components.tabs.TabManager;
36
import net.minecraft.client.gui.components.toasts.SystemToast;
37
import net.minecraft.client.gui.layouts.CommonLayouts;
38
import net.minecraft.client.gui.layouts.GridLayout;
39
import net.minecraft.client.gui.layouts.HeaderAndFooterLayout;
40
import net.minecraft.client.gui.layouts.LayoutSettings;
41
import net.minecraft.client.gui.layouts.LinearLayout;
42
import net.minecraft.client.gui.navigation.ScreenRectangle;
43
import net.minecraft.client.gui.screens.ConfirmScreen;
44
import net.minecraft.client.gui.screens.GenericMessageScreen;
45
import net.minecraft.client.gui.screens.Screen;
46
import net.minecraft.client.gui.screens.packs.PackSelectionScreen;
47
import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen.WorldTab.1;
48
import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen.WorldTab.2;
49
import net.minecraft.client.input.KeyEvent;
50
import net.minecraft.client.renderer.RenderPipelines;
51
import net.minecraft.commands.Commands.CommandSelection;
52
import net.minecraft.core.LayeredRegistryAccess;
53
import net.minecraft.core.registries.Registries;
54
import net.minecraft.network.chat.CommonComponents;
55
import net.minecraft.network.chat.Component;
56
import net.minecraft.resources.Identifier;
57
import net.minecraft.resources.ResourceKey;
58
import net.minecraft.server.MinecraftServer;
59
import net.minecraft.server.RegistryLayer;
60
import net.minecraft.server.WorldLoader;
61
import net.minecraft.server.WorldLoader.DataLoadContext;
62
import net.minecraft.server.WorldLoader.DataLoadOutput;
63
import net.minecraft.server.WorldLoader.InitConfig;
64
import net.minecraft.server.WorldLoader.PackConfig;
65
import net.minecraft.server.packs.repository.PackRepository;
66
import net.minecraft.server.packs.repository.ServerPacksSource;
67
import net.minecraft.server.permissions.LevelBasedPermissionSet;
68
import net.minecraft.util.FileUtil;
69
import net.minecraft.util.Util;
70
import net.minecraft.world.Difficulty;
71
import net.minecraft.world.flag.FeatureFlagSet;
72
import net.minecraft.world.flag.FeatureFlags;
73
import net.minecraft.world.level.DataPackConfig;
74
import net.minecraft.world.level.GameType;
75
import net.minecraft.world.level.LevelSettings;
76
import net.minecraft.world.level.WorldDataConfiguration;
77
import net.minecraft.world.level.LevelSettings.DifficultySettings;
78
import net.minecraft.world.level.gamerules.GameRules;
79
import net.minecraft.world.level.gamerules.GameRuleMap.Builder;
80
import net.minecraft.world.level.levelgen.WorldDimensions;
81
import net.minecraft.world.level.levelgen.WorldGenSettings;
82
import net.minecraft.world.level.levelgen.WorldOptions;
83
import net.minecraft.world.level.levelgen.WorldDimensions.Complete;
84
import net.minecraft.world.level.levelgen.presets.WorldPreset;
85
import net.minecraft.world.level.levelgen.presets.WorldPresets;
86
import net.minecraft.world.level.storage.LevelResource;
87
import net.minecraft.world.level.storage.PrimaryLevelData;
88
import net.minecraft.world.level.storage.LevelDataAndDimensions.WorldDataAndGenSettings;
89
import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess;
90
import net.minecraft.world.level.storage.PrimaryLevelData.SpecialWorldProperty;
91
import net.minecraft.world.level.validation.DirectoryValidator;
92
import org.apache.commons.lang3.mutable.MutableObject;
93
import org.jspecify.annotations.Nullable;
94
import org.slf4j.Logger;
95
96
@Environment(EnvType.CLIENT)
97
public class CreateWorldScreen extends Screen {
98
	private static final int GROUP_BOTTOM = 1;
99
	private static final int TAB_COLUMN_WIDTH = 210;
100
	private static final Logger LOGGER = LogUtils.getLogger();
101
	private static final String TEMP_WORLD_PREFIX = "mcworld-";
102
	private static final Component GAME_MODEL_LABEL = Component.translatable("selectWorld.gameMode");
103
	private static final Component NAME_LABEL = Component.translatable("selectWorld.enterName");
104
	private static final Component EXPERIMENTS_LABEL = Component.translatable("selectWorld.experiments");
105
	private static final Component ALLOW_COMMANDS_INFO = Component.translatable("selectWorld.allowCommands.info");
106
	private static final Component PREPARING_WORLD_DATA = Component.translatable("createWorld.preparing");
107
	private static final int HORIZONTAL_BUTTON_SPACING = 10;
108
	private static final int VERTICAL_BUTTON_SPACING = 8;
109
	public static final Identifier TAB_HEADER_BACKGROUND = Identifier.withDefaultNamespace("textures/gui/tab_header_background.png");
110
	private final HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this);
111
	private final WorldCreationUiState uiState;
112
	private final TabManager tabManager = new TabManager(x$0 -> this.addRenderableWidget(x$0), x$0 -> this.removeWidget(x$0));
113
	private boolean recreated;
114
	private final DirectoryValidator packValidator;
115
	private final CreateWorldCallback createWorldCallback;
116
	private final Runnable onClose;
117
	private @Nullable Path tempDataPackDir;
118
	private @Nullable PackRepository tempDataPackRepository;
119
	private @Nullable MenuTabBar tabNavigationBar;
120
121
	public static void openFresh(final Minecraft minecraft, final Runnable onClose) {
122
		openFresh(
123
			minecraft,
124
			onClose,
125
			(createWorldScreen, finalLayers, worldDataAndGenSettings, gameRules, tempDataPackDir) -> createWorldScreen.createNewWorld(
126
				finalLayers, worldDataAndGenSettings, gameRules
127
			)
128
		);
129
	}
130
131
	public static void openFresh(final Minecraft minecraft, final Runnable onClose, final CreateWorldCallback createWorld) {
132
		WorldCreationContextMapper worldCreationContext = (managers, registries, cookie) -> new WorldCreationContext(
133
			cookie.worldGenSettings(), registries, managers, cookie.dataConfiguration()
134
		);
135
		Function<DataLoadContext, WorldGenSettings> worldGenSettings = context -> new WorldGenSettings(
136
			WorldOptions.defaultWithRandomSeed(), WorldPresets.createNormalWorldDimensions(context.datapackWorldRegistries())
137
		);
138
		openCreateWorldScreen(minecraft, onClose, worldGenSettings, worldCreationContext, WorldPresets.NORMAL, createWorld);
139
	}
140
141
	public static void testWorld(final Minecraft minecraft, final Runnable onClose) {
142
		WorldCreationContextMapper worldCreationContext = (managers, registries, cookie) -> new WorldCreationContext(
143
			cookie.worldGenSettings().options(),
144
			cookie.worldGenSettings().dimensions(),
145
			registries,
146
			managers,
147
			cookie.dataConfiguration(),
148
			new InitialWorldCreationOptions(
149
				WorldCreationUiState.SelectedGameMode.CREATIVE,
150
				new Builder().set(GameRules.ADVANCE_TIME, false).set(GameRules.ADVANCE_WEATHER, false).set(GameRules.SPAWN_MOBS, false).build(),
151
				null
152
			)
153
		);
154
		Function<DataLoadContext, WorldGenSettings> worldGenSettings = context -> new WorldGenSettings(
155
			WorldOptions.testWorldWithRandomSeed(), WorldPresets.createTestWorldDimensions(context.datapackWorldRegistries())
156
		);
157
		openCreateWorldScreen(
158
			minecraft,
159
			onClose,
160
			worldGenSettings,
161
			worldCreationContext,
162
			WorldPresets.FLAT_ALL_DIMENSIONS,
163
			(createWorldScreen, finalLayers, worldDataAndGenSettings, gameRules, tempDataPackDir) -> createWorldScreen.createNewWorld(
164
				finalLayers, worldDataAndGenSettings, gameRules
165
			)
166
		);
167
	}
168
169
	private static void openCreateWorldScreen(
170
		final Minecraft minecraft,
171
		final Runnable onClose,
172
		final Function<DataLoadContext, WorldGenSettings> worldGenSettings,
173
		final WorldCreationContextMapper worldCreationContext,
174
		final ResourceKey<WorldPreset> worldPreset,
175
		final CreateWorldCallback createWorld
176
	) {
177
		queueLoadScreen(minecraft, PREPARING_WORLD_DATA);
178
		long start = Util.getMillis();
179
		PackRepository vanillaOnlyPackRepository = new PackRepository(new ServerPacksSource(minecraft.directoryValidator()));
180
		WorldDataConfiguration dataConfig = SharedConstants.IS_RUNNING_IN_IDE
181
			? new WorldDataConfiguration(new DataPackConfig(List.of("vanilla", "tests"), List.of()), FeatureFlags.DEFAULT_FLAGS)
182
			: WorldDataConfiguration.DEFAULT;
183
		InitConfig loadConfig = createDefaultLoadConfig(vanillaOnlyPackRepository, dataConfig);
184
		CompletableFuture<WorldCreationContext> loadResult = WorldLoader.load(
185
			loadConfig,
186
			context -> new DataLoadOutput<>(new DataPackReloadCookie(worldGenSettings.apply(context), context.dataConfiguration()), context.datapackDimensions()),
187
			(resources, managers, registries, cookie) -> {
188
				resources.close();
189
				return worldCreationContext.apply(managers, registries, cookie);
190
			},
191
			Util.backgroundExecutor(),
192
			minecraft
193
		);
194
		minecraft.managedBlock(loadResult::isDone);
195
		long end = Util.getMillis();
196
		LOGGER.debug("Resource load for world creation blocked for {} ms", end - start);
197
		minecraft.gui.setScreen(new CreateWorldScreen(minecraft, onClose, loadResult.join(), Optional.of(worldPreset), OptionalLong.empty(), createWorld));
198
	}
199
200
	public static CreateWorldScreen createFromExisting(
201
		final Minecraft minecraft,
202
		final Runnable onClose,
203
		final LevelSettings levelSettings,
204
		final WorldCreationContext worldCreationContext,
205
		final @Nullable Path newDataPackDir
206
	) {
207
		CreateWorldScreen result = new CreateWorldScreen(
208
			minecraft,
209
			onClose,
210
			worldCreationContext,
211
			WorldPresets.fromSettings(worldCreationContext.selectedDimensions()),
212
			OptionalLong.of(worldCreationContext.options().seed()),
213
			(createWorldScreen, finalLayers, worldDataAndGenSettings, gameRules, tempDataPackDir) -> createWorldScreen.createNewWorld(
214
				finalLayers, worldDataAndGenSettings, gameRules
215
			)
216
		);
217
		result.recreated = true;
218
		result.uiState.setName(levelSettings.levelName());
219
		result.uiState.setAllowCommands(levelSettings.allowCommands());
220
		result.uiState.setDifficulty(levelSettings.difficultySettings().difficulty());
221
		result.uiState.getGameRules().setAll(worldCreationContext.initialWorldCreationOptions().gameRuleOverwrites(), null);
222
		if (levelSettings.difficultySettings().hardcore()) {
223
			result.uiState.setGameMode(WorldCreationUiState.SelectedGameMode.HARDCORE);
224
		} else if (levelSettings.gameType().isSurvival()) {
225
			result.uiState.setGameMode(WorldCreationUiState.SelectedGameMode.SURVIVAL);
226
		} else if (levelSettings.gameType().isCreative()) {
227
			result.uiState.setGameMode(WorldCreationUiState.SelectedGameMode.CREATIVE);
228
		}
229
230
		result.tempDataPackDir = newDataPackDir;
231
		return result;
232
	}
233
234
	private CreateWorldScreen(
235
		final Minecraft minecraft,
236
		final Runnable onClose,
237
		final WorldCreationContext settings,
238
		final Optional<ResourceKey<WorldPreset>> preset,
239
		final OptionalLong seed,
240
		final CreateWorldCallback createWorldCallback
241
	) {
242
		super(Component.translatable("selectWorld.create"));
243
		this.onClose = onClose;
244
		this.packValidator = minecraft.directoryValidator();
245
		this.createWorldCallback = createWorldCallback;
246
		this.uiState = new WorldCreationUiState(minecraft.getLevelSource().getBaseDir(), settings, preset, seed);
247
	}
248
249
	public WorldCreationUiState getUiState() {
250
		return this.uiState;
251
	}
252
253
	@Override
254
	protected void init() {
255
		this.tabNavigationBar = MenuTabBar.builder(this.tabManager, this.width)
256
			.addTabs(new CreateWorldScreen.GameTab(), new CreateWorldScreen.WorldTab(), new CreateWorldScreen.MoreTab())
257
			.build();
258
		this.addRenderableWidget(this.tabNavigationBar);
259
		LinearLayout footer = this.layout.addToFooter(LinearLayout.horizontal().spacing(8));
260
		footer.addChild(Button.builder(Component.translatable("selectWorld.create"), button -> this.onCreate()).build());
261
		footer.addChild(Button.builder(CommonComponents.GUI_CANCEL, button -> this.popScreen()).build());
262
		this.layout.visitWidgets(button -> {
263
			button.setTabOrderGroup(1);
264
			this.addRenderableWidget(button);
265
		});
266
		this.tabNavigationBar.selectTab(0, false);
267
		this.uiState.onChanged();
268
		this.repositionElements();
269
	}
270
271
	@Override
272
	protected void setInitialFocus() {
273
	}
274
275
	@Override
276
	public void repositionElements() {
277
		if (this.tabNavigationBar != null) {
278
			this.tabNavigationBar.arrangeElements(this.width);
279
			int tabAreaTop = this.tabNavigationBar.getRectangle().bottom();
280
			ScreenRectangle tabArea = new ScreenRectangle(0, tabAreaTop, this.width, this.height - this.layout.getFooterHeight() - tabAreaTop);
281
			this.tabManager.setTabArea(tabArea);
282
			this.layout.setHeaderHeight(tabAreaTop);
283
			this.layout.arrangeElements();
284
		}
285
	}
286
287
	private static void queueLoadScreen(final Minecraft minecraft, final Component message) {
288
		minecraft.setScreenAndShow(new GenericMessageScreen(message));
289
	}
290
291
	private void onCreate() {
292
		WorldCreationContext context = this.uiState.getSettings();
293
		WorldDimensions worldDimensions = context.selectedDimensions();
294
		Complete finalDimensions = worldDimensions.bake(context.datapackDimensions());
295
		LayeredRegistryAccess<RegistryLayer> finalLayers = context.worldgenRegistries()
296
			.replaceFrom(RegistryLayer.DIMENSIONS, finalDimensions.dimensionsRegistryAccess());
297
		FeatureFlagSet enabledFeatures = context.dataConfiguration().enabledFeatures();
298
		Lifecycle lifecycleFromFeatures = FeatureFlags.isExperimental(enabledFeatures) ? Lifecycle.experimental() : Lifecycle.stable();
299
		Lifecycle lifecycleFromRegistries = finalLayers.compositeAccess().allRegistriesLifecycle();
300
		Lifecycle lifecycle = lifecycleFromRegistries.add(lifecycleFromFeatures);
301
		boolean skipWarning = !this.recreated && lifecycleFromRegistries == Lifecycle.stable();
302
		boolean isDebug = finalDimensions.specialWorldProperty() == SpecialWorldProperty.DEBUG;
303
		LevelSettings levelSettings = this.createLevelSettings(isDebug);
304
		GameRules gameRules;
305
		if (isDebug) {
306
			gameRules = MinecraftServer.DEFAULT_GAME_RULES.get();
307
			gameRules.set(GameRules.ADVANCE_TIME, false, null);
308
		} else {
309
			gameRules = this.uiState.getGameRules().copy(enabledFeatures);
310
		}
311
312
		PrimaryLevelData worldData = new PrimaryLevelData(levelSettings, finalDimensions.specialWorldProperty(), lifecycle);
313
		WorldOptions options = this.uiState.getSettings().options();
314
		WorldGenSettings worldGenSettings = new WorldGenSettings(options, worldDimensions);
315
		WorldDataAndGenSettings worldDataAndGenSettings = new WorldDataAndGenSettings(worldData, worldGenSettings);
316
		WorldOpenFlows.confirmWorldCreation(
317
			this.minecraft, this, lifecycle, () -> this.createWorldAndCleanup(finalLayers, worldDataAndGenSettings, Optional.of(gameRules)), skipWarning
318
		);
319
	}
320
321
	private void createWorldAndCleanup(
322
		final LayeredRegistryAccess<RegistryLayer> finalLayers, final WorldDataAndGenSettings worldDataAndGenSettings, final Optional<GameRules> gameRules
323
	) {
324
		boolean worldCreationSuccessful = this.createWorldCallback.create(this, finalLayers, worldDataAndGenSettings, gameRules, this.tempDataPackDir);
325
		this.removeTempDataPackDir();
326
		if (!worldCreationSuccessful) {
327
			this.popScreen();
328
		}
329
	}
330
331
	private boolean createNewWorld(
332
		final LayeredRegistryAccess<RegistryLayer> finalLayers, final WorldDataAndGenSettings worldDataAndGenSettings, final Optional<GameRules> gameRules
333
	) {
334
		String worldFolder = this.uiState.getTargetFolder();
335
		WorldCreationContext context = this.uiState.getSettings();
336
		queueLoadScreen(this.minecraft, PREPARING_WORLD_DATA);
337
		Optional<LevelStorageAccess> newWorldAccess = createNewWorldDirectory(this.minecraft, worldFolder, this.tempDataPackDir);
338
		if (newWorldAccess.isEmpty()) {
339
			SystemToast.onPackCopyFailure(this.minecraft, worldFolder);
340
			return false;
341
		} else {
342
			this.minecraft
343
				.createWorldOpenFlows()
344
				.createLevelFromExistingSettings(newWorldAccess.get(), context.dataPackResources(), finalLayers, worldDataAndGenSettings, gameRules);
345
			return true;
346
		}
347
	}
348
349
	private LevelSettings createLevelSettings(final boolean isDebug) {
350
		String name = this.uiState.getName().trim();
351
		return isDebug
352
			? new LevelSettings(name, GameType.SPECTATOR, new DifficultySettings(Difficulty.PEACEFUL, false, false), true, WorldDataConfiguration.DEFAULT)
353
			: new LevelSettings(
354
				name,
355
				this.uiState.getGameMode().gameType,
356
				new DifficultySettings(this.uiState.getDifficulty(), this.uiState.isHardcore(), false),
357
				this.uiState.isAllowCommands(),
358
				this.uiState.getSettings().dataConfiguration()
359
			);
360
	}
361
362
	@Override
363
	public boolean keyPressed(final KeyEvent event) {
364
		if (this.tabNavigationBar.keyPressed(event)) {
365
			return true;
366
		} else if (super.keyPressed(event)) {
367
			return true;
368
		} else if (event.isConfirmation()) {
369
			this.onCreate();
370
			return true;
371
		} else {
372
			return false;
373
		}
374
	}
375
376
	@Override
377
	public void onClose() {
378
		this.popScreen();
379
	}
380
381
	public void popScreen() {
382
		this.onClose.run();
383
		this.removeTempDataPackDir();
384
	}
385
386
	@Override
387
	public void extractRenderState(final GuiGraphicsExtractor graphics, final int mouseX, final int mouseY, final float a) {
388
		super.extractRenderState(graphics, mouseX, mouseY, a);
389
		graphics.blit(RenderPipelines.GUI_TEXTURED, Screen.FOOTER_SEPARATOR, 0, this.height - this.layout.getFooterHeight() - 2, 0.0F, 0.0F, this.width, 2, 32, 2);
390
	}
391
392
	@Override
393
	protected void extractMenuBackground(final GuiGraphicsExtractor graphics) {
394
		graphics.blit(RenderPipelines.GUI_TEXTURED, TAB_HEADER_BACKGROUND, 0, 0, 0.0F, 0.0F, this.width, this.layout.getHeaderHeight(), 16, 16);
395
		this.extractMenuBackground(graphics, 0, this.layout.getHeaderHeight(), this.width, this.height);
396
	}
397
398
	private @Nullable Path getOrCreateTempDataPackDir() {
399
		if (this.tempDataPackDir == null) {
400
			try {
401
				this.tempDataPackDir = Files.createTempDirectory("mcworld-");
402
			} catch (IOException e) {
403
				LOGGER.warn("Failed to create temporary dir", e);
404
				SystemToast.onPackCopyFailure(this.minecraft, this.uiState.getTargetFolder());
405
				this.popScreen();
406
			}
407
		}
408
409
		return this.tempDataPackDir;
410
	}
411
412
	private void openExperimentsScreen(final WorldDataConfiguration dataConfiguration) {
413
		Pair<Path, PackRepository> settings = this.getDataPackSelectionSettings(dataConfiguration);
414
		if (settings != null) {
415
			this.minecraft
416
				.gui
417
				.setScreen(
418
					new ExperimentsScreen(this, settings.getSecond(), packRepository -> this.tryApplyNewDataPacks(packRepository, false, this::openExperimentsScreen))
419
				);
420
		}
421
	}
422
423
	private void openDataPackSelectionScreen(final WorldDataConfiguration dataConfiguration) {
424
		Pair<Path, PackRepository> settings = this.getDataPackSelectionSettings(dataConfiguration);
425
		if (settings != null) {
426
			this.minecraft
427
				.gui
428
				.setScreen(
429
					new PackSelectionScreen(
430
						settings.getSecond(),
431
						packRepository -> this.tryApplyNewDataPacks(packRepository, true, this::openDataPackSelectionScreen),
432
						settings.getFirst(),
433
						Component.translatable("dataPack.title")
434
					)
435
				);
436
		}
437
	}
438
439
	private void tryApplyNewDataPacks(final PackRepository packRepository, final boolean isDataPackScreen, final Consumer<WorldDataConfiguration> onAbort) {
440
		List<String> newEnabled = ImmutableList.copyOf(packRepository.getSelectedIds());
441
		List<String> newDisabled = packRepository.getAvailableIds().stream().filter(id -> !newEnabled.contains(id)).collect(ImmutableList.toImmutableList());
442
		WorldDataConfiguration newConfig = new WorldDataConfiguration(
443
			new DataPackConfig(newEnabled, newDisabled), this.uiState.getSettings().dataConfiguration().enabledFeatures()
444
		);
445
		if (this.uiState.tryUpdateDataConfiguration(newConfig)) {
446
			this.minecraft.gui.setScreen(this);
447
		} else {
448
			FeatureFlagSet requestedFeatureFlags = packRepository.getRequestedFeatureFlags();
449
			if (FeatureFlags.isExperimental(requestedFeatureFlags) && isDataPackScreen) {
450
				this.minecraft.gui.setScreen(new ConfirmExperimentalFeaturesScreen(packRepository.getSelectedPacks(), accepted -> {
451
					if (accepted) {
452
						this.applyNewPackConfig(packRepository, newConfig, onAbort);
453
					} else {
454
						onAbort.accept(this.uiState.getSettings().dataConfiguration());
455
					}
456
				}));
457
			} else {
458
				this.applyNewPackConfig(packRepository, newConfig, onAbort);
459
			}
460
		}
461
	}
462
463
	private void applyNewPackConfig(final PackRepository packRepository, final WorldDataConfiguration newConfig, final Consumer<WorldDataConfiguration> onAbort) {
464
		this.minecraft.setScreenAndShow(new GenericMessageScreen(Component.translatable("dataPack.validation.working")));
465
		InitConfig config = createDefaultLoadConfig(packRepository, newConfig);
466
		WorldLoader.<DataPackReloadCookie, WorldCreationContext>load(
467
				config,
468
				context -> {
469
					if (context.datapackWorldRegistries().lookupOrThrow(Registries.WORLD_PRESET).listElements().findAny().isEmpty()) {
470
						throw new IllegalStateException("Needs at least one world preset to continue");
471
					}
472
473
					if (context.datapackWorldRegistries().lookupOrThrow(Registries.BIOME).listElements().findAny().isEmpty()) {
474
						throw new IllegalStateException("Needs at least one biome continue");
475
					}
476
477
					WorldCreationContext existingContext = this.uiState.getSettings();
478
					DynamicOps<JsonElement> writeOps = existingContext.worldgenLoadContext().createSerializationContext(JsonOps.INSTANCE);
479
					DataResult<JsonElement> encoded = WorldGenSettings.CODEC
480
						.encodeStart(writeOps, new WorldGenSettings(existingContext.options(), existingContext.selectedDimensions()))
481
						.setLifecycle(Lifecycle.stable());
482
					DynamicOps<JsonElement> readOps = context.datapackWorldRegistries().createSerializationContext(JsonOps.INSTANCE);
483
					WorldGenSettings settings = encoded.<WorldGenSettings>flatMap(r -> WorldGenSettings.CODEC.parse(readOps, r))
484
						.getOrThrow(error -> new IllegalStateException("Error parsing worldgen settings after loading data packs: " + error));
485
					return new DataLoadOutput<>(new DataPackReloadCookie(settings, context.dataConfiguration()), context.datapackDimensions());
486
				},
487
				(resources, managers, registries, cookie) -> {
488
					resources.close();
489
					return new WorldCreationContext(cookie.worldGenSettings(), registries, managers, cookie.dataConfiguration());
490
				},
491
				Util.backgroundExecutor(),
492
				this.minecraft
493
			)
494
			.thenApply(settings -> {
495
				settings.validate();
496
				return (WorldCreationContext)settings;
497
			})
498
			.thenAcceptAsync(this.uiState::setSettings, this.minecraft)
499
			.handleAsync(
500
				(nothing, throwable) -> {
501
					if (throwable != null) {
502
						LOGGER.warn("Failed to validate datapack", throwable);
503
						this.minecraft
504
							.gui
505
							.setScreen(
506
								new ConfirmScreen(
507
									retry -> {
508
										if (retry) {
509
											onAbort.accept(this.uiState.getSettings().dataConfiguration());
510
										} else {
511
											onAbort.accept(WorldDataConfiguration.DEFAULT);
512
										}
513
									},
514
									Component.translatable("dataPack.validation.failed"),
515
									CommonComponents.EMPTY,
516
									Component.translatable("dataPack.validation.back"),
517
									Component.translatable("dataPack.validation.reset")
518
								)
519
							);
520
					} else {
521
						this.minecraft.gui.setScreen(this);
522
					}
523
524
					return null;
525
				},
526
				this.minecraft
527
			);
528
	}
529
530
	private static InitConfig createDefaultLoadConfig(final PackRepository packRepository, final WorldDataConfiguration config) {
531
		PackConfig packConfig = new PackConfig(packRepository, config, false, true);
532
		return new InitConfig(packConfig, CommandSelection.INTEGRATED, LevelBasedPermissionSet.GAMEMASTER);
533
	}
534
535
	private void removeTempDataPackDir() {
536
		if (this.tempDataPackDir != null && Files.exists(this.tempDataPackDir)) {
537
			try (Stream<Path> files = Files.walk(this.tempDataPackDir)) {
538
				files.sorted(Comparator.reverseOrder()).forEach(path -> {
539
					try {
540
						Files.delete(path);
541
					} catch (IOException e) {
542
						LOGGER.warn("Failed to remove temporary file {}", path, ex);
543
					}
544
				});
545
			} catch (IOException e) {
546
				LOGGER.warn("Failed to list temporary dir {}", this.tempDataPackDir);
547
			}
548
		}
549
550
		this.tempDataPackDir = null;
551
	}
552
553
	private static void copyBetweenDirs(final Path sourceDir, final Path targetDir, final Path sourcePath) {
554
		try {
555
			Util.copyBetweenDirs(sourceDir, targetDir, sourcePath);
556
		} catch (IOException e) {
557
			LOGGER.warn("Failed to copy datapack file from {} to {}", sourcePath, targetDir);
558
			throw new UncheckedIOException(e);
559
		}
560
	}
561
562
	private static Optional<LevelStorageAccess> createNewWorldDirectory(final Minecraft minecraft, final String worldFolder, final @Nullable Path tempDataPackDir) {
563
		try {
564
			LevelStorageAccess access = minecraft.getLevelSource().createAccess(worldFolder);
565
			if (tempDataPackDir == null) {
566
				return Optional.of(access);
567
			}
568
569
			try (Stream<Path> files = Files.walk(tempDataPackDir)) {
570
				Path targetDir = access.getLevelPath(LevelResource.DATAPACK_DIR);
571
				FileUtil.createDirectoriesSafe(targetDir);
572
				files.filter(f -> !f.equals(tempDataPackDir)).forEach(source -> copyBetweenDirs(tempDataPackDir, targetDir, source));
573
				return Optional.of(access);
574
			} catch (IOException | UncheckedIOException e) {
575
				LOGGER.warn("Failed to copy datapacks to world {}", worldFolder, e);
576
				access.close();
577
			}
578
		} catch (IOException | UncheckedIOException e) {
579
			LOGGER.warn("Failed to create access for {}", worldFolder, e);
580
		}
581
582
		return Optional.empty();
583
	}
584
585
	public static Path createTempDataPackDirFromExistingWorld(final Path sourcePackDir, final Minecraft minecraft) {
586
		MutableObject<Path> tempDataPackDir = new MutableObject<>();
587
588
		try (Stream<Path> dataPackContents = Files.walk(sourcePackDir)) {
589
			dataPackContents.filter(p -> !p.equals(sourcePackDir)).forEach(source -> {
590
				Path targetDir = tempDataPackDir.get();
591
				if (targetDir == null) {
592
					try {
593
						targetDir = Files.createTempDirectory("mcworld-");
594
					} catch (IOException e) {
595
						LOGGER.warn("Failed to create temporary dir");
596
						throw new UncheckedIOException(ex);
597
					}
598
599
					tempDataPackDir.setValue(targetDir);
600
				}
601
602
				copyBetweenDirs(sourcePackDir, targetDir, source);
603
			});
604
		} catch (IOException | UncheckedIOException e) {
605
			LOGGER.warn("Failed to copy datapacks from world {}", sourcePackDir, e);
606
			SystemToast.onPackCopyFailure(minecraft, sourcePackDir.toString());
607
			return null;
608
		}
609
610
		return tempDataPackDir.get();
611
	}
612
613
	private @Nullable Pair<Path, PackRepository> getDataPackSelectionSettings(final WorldDataConfiguration dataConfiguration) {
614
		Path dataPackDir = this.getOrCreateTempDataPackDir();
615
		if (dataPackDir != null) {
616
			if (this.tempDataPackRepository == null) {
617
				this.tempDataPackRepository = ServerPacksSource.createPackRepository(dataPackDir, this.packValidator);
618
				this.tempDataPackRepository.reload();
619
			}
620
621
			this.tempDataPackRepository.setSelected(dataConfiguration.dataPacks().getEnabled());
622
			return Pair.of(dataPackDir, this.tempDataPackRepository);
623
		} else {
624
			return null;
625
		}
626
	}
627
628
	@Environment(EnvType.CLIENT)
629
	private class GameTab extends GridLayoutTab {
630
		private static final Component TITLE = Component.translatable("createWorld.tab.game.title");
631
		private static final Component ALLOW_COMMANDS = Component.translatable("selectWorld.allowCommands");
632
		private final EditBox nameEdit;
633
634
		private GameTab() {
635
			super(TITLE);
636
			GridLayout.RowHelper helper = this.layout.rowSpacing(8).createRowHelper(1);
637
			LayoutSettings buttonLayoutSettings = helper.newCellSettings();
638
			this.nameEdit = new EditBox(CreateWorldScreen.this.font, 208, 20, Component.translatable("selectWorld.enterName"));
639
			this.nameEdit.setValue(CreateWorldScreen.this.uiState.getName());
640
			this.nameEdit.setResponder(CreateWorldScreen.this.uiState::setName);
641
			CreateWorldScreen.this.uiState
642
				.addListener(
643
					uiState -> this.nameEdit
644
						.setTooltip(
645
							Tooltip.create(Component.translatable("selectWorld.targetFolder", Component.literal(uiState.getTargetFolder()).withStyle(ChatFormatting.ITALIC)))
646
						)
647
				);
648
			CreateWorldScreen.this.setInitialFocus(this.nameEdit);
649
			helper.addChild(
650
				CommonLayouts.labeledElement(CreateWorldScreen.this.font, this.nameEdit, CreateWorldScreen.NAME_LABEL), helper.newCellSettings().alignHorizontallyCenter()
651
			);
652
			CycleButton<WorldCreationUiState.SelectedGameMode> gameModeButton = helper.addChild(
653
				CycleButton.<WorldCreationUiState.SelectedGameMode>builder(selectedGameMode -> selectedGameMode.displayName, CreateWorldScreen.this.uiState.getGameMode())
654
					.withValues(WorldCreationUiState.SelectedGameMode.SURVIVAL, WorldCreationUiState.SelectedGameMode.HARDCORE, WorldCreationUiState.SelectedGameMode.CREATIVE)
655
					.create(0, 0, 210, 20, CreateWorldScreen.GAME_MODEL_LABEL, (button, gameMode) -> CreateWorldScreen.this.uiState.setGameMode(gameMode)),
656
				buttonLayoutSettings
657
			);
658
			CreateWorldScreen.this.uiState.addListener(data -> {
659
				gameModeButton.setValue(data.getGameMode());
660
				gameModeButton.active = !data.isDebug();
661
				gameModeButton.setTooltip(Tooltip.create(data.getGameMode().getInfo()));
662
			});
663
			CycleButton<Difficulty> difficultyButton = helper.addChild(
664
				CycleButton.builder(Difficulty::getDisplayName, CreateWorldScreen.this.uiState.getDifficulty())
665
					.withValues(Difficulty.values())
666
					.create(0, 0, 210, 20, Component.translatable("options.difficulty"), (button, value) -> CreateWorldScreen.this.uiState.setDifficulty(value)),
667
				buttonLayoutSettings
668
			);
669
			CreateWorldScreen.this.uiState.addListener(d -> {
670
				difficultyButton.setValue(CreateWorldScreen.this.uiState.getDifficulty());
671
				difficultyButton.active = !CreateWorldScreen.this.uiState.isHardcore();
672
				difficultyButton.setTooltip(Tooltip.create(CreateWorldScreen.this.uiState.getDifficulty().getInfo()));
673
			});
674
			CycleButton<Boolean> allowCommandsButton = helper.addChild(
675
				CycleButton.onOffBuilder(CreateWorldScreen.this.uiState.isAllowCommands())
676
					.withTooltip(state -> Tooltip.create(CreateWorldScreen.ALLOW_COMMANDS_INFO))
677
					.create(0, 0, 210, 20, ALLOW_COMMANDS, (b, state) -> CreateWorldScreen.this.uiState.setAllowCommands(state))
678
			);
679
			CreateWorldScreen.this.uiState.addListener(d -> {
680
				allowCommandsButton.setValue(CreateWorldScreen.this.uiState.isAllowCommands());
681
				allowCommandsButton.active = !CreateWorldScreen.this.uiState.isDebug() && !CreateWorldScreen.this.uiState.isHardcore();
682
			});
683
			if (!SharedConstants.getCurrentVersion().stable()) {
684
				helper.addChild(
685
					Button.builder(
686
							CreateWorldScreen.EXPERIMENTS_LABEL,
687
							button -> CreateWorldScreen.this.openExperimentsScreen(CreateWorldScreen.this.uiState.getSettings().dataConfiguration())
688
						)
689
						.width(210)
690
						.build()
691
				);
692
			}
693
		}
694
	}
695
696
	@Environment(EnvType.CLIENT)
697
	private class MoreTab extends GridLayoutTab {
698
		private static final Component TITLE = Component.translatable("createWorld.tab.more.title");
699
		private static final Component GAME_RULES_LABEL = Component.translatable("selectWorld.gameRules");
700
		private static final Component DATA_PACKS_LABEL = Component.translatable("selectWorld.dataPacks");
701
702
		private MoreTab() {
703
			super(TITLE);
704
			GridLayout.RowHelper helper = this.layout.rowSpacing(8).createRowHelper(1);
705
			helper.addChild(Button.builder(GAME_RULES_LABEL, b -> this.openGameRulesScreen()).width(210).build());
706
			helper.addChild(
707
				Button.builder(
708
						CreateWorldScreen.EXPERIMENTS_LABEL, b -> CreateWorldScreen.this.openExperimentsScreen(CreateWorldScreen.this.uiState.getSettings().dataConfiguration())
709
					)
710
					.width(210)
711
					.build()
712
			);
713
			helper.addChild(
714
				Button.builder(DATA_PACKS_LABEL, b -> CreateWorldScreen.this.openDataPackSelectionScreen(CreateWorldScreen.this.uiState.getSettings().dataConfiguration()))
715
					.width(210)
716
					.build()
717
			);
718
		}
719
720
		private void openGameRulesScreen() {
721
			CreateWorldScreen.this.minecraft
722
				.gui
723
				.setScreen(
724
					new WorldCreationGameRulesScreen(
725
						CreateWorldScreen.this.uiState.getGameRules().copy(CreateWorldScreen.this.uiState.getSettings().dataConfiguration().enabledFeatures()), gameRules -> {
726
							CreateWorldScreen.this.minecraft.gui.setScreen(CreateWorldScreen.this);
727
							gameRules.ifPresent(CreateWorldScreen.this.uiState::setGameRules);
728
						}
729
					)
730
				);
731
		}
732
	}
733
734
	@Environment(EnvType.CLIENT)
735
	private class WorldTab extends GridLayoutTab {
736
		private static final Component TITLE = Component.translatable("createWorld.tab.world.title");
737
		private static final Component AMPLIFIED_HELP_TEXT = Component.translatable("generator.minecraft.amplified.info");
738
		private static final Component GENERATE_STRUCTURES = Component.translatable("selectWorld.mapFeatures");
739
		private static final Component GENERATE_STRUCTURES_INFO = Component.translatable("selectWorld.mapFeatures.info");
740
		private static final Component BONUS_CHEST = Component.translatable("selectWorld.bonusItems");
741
		private static final Component SEED_LABEL = Component.translatable("selectWorld.enterSeed");
742
		private static final Component SEED_EMPTY_HINT = Component.translatable("selectWorld.seedInfo");
743
		private static final int WORLD_TAB_WIDTH = 310;
744
		private final EditBox seedEdit;
745
		private final Button customizeTypeButton;
746
747
		private WorldTab() {
748
			super(TITLE);
749
			GridLayout.RowHelper helper = this.layout.columnSpacing(10).rowSpacing(8).createRowHelper(2);
750
			CycleButton<WorldCreationUiState.WorldTypeEntry> typeButton = helper.addChild(
751
				CycleButton.builder(WorldCreationUiState.WorldTypeEntry::describePreset, CreateWorldScreen.this.uiState.getWorldType())
752
					.withValues(this.createWorldTypeValueSupplier())
753
					.create(0, 0, 150, 20, Component.translatable("selectWorld.mapType"), (button, newPreset) -> CreateWorldScreen.this.uiState.setWorldType(newPreset))
754
			);
755
			typeButton.setValue(CreateWorldScreen.this.uiState.getWorldType());
756
			CreateWorldScreen.this.uiState.addListener(data -> {
757
				WorldCreationUiState.WorldTypeEntry worldType = data.getWorldType();
758
				typeButton.setValue(worldType);
759
				if (worldType.isAmplified()) {
760
					typeButton.setTooltip(Tooltip.create(AMPLIFIED_HELP_TEXT));
761
				} else {
762
					typeButton.setTooltip(null);
763
				}
764
765
				typeButton.active = CreateWorldScreen.this.uiState.getWorldType().preset() != null;
766
			});
767
			this.customizeTypeButton = helper.addChild(Button.builder(Component.translatable("selectWorld.customizeType"), b -> this.openPresetEditor()).build());
768
			CreateWorldScreen.this.uiState.addListener(data -> this.customizeTypeButton.active = !data.isDebug() && data.getPresetEditor() != null);
769
			this.seedEdit = new 1(this, CreateWorldScreen.this.font, 308, 20, Component.translatable("selectWorld.enterSeed"));
770
			this.seedEdit.setHint(SEED_EMPTY_HINT);
771
			this.seedEdit.setValue(CreateWorldScreen.this.uiState.getSeed());
772
			this.seedEdit.setResponder(value -> CreateWorldScreen.this.uiState.setSeed(this.seedEdit.getValue()));
773
			helper.addChild(CommonLayouts.labeledElement(CreateWorldScreen.this.font, this.seedEdit, SEED_LABEL), 2);
774
			SwitchGrid.Builder switchGridBuilder = SwitchGrid.builder(310);
775
			switchGridBuilder.addSwitch(GENERATE_STRUCTURES, CreateWorldScreen.this.uiState::isGenerateStructures, CreateWorldScreen.this.uiState::setGenerateStructures)
776
				.withIsActiveCondition(() -> !CreateWorldScreen.this.uiState.isDebug())
777
				.withInfo(GENERATE_STRUCTURES_INFO);
778
			switchGridBuilder.addSwitch(BONUS_CHEST, CreateWorldScreen.this.uiState::isBonusChest, CreateWorldScreen.this.uiState::setBonusChest)
779
				.withIsActiveCondition(() -> !CreateWorldScreen.this.uiState.isHardcore() && !CreateWorldScreen.this.uiState.isDebug());
780
			SwitchGrid switchGrid = switchGridBuilder.build();
781
			helper.addChild(switchGrid.layout(), 2);
782
			CreateWorldScreen.this.uiState.addListener(d -> switchGrid.refreshStates());
783
		}
784
785
		private void openPresetEditor() {
786
			PresetEditor editor = CreateWorldScreen.this.uiState.getPresetEditor();
787
			if (editor != null) {
788
				CreateWorldScreen.this.minecraft.gui.setScreen(editor.createEditScreen(CreateWorldScreen.this, CreateWorldScreen.this.uiState.getSettings()));
789
			}
790
		}
791
792
		private CycleButton.ValueListSupplier<WorldCreationUiState.WorldTypeEntry> createWorldTypeValueSupplier() {
793
			return new 2(this);
794
		}
795
	}
796
}
797

Decompiled Minecraft 26.3 source of CreateWorldScreen (net/minecraft/client/gui/screens/worldselection/CreateWorldScreen.java) with Mojang official mappings, stored verbatim on the site.