ResourceLoader.java 14.1 KB
Newer Older
Melledy's avatar
Melledy committed
1
2
package emu.grasscutter.data;

3
import java.io.*;
4
5
import java.nio.file.Files;
import java.nio.file.Path;
KingRainbow44's avatar
KingRainbow44 committed
6
import java.util.*;
Melledy's avatar
Melledy committed
7
8
9
10
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

11
import com.google.gson.Gson;
12
import emu.grasscutter.data.binout.*;
KingRainbow44's avatar
KingRainbow44 committed
13
import emu.grasscutter.utils.Utils;
14
import lombok.SneakyThrows;
Melledy's avatar
Melledy committed
15
16
import org.reflections.Reflections;

Yazawazi's avatar
Yazawazi committed
17
import com.google.gson.JsonElement;
18
import com.google.gson.annotations.SerializedName;
Melledy's avatar
Melledy committed
19
20
21
import com.google.gson.reflect.TypeToken;

import emu.grasscutter.Grasscutter;
Melledy's avatar
Melledy committed
22
23
24
import emu.grasscutter.data.binout.AbilityModifier.AbilityConfigData;
import emu.grasscutter.data.binout.AbilityModifier.AbilityModifierAction;
import emu.grasscutter.data.binout.AbilityModifier.AbilityModifierActionType;
Yazawazi's avatar
Yazawazi committed
25
26
import emu.grasscutter.data.common.PointData;
import emu.grasscutter.data.common.ScenePointConfig;
27
import emu.grasscutter.game.world.SpawnDataEntry.*;
Melledy's avatar
Melledy committed
28
29
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;

30
31
import static emu.grasscutter.Configuration.*;

Melledy's avatar
Melledy committed
32
33
public class ResourceLoader {

34
35
	private static List<String> loadedResources = new ArrayList<String>();

Melledy's avatar
Melledy committed
36
37
	public static List<Class<?>> getResourceDefClasses() {
		Reflections reflections = new Reflections(ResourceLoader.class.getPackage().getName());
38
		Set<?> classes = reflections.getSubTypesOf(GameResource.class);
Melledy's avatar
Melledy committed
39
40
41
42
43
44
45
46
47

		List<Class<?>> classList = new ArrayList<>(classes.size());
		classes.forEach(o -> {
			Class<?> c = (Class<?>) o;
			if (c.getAnnotation(ResourceType.class) != null) {
				classList.add(c);
			}
		});

KingRainbow44's avatar
KingRainbow44 committed
48
		classList.sort((a, b) -> b.getAnnotation(ResourceType.class).loadPriority().value() - a.getAnnotation(ResourceType.class).loadPriority().value());
Melledy's avatar
Melledy committed
49
50
51
52
53
54
55
56

		return classList;
	}
	
	public static void loadAll() {
		// Load ability lists
		loadAbilityEmbryos();
		loadOpenConfig();
Melledy's avatar
Melledy committed
57
		loadAbilityModifiers();
Melledy's avatar
Melledy committed
58
59
60
		// Load resources
		loadResources();
		// Process into depots
61
		GameDepot.load();
Melledy's avatar
Melledy committed
62
		// Load spawn data and quests
Melledy's avatar
Melledy committed
63
		loadSpawnData();
Melledy's avatar
Melledy committed
64
		loadQuests();
65
66
		// Load scene points - must be done AFTER resources are loaded
		loadScenePoints();
67
68
69

		// Load default home layout
		loadHomeworldDefaultSaveData();
Akka's avatar
Akka committed
70

Melledy's avatar
Melledy committed
71
72
73
	}

	public static void loadResources() {
74
75
76
77
		loadResources(false);
	}

