GachaManager.java 12 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.game.gacha;

3
import java.io.File;
Melledy's avatar
Melledy committed
4
import java.io.FileReader;
5
import java.nio.file.*;
Melledy's avatar
Melledy committed
6
7
8
9
10
11
12
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import com.google.gson.reflect.TypeToken;

13
import com.sun.nio.file.SensitivityWatchEventModifier;
Melledy's avatar
Melledy committed
14
import emu.grasscutter.Grasscutter;
15
import emu.grasscutter.data.GameData;
16
import emu.grasscutter.data.common.ItemParamData;
Melledy's avatar
Melledy committed
17
import emu.grasscutter.data.def.ItemData;
18
import emu.grasscutter.database.DatabaseHelper;
19
import emu.grasscutter.game.avatar.Avatar;
Melledy's avatar
Melledy committed
20
import emu.grasscutter.game.gacha.GachaBanner.BannerType;
21
import emu.grasscutter.game.inventory.GameItem;
Melledy's avatar
Melledy committed
22
23
import emu.grasscutter.game.inventory.ItemType;
import emu.grasscutter.game.inventory.MaterialType;
Melledy's avatar
Melledy committed
24
import emu.grasscutter.game.player.Player;
Melledy's avatar
Melledy committed
25
26
27
28
29
import emu.grasscutter.net.proto.GachaItemOuterClass.GachaItem;
import emu.grasscutter.net.proto.GachaTransferItemOuterClass.GachaTransferItem;
import emu.grasscutter.net.proto.GetGachaInfoRspOuterClass.GetGachaInfoRsp;
import emu.grasscutter.net.proto.ItemParamOuterClass.ItemParam;
import emu.grasscutter.server.game.GameServer;
30
import emu.grasscutter.server.game.GameServerTickEvent;
Melledy's avatar
Melledy committed
31
32
33
34
35
import emu.grasscutter.server.packet.send.PacketDoGachaRsp;
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.ints.IntList;
36
37
import org.greenrobot.eventbus.Subscribe;

38
39
import static emu.grasscutter.Configuration.*;

Melledy's avatar
Melledy committed
40
41
42
43
public class GachaManager {
	private final GameServer server;
	private final Int2ObjectMap<GachaBanner> gachaBanners;
	private GetGachaInfoRsp cachedProto;
44
45
	WatchService watchService;

46
47
48
49
50
	private final int[] yellowAvatars = new int[] {1003, 1016, 1042, 1035, 1041};
	private final int[] yellowWeapons = new int[] {11501, 11502, 12501, 12502, 13502, 13505, 14501, 14502, 15501, 15502};
	private final int[] purpleAvatars = new int[] {1006, 1014, 1015, 1020, 1021, 1023, 1024, 1025, 1027, 1031, 1032, 1034, 1036, 1039, 1043, 1044, 1045, 1048, 1053, 1055, 1056, 1064};
	private final int[] purpleWeapons = new int[] {11401, 11402, 11403, 11405, 12401, 12402, 12403, 12405, 13401, 13407, 14401, 14402, 14403, 14409, 15401, 15402, 15403, 15405};
	private final int[] blueWeapons = new int[] {11301, 11302, 11306, 12301, 12302, 12305, 13303, 14301, 14302, 14304, 15301, 15302, 15304};
Melledy's avatar
Melledy committed
51
	
52
53
	private static final int starglitterId = 221;
	private static final int stardustId = 222;
54

Melledy's avatar
Melledy committed
55
56
57
58
	public GachaManager(GameServer server) {
		this.server = server;
		this.gachaBanners = new Int2ObjectOpenHashMap<>();
		this.load();
59
		this.startWatcher(server);
Melledy's avatar
Melledy committed
60
61
62
63
64
65
66
67
68
	}

	public GameServer getServer() {
		return server;
	}

	public Int2ObjectMap<GachaBanner> getGachaBanners() {
		return gachaBanners;
	}
ImmuState's avatar
ImmuState committed
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

