ServerPlayerGameMode .java

net.minecraft.server.level.ServerPlayerGameMode (class, 455 lines): members: getPreviousGameModeForPlayer, previousGameModeForPlayer, FLIGHT_DISABLE_RANGE.

net.minecraft.server.levelclass455 linesserver16.5 KB

API Surface (12)

boolean changeGameModeForPlayer(final GameType gameModeForPlayer)
void setGameModeForPlayer(final GameType gameModeForPlayer, final @Nullable GameType previousGameModeForPlayer)
GameType getGameModeForPlayer()
boolean isSurvival()
boolean isCreative()
void tick()
void handleBlockBreakAction(final BlockPos pos, final ServerboundPlayerActionPacket.Action action, final Direction direction, final int maxY, final int sequence)
void destroyAndAck(final BlockPos pos, final int sequence, final String exitId)
boolean destroyBlock(final BlockPos pos)
InteractionResult useItem(final ServerPlayer player, final Level level, final ItemStack itemStack, final InteractionHand hand)
InteractionResult useItemOn(final ServerPlayer player, final Level level, final ItemStack itemStack, final InteractionHand hand, final BlockHitResult hitResult)
void setLevel(final ServerLevel newLevel)

Fields & Constants (17)

FLIGHT_DISABLE_RANGE
LOGGER
level
player
gameModeForPlayer
previousGameModeForPlayer
isDestroyingBlock
destroyProgressStart
destroyPos
destroyDirection
gameTicks
hasDelayedDestroy
delayedDestroyPos
delayedTickStart
lastSentState
maxY
hand

String literals (13)

"too far"
"too high"
"spawn protection"
"may not interact"
"creative destroy"
"block action restricted"
"insta mine"
"actual start of destroying"
"destroyed"
"stopped destroying"
"aborted mismatched destroying"
"aborted destroying"
"spectator.cannot_teleport"

Full Source

