ResourceLoader.java 14.9 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.*;
13
import emu.grasscutter.scripts.SceneIndexManager;
KingRainbow44's avatar
KingRainbow44 committed
14
import emu.grasscutter.utils.Utils;
15
import lombok.SneakyThrows;
Melledy's avatar
Melledy committed
16
17
import org.reflections.Reflections;

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

import emu.grasscutter.Grasscutter;
Melledy's avatar
Melledy committed
23
24
25
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
26
27
import emu.grasscutter.data.common.PointData;
import emu.grasscutter.data.common.ScenePointConfig;
28
import emu.grasscutter.game.world.SpawnDataEntry.*;
Melledy's avatar
Melledy committed
29
30
import it.unimi.dsi.fastutil.ints.Int2ObjectMap;

31
import static emu.grasscutter.Configuration.*;
32
import static emu.grasscutter.utils.Language.translate;
33

Melledy's avatar
Melledy committed
34
35
public class ResourceLoader {

36
	private static final List<String> loadedResources = new ArrayList<>();
37

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

		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
50
		classList.sort((a, b) -> b.getAnnotation(ResourceType.class).loadPriority().value() - a.getAnnotation(ResourceType.class).loadPriority().value());
Melledy's avatar
Melledy committed
51
52
53

		return classList;
	}
54

Melledy's avatar
Melledy committed
55
	public static void loadAll() {
56
57
        Grasscutter.getLogger().info(translate("messages.status.resources.loading"));

Melledy's avatar
Melledy committed
58
59
60
		// Load ability lists
		loadAbilityEmbryos();
		loadOpenConfig();
Melledy's avatar
Melledy committed
61
		loadAbilityModifiers();
Melledy's avatar
Melledy committed
62
63
64
		// Load resources
		loadResources();
		// Process into depots
65
		GameDepot.load();
Melledy's avatar
Melledy committed
66
		// Load spawn data and quests
Melledy's avatar
Melledy committed
67
		loadSpawnData();
Melledy's avatar
Melledy committed
68
		loadQuests();
69
70
		// Load scene points - must be done AFTER resources are loaded
		loadScenePoints();
71
72
		// Load default home layout
		loadHomeworldDefaultSaveData();
Akka's avatar
Akka committed
73
		loadNpcBornData();
74
75

        Grasscutter.getLogger().info(translate("messages.status.resources.finish"));
Melledy's avatar
Melledy committed
76
77
78
	}

	public static void loadResources() {
79
80
81
82
		loadResources(false);
	}

	public static void loadResources(boolean doReload) {
Melledy's avatar
Melledy committed
83
84
85
86
87
88
89
90
		for (Class<?> resourceDefinition : getResourceDefClasses()) {
			ResourceType type = resourceDefinition.getAnnotation(ResourceType.class);

			if (type == null) {
				continue;
			}

			@SuppressWarnings("rawtypes")
91
			Int2ObjectMap map = GameData.getMapByResourceDef(resourceDefinition);
Melledy's avatar
Melledy committed
92
93
94
95
96
97

			if (map == null) {
				continue;
			}

			try {
98
				loadFromResource(resourceDefinition, type, map, doReload);
Melledy's avatar
Melledy committed
99
			} catch (Exception e) {
KingRainbow44's avatar
KingRainbow44 committed
100
				Grasscutter.getLogger().error("Error loading resource file: " + Arrays.toString(type.name()), e);
Melledy's avatar
Melledy committed
101
102
103
			}
		}
	}
104

Melledy's avatar
Melledy committed
105
	@SuppressWarnings("rawtypes")
106
107
108
109
110
111
	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);
			}
			loadedResources.add(c.getSimpleName());
112
            Grasscutter.getLogger().debug("Loaded " + map.size() + " " + c.getSimpleName() + "s.");
Melledy's avatar
Melledy committed
113
114
		}
	}
115

Melledy's avatar
Melledy committed
116
117
	@SuppressWarnings({"rawtypes", "unchecked"})
	protected static void loadFromResource(Class<?> c, String fileName, Int2ObjectMap map) throws Exception {
Melledy's avatar
Melledy committed
118
119
120
121
122
123
124
		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);
125
			}
Melledy's avatar
Melledy committed
126
127
128
		}
	}