	public static void loadResources(boolean doReload) {
Melledy's avatar
Melledy committed
78
79
80
81
82
83
84
85
		for (Class<?> resourceDefinition : getResourceDefClasses()) {
			ResourceType type = resourceDefinition.getAnnotation(ResourceType.class);

			if (type == null) {
				continue;
			}

			@SuppressWarnings("rawtypes")
86
			Int2ObjectMap map = GameData.getMapByResourceDef(resourceDefinition);
Melledy's avatar
Melledy committed
87
88
89
90
91
92

			if (map == null) {
				continue;
			}

			try {
93
				loadFromResource(resourceDefinition, type, map, doReload);
Melledy's avatar
Melledy committed
94
			} catch (Exception e) {
KingRainbow44's avatar
KingRainbow44 committed
95
				Grasscutter.getLogger().error("Error loading resource file: " + Arrays.toString(type.name()), e);
Melledy's avatar
Melledy committed
96
97
98
99
100
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
101
102
103
104
105
106
107
	protected static void loadFromResource(Class<?> c, ResourceType type, Int2ObjectMap map, boolean doReload) throws Exception {
		if(!loadedResources.contains(c.getSimpleName()) || doReload) {
			for (String name : type.name()) {
				loadFromResource(c, name, map);
			}
			Grasscutter.getLogger().info("Loaded " + map.size() + " " + c.getSimpleName() + "s.");
			loadedResources.add(c.getSimpleName());
Melledy's avatar
Melledy committed
108
109
		}
	}
110

Melledy's avatar
Melledy committed
111
112
	@SuppressWarnings({"rawtypes", "unchecked"})
	protected static void loadFromResource(Class<?> c, String fileName, Int2ObjectMap map) throws Exception {
Melledy's avatar
Melledy committed
113
114
115
116
117
118
119
		try (FileReader fileReader = new FileReader(RESOURCE("ExcelBinOutput/" + fileName))) {
			List list = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, c).getType());

			for (Object o : list) {
				GameResource res = (GameResource) o;
				res.onLoad();
				map.put(res.getId(), res);
120
			}
Melledy's avatar
Melledy committed
121
122
123
		}
	}

Yazawazi's avatar
Yazawazi committed
124
125
	private static void loadScenePoints() {
		Pattern pattern = Pattern.compile("(?<=scene)(.*?)(?=_point.json)");
126
		File folder = new File(RESOURCE("BinOutput/Scene/Point"));
Yazawazi's avatar
Yazawazi committed
127
128
129
130
131
132

		if (!folder.isDirectory() || !folder.exists() || folder.listFiles() == null) {
			Grasscutter.getLogger().error("Scene point files cannot be found, you cannot use teleport waypoints!");
			return;
		}

Yazawazi's avatar
Yazawazi committed
133
		List<ScenePointEntry> scenePointList = new ArrayList<>();
134
		for (File file : Objects.requireNonNull(folder.listFiles())) {
135
			ScenePointConfig config; Integer sceneId;
Yazawazi's avatar
Yazawazi committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
			
			Matcher matcher = pattern.matcher(file.getName());
			if (matcher.find()) {
				sceneId = Integer.parseInt(matcher.group(1));
			} else {
				continue;
			}

			try (FileReader fileReader = new FileReader(file)) {
				config = Grasscutter.getGsonFactory().fromJson(fileReader, ScenePointConfig.class);
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}

			if (config.points == null) {
				continue;
			}

			for (Map.Entry<String, JsonElement> entry : config.points.entrySet()) {
				PointData pointData = Grasscutter.getGsonFactory().fromJson(entry.getValue(), PointData.class);
Melledy's avatar
Melledy committed
157
				pointData.setId(Integer.parseInt(entry.getKey()));
Yazawazi's avatar
Yazawazi committed
158
159
160

				ScenePointEntry sl = new ScenePointEntry(sceneId + "_" + entry.getKey(), pointData);
				scenePointList.add(sl);
161
162
163
				GameData.getScenePointIdList().add(pointData.getId());
				
				pointData.updateDailyDungeon();
Yazawazi's avatar
Yazawazi committed
164
165
166
			}

			for (ScenePointEntry entry : scenePointList) {
167
				GameData.getScenePointEntries().put(entry.getName(), entry);
Yazawazi's avatar
Yazawazi committed
168
169
170
171
			}
		}
	}

Melledy's avatar
Melledy committed
172
173
	private static void loadAbilityEmbryos() {
		List<AbilityEmbryoEntry> embryoList = null;
174
175
176
177
178
179
180

		// Read from cached file if exists
		try(InputStream embryoCache = DataLoader.load("AbilityEmbryos.json", false)) {
			embryoList = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(embryoCache), TypeToken.getParameterized(Collection.class, AbilityEmbryoEntry.class).getType());
		} catch(Exception ignored) {}

		if(embryoList == null) {
Melledy's avatar
Melledy committed
181
182
			// Load from BinOutput
			Pattern pattern = Pattern.compile("(?<=ConfigAvatar_)(.*?)(?=.json)");
183

Melledy's avatar
Melledy committed
184
			embryoList = new LinkedList<>();
185
			File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Avatar/")));
KingRainbow44's avatar
KingRainbow44 committed
186
187
188
189
190
			File[] files = folder.listFiles();
			if(files == null) {
				Grasscutter.getLogger().error("Error loading ability embryos: no files found in " + folder.getAbsolutePath());
				return;
			}
191

KingRainbow44's avatar
KingRainbow44 committed
192
193
194
			for (File file : files) {
				AvatarConfig config;
				String avatarName;
195

Melledy's avatar
Melledy committed
196
197
198
199
200
201
				Matcher matcher = pattern.matcher(file.getName());
				if (matcher.find()) {
					avatarName = matcher.group(0);
				} else {
					continue;
				}
202

Melledy's avatar
Melledy committed
203
204
205
206
207
208
				try (FileReader fileReader = new FileReader(file)) {
					config = Grasscutter.getGsonFactory().fromJson(fileReader, AvatarConfig.class);
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
209

Melledy's avatar
Melledy committed
210
211
212
				if (config.abilities == null) {
					continue;
				}
213

Melledy's avatar
Melledy committed
214
215
216
217
				int s = config.abilities.size();
				AbilityEmbryoEntry al = new AbilityEmbryoEntry(avatarName, config.abilities.stream().map(Object::toString).toArray(size -> new String[s]));
				embryoList.add(al);
			}
218
219
220
221
222
223
224
225
226
227
			
			File playerElementsFile = new File(Utils.toFilePath(RESOURCE("BinOutput/AbilityGroup/AbilityGroup_Other_PlayerElementAbility.json")));
			
			if (playerElementsFile.exists()) {
				try (FileReader fileReader = new FileReader(playerElementsFile)) {
					GameDepot.setPlayerAbilities(Grasscutter.getGsonFactory().fromJson(fileReader, new TypeToken<Map<String, AvatarConfig>>(){}.getType()));
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
Melledy's avatar
Melledy committed
228
229
230
231
232
233
234
235
		}
		
		if (embryoList == null || embryoList.isEmpty()) {
			Grasscutter.getLogger().error("No embryos loaded!");
			return;
		}

		for (AbilityEmbryoEntry entry : embryoList) {
236
			GameData.getAbilityEmbryoInfo().put(entry.getName(), entry);
Melledy's avatar
Melledy committed
237
238
239
		}
	}
	
Melledy's avatar
Melledy committed
240
241
	private static void loadAbilityModifiers() {
		// Load from BinOutput
242
		File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Ability/Temp/AvatarAbilities/")));
Melledy's avatar
Melledy committed
243
244
245
246
247
248
249
		File[] files = folder.listFiles();
		if (files == null) {
			Grasscutter.getLogger().error("Error loading ability modifiers: no files found in " + folder.getAbsolutePath());
			return;
		}

		for (File file : files) {
250
			List<AbilityConfigData> abilityConfigList;
Melledy's avatar
Melledy committed
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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
296
297
298
299
300
301
302
			
			try (FileReader fileReader = new FileReader(file)) {
				abilityConfigList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, AbilityConfigData.class).getType());
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
			
			for (AbilityConfigData data : abilityConfigList) {
				if (data.Default.modifiers == null || data.Default.modifiers.size() == 0) {
					continue;
				}
				
				AbilityModifierEntry modifierEntry = new AbilityModifierEntry(data.Default.abilityName);
				
				for (Entry<String, AbilityModifier> entry : data.Default.modifiers.entrySet()) {
					AbilityModifier modifier = entry.getValue();
					
					// Stare.
					if (modifier.onAdded != null) {
						for (AbilityModifierAction action : modifier.onAdded) {
							if (action.$type.contains("HealHP")) {
								action.type = AbilityModifierActionType.HealHP;
								modifierEntry.getOnAdded().add(action);
							}
						}
					}
					
					if (modifier.onThinkInterval != null) {
						for (AbilityModifierAction action : modifier.onThinkInterval) {
							if (action.$type.contains("HealHP")) {
								action.type = AbilityModifierActionType.HealHP;
								modifierEntry.getOnThinkInterval().add(action);
							}
						}
					}
					
					if (modifier.onRemoved != null) {
						for (AbilityModifierAction action : modifier.onRemoved) {
							if (action.$type.contains("HealHP")) {
								action.type = AbilityModifierActionType.HealHP;
								modifierEntry.getOnRemoved().add(action);
							}
						}
					}
				}
				
				GameData.getAbilityModifiers().put(modifierEntry.getName(), modifierEntry);
			}
		}
	}
	
Melledy's avatar
Melledy committed
303
304
	private static void loadSpawnData() {
		List<SpawnGroupEntry> spawnEntryList = null;
305
306
307
308
309

		// Read from cached file if exists
		try(InputStream spawnDataEntries = DataLoader.load("Spawns.json")) {
			spawnEntryList = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(spawnDataEntries), TypeToken.getParameterized(Collection.class, SpawnGroupEntry.class).getType());
		} catch (Exception ignored) {}
Melledy's avatar
Melledy committed
310
311
312
313
314
315
316
		
		if (spawnEntryList == null || spawnEntryList.isEmpty()) {
			Grasscutter.getLogger().error("No spawn data loaded!");
			return;
		}

		for (SpawnGroupEntry entry : spawnEntryList) {
317
			entry.getSpawns().forEach(s -> s.setGroup(entry));
318
			GameDepot.getSpawnListById(entry.getSceneId()).insert(entry, entry.getPos().getX(), entry.getPos().getZ());
Melledy's avatar
Melledy committed
319
320
321
		}
	}
	
Melledy's avatar
Melledy committed
322
323
324
	private static void loadOpenConfig() {
		// Read from cached file if exists
		List<OpenConfigEntry> list = null;
325
326
327
328
329
330

		try(InputStream openConfigCache = DataLoader.load("OpenConfig.json", false)) {
			list = Grasscutter.getGsonFactory().fromJson(new InputStreamReader(openConfigCache), TypeToken.getParameterized(Collection.class, SpawnGroupEntry.class).getType());
		} catch (Exception ignored) {}

		if (list == null) {
Melledy's avatar
Melledy committed
331
332
			Map<String, OpenConfigEntry> map = new TreeMap<>();
			java.lang.reflect.Type type = new TypeToken<Map<String, OpenConfigData[]>>() {}.getType();
ayy lmao's avatar
ayy lmao committed
333
			String[] folderNames = {"BinOutput/Talent/EquipTalents/", "BinOutput/Talent/AvatarTalents/"};
Melledy's avatar
Melledy committed
334
335
			
			for (String name : folderNames) {
336
				File folder = new File(Utils.toFilePath(RESOURCE(name)));
KingRainbow44's avatar
KingRainbow44 committed
337
338
339
340
				File[] files = folder.listFiles();
				if(files == null) {
					Grasscutter.getLogger().error("Error loading open config: no files found in " + folder.getAbsolutePath()); return;
				}
Melledy's avatar
Melledy committed
341
				
KingRainbow44's avatar
KingRainbow44 committed
342
				for (File file : files) {
Melledy's avatar
Melledy committed
343
344
345
346
					if (!file.getName().endsWith(".json")) {
						continue;
					}
					
KingRainbow44's avatar
KingRainbow44 committed
347
					Map<String, OpenConfigData[]> config;
Melledy's avatar
Melledy committed
348
349
350
351
352
353
354
355
356
					
					try (FileReader fileReader = new FileReader(file)) {
						config = Grasscutter.getGsonFactory().fromJson(fileReader, type);
					} catch (Exception e) {
						e.printStackTrace();
						continue;
					}
					
					for (Entry<String, OpenConfigData[]> e : config.entrySet()) {
357
						OpenConfigEntry entry = new OpenConfigEntry(e.getKey(), e.getValue());
Melledy's avatar
Melledy committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
						map.put(entry.getName(), entry);
					}
				}
			}
			
			list = new ArrayList<>(map.values());
		}
		
		if (list == null || list.isEmpty()) {
			Grasscutter.getLogger().error("No openconfig entries loaded!");
			return;
		}
		
		for (OpenConfigEntry entry : list) {
372
			GameData.getOpenConfigEntries().put(entry.getName(), entry);
Melledy's avatar
Melledy committed
373
374
		}
	}
Melledy's avatar
Melledy committed
375
376
	
	private static void loadQuests() {
Melledy's avatar
Melledy committed
377
		File folder = new File(RESOURCE("BinOutput/Quest/"));
Melledy's avatar
Melledy committed
378
379
380
381
382
383
		
		if (!folder.exists()) {
			return;
		}
		
		for (File file : folder.listFiles()) {
Melledy's avatar
Melledy committed
384
			MainQuestData mainQuest = null;
Melledy's avatar
Melledy committed
385
386
			
			try (FileReader fileReader = new FileReader(file)) {
Melledy's avatar
Melledy committed
387
				mainQuest = Grasscutter.getGsonFactory().fromJson(fileReader, MainQuestData.class);
Melledy's avatar
Melledy committed
388
389
390
391
392
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
			
Melledy's avatar
Melledy committed
393
			GameData.getMainQuestDataMap().put(mainQuest.getId(), mainQuest);
Melledy's avatar
Melledy committed
394
395
		}
		
Melledy's avatar
Melledy committed
396
		Grasscutter.getLogger().info("Loaded " + GameData.getMainQuestDataMap().size() + " MainQuestDatas.");
Melledy's avatar
Melledy committed
397
	}
398

399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
	@SneakyThrows
	private static void loadHomeworldDefaultSaveData(){
		var folder = Files.list(Path.of(RESOURCE("BinOutput/HomeworldDefaultSave"))).toList();
		var pattern = Pattern.compile("scene(.*)_home_config.json");

		for(var file : folder){
			var matcher = pattern.matcher(file.getFileName().toString());
			if(!matcher.find()){
				continue;
			}
			var sceneId = matcher.group(1);

			var data = Grasscutter.getGsonFactory().fromJson(Files.readString(file), HomeworldDefaultSaveData.class);

			GameData.getHomeworldDefaultSaveData().put(Integer.parseInt(sceneId), data);
		}

		Grasscutter.getLogger().info("Loaded " + GameData.getHomeworldDefaultSaveData().size() + " HomeworldDefaultSaveDatas.");
	}

Melledy's avatar
Melledy committed
419
420
	// BinOutput configs
	
421
422
	public static class AvatarConfig {
		@SerializedName(value="abilities", alternate={"targetAbilities"})
Melledy's avatar
Melledy committed
423
		public ArrayList<AvatarConfigAbility> abilities;
424
425
426
427
428
429
	}
	
	public static class AvatarConfigAbility {
		public String abilityName;
		public String toString() {
			return abilityName;
Melledy's avatar
Melledy committed
430
431
432
433
434
435
436
		}
	}
	
	private static class OpenConfig {
		public OpenConfigData[] data;
	}
	
437
	public static class OpenConfigData {
Melledy's avatar
Melledy committed
438
439
		public String $type;
		public String abilityName;
440
441
		
		@SerializedName(value="talentIndex", alternate={"OJOFFKLNAHN"})
Melledy's avatar
Melledy committed
442
		public int talentIndex;
443
444
		
		@SerializedName(value="skillID", alternate={"overtime"})
445
		public int skillID;
446
447
		
		@SerializedName(value="pointDelta", alternate={"IGEBKIHPOIF"})
448
		public int pointDelta;
Melledy's avatar
Melledy committed
449
450
	}
}