ServerPlayerGameMode.java455 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.server.level;
2
3
import com.mojang.logging.LogUtils;
4
import java.util.List;
5
import java.util.Objects;
6
import net.minecraft.ChatFormatting;
7
import net.minecraft.SharedConstants;
8
import net.minecraft.advancements.triggers.CriteriaTriggers;
9
import net.minecraft.core.BlockPos;
10
import net.minecraft.core.Direction;
11
import net.minecraft.network.chat.Component;
12
import net.minecraft.network.protocol.game.ClientboundBlockUpdatePacket;
13
import net.minecraft.network.protocol.game.ClientboundPlayerInfoUpdatePacket;
14
import net.minecraft.network.protocol.game.ServerboundPlayerActionPacket;
15
import net.minecraft.world.InteractionHand;
16
import net.minecraft.world.InteractionResult;
17
import net.minecraft.world.MenuProvider;
18
import net.minecraft.world.entity.Entity;
19
import net.minecraft.world.entity.EquipmentSlot;
20
import net.minecraft.world.entity.player.Abilities;
21
import net.minecraft.world.item.ItemStack;
22
import net.minecraft.world.item.context.UseOnContext;
23
import net.minecraft.world.item.enchantment.EnchantmentHelper;
24
import net.minecraft.world.level.GameType;
25
import net.minecraft.world.level.Level;
26
import net.minecraft.world.level.block.Block;
27
import net.minecraft.world.level.block.GameMasterBlock;
28
import net.minecraft.world.level.block.Portal;
29
import net.minecraft.world.level.block.entity.BlockEntity;
30
import net.minecraft.world.level.block.state.BlockState;
31
import net.minecraft.world.level.portal.TeleportTransition;
32
import net.minecraft.world.phys.BlockHitResult;
33
import net.minecraft.world.phys.Vec3;
34
import net.minecraft.world.phys.shapes.VoxelShape;
35
import org.jspecify.annotations.Nullable;
36
import org.slf4j.Logger;
37
38
public class ServerPlayerGameMode {
39
	private static final double FLIGHT_DISABLE_RANGE = 1.0;
40
	private static final Logger LOGGER = LogUtils.getLogger();
41
	protected ServerLevel level;
42
	protected final ServerPlayer player;
43
	private GameType gameModeForPlayer = GameType.DEFAULT_MODE;
44
	private @Nullable GameType previousGameModeForPlayer;
45
	private boolean isDestroyingBlock;
46
	private int destroyProgressStart;
47
	private BlockPos destroyPos = BlockPos.ZERO;
48
	private Direction destroyDirection = Direction.DOWN;
49
	private int gameTicks;
50
	private boolean hasDelayedDestroy;
51
	private BlockPos delayedDestroyPos = BlockPos.ZERO;
52
	private int delayedTickStart;
53
	private int lastSentState = -1;
54
55
	public ServerPlayerGameMode(final ServerPlayer player) {
56
		this.player = player;
57
		this.level = player.level();
58
	}
59
60
	public boolean changeGameModeForPlayer(final GameType gameModeForPlayer) {
61
		if (gameModeForPlayer == this.gameModeForPlayer) {
62
			return false;
63
		}
64
65
		Abilities abilities = this.player.getAbilities();
66
		this.setGameModeForPlayer(gameModeForPlayer, this.gameModeForPlayer);
67
		if (abilities.flying && gameModeForPlayer != GameType.SPECTATOR && this.isInRangeOfGround()) {
68
			abilities.flying = false;
69
		}
70
71
		this.player.onUpdateAbilities();
72
		this.level
73
			.getServer()
74
			.getPlayerList()
75
			.broadcastAll(new ClientboundPlayerInfoUpdatePacket(ClientboundPlayerInfoUpdatePacket.Action.UPDATE_GAME_MODE, this.player));
76
		this.level.updateSleepingPlayerList();
77
		if (gameModeForPlayer == GameType.CREATIVE) {
78
			this.player.resetCurrentImpulseContext();
79
		}
80
81
		return true;
82
	}
83
84
	protected void setGameModeForPlayer(final GameType gameModeForPlayer, final @Nullable GameType previousGameModeForPlayer) {
85
		this.previousGameModeForPlayer = previousGameModeForPlayer;
86
		this.gameModeForPlayer = gameModeForPlayer;
87
		Abilities abilities = this.player.getAbilities();
88
		gameModeForPlayer.updatePlayerAbilities(abilities);
89
	}
90
91
	private boolean isInRangeOfGround() {
92
		List<VoxelShape> clipping = Entity.collectAllColliders(this.player, this.level, this.player.getBoundingBox());
93
		return clipping.isEmpty() && this.player.getAvailableSpaceBelow(1.0) < 1.0;
94
	}
95
96
	public GameType getGameModeForPlayer() {
97
		return this.gameModeForPlayer;
98
	}
99
100
	public @Nullable GameType getPreviousGameModeForPlayer() {
101
		return this.previousGameModeForPlayer;
102
	}
103
104
	public boolean isSurvival() {
105
		return this.gameModeForPlayer.isSurvival();
106
	}
107
108
	public boolean isCreative() {
109
		return this.gameModeForPlayer.isCreative();
110
	}
111
112
	public void tick() {
113
		this.gameTicks++;
114
		if (this.hasDelayedDestroy) {
115
			BlockState blockState = this.level.getBlockState(this.delayedDestroyPos);
116
			if (blockState.isAir()) {
117
				this.hasDelayedDestroy = false;
118
			} else {
119
				float destroyProgress = this.incrementDestroyProgress(blockState, this.delayedDestroyPos, this.delayedTickStart);
120
				if (destroyProgress >= 1.0F) {
121
					this.hasDelayedDestroy = false;
122
					this.destroyBlock(this.delayedDestroyPos);
123
				}
124
			}
125
		} else if (this.isDestroyingBlock) {
126
			BlockState blockState = this.level.getBlockState(this.destroyPos);
127
			if (blockState.isAir()) {
128
				this.level.destroyBlockProgress(this.player.getId(), this.destroyPos, -1);
129
				this.lastSentState = -1;
130
				this.isDestroyingBlock = false;
131
			} else {
132
				int ticksSpentDestroying = this.gameTicks - this.destroyProgressStart;
133
				int event;
134
				if (ticksSpentDestroying % 4 == 0) {
135
					event = 2020;
136
				} else {
137
					event = 2019;
138
				}
139
140
				this.incrementDestroyProgress(blockState, this.destroyPos, ticksSpentDestroying);
141
				this.level.levelEvent(null, event, this.destroyPos, this.destroyDirection.ordinal());
142
			}
143
		}
144
	}
145
146
	private float incrementDestroyProgress(final BlockState blockState, final BlockPos delayedDestroyPos, final int ticksSpentDestroying) {
147
		float destroyProgress = blockState.getDestroyProgress(this.player, this.player.level(), delayedDestroyPos) * (ticksSpentDestroying + 1);
148
		int state = (int)(destroyProgress * 10.0F);
149
		if (state != this.lastSentState) {
150
			this.level.destroyBlockProgress(this.player.getId(), delayedDestroyPos, state);
151
			this.lastSentState = state;
152
		}
153
154
		return destroyProgress;
155
	}
156
157
	private void debugLogging(final BlockPos pos, final boolean allGood, final int sequence, final String message) {
158
		if (SharedConstants.DEBUG_BLOCK_BREAK) {
159
			LOGGER.debug("Server ACK {} {} {} {}", sequence, pos, allGood, message);
160
		}
161
	}
162
163
	public void handleBlockBreakAction(
164
		final BlockPos pos, final ServerboundPlayerActionPacket.Action action, final Direction direction, final int maxY, final int sequence
165
	) {
166
		if (!this.player.isWithinBlockInteractionRange(pos, 1.0)) {
167
			if (this.isDestroyingBlock && action == ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK) {
168
				this.abortDestroyBlock(pos, sequence);
169
			}
170
171
			this.debugLogging(pos, false, sequence, "too far");
172
		} else if (pos.getY() > maxY) {
173
			this.player.connection.send(new ClientboundBlockUpdatePacket(pos, this.level.getBlockState(pos)));
174
			this.debugLogging(pos, false, sequence, "too high");
175
		} else {
176
			if (action == ServerboundPlayerActionPacket.Action.START_DESTROY_BLOCK) {
177
				if (this.level.getServer().isUnderSpawnProtection(this.level, pos, this.player)) {
178
					this.player.sendSpawnProtectionMessage(pos);
179
					this.debugLogging(pos, false, sequence, "spawn protection");
180
					return;
181
				}
182
183
				if (!this.level.mayInteract(this.player, pos)) {
184
					this.player.connection.send(new ClientboundBlockUpdatePacket(pos, this.level.getBlockState(pos)));
185
					this.debugLogging(pos, false, sequence, "may not interact");
186
					return;
187
				}
188
189
				if (this.player.getAbilities().instabuild) {
190
					this.destroyAndAck(pos, sequence, "creative destroy");
191
					return;
192
				}
193
194
				if (this.player.blockActionRestricted(this.level, pos, this.gameModeForPlayer)) {
195
					this.player.connection.send(new ClientboundBlockUpdatePacket(pos, this.level.getBlockState(pos)));
196
					this.debugLogging(pos, false, sequence, "block action restricted");
197
					return;
198
				}
199
200
				this.destroyProgressStart = this.gameTicks;
201
				float progress = 1.0F;
202
				BlockState blockState = this.level.getBlockState(pos);
203
				if (!blockState.isAir()) {
204
					EnchantmentHelper.onHitBlock(
205
						this.level,
206
						this.player.getMainHandItem(),
207
						this.player,
208
						this.player,
209
						EquipmentSlot.MAINHAND,
210
						Vec3.atCenterOf(pos),
211
						blockState,
212
						item -> this.player.onEquippedItemBroken(item, EquipmentSlot.MAINHAND)
213
					);
214
					blockState.attack(this.level, pos, this.player);
215
					progress = blockState.getDestroyProgress(this.player, this.player.level(), pos);
216
				}
217
218
				if (!blockState.isAir() && progress >= 1.0F) {
219
					this.destroyAndAck(pos, sequence, "insta mine");
220
				} else {
221
					if (this.isDestroyingBlock) {
222
						this.player.connection.send(new ClientboundBlockUpdatePacket(this.destroyPos, this.level.getBlockState(this.destroyPos)));
223
						this.debugLogging(pos, false, sequence, "abort destroying since another started (client insta mine, server disagreed)");
224
					}
225
226
					this.isDestroyingBlock = true;
227
					this.destroyPos = pos.immutable();
228
					this.destroyDirection = direction;
229
					int state = (int)(progress * 10.0F);
230
					this.level.destroyBlockProgress(this.player.getId(), pos, state);
231
					this.debugLogging(pos, true, sequence, "actual start of destroying");
232
					this.lastSentState = state;
233
				}
234
			} else if (action == ServerboundPlayerActionPacket.Action.CHANGE_DESTROY_DIRECTION) {
235
				this.destroyDirection = direction;
236
			} else if (action == ServerboundPlayerActionPacket.Action.STOP_DESTROY_BLOCK) {
237
				if (pos.equals(this.destroyPos)) {
238
					int ticksSpentDestroying = this.gameTicks - this.destroyProgressStart;
239
					BlockState state = this.level.getBlockState(pos);
240
					if (!state.isAir()) {
241
						float destroyProgress = state.getDestroyProgress(this.player, this.player.level(), pos) * (ticksSpentDestroying + 1);
242
						if (destroyProgress >= 0.7F) {
243
							this.isDestroyingBlock = false;
244
							this.level.destroyBlockProgress(this.player.getId(), pos, -1);
245
							this.destroyAndAck(pos, sequence, "destroyed");
246
							return;
247
						}
248
249
						if (!this.hasDelayedDestroy) {
250
							this.isDestroyingBlock = false;
251
							this.hasDelayedDestroy = true;
252
							this.delayedDestroyPos = pos;
253
							this.delayedTickStart = this.destroyProgressStart;
254
						}
255
					}
256
				}
257
258
				this.debugLogging(pos, true, sequence, "stopped destroying");
259
			} else if (action == ServerboundPlayerActionPacket.Action.ABORT_DESTROY_BLOCK) {
260
				this.abortDestroyBlock(pos, sequence);
261
			}
262
		}
263
	}
264
265
	private void abortDestroyBlock(final BlockPos pos, final int sequence) {
266
		this.isDestroyingBlock = false;
267
		if (!Objects.equals(this.destroyPos, pos)) {
268
			LOGGER.warn("Mismatch in destroy block pos: {} {}", this.destroyPos, pos);
269
			this.level.destroyBlockProgress(this.player.getId(), this.destroyPos, -1);
270
			this.debugLogging(pos, true, sequence, "aborted mismatched destroying");
271
		}
272
273
		this.level.destroyBlockProgress(this.player.getId(), pos, -1);
274
		this.debugLogging(pos, true, sequence, "aborted destroying");
275
	}
276
277
	public void destroyAndAck(final BlockPos pos, final int sequence, final String exitId) {
278
		if (this.destroyBlock(pos)) {
279
			this.debugLogging(pos, true, sequence, exitId);
280
		} else {
281
			this.player.connection.send(new ClientboundBlockUpdatePacket(pos, this.level.getBlockState(pos)));
282
			this.debugLogging(pos, false, sequence, exitId);
283
		}
284
	}
285
286
	public boolean destroyBlock(final BlockPos pos) {
287
		BlockState state = this.level.getBlockState(pos);
288
		if (!this.player.getMainHandItem().canDestroyBlock(state, this.level, pos, this.player)) {
289
			return false;
290
		}
291
292
		BlockEntity blockEntity = this.level.getBlockEntity(pos);
293
		Block block = state.getBlock();
294
		if (block instanceof GameMasterBlock && !this.player.canUseGameMasterBlocks()) {
295
			this.level.sendBlockUpdated(pos, state, state, 3);
296
			return false;
297
		}
298
299
		if (this.player.blockActionRestricted(this.level, pos, this.gameModeForPlayer)) {
300
			return false;
301
		}
302
303
		BlockState adjustedState = block.playerWillDestroy(this.level, pos, state, this.player);
304
		boolean changed = this.level.removeBlock(pos, false);
305
		if (SharedConstants.DEBUG_BLOCK_BREAK) {
306
			LOGGER.info("server broke {} {} -> {}", pos, adjustedState, this.level.getBlockState(pos));
307
		}
308
309
		if (changed) {
310
			block.destroy(this.level, pos, adjustedState);
311
		}
312
313
		if (this.player.preventsBlockDrops()) {
314
			return true;
315
		}
316
317
		ItemStack itemStack = this.player.getMainHandItem();
318
		ItemStack destroyedWith = itemStack.copy();
319
		boolean canDestroy = this.player.hasCorrectToolForDrops(adjustedState);
320
		itemStack.mineBlock(this.level, adjustedState, pos, this.player);
321
		if (changed && canDestroy) {
322
			block.playerDestroy(this.level, this.player, pos, adjustedState, blockEntity, destroyedWith);
323
		}
324
325
		return true;
326
	}
327
328
	public InteractionResult useItem(final ServerPlayer player, final Level level, final ItemStack itemStack, final InteractionHand hand) {
329
		if (this.gameModeForPlayer == GameType.SPECTATOR) {
330
			return InteractionResult.PASS;
331
		}
332
333
		if (player.getCooldowns().isOnCooldown(itemStack)) {
334
			return InteractionResult.PASS;
335
		}
336
337
		int oldCount = itemStack.getCount();
338
		int oldDamage = itemStack.getDamageValue();
339
		InteractionResult result = itemStack.use(level, player, hand);
340
		ItemStack resultStack;
341
		if (result instanceof InteractionResult.Success success) {
342
			resultStack = Objects.requireNonNullElse(success.heldItemTransformedTo(), player.getItemInHand(hand));
343
		} else {
344
			resultStack = player.getItemInHand(hand);
345
		}
346
347
		if (resultStack == itemStack && resultStack.getCount() == oldCount && resultStack.getUseDuration(player) <= 0 && resultStack.getDamageValue() == oldDamage) {
348
			return result;
349
		}
350
351
		if (result instanceof InteractionResult.Fail && resultStack.getUseDuration(player) > 0 && !player.isUsingItem()) {
352
			return result;
353
		}
354
355
		if (itemStack != resultStack) {
356
			player.setItemInHand(hand, resultStack);
357
		}
358
359
		if (resultStack.isEmpty()) {
360
			player.setItemInHand(hand, ItemStack.EMPTY);
361
		}
362
363
		if (!player.isUsingItem()) {
364
			player.inventoryMenu.sendAllDataToRemote();
365
		}
366
367
		return result;
368
	}
369
370
	public InteractionResult useItemOn(
371
		final ServerPlayer player, final Level level, final ItemStack itemStack, final InteractionHand hand, final BlockHitResult hitResult
372
	) {
373
		BlockPos pos = hitResult.getBlockPos();
374
		BlockState state = level.getBlockState(pos);
375
		if (!state.getBlock().isEnabled(level.enabledFeatures())) {
376
			return InteractionResult.FAIL;
377
		}
378
379
		if (this.gameModeForPlayer == GameType.SPECTATOR) {
380
			MenuProvider menuProvider = state.getMenuProvider(level, pos);
381
			if (menuProvider != null) {
382
				player.openMenu(menuProvider);
383
				return InteractionResult.CONSUME;
384
			}
385
386
			if (state.getBlock() instanceof Portal portal) {
387
				ServerLevel serverLevel = player.level();
388
				TeleportTransition teleportTransition = portal.getPortalDestination(serverLevel, player, pos);
389
				if (teleportTransition != null) {
390
					if (player.getCamera() != player) {
391
						player.setCamera(player);
392
					}
393
394
					player.teleportToPortalDestination(serverLevel, teleportTransition);
395
				} else {
396
					player.sendOverlayMessage(Component.translatable("spectator.cannot_teleport").withStyle(ChatFormatting.RED));
397
				}
398
399
				return InteractionResult.CONSUME;
400
			} else {
401
				return InteractionResult.PASS;
402
			}
403
		} else {
404
			boolean haveSomethingInOurHands = !player.getMainHandItem().isEmpty() || !player.getOffhandItem().isEmpty();
405
			boolean suppressUsingBlock = player.isSecondaryUseActive() && haveSomethingInOurHands;
406
			ItemStack usedItemStack = itemStack.copy();
407
			if (!suppressUsingBlock) {
408
				InteractionResult itemUse = state.useItemOn(player.getItemInHand(hand), level, player, hand, hitResult);
409
				if (itemUse.consumesAction()) {
410
					CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(player, pos, usedItemStack);
411
					return itemUse;
412
				}
413
414
				if (itemUse instanceof InteractionResult.TryEmptyHandInteraction && hand == InteractionHand.MAIN_HAND) {
415
					InteractionResult use = state.useWithoutItem(level, player, hitResult);
416
					if (use.consumesAction()) {
417
						CriteriaTriggers.DEFAULT_BLOCK_USE.trigger(player, pos);
418
						return use;
419
					}
420
				}
421
			}
422
423
			if (!itemStack.isEmpty() && !player.getCooldowns().isOnCooldown(itemStack)) {
424
				UseOnContext context = new UseOnContext(player, hand, hitResult);
425
				InteractionResult result;
426
				if (player.hasInfiniteMaterials()) {
427
					int count = itemStack.getCount();
428
					result = itemStack.useOn(context);
429
					itemStack.setCount(count);
430
				} else {
431
					result = itemStack.useOn(context);
432
					if (result instanceof InteractionResult.Success success) {
433
						ItemStack resultItemStack = Objects.requireNonNullElseGet(success.heldItemTransformedTo(), () -> player.getItemInHand(hand));
434
						if (resultItemStack != itemStack) {
435
							player.setItemInHand(hand, resultItemStack);
436
						}
437
					}
438
				}
439
440
				if (result.consumesAction()) {
441
					CriteriaTriggers.ITEM_USED_ON_BLOCK.trigger(player, pos, usedItemStack);
442
				}
443
444
				return result;
445
			} else {
446
				return InteractionResult.PASS;
447
			}
448
		}
449
	}
450
451
	public void setLevel(final ServerLevel newLevel) {
452
		this.level = newLevel;
453
	}
454
}
455

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