Yazawazi's avatar
Yazawazi committed
129
130
	private static void loadScenePoints() {
		Pattern pattern = Pattern.compile("(?<=scene)(.*?)(?=_point.json)");
131
		File folder = new File(RESOURCE("BinOutput/Scene/Point"));
Yazawazi's avatar
Yazawazi committed
132
133
134
135
136
137

		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
138
		List<ScenePointEntry> scenePointList = new ArrayList<>();
139
		for (File file : Objects.requireNonNull(folder.listFiles())) {
140
			ScenePointConfig config; Integer sceneId;
141

Yazawazi's avatar
Yazawazi committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
			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
162
				pointData.setId(Integer.parseInt(entry.getKey()));
Yazawazi's avatar
Yazawazi committed
163
164
165

				ScenePointEntry sl = new ScenePointEntry(sceneId + "_" + entry.getKey(), pointData);
				scenePointList.add(sl);
166
				GameData.getScenePointIdList().add(pointData.getId());
167

168
				pointData.updateDailyDungeon();
Yazawazi's avatar
Yazawazi committed
169
170
171
			}

			for (ScenePointEntry entry : scenePointList) {
172
				GameData.getScenePointEntries().put(entry.getName(), entry);
Yazawazi's avatar
Yazawazi committed
173
174
175
176
			}
		}
	}

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

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

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

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

KingRainbow44's avatar
KingRainbow44 committed
197
198
199
			for (File file : files) {
				AvatarConfig config;
				String avatarName;
200

Melledy's avatar
Melledy committed
201
202
203
204
205
206
				Matcher matcher = pattern.matcher(file.getName());
				if (matcher.find()) {
					avatarName = matcher.group(0);
				} else {
					continue;
				}
207

Melledy's avatar
Melledy committed
208
209
210
211
212
213
				try (FileReader fileReader = new FileReader(file)) {
					config = Grasscutter.getGsonFactory().fromJson(fileReader, AvatarConfig.class);
				} catch (Exception e) {
					e.printStackTrace();
					continue;
				}
214

Melledy's avatar
Melledy committed
215
216
217
				if (config.abilities == null) {
					continue;
				}
218

Melledy's avatar
Melledy committed
219
220
221
222
				int s = config.abilities.size();
				AbilityEmbryoEntry al = new AbilityEmbryoEntry(avatarName, config.abilities.stream().map(Object::toString).toArray(size -> new String[s]));
				embryoList.add(al);
			}
223

224
			File playerElementsFile = new File(Utils.toFilePath(RESOURCE("BinOutput/AbilityGroup/AbilityGroup_Other_PlayerElementAbility.json")));
225

226
227
228
229
230
231
232
			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
233
		}
234

Melledy's avatar
Melledy committed
235
236
237
238
239
240
		if (embryoList == null || embryoList.isEmpty()) {
			Grasscutter.getLogger().error("No embryos loaded!");
			return;
		}

		for (AbilityEmbryoEntry entry : embryoList) {
241
			GameData.getAbilityEmbryoInfo().put(entry.getName(), entry);
Melledy's avatar
Melledy committed
242
243
		}
	}
244

