GameServer.java 9.01 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.server.game;

3
import emu.grasscutter.GameConstants;
Melledy's avatar
Melledy committed
4
import emu.grasscutter.Grasscutter;
Jaida Wu's avatar
Jaida Wu committed
5
import emu.grasscutter.command.CommandMap;
Melledy's avatar
Melledy committed
6
import emu.grasscutter.database.DatabaseHelper;
Melledy's avatar
Melledy committed
7
import emu.grasscutter.game.Account;
Akka's avatar
Akka committed
8
import emu.grasscutter.game.combine.CombineManger;
Kengxxiao's avatar
Kengxxiao committed
9
import emu.grasscutter.game.drop.DropManager;
Melledy's avatar
Melledy committed
10
import emu.grasscutter.game.dungeons.DungeonManager;
Kinesis's avatar
Kinesis committed
11
import emu.grasscutter.game.expedition.ExpeditionManager;
Melledy's avatar
Melledy committed
12
13
14
import emu.grasscutter.game.gacha.GachaManager;
import emu.grasscutter.game.managers.InventoryManager;
import emu.grasscutter.game.managers.MultiplayerManager;
Melledy's avatar
Melledy committed
15
16
import emu.grasscutter.game.managers.chat.ChatManager;
import emu.grasscutter.game.managers.chat.ChatManagerHandler;
Melledy's avatar
Melledy committed
17
import emu.grasscutter.game.player.Player;
18
import emu.grasscutter.game.quest.ServerQuestHandler;
Melledy's avatar
Melledy committed
19
import emu.grasscutter.game.shop.ShopManager;
20
import emu.grasscutter.game.tower.TowerScheduleManager;
Melledy's avatar
Melledy committed
21
import emu.grasscutter.game.world.World;
Akka's avatar
Akka committed
22
import emu.grasscutter.game.world.WorldDataManager;
Melledy's avatar
Melledy committed
23
24
import emu.grasscutter.net.packet.PacketHandler;
import emu.grasscutter.net.proto.SocialDetailOuterClass.SocialDetail;
KingRainbow44's avatar
KingRainbow44 committed
25
import emu.grasscutter.server.event.types.ServerEvent;
KingRainbow44's avatar
KingRainbow44 committed
26
27
28
import emu.grasscutter.server.event.game.ServerTickEvent;
import emu.grasscutter.server.event.internal.ServerStartEvent;
import emu.grasscutter.server.event.internal.ServerStopEvent;
29
import emu.grasscutter.server.scheduler.ServerTaskScheduler;
Yazawazi's avatar
Yazawazi committed
30
import emu.grasscutter.task.TaskMap;
31
32
import kcp.highway.ChannelConfig;
import kcp.highway.KcpServer;
33
import lombok.Getter;
Melledy's avatar
Melledy committed
34

Kengxxiao's avatar
Kengxxiao committed
35
import java.net.InetSocketAddress;
36
import java.time.Instant;
Kengxxiao's avatar
Kengxxiao committed
37
38
39
40
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

41
import static emu.grasscutter.utils.Language.translate;
42
import static emu.grasscutter.Configuration.*;
43

