IntegratedServer .java

net.minecraft.client.server.IntegratedServer (class): members: previousSimulationDistance, getCustomPermissionLevel, getGuestCommandAccess, lanPinger.

net.minecraft.client.serverclass539 linesclientextends MinecraftServer16.0 KB

API Surface (47)

boolean initServer()
boolean isPaused()
void processPacketsAndTick(final boolean sprinting)
void tickServer(final BooleanSupplier haveTime)
LocalSampleLogger getTickTimeLogger()
boolean isTickTimeLoggingEnabled()
boolean shouldRconBroadcast()
boolean shouldInformAdmins()
Path getServerDirectory()
boolean isDedicatedServer()
int getRateLimitPacketsPerSecond()
int getCommandSpamThresholdSeconds()
int getChatSpamThresholdSeconds()
boolean useNativeTransport()
void onServerCrash(final CrashReport report)
SystemReport fillServerSystemReport(final SystemReport systemReport)
ModCheck getModdedStatus()
boolean publishServer(final MultiplayerScope scope, final boolean allowCommands, final int port)
boolean publishServer(final MultiplayerScope scope, final int port)
void setWorldGameType(final GameType gameMode)
void setPersonalGameType(final GameType gameMode)
int enforceGameTypeForPlayers(final @Nullable GameType gameType)
void setWorldAllowCommands(final boolean allowCommands)
LevelBasedPermissionSet getProfilePermissions(final NameAndId nameAndId)
boolean getGuestCommandAccess()
void setGuestCommandAccess(final boolean commandAccess)
boolean unpublishServer()
void stopServer()
void halt(final boolean wait)
boolean isPublished()
void setDefaultGameType(final GameType gameType)
int getPort()
LevelBasedPermissionSet operatorUserPermissions()
LevelBasedPermissionSet getFunctionCompilationPermissions()
void setUUID(final UUID uuid)
boolean isSingleplayerOwner(final NameAndId nameAndId)
int getScaledTrackingDistance(final int baseRange)
boolean forceSynchronousWrites()
boolean forceGameMode()
void setForceGameMode(final boolean forceGameMode)
GlobalPos selectLevelLoadFocusPos()
void sendLowDiskSpaceWarning()
void reportChunkLoadFailure(final Throwable throwable, final RegionStorageInfo storageInfo, final ChunkPos pos)
void reportChunkSaveFailure(final Throwable throwable, final RegionStorageInfo storageInfo, final ChunkPos pos)
int getMaxPlayers()
Collection<GizmoInstance> getPerTickGizmos()
MultiplayerScope getMultiplayerScope()

Fields & Constants (20)

LOGGER
MIN_SIM_DISTANCE
MAX_PLAYERS
minecraft
paused
publishedPort
lanPinger
uuid
previousSimulationDistance
latestTicksGizmos
gizmoCollector
multiplayerScope
guestCommandAccess
forceGameMode
serverThread
levelStorageAccess
packRepository
worldStem
gameRules
services

String literals (7)

"autoSave"
"Saving and pausing game..."
"Integrated Server"
"Is Modded"
"Launched Version"
"multiplayer.disconnect.server_shutdown"
"<single player owner>"

Full Source