	public int[] getYellowAvatars() {
		return this.yellowAvatars;
	}
	public int[] getYellowWeapons() {
		return this.yellowWeapons;
	}
	public int[] getPurpleAvatars() {
		return this.purpleAvatars;
	}
	public int[] getPurpleWeapons() {
		return this.purpleWeapons;
	}
	public int[] getBlueWeapons() {
		return this.blueWeapons;
	}

Melledy's avatar
Melledy committed
86
87
88
89
90
91
92
93
94
	public int randomRange(int min, int max) {
		return ThreadLocalRandom.current().nextInt(max - min + 1) + min;
	}
	
	public int getRandom(int[] array) {
		return array[randomRange(0, array.length - 1)];
	}
	
	public synchronized void load() {
95
		try (FileReader fileReader = new FileReader(DATA("Banners.json"))) {
96
			getGachaBanners().clear();
Melledy's avatar
Melledy committed
97
			List<GachaBanner> banners = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, GachaBanner.class).getType());
98
99
100
101
102
103
104
105
			if(banners.size() > 0) {
				for (GachaBanner banner : banners) {
					getGachaBanners().put(banner.getGachaType(), banner);
				}
				Grasscutter.getLogger().info("Banners successfully loaded.");
				this.cachedProto = createProto();
			} else {
				Grasscutter.getLogger().error("Unable to load banners. Banners size is 0.");
Melledy's avatar
Melledy committed
106
107
108
109
110
111
112
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
113
	public synchronized void doPulls(Player player, int gachaType, int times) {
Melledy's avatar
Melledy committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
		// Sanity check
		if (times != 10 && times != 1) {
			return;
		} 
		if (player.getInventory().getInventoryTab(ItemType.ITEM_WEAPON).getSize() + times > player.getInventory().getInventoryTab(ItemType.ITEM_WEAPON).getMaxCapacity()) {
			player.sendPacket(new PacketDoGachaRsp());
			return;
		}
		
		// Get banner
		GachaBanner banner = this.getGachaBanners().get(gachaType);
		if (banner == null) {
			player.sendPacket(new PacketDoGachaRsp());
			return;
		}

		// Spend currency
AnimeGitB's avatar
AnimeGitB committed
131
		if (banner.getCostItem() > 0 && !player.getInventory().payItem(banner.getCostItem(), times)) {
132
			return;
Melledy's avatar
Melledy committed
133
134
135
136
137
138
139
140
141
142
143
		}
		
		// Roll
		PlayerGachaBannerInfo gachaInfo = player.getGachaInfo().getBannerInfo(banner);
		IntList wonItems = new IntArrayList(times);
		
		for (int i = 0; i < times; i++) {
			int random = this.randomRange(1, 10000);
			int itemId = 0;
			
			int bonusYellowChance = gachaInfo.getPity5() >= banner.getSoftPity() ? 100 * (gachaInfo.getPity5() - banner.getSoftPity() - 1): 0;
Melledy's avatar
Melledy committed
144
145
			int yellowChance = banner.getBaseYellowWeight() + (int) Math.floor(100f * (gachaInfo.getPity5() / (banner.getSoftPity() - 1D))) + bonusYellowChance;
			int purpleChance = 10000 - (banner.getBasePurpleWeight() + (int) Math.floor(790f * (gachaInfo.getPity4() / 8f)));
Melledy's avatar
Melledy committed
146
147
148
149
150
		
			if (random <= yellowChance || gachaInfo.getPity5() >= banner.getHardPity()) {
				if (banner.getRateUpItems1().length > 0) {
					int eventChance = this.randomRange(1, 100);
					
Melledy's avatar
Melledy committed
151
					if (eventChance <= banner.getEventChance() || gachaInfo.getFailedFeaturedItemPulls() >= 1) {
Melledy's avatar
Melledy committed
152
153
154
155
156
157
158
159
160
						itemId = getRandom(banner.getRateUpItems1());
						gachaInfo.setFailedFeaturedItemPulls(0);
					} else {
						// Lost the 50/50... rip
						gachaInfo.addFailedFeaturedItemPulls(1);
					}
				}
				
				if (itemId == 0) {
Melledy's avatar
Melledy committed
161
					int typeChance = this.randomRange(banner.getBannerType() == BannerType.WEAPON ? 2 : 1, banner.getBannerType() == BannerType.EVENT ? 1 : 2);
Melledy's avatar
Melledy committed
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
					if (typeChance == 1) {
						itemId = getRandom(this.yellowAvatars);
					} else {
						itemId = getRandom(this.yellowWeapons);
					}
				}

				// Pity
				gachaInfo.addPity4(1);
				gachaInfo.setPity5(0);
			} else if (random >= purpleChance || gachaInfo.getPity4() >= 9) {
				if (banner.getRateUpItems2().length > 0) {
					int eventChance = this.randomRange(1, 100);
					
					if (eventChance >= 50) {
						itemId = getRandom(banner.getRateUpItems2());
					}
				}
				
				if (itemId == 0) {
Melledy's avatar
Melledy committed
182
					int typeChance = this.randomRange(banner.getBannerType() == BannerType.WEAPON ? 2 : 1, banner.getBannerType() == BannerType.EVENT ? 1 : 2);
Melledy's avatar
Melledy committed
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
					if (typeChance == 1) {
						itemId = getRandom(this.purpleAvatars);
					} else {
						itemId = getRandom(this.purpleWeapons);
					}
				}
				
				// Pity
				gachaInfo.addPity5(1);
				gachaInfo.setPity4(0);
			} else {
				itemId = getRandom(this.blueWeapons);
				
				// Pity
				gachaInfo.addPity4(1);
				gachaInfo.addPity5(1);
			}
			
			// Add winning item
			wonItems.add(itemId);
		}
		
		// Add to character
		List<GachaItem> list = new ArrayList<>();
		int stardust = 0, starglitter = 0;
		
		for (int itemId : wonItems) {
210
			ItemData itemData = GameData.getItemDataMap().get(itemId);
Melledy's avatar
Melledy committed
211
212
213
			if (itemData == null) {
				continue;
			}
214
215
216
217

			// Write gacha record
			GachaRecord gachaRecord = new GachaRecord(itemId, player.getUid(), gachaType);
			DatabaseHelper.saveGachaRecord(gachaRecord);
Melledy's avatar
Melledy committed
218
219
220
221
222
223
224
225
226
			
			// Create gacha item
			GachaItem.Builder gachaItem = GachaItem.newBuilder();
			int addStardust = 0, addStarglitter = 0;
			boolean isTransferItem = false;
			
			// Const check
			if (itemData.getMaterialType() == MaterialType.MATERIAL_AVATAR) {
				int avatarId = (itemData.getId() % 1000) + 10000000;
227
				Avatar avatar = player.getAvatars().getAvatarById(avatarId);
Melledy's avatar
Melledy committed
228
229
230
				if (avatar != null) {
					int constLevel = avatar.getCoreProudSkillLevel();
					int constItemId = itemData.getId() + 100;
231
					GameItem constItem = player.getInventory().getInventoryTab(ItemType.ITEM_MATERIAL).getItemById(constItemId);
Melledy's avatar
Melledy committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
					if (constItem != null) {
						constLevel += constItem.getCount();
					}
					
					if (constLevel < 6) {
						// Not max const
						addStarglitter = 2;
						// Add 1 const
						gachaItem.addTransferItems(GachaTransferItem.newBuilder().setItem(ItemParam.newBuilder().setItemId(constItemId).setCount(1)).setIsTransferItemNew(constItem == null));
						player.getInventory().addItem(constItemId, 1);
					} else {
						// Is max const
						addStarglitter = 5;
					}
					
					if (itemData.getRankLevel() == 5) {
						addStarglitter *= 5;
					}
					
					isTransferItem = true;
				} else {
					// New
					gachaItem.setIsGachaItemNew(true);
				}
			} else {
				// Is weapon
				switch (itemData.getRankLevel()) {
259
260
261
					case 5 -> addStarglitter = 10;
					case 4 -> addStarglitter = 2;
					case 3 -> addStardust = 15;
Melledy's avatar
Melledy committed
262
263
264
265
				}
			}

			// Create item
266
			GameItem item = new GameItem(itemData);
Melledy's avatar
Melledy committed
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
			gachaItem.setGachaItem(item.toItemParam());
			player.getInventory().addItem(item);
			
			stardust += addStardust;
			starglitter += addStarglitter;
			
			if (addStardust > 0) {
				gachaItem.addTokenItemList(ItemParam.newBuilder().setItemId(stardustId).setCount(addStardust));
			} if (addStarglitter > 0) {
				ItemParam starglitterParam = ItemParam.newBuilder().setItemId(starglitterId).setCount(addStarglitter).build();
				if (isTransferItem) {
					gachaItem.addTransferItems(GachaTransferItem.newBuilder().setItem(starglitterParam));
				}
				gachaItem.addTokenItemList(starglitterParam);
			}
			
			list.add(gachaItem.build());
		}
		
		// Add stardust/starglitter
		if (stardust > 0) {
			player.getInventory().addItem(stardustId, stardust);
		} if (starglitter > 0) {
			player.getInventory().addItem(starglitterId, starglitter);
		}
		
		// Packets
		player.sendPacket(new PacketDoGachaRsp(banner, list));
	}
296
297
298
299
300

	private synchronized void startWatcher(GameServer server) {
		if(this.watchService == null) {
			try {
				this.watchService = FileSystems.getDefault().newWatchService();
301
				Path path = new File(DATA_FOLDER).toPath();
302
				path.register(watchService, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_MODIFY}, SensitivityWatchEventModifier.HIGH);
303
304
305
306
307
308
309
310
311
312
313
			} catch (Exception e) {
				Grasscutter.getLogger().error("Unable to load the Gacha Manager Watch Service. If ServerOptions.watchGacha is true it will not auto-reload");
				e.printStackTrace();
			}
		} else {
			Grasscutter.getLogger().error("Cannot reinitialise watcher ");
		}
	}