44
public final class GameServer extends KcpServer {
Melledy's avatar
Melledy committed
45
46
	private final InetSocketAddress address;
	private final GameServerPacketHandler packetHandler;
47
	private final ServerQuestHandler questHandler;
48
49
    @Getter private final ServerTaskScheduler scheduler;

50
	private final Map<Integer, Player> players;
51
	private final Set<World> worlds;
52

53
	private ChatManagerHandler chatManager;
Melledy's avatar
Melledy committed
54
55
56
57
58
	private final InventoryManager inventoryManager;
	private final GachaManager gachaManager;
	private final ShopManager shopManager;
	private final MultiplayerManager multiplayerManager;
	private final DungeonManager dungeonManager;
Kinesis's avatar
Kinesis committed
59
	private final ExpeditionManager expeditionManager;
Melledy's avatar
Melledy committed
60
	private final CommandMap commandMap;
Yazawazi's avatar
Yazawazi committed
61
	private final TaskMap taskMap;
Kengxxiao's avatar
Kengxxiao committed
62
	private final DropManager dropManager;
63
	private final WorldDataManager worldDataManager;
64

Akka's avatar
Akka committed
65
	private final CombineManger combineManger;
66
	private final TowerScheduleManager towerScheduleManager;
Akka's avatar
Akka committed
67

68
	public GameServer() {
69
		this(getAdapterInetSocketAddress());
70
	}
71

Melledy's avatar
Melledy committed
72
	public GameServer(InetSocketAddress address) {
73
74
75
76
77
78
79
80
81
82
		ChannelConfig channelConfig = new ChannelConfig();
		channelConfig.nodelay(true,40,2,true);
		channelConfig.setMtu(1400);
		channelConfig.setSndwnd(256);
		channelConfig.setRcvwnd(256);
		channelConfig.setTimeoutMillis(30*1000);//30s
		channelConfig.setUseConvChannel(true);
		channelConfig.setAckNoDelay(false);

		this.init(GameSessionManager.getListener(),channelConfig,address);
83

Melledy's avatar
Melledy committed
84
85
		this.address = address;
		this.packetHandler = new GameServerPacketHandler(PacketHandler.class);
86
		this.questHandler = new ServerQuestHandler();
87
        this.scheduler = new ServerTaskScheduler();
Melledy's avatar
Melledy committed
88
		this.players = new ConcurrentHashMap<>();
89
		this.worlds = Collections.synchronizedSet(new HashSet<>());
90

Melledy's avatar
Melledy committed
91
92
93
94
95
96
		this.chatManager = new ChatManager(this);
		this.inventoryManager = new InventoryManager(this);
		this.gachaManager = new GachaManager(this);
		this.shopManager = new ShopManager(this);
		this.multiplayerManager = new MultiplayerManager(this);
		this.dungeonManager = new DungeonManager(this);
Melledy's avatar
Melledy committed
97
		this.commandMap = new CommandMap(true);
Yazawazi's avatar
Yazawazi committed
98
		this.taskMap = new TaskMap(true);
Kengxxiao's avatar
Kengxxiao committed
99
		this.dropManager = new DropManager(this);
Kinesis's avatar
Kinesis committed
100
		this.expeditionManager = new ExpeditionManager(this);
Akka's avatar
Akka committed
101
		this.combineManger = new CombineManger(this);
102
		this.towerScheduleManager = new TowerScheduleManager(this);
Akka's avatar
Akka committed
103
		this.worldDataManager = new WorldDataManager(this);
Melledy's avatar
Melledy committed
104
		// Hook into shutdown event.
Melledy's avatar
Melledy committed
105
106
		Runtime.getRuntime().addShutdownHook(new Thread(this::onServerShutdown));
	}
107

Melledy's avatar
Melledy committed
108
109
110
111
	public GameServerPacketHandler getPacketHandler() {
		return packetHandler;
	}

112
113
114
115
	public ServerQuestHandler getQuestHandler() {
		return questHandler;
	}

116
	public Map<Integer, Player> getPlayers() {
Melledy's avatar
Melledy committed
117
118
119
		return players;
	}

120
121
122
123
	public Set<World> getWorlds() {
		return worlds;
	}

124
	public ChatManagerHandler getChatManager() {
Melledy's avatar
Melledy committed
125
126
		return chatManager;
	}
127

128
129
130
	public void setChatManager(ChatManagerHandler chatManager) {
		this.chatManager = chatManager;
	}
Melledy's avatar
Melledy committed
131
132
133
134
135
136
137
138

	public InventoryManager getInventoryManager() {
		return inventoryManager;
	}

	public GachaManager getGachaManager() {
		return gachaManager;
	}
139

Melledy's avatar
Melledy committed
140
141
142
143
144
145
146
	public ShopManager getShopManager() {
		return shopManager;
	}

	public MultiplayerManager getMultiplayerManager() {
		return multiplayerManager;
	}
Kengxxiao's avatar
Kengxxiao committed
147
148
149
150

	public DropManager getDropManager() {
		return dropManager;
	}
151

Melledy's avatar
Melledy committed
152
153
154
	public DungeonManager getDungeonManager() {
		return dungeonManager;
	}
Kinesis's avatar
Kinesis committed
155
156
157
158
159