IntegratedServer.java539 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.client.server;
2
3
import com.google.common.collect.Lists;
4
import com.mojang.authlib.GameProfile;
5
import com.mojang.logging.LogUtils;
6
import java.io.IOException;
7
import java.nio.file.Path;
8
import java.util.ArrayList;
9
import java.util.Collection;
10
import java.util.List;
11
import java.util.Optional;
12
import java.util.UUID;
13
import java.util.function.BooleanSupplier;
14
import net.fabricmc.api.EnvType;
15
import net.fabricmc.api.Environment;
16
import net.minecraft.CrashReport;
17
import net.minecraft.SharedConstants;
18
import net.minecraft.SystemReport;
19
import net.minecraft.client.Minecraft;
20
import net.minecraft.client.gui.components.toasts.SystemToast;
21
import net.minecraft.client.gui.screens.WorldOptionsScreen;
22
import net.minecraft.core.BlockPos;
23
import net.minecraft.core.GlobalPos;
24
import net.minecraft.gizmos.Gizmos;
25
import net.minecraft.gizmos.SimpleGizmoCollector;
26
import net.minecraft.gizmos.Gizmos.TemporaryCollection;
27
import net.minecraft.gizmos.SimpleGizmoCollector.GizmoInstance;
28
import net.minecraft.nbt.CompoundTag;
29
import net.minecraft.network.chat.Component;
30
import net.minecraft.server.MinecraftServer;
31
import net.minecraft.server.Services;
32
import net.minecraft.server.WorldStem;
33
import net.minecraft.server.MinecraftServer.MultiplayerScope;
34
import net.minecraft.server.level.ServerPlayer;
35
import net.minecraft.server.level.ServerPlayer.SavedPosition;
36
import net.minecraft.server.level.progress.LevelLoadListener;
37
import net.minecraft.server.notifications.NotificationManager;
38
import net.minecraft.server.packs.repository.PackRepository;
39
import net.minecraft.server.permissions.LevelBasedPermissionSet;
40
import net.minecraft.server.permissions.Permissions;
41
import net.minecraft.server.players.NameAndId;
42
import net.minecraft.stats.Stats;
43
import net.minecraft.util.ModCheck;
44
import net.minecraft.util.ProblemReporter.ScopedCollector;
45
import net.minecraft.util.debugchart.LocalSampleLogger;
46
import net.minecraft.util.profiling.Profiler;
47
import net.minecraft.util.profiling.ProfilerFiller;
48
import net.minecraft.util.thread.BlockableEventLoop;
49
import net.minecraft.world.level.ChunkPos;
50
import net.minecraft.world.level.GameType;
51
import net.minecraft.world.level.chunk.storage.RegionStorageInfo;
52
import net.minecraft.world.level.gamerules.GameRules;
53
import net.minecraft.world.level.storage.TagValueInput;
54
import net.minecraft.world.level.storage.ValueInput;
55
import net.minecraft.world.level.storage.LevelStorageSource.LevelStorageAccess;
56
import org.jspecify.annotations.Nullable;
57
import org.slf4j.Logger;
58
59
@Environment(EnvType.CLIENT)
60
public class IntegratedServer extends MinecraftServer {
61
	private static final Logger LOGGER = LogUtils.getLogger();
62
	private static final int MIN_SIM_DISTANCE = 2;
63
	public static final int MAX_PLAYERS = 8;
64
	private final Minecraft minecraft;
65
	private boolean paused = true;
66
	private int publishedPort = -1;
67
	private @Nullable LanServerPinger lanPinger;
68
	private @Nullable UUID uuid;
69
	private int previousSimulationDistance = 0;
70
	private volatile List<GizmoInstance> latestTicksGizmos = new ArrayList<>();
71
	private final SimpleGizmoCollector gizmoCollector = new SimpleGizmoCollector();
72
	private MultiplayerScope multiplayerScope = MultiplayerScope.OFF;
73
	private boolean guestCommandAccess = false;
74
	private boolean forceGameMode = true;
75
76
	public IntegratedServer(
77
		final Thread serverThread,
78
		final Minecraft minecraft,
79
		final LevelStorageAccess levelStorageAccess,
80
		final PackRepository packRepository,
81
		final WorldStem worldStem,
82
		final Optional<GameRules> gameRules,
83
		final Services services,
84
		final LevelLoadListener levelLoadListener
85
	) {
86
		super(
87
			serverThread,
88
			levelStorageAccess,
89
			packRepository,
90
			worldStem,
91
			gameRules,
92
			minecraft.getProxy(),
93
			minecraft.getFixerUpper(),
94
			services,
95
			levelLoadListener,
96
			false,
97
			new NotificationManager()
98
		);
99
		this.setSingleplayerProfile(minecraft.getGameProfile());
100
		this.setDemo(minecraft.isDemo());
101
		this.setPlayerList(new IntegratedPlayerList(this, this.registries(), this.playerDataStorage));
102
		this.minecraft = minecraft;
103
	}
104
105
	@Override
106
	protected boolean initServer() {
107
		LOGGER.info("Starting integrated minecraft server version {}", SharedConstants.getCurrentVersion().name());
108
		this.setUsesAuthentication(true);
109
		this.initializeKeyPair();
110
		this.loadLevel();
111
		GameProfile host = this.getSingleplayerProfile();
112
		String levelName = this.getWorldData().getLevelName();
113
		this.setMotd(host != null ? host.name() + " - " + levelName : levelName);
114
		this.saveEverything(false, true, true);
115
		return true;
116
	}
117
118
	@Override
119
	public boolean isPaused() {
120
		return this.paused;
121
	}
122
123
	@Override
124
	protected void processPacketsAndTick(final boolean sprinting) {
125
		try (TemporaryCollection ignored = Gizmos.withCollector(this.gizmoCollector)) {
126
			super.processPacketsAndTick(sprinting);
127
		}
128
129
		if (this.tickRateManager().runsNormally()) {
130
			this.latestTicksGizmos = this.gizmoCollector.drainGizmos();
131
		}
132
	}
133
134
	@Override
135
	protected void tickServer(final BooleanSupplier haveTime) {
136
		boolean wasPaused = this.paused;
137
		this.paused = Minecraft.getInstance().isPaused() || this.getPlayerList().getPlayers().isEmpty();
138
		ProfilerFiller profiler = Profiler.get();
139
		if (!wasPaused && this.paused) {
140
			profiler.push("autoSave");
141
			LOGGER.info("Saving and pausing game...");
142
			this.saveEverything(false, false, false);
143
			profiler.pop();
144
		}
145
146
		if (this.paused) {
147
			this.tickPaused();
148
		} else {
149
			if (wasPaused) {
150
				this.forceGameTimeSynchronization();
151
			}
152
153
			super.tickServer(haveTime);
154
			int serverViewDistance = Math.max(2, this.minecraft.options.renderDistance().get());
155
			if (serverViewDistance != this.getPlayerList().getViewDistance()) {
156
				LOGGER.info("Changing view distance to {}, from {}", serverViewDistance, this.getPlayerList().getViewDistance());
157
				this.getPlayerList().setViewDistance(serverViewDistance);
158
			}
159
160
			int serverSimulationDistance = Math.max(2, this.minecraft.options.simulationDistance().get());
161
			if (serverSimulationDistance != this.previousSimulationDistance) {
162
				LOGGER.info("Changing simulation distance to {}, from {}", serverSimulationDistance, this.previousSimulationDistance);
163
				this.getPlayerList().setSimulationDistance(serverSimulationDistance);
164
				this.previousSimulationDistance = serverSimulationDistance;
165
			}
166
		}
167
	}
168
169
	protected LocalSampleLogger getTickTimeLogger() {
170
		return this.minecraft.getDebugOverlay().getTickTimeLogger();
171
	}
172
173
	@Override
174
	public boolean isTickTimeLoggingEnabled() {
175
		return true;
176
	}
177
178
	private void tickPaused() {
179
		this.tickConnection();
180
181
		for (ServerPlayer player : this.getPlayerList().getPlayers()) {
182
			player.awardStat(Stats.TOTAL_WORLD_TIME);
183
		}
184
	}
185
186
	@Override
187
	public boolean shouldRconBroadcast() {
188
		return true;
189
	}
190
191
	@Override
192
	public boolean shouldInformAdmins() {
193
		return true;
194
	}
195
196
	@Override
197
	public Path getServerDirectory() {
198
		return this.minecraft.gameDirectory.toPath();
199
	}
200
201
	@Override
202
	public boolean isDedicatedServer() {
203
		return false;
204
	}
205
206
	@Override
207
	public int getRateLimitPacketsPerSecond() {
208
		return 0;
209
	}
210
211
	@Override
212
	public int getCommandSpamThresholdSeconds() {
213
		return 0;
214
	}
215
216
	@Override
217
	public int getChatSpamThresholdSeconds() {
218
		return 0;
219
	}
220
221
	@Override
222
	public boolean useNativeTransport() {
223
		return this.minecraft.options.useNativeTransport();
224
	}
225
226
	@Override
227
	protected void onServerCrash(final CrashReport report) {
228
		BlockableEventLoop.relayDelayCrash(report);
229
	}
230
231
	@Override
232
	public SystemReport fillServerSystemReport(final SystemReport systemReport) {
233
		systemReport.setDetail("Type", "Integrated Server");
234
		systemReport.setDetail("Is Modded", () -> this.getModdedStatus().fullDescription());
235
		systemReport.setDetail("Launched Version", this.minecraft::getLaunchedVersion);
236
		return systemReport;
237
	}
238
239
	@Override
240
	public ModCheck getModdedStatus() {
241
		return Minecraft.checkModStatus().merge(super.getModdedStatus());
242
	}
243
244
	@Override
245
	public boolean publishServer(final MultiplayerScope scope, final boolean allowCommands, final int port) {
246
		this.setGuestCommandAccess(allowCommands);
247
		return this.publishServer(scope, port);
248
	}
249
250
	public boolean publishServer(final MultiplayerScope scope, final int port) {
251
		if (scope != MultiplayerScope.OFF && !this.isPublished()) {
252
			try {
253
				this.minecraft.prepareForMultiplayer();
254
				this.minecraft.getConnection().prepareKeyPair();
255
				this.getConnection().startTcpServerListener(null, port);
256
				LOGGER.info("Published LAN server on port {}", port);
257
				this.publishedPort = port;
258
				this.lanPinger = new LanServerPinger(this.getMotd(), Integer.toString(port));
259
				this.lanPinger.start();
260
				this.setMultiplayerScope(scope);
261
				return true;
262
			} catch (IOException var4) {
263
				return false;
264
			}
265
		} else {
266
			return false;
267
		}
268
	}
269
270
	public void setWorldGameType(final GameType gameMode) {
271
		this.setDefaultGameType(gameMode);
272
		this.updateGameModeBasedOnPermission();
273
	}
274
275
	public void setPersonalGameType(final GameType gameMode) {
276
		if (this.minecraft.player != null) {
277
			ServerPlayer serverPlayer = this.getPlayerList().getPlayer(this.minecraft.player.getUUID());
278
			if (serverPlayer != null) {
279
				serverPlayer.setGameMode(gameMode);
280
			}
281
		}
282
	}
283
284
	@Override
285
	public int enforceGameTypeForPlayers(final @Nullable GameType gameType) {
286
		return gameType == null ? 0 : this.updateGameModeBasedOnPermission();
287
	}
288
289
	public void setWorldAllowCommands(final boolean allowCommands) {
290
		this.getWorldData().setAllowCommands(allowCommands);
291
		this.updateGameModeBasedOnPermission();
292
		this.updatePermissions();
293
	}
294
295
	public @Nullable GameType getPersonalGameMode() {
296
		if (this.minecraft.player == null) {
297
			return null;
298
		}
299
300
		ServerPlayer serverPlayer = this.getPlayerList().getPlayer(this.minecraft.player.getUUID());
301
		return serverPlayer == null ? null : serverPlayer.gameMode();
302
	}
303
304
	private int updateGameModeBasedOnPermission() {
305
		if (!this.forceGameMode()) {
306
			return 0;
307
		}
308
309
		int count = 0;
310
311
		for (ServerPlayer player : this.getPlayerList().getPlayers()) {
312
			if (!player.permissions().hasPermission(Permissions.COMMANDS_GAMEMASTER) && player.setGameMode(this.getWorldData().getGameType())) {
313
				count++;
314
			}
315
		}
316
317
		return count;
318
	}
319
320
	@Override
321
	public LevelBasedPermissionSet getProfilePermissions(final NameAndId nameAndId) {
322
		if (this.isSingleplayerOwner(nameAndId)) {
323
			if (this.getPlayerList().isOp(nameAndId)) {
324
				return LevelBasedPermissionSet.OWNER;
325
			}
326
		} else {
327
			LevelBasedPermissionSet customPermissionLevel = this.getCustomPermissionLevel();
328
			if (customPermissionLevel != null) {
329
				return customPermissionLevel;
330
			}
331
		}
332
333
		return super.getProfilePermissions(nameAndId);
334
	}
335
336
	protected @Nullable LevelBasedPermissionSet getCustomPermissionLevel() {
337
		if (this.worldData.isAllowCommands()) {
338
			return this.guestCommandAccess ? LevelBasedPermissionSet.GAMEMASTER : LevelBasedPermissionSet.ALL;
339
		} else {
340
			return null;
341
		}
342
	}
343
344
	public boolean getGuestCommandAccess() {
345
		return this.guestCommandAccess;
346
	}
347
348
	public void setGuestCommandAccess(final boolean commandAccess) {
349
		this.guestCommandAccess = commandAccess;
350
		this.updatePermissions();
351
		this.updateGameModeBasedOnPermission();
352
	}
353
354
	private void updatePermissions() {
355
		for (ServerPlayer player : this.getPlayerList().getPlayers()) {
356
			this.getPlayerList().sendPlayerPermissionLevel(player);
357
		}
358
	}
359
360
	private void teardownPublishedState() {
361
		this.stopLanPinger();
362
		this.publishedPort = -1;
363
		this.setMultiplayerScope(MultiplayerScope.OFF);
364
	}
365
366
	private void stopLanPinger() {
367
		if (this.lanPinger != null) {
368
			this.lanPinger.interrupt();
369
			this.lanPinger = null;
370
		}
371
	}
372
373
	@Override
374
	public boolean unpublishServer() {
375
		if (!this.isPublished()) {
376
			return false;
377
		}
378
379
		if (this.multiplayerScope == MultiplayerScope.LAN) {
380
			LOGGER.info("Unpublishing integrated server (was on port {})", this.publishedPort);
381
		}
382
383
		this.getConnection().stopTcpServerListener();
384
		Component reason = Component.translatable("multiplayer.disconnect.server_shutdown");
385
386
		for (ServerPlayer player : Lists.newArrayList(this.getPlayerList().getPlayers())) {
387
			if (!player.getUUID().equals(this.uuid)) {
388
				player.connection.disconnect(reason);
389
			}
390
		}
391
392
		this.teardownPublishedState();
393
		return true;
394
	}
395
396
	@Override
397
	public void stopServer() {
398
		this.teardownPublishedState();
399
		super.stopServer();
400
	}
401
402
	@Override
403
	public void halt(final boolean wait) {
404
		this.executeBlocking(() -> {
405
			for (ServerPlayer player : Lists.newArrayList(this.getPlayerList().getPlayers())) {
406
				if (!player.getUUID().equals(this.uuid)) {
407
					this.getPlayerList().remove(player);
408
				}
409
			}
410
		});
411
		super.halt(wait);
412
		this.stopLanPinger();
413
	}
414
415
	@Override
416
	public boolean isPublished() {
417
		return this.multiplayerScope != MultiplayerScope.OFF;
418
	}
419
420
	@Override
421
	public void setDefaultGameType(final GameType gameType) {
422
		super.setDefaultGameType(gameType);
423
		if (this.minecraft.gui.screen() instanceof WorldOptionsScreen worldOptionsScreen) {
424
			worldOptionsScreen.onDefaultGameModeChanged(gameType);
425
		}
426
	}
427
428
	@Override
429
	public int getPort() {
430
		return this.publishedPort;
431
	}
432
433
	@Override
434
	public LevelBasedPermissionSet operatorUserPermissions() {
435
		return LevelBasedPermissionSet.GAMEMASTER;
436
	}
437
438
	public LevelBasedPermissionSet getFunctionCompilationPermissions() {
439
		return LevelBasedPermissionSet.GAMEMASTER;
440
	}
441
442
	public void setUUID(final UUID uuid) {
443
		this.uuid = uuid;
444
	}
445
446
	@Override
447
	public boolean isSingleplayerOwner(final NameAndId nameAndId) {
448
		return this.getSingleplayerProfile() != null && nameAndId.name().equalsIgnoreCase(this.getSingleplayerProfile().name());
449
	}
450
451
	@Override
452
	public int getScaledTrackingDistance(final int baseRange) {
453
		return (int)(this.minecraft.options.entityDistanceScaling().get() * baseRange);
454
	}
455
456
	@Override
457
	public boolean forceSynchronousWrites() {
458
		return this.minecraft.options.syncWrites;
459
	}
460
461
	@Override
462
	public @Nullable GameType getForcedGameType() {
463
		return this.forceGameMode() && this.isPublished() && !this.isHardcore() ? this.worldData.getGameType() : null;
464
	}
465
466
	@Override
467
	public boolean forceGameMode() {
468
		return this.forceGameMode;
469
	}
470
471
	@Override
472
	public void setForceGameMode(final boolean forceGameMode) {
473
		this.forceGameMode = forceGameMode;
474
		this.enforceGameTypeForPlayers(this.getDefaultGameType());
475
	}
476
477
	@Override
478
	protected GlobalPos selectLevelLoadFocusPos() {
479
		UUID lastSinglePlayerOwnerUUID = this.worldData.getSinglePlayerUUID();
480
		if (lastSinglePlayerOwnerUUID == null) {
481
			return super.selectLevelLoadFocusPos();
482
		}
483
484
		Optional<CompoundTag> playerData = this.playerDataStorage.load(new NameAndId(lastSinglePlayerOwnerUUID, "<single player owner>"));
485
		if (playerData.isEmpty()) {
486
			return super.selectLevelLoadFocusPos();
487
		}
488
489
		try (ScopedCollector reporter = new ScopedCollector(LOGGER)) {
490
			ValueInput input = TagValueInput.create(reporter, this.registryAccess(), playerData.get());
491
			SavedPosition loadedPosition = input.read(SavedPosition.MAP_CODEC).orElse(SavedPosition.EMPTY);
492
			if (loadedPosition.dimension().isPresent() && loadedPosition.position().isPresent()) {
493
				return new GlobalPos(loadedPosition.dimension().get(), BlockPos.containing(loadedPosition.position().get()));
494
			}
495
		}
496
497
		return super.selectLevelLoadFocusPos();
498
	}
499
500
	@Override
501
	public void sendLowDiskSpaceWarning() {
502
		super.sendLowDiskSpaceWarning();
503
		this.minecraft.sendLowDiskSpaceWarning();
504
	}
505
506
	@Override
507
	public void reportChunkLoadFailure(final Throwable throwable, final RegionStorageInfo storageInfo, final ChunkPos pos) {
508
		super.reportChunkLoadFailure(throwable, storageInfo, pos);
509
		this.warnOnLowDiskSpace();
510
		this.minecraft.execute(() -> SystemToast.onChunkLoadFailure(this.minecraft, pos));
511
	}
512
513
	@Override
514
	public void reportChunkSaveFailure(final Throwable throwable, final RegionStorageInfo storageInfo, final ChunkPos pos) {
515
		super.reportChunkSaveFailure(throwable, storageInfo, pos);
516
		this.warnOnLowDiskSpace();
517
		this.minecraft.execute(() -> SystemToast.onChunkSaveFailure(this.minecraft, pos));
518
	}
519
520
	@Override
521
	public int getMaxPlayers() {
522
		return 8;
523
	}
524
525
	public Collection<GizmoInstance> getPerTickGizmos() {
526
		return this.latestTicksGizmos;
527
	}
528
529
	private void setMultiplayerScope(final MultiplayerScope multiplayerScope) {
530
		if (this.multiplayerScope != multiplayerScope) {
531
			this.multiplayerScope = multiplayerScope;
532
		}
533
	}
534
535
	public MultiplayerScope getMultiplayerScope() {
536
		return this.multiplayerScope;
537
	}
538
}
539

Decompiled Minecraft 26.3 source of IntegratedServer (net/minecraft/client/server/IntegratedServer.java) with Mojang official mappings, stored verbatim on the site.