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

import java.util.ArrayList;
import java.util.List;
5
import emu.grasscutter.net.packet.BasePacket;
Melledy's avatar
Melledy committed
6
7
8
9
10
11
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;
12
	private final Class<? extends BasePacket> packetClass;
Melledy's avatar
Melledy committed
13
	
14
	public InvokeHandler(Class<? extends BasePacket> packetClass) {
Melledy's avatar
Melledy committed
15
16
17
18
19
20
21
22
		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) {
23
24
25
26
27
			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
28
29
30
		}
	}
	
31
	public synchronized void update(Player player) {
Melledy's avatar
Melledy committed
32
33
34
35
36
37
38
39
40
		if (player.getWorld() == null) {
			this.entryListForwardAll.clear();
			this.entryListForwardAllExceptCur.clear();
			this.entryListForwardHost.clear();
			return;
		}
		
		try {
			if (entryListForwardAll.size() > 0) {
41
				BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardAll);
42
				player.getScene().broadcastPacket(packet);
Melledy's avatar
Melledy committed
43
44
45
				this.entryListForwardAll.clear();
			}
			if (entryListForwardAllExceptCur.size() > 0) {
46
				BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardAllExceptCur);
47
				player.getScene().broadcastPacketToOthers(player, packet);
Melledy's avatar
Melledy committed
48
49
50
				this.entryListForwardAllExceptCur.clear();
			}
			if (entryListForwardHost.size() > 0) {
51
				BasePacket packet = packetClass.getDeclaredConstructor(List.class).newInstance(this.entryListForwardHost);
Melledy's avatar
Melledy committed
52
53
54
55
56
57
58
59
				player.getWorld().getHost().sendPacket(packet);
				this.entryListForwardHost.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}