	public ExpeditionManager getExpeditionManager() {
		return expeditionManager;
	}

Melledy's avatar
Melledy committed
160
161
162
	public CommandMap getCommandMap() {
		return this.commandMap;
	}
Yazawazi's avatar
Yazawazi committed
163

Akka's avatar
Akka committed
164
165
166
	public CombineManger getCombineManger(){
		return this.combineManger;
	}
Kinesis's avatar
Kinesis committed
167

168
169
170
171
	public TowerScheduleManager getTowerScheduleManager() {
		return towerScheduleManager;
	}

Akka's avatar
Akka committed
172
173
174
	public WorldDataManager getWorldDataManager() {
		return worldDataManager;
	}
175

Yazawazi's avatar
Yazawazi committed
176
177
178
	public TaskMap getTaskMap() {
		return this.taskMap;
	}
179

180
181
182
183
184
185
186
187
188
189
190
191
	private static InetSocketAddress getAdapterInetSocketAddress(){
		InetSocketAddress inetSocketAddress;
		if(GAME_INFO.bindAddress.equals("")){
			inetSocketAddress=new InetSocketAddress(GAME_INFO.bindPort);
		}else{
			inetSocketAddress=new InetSocketAddress(
					GAME_INFO.bindAddress,
					GAME_INFO.bindPort
			);
		}
		return inetSocketAddress;
	}
192

193
	public void registerPlayer(Player player) {
194
		getPlayers().put(player.getUid(), player);
Melledy's avatar
Melledy committed
195
196
	}

197
	public Player getPlayerByUid(int id) {
198
		return this.getPlayerByUid(id, false);
Melledy's avatar
Melledy committed
199
	}
200

201
	public Player getPlayerByUid(int id, boolean allowOfflinePlayers) {
Melledy's avatar
Melledy committed
202
		// Console check
203
		if (id == GameConstants.SERVER_CONSOLE_UID) {
Melledy's avatar
Melledy committed
204
205
			return null;
		}
206

Melledy's avatar
Melledy committed
207
		// Get from online players
208
		Player player = this.getPlayers().get(id);
209

210
211
212
		if (!allowOfflinePlayers) {
			return player;
		}
213

Melledy's avatar
Melledy committed
214
215
		// Check database if character isnt here
		if (player == null) {
216
			player = DatabaseHelper.getPlayerByUid(id);
Melledy's avatar
Melledy committed
217
		}
218

Melledy's avatar
Melledy committed
219
220
		return player;
	}
221

222
223
224
225
	public Player getPlayerByAccountId(String accountId) {
		Optional<Player> playerOpt = getPlayers().values().stream().filter(player -> player.getAccount().getId().equals(accountId)).findFirst();
		return playerOpt.orElse(null);
	}
226

227
	public SocialDetail.Builder getSocialDetailByUid(int id) {
Melledy's avatar
Melledy committed
228
		// Get from online players
229
		Player player = this.getPlayerByUid(id, true);
230

Melledy's avatar
Melledy committed
231
232
233
		if (player == null) {
			return null;
		}
234

Melledy's avatar
Melledy committed
235
236
		return player.getSocialDetail();
	}
237

Melledy's avatar
Melledy committed
238
	public Account getAccountByName(String username) {
239
		Optional<Player> playerOpt = getPlayers().values().stream().filter(player -> player.getAccount().getUsername().equals(username)).findFirst();
240
		if (playerOpt.isPresent()) {
Melledy's avatar
Melledy committed
241
242
243
244
			return playerOpt.get().getAccount();
		}
		return DatabaseHelper.getAccountByName(username);
	}
245

246
247
    public synchronized void onTick() {
        var tickStart = Instant.now();
248

249
250
251
252
        // Tick worlds.
        Iterator<World> it = this.getWorlds().iterator();
        while (it.hasNext()) {
            World world = it.next();
253

254
255
256
            if (world.getPlayerCount() == 0) {
                it.remove();
            }
257

258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
            world.onTick();
        }

        // Tick players.
        for (Player player : this.getPlayers().values()) {
            player.onTick();
        }

        // Tick scheduler.
        this.getScheduler().runTasks();

        // Call server tick event.
        ServerTickEvent event = new ServerTickEvent(tickStart, Instant.now());
        event.call();
    }
273

274
275
276
	public void registerWorld(World world) {
		this.getWorlds().add(world);
	}
277

278
279
	public void deregisterWorld(World world) {
		// TODO Auto-generated method stub
280

281
	}
Melledy's avatar
Melledy committed
282

283
	public void start() {
284
		// Schedule game loop.
Bwly999's avatar
Bwly999 committed
285
		Timer gameLoop = new Timer();
286
287
288
289
290
291
		gameLoop.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				try {
					onTick();
				} catch (Exception e) {
292
					Grasscutter.getLogger().error(translate("messages.game.game_update_error"), e);
293
294
				}
			}
Bwly999's avatar
Bwly999 committed
295
		}, new Date(), 1000L);
296
297
		Grasscutter.getLogger().info(translate("messages.status.free_software"));
		Grasscutter.getLogger().info(translate("messages.game.port_bind", Integer.toString(address.getPort())));
298
299
		ServerStartEvent event = new ServerStartEvent(ServerEvent.Type.GAME, OffsetDateTime.now());
		event.call();
Melledy's avatar
Melledy committed
300
	}
301

Melledy's avatar
Melledy committed
302
	public void onServerShutdown() {
KingRainbow44's avatar
KingRainbow44 committed
303
		ServerStopEvent event = new ServerStopEvent(ServerEvent.Type.GAME, OffsetDateTime.now()); event.call();
304

Melledy's avatar
Melledy committed
305
		// Kick and save all players
306
		List<Player> list = new ArrayList<>(this.getPlayers().size());
Melledy's avatar
Melledy committed
307
		list.addAll(this.getPlayers().values());
308

309
		for (Player player : list) {
Melledy's avatar
Melledy committed
310
311
312
313
			player.getSession().close();
		}
	}
}