	@Subscribe
	public synchronized void watchBannerJson(GameServerTickEvent tickEvent) {
314
		if(GAME_OPTIONS.watchGachaConfig) {
Benjamin Elsdon's avatar
Benjamin Elsdon committed
315
			try {
316
317
				WatchKey watchKey = watchService.take();

Benjamin Elsdon's avatar
Benjamin Elsdon committed
318
319
320
321
322
323
				for (WatchEvent<?> event : watchKey.pollEvents()) {
					final Path changed = (Path) event.context();
					if (changed.endsWith("Banners.json")) {
						Grasscutter.getLogger().info("Change detected with banners.json. Reloading gacha config");
						this.load();
					}
324
				}
325
326
327
328
329
330

				boolean valid = watchKey.reset();
				if (!valid) {
					Grasscutter.getLogger().error("Unable to reset Gacha Manager Watch Key. Auto-reload of banners.json will no longer work.");
					return;
				}
Benjamin Elsdon's avatar
Benjamin Elsdon committed
331
332
			} catch (Exception e) {
				e.printStackTrace();
333
334
335
			}
		}
	}
Melledy's avatar
Melledy committed
336
	
337
	@Deprecated
Melledy's avatar
Melledy committed
338
339
340
341
342
343
344
345
346
	private synchronized GetGachaInfoRsp createProto() {
		GetGachaInfoRsp.Builder proto = GetGachaInfoRsp.newBuilder().setGachaRandom(12345);
		
		for (GachaBanner banner : getGachaBanners().values()) {
			proto.addGachaInfoList(banner.toProto());
		}
				
		return proto.build();
	}
347
348
349
350
351
352
353
354
355
356

	private synchronized GetGachaInfoRsp createProto(String sessionKey) {
		GetGachaInfoRsp.Builder proto = GetGachaInfoRsp.newBuilder().setGachaRandom(12345);
		
		for (GachaBanner banner : getGachaBanners().values()) {
			proto.addGachaInfoList(banner.toProto(sessionKey));
		}
				
		return proto.build();
	}
Melledy's avatar
Melledy committed
357
	
358
	@Deprecated
Melledy's avatar
Melledy committed
359
360
361
362
363
364
	public GetGachaInfoRsp toProto() {
		if (this.cachedProto == null) {
			this.cachedProto = createProto();
		}
		return this.cachedProto;
	}
365
366
367
368

	public GetGachaInfoRsp toProto(String sessionKey) {
		return createProto(sessionKey);
	}
Melledy's avatar
Melledy committed
369
}