InvokeHandler.java 2.06 KB
Newer Older
Melledy's avatar
Melledy committed
1
package emu.grasscutter.game.player;
Melledy's avatar
Melledy committed
2
3
4

import java.util.ArrayList;
import java.util.List;
Melledy's avatar
Melledy committed
5

6
import emu.grasscutter.net.packet.BasePacket;
Melledy's avatar
Melledy committed
7
8
9
10
11
12
import emu.grasscutter.net.proto.ForwardTypeOuterClass.ForwardType;

public class InvokeHandler<T> {
	private final List<T> entryListForwardAll;
	private final List<T> entryListForwardAllExceptCur;
	private final List<T> entryListForwardHost;
13
	private final Class<? extends BasePacket> packetClass;
Melledy's avatar
Melledy committed
14
	
15
	public InvokeHandler(Class<? extends BasePacket> packetClass) {
Melledy's avatar
Melledy committed
16
17
18
19
20
21
22
23
		this.entryListForwardAll = new ArrayList<>();
		this.entryListForwardAllExceptCur = new ArrayList<>();
		this.entryListForwardHost = new ArrayList<>();
		this.packetClass = packetClass;
	}

	public synchronized void addEntry(ForwardType forward, T entry) {
		switch (forward) {
24
25
26
27
28
			case FORWARD_TO_ALL -> entryListForwardAll.add(entry);
			case FORWARD_TO_ALL_EXCEPT_CUR, FORWARD_TO_ALL_EXIST_EXCEPT_CUR -> entryListForwardAllExceptCur.add(entry);
			case FORWARD_TO_HOST -> entryListForwardHost.add(entry);
			default -> {
			}
Melledy's avatar
Melledy committed
29
30
31
		}
	}
	
32
	public synchronized void update(Player player) {
Melledy's avatar
Melledy committed
33
34
35
36
37
38
39
40
41
		if (player.getWorld() == null) {
			this.entryListForwardAll.clear();
			this.entryListForwardAllExceptCur.clear();
			this.entryListForwardHost.clear();
			return;
		}
		
		try {
			if (entryListForwardAll.size() > 0) {
42
				BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardAll);
43
				player.getScene().broadcastPacket(packet);
Melledy's avatar
Melledy committed
44
45
46
				this.entryListForwardAll.clear();
			}
			if (entryListForwardAllExceptCur.size() > 0) {
47
				BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardAllExceptCur);
48
				player.getScene().broadcastPacketToOthers(player, packet);
Melledy's avatar
Melledy committed
49
50
51
				this.entryListForwardAllExceptCur.clear();
			}
			if (entryListForwardHost.size() > 0) {
52
				BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardHost);
Melledy's avatar
Melledy committed
53
54
55
56
57
58
59
60
				player.getWorld().getHost().sendPacket(packet);
				this.entryListForwardHost.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}