Melledy's avatar
Melledy committed
245
246
	private static void loadAbilityModifiers() {
		// Load from BinOutput
247
		File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Ability/Temp/AvatarAbilities/")));
Melledy's avatar
Melledy committed
248
249
250
251
252
253
254
		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) {
255
			List<AbilityConfigData> abilityConfigList;
256

Melledy's avatar
Melledy committed
257
258
259
260
261
262
			try (FileReader fileReader = new FileReader(file)) {
				abilityConfigList = Grasscutter.getGsonFactory().fromJson(fileReader, TypeToken.getParameterized(Collection.class, AbilityConfigData.class).getType());
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
263

Melledy's avatar
Melledy committed
264
265
266
267
			for (AbilityConfigData data : abilityConfigList) {
				if (data.Default.modifiers == null || data.Default.modifiers.size() == 0) {
					continue;
				}
268

Melledy's avatar
Melledy committed
269
				AbilityModifierEntry modifierEntry = new AbilityModifierEntry(data.Default.abilityName);
270

Melledy's avatar
Melledy committed
271
272
				for (Entry<String, AbilityModifier> entry : data.Default.modifiers.entrySet()) {
					AbilityModifier modifier = entry.getValue();
273

Melledy's avatar
Melledy committed
274
275
276
277
278
279
280
281
282
					// Stare.
					if (modifier.onAdded != null) {
						for (AbilityModifierAction action : modifier.onAdded) {
							if (action.$type.contains("HealHP")) {
								action.type = AbilityModifierActionType.HealHP;
								modifierEntry.getOnAdded().add(action);
							}
						}
					}
283

Melledy's avatar
Melledy committed
284
285
286
287
288
289
290
291
					if (modifier.onThinkInterval != null) {
						for (AbilityModifierAction action : modifier.onThinkInterval) {
							if (action.$type.contains("HealHP")) {
								action.type = AbilityModifierActionType.HealHP;
								modifierEntry.getOnThinkInterval().add(action);
							}
						}
					}
292

Melledy's avatar
Melledy committed
293
294
295
296
297
298
299
300
301
					if (modifier.onRemoved != null) {
						for (AbilityModifierAction action : modifier.onRemoved) {
							if (action.$type.contains("HealHP")) {
								action.type = AbilityModifierActionType.HealHP;
								modifierEntry.getOnRemoved().add(action);
							}
						}
					}
				}
302

Melledy's avatar
Melledy committed
303
304
305
306
				GameData.getAbilityModifiers().put(modifierEntry.getName(), modifierEntry);
			}
		}
	}
307

Melledy's avatar
Melledy committed
308
309
	private static void loadSpawnData() {
		List<SpawnGroupEntry> spawnEntryList = null;
310
311
312
313
314

		// 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) {}
315

Melledy's avatar
Melledy committed
316
317
318
319
320
321
		if (spawnEntryList == null || spawnEntryList.isEmpty()) {
			Grasscutter.getLogger().error("No spawn data loaded!");
			return;
		}

		for (SpawnGroupEntry entry : spawnEntryList) {
322
			entry.getSpawns().forEach(s -> s.setGroup(entry));
323
			GameDepot.getSpawnListById(entry.getSceneId()).insert(entry, entry.getPos().getX(), entry.getPos().getZ());
Melledy's avatar
Melledy committed
324
325
		}
	}
326

Melledy's avatar
Melledy committed
327
328
329
	private static void loadOpenConfig() {
		// Read from cached file if exists
		List<OpenConfigEntry> list = null;
330
331
332
333
334
335

		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
336
337
			Map<String, OpenConfigEntry> map = new TreeMap<>();
			java.lang.reflect.Type type = new TypeToken<Map<String, OpenConfigData[]>>() {}.getType();
ayy lmao's avatar
ayy lmao committed
338
			String[] folderNames = {"BinOutput/Talent/EquipTalents/", "BinOutput/Talent/AvatarTalents/"};
339

Melledy's avatar
Melledy committed
340
			for (String name : folderNames) {
341
				File folder = new File(Utils.toFilePath(RESOURCE(name)));
KingRainbow44's avatar
KingRainbow44 committed
342
343
344
345
				File[] files = folder.listFiles();
				if(files == null) {
					Grasscutter.getLogger().error("Error loading open config: no files found in " + folder.getAbsolutePath()); return;
				}
346

KingRainbow44's avatar
KingRainbow44 committed
347
				for (File file : files) {
Melledy's avatar
Melledy committed
348
349
350
					if (!file.getName().endsWith(".json")) {
						continue;
					}
351

KingRainbow44's avatar
KingRainbow44 committed
352
					Map<String, OpenConfigData[]> config;
353

Melledy's avatar
Melledy committed
354
355
356
357
358
359
					try (FileReader fileReader = new FileReader(file)) {
						config = Grasscutter.getGsonFactory().fromJson(fileReader, type);
					} catch (Exception e) {
						e.printStackTrace();
						continue;
					}
360

Melledy's avatar
Melledy committed
361
					for (Entry<String, OpenConfigData[]> e : config.entrySet()) {
362
						OpenConfigEntry entry = new OpenConfigEntry(e.getKey(), e.getValue());
Melledy's avatar
Melledy committed
363
364
365
366
						map.put(entry.getName(), entry);
					}
				}
			}
367

Melledy's avatar
Melledy committed
368
369
			list = new ArrayList<>(map.values());
		}
370

Melledy's avatar
Melledy committed
371
372
373
374
		if (list == null || list.isEmpty()) {
			Grasscutter.getLogger().error("No openconfig entries loaded!");
			return;
		}
375

Melledy's avatar
Melledy committed
376
		for (OpenConfigEntry entry : list) {
377
			GameData.getOpenConfigEntries().put(entry.getName(), entry);
Melledy's avatar
Melledy committed
378
379
		}
	}
380

Melledy's avatar
Melledy committed
381
	private static void loadQuests() {
Melledy's avatar
Melledy committed
382
		File folder = new File(RESOURCE("BinOutput/Quest/"));
383

Melledy's avatar
Melledy committed
384
385
386
		if (!folder.exists()) {
			return;
		}
387

Melledy's avatar
Melledy committed
388
		for (File file : folder.listFiles()) {
Melledy's avatar
Melledy committed
389
			MainQuestData mainQuest = null;
390

Melledy's avatar
Melledy committed
391
			try (FileReader fileReader = new FileReader(file)) {
Melledy's avatar
Melledy committed
392
				mainQuest = Grasscutter.getGsonFactory().fromJson(fileReader, MainQuestData.class);
Melledy's avatar
Melledy committed
393
394
395
396
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
397

Melledy's avatar
Melledy committed
398
			GameData.getMainQuestDataMap().put(mainQuest.getId(), mainQuest);
Melledy's avatar
Melledy committed
399
		}
400
401

		Grasscutter.getLogger().debug("Loaded " + GameData.getMainQuestDataMap().size() + " MainQuestDatas.");
Melledy's avatar
Melledy committed
402
	}
403

404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
	@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);
		}

421
		Grasscutter.getLogger().debug("Loaded " + GameData.getHomeworldDefaultSaveData().size() + " HomeworldDefaultSaveDatas.");
422
423
	}

Akka's avatar
Akka committed
424
425
426
427
428
429
430
431
432
433
434
435
436
437
	@SneakyThrows
	private static void loadNpcBornData(){
		var folder = Files.list(Path.of(RESOURCE("BinOutput/Scene/SceneNpcBorn"))).toList();

		for(var file : folder){
			if(file.toFile().isDirectory()){
				continue;
			}

			var data = Grasscutter.getGsonFactory().fromJson(Files.readString(file), SceneNpcBornData.class);
			if(data.getBornPosList() == null || data.getBornPosList().size() == 0){
				continue;
			}

438
			data.setIndex(SceneIndexManager.buildIndex(3, data.getBornPosList(), item -> item.getPos().toPoint()));
Akka's avatar
Akka committed
439
440
441
			GameData.getSceneNpcBornData().put(data.getSceneId(), data);
		}

442
		Grasscutter.getLogger().debug("Loaded " + GameData.getSceneNpcBornData().size() + " SceneNpcBornDatas.");
Akka's avatar
Akka committed
443
	}
444

Melledy's avatar
Melledy committed
445
	// BinOutput configs
446

447
448
	public static class AvatarConfig {
		@SerializedName(value="abilities", alternate={"targetAbilities"})
Melledy's avatar
Melledy committed
449
		public ArrayList<AvatarConfigAbility> abilities;
450
	}
451

452
453
454
455
	public static class AvatarConfigAbility {
		public String abilityName;
		public String toString() {
			return abilityName;
Melledy's avatar
Melledy committed
456
457
		}
	}
458

Melledy's avatar
Melledy committed
459
460
461
	private static class OpenConfig {
		public OpenConfigData[] data;
	}
462

463
	public static class OpenConfigData {
Melledy's avatar
Melledy committed
464
465
		public String $type;
		public String abilityName;
466

467
		@SerializedName(value="talentIndex", alternate={"OJOFFKLNAHN"})
Melledy's avatar
Melledy committed
468
		public int talentIndex;
469

470
		@SerializedName(value="skillID", alternate={"overtime"})
471
		public int skillID;
472

473
		@SerializedName(value="pointDelta", alternate={"IGEBKIHPOIF"})
474
		public int pointDelta;
Melledy's avatar
Melledy committed
475
476
	}
}