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

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

12
import emu.grasscutter.data.binout.*;
13
import emu.grasscutter.game.world.SpawnDataEntry;
14
import emu.grasscutter.scripts.SceneIndexManager;
KingRainbow44's avatar
KingRainbow44 committed
15
import emu.grasscutter.utils.Utils;
16
import lombok.SneakyThrows;
Melledy's avatar
Melledy committed
17
18
import org.reflections.Reflections;

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

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

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

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

github-actions's avatar
github-actions committed
37
    private static final List<String> loadedResources = new ArrayList<>();
38

github-actions's avatar
github-actions committed
39
40
41
    public static List<Class<?>> getResourceDefClasses() {
        Reflections reflections = new Reflections(ResourceLoader.class.getPackage().getName());
        Set<?> classes = reflections.getSubTypesOf(GameResource.class);
Melledy's avatar
Melledy committed
42

github-actions's avatar
github-actions committed
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);
            }
        });
Melledy's avatar
Melledy committed
50

github-actions's avatar
github-actions committed
51
        classList.sort((a, b) -> b.getAnnotation(ResourceType.class).loadPriority().value() - a.getAnnotation(ResourceType.class).loadPriority().value());
Melledy's avatar
Melledy committed
52

github-actions's avatar
github-actions committed
53
54
        return classList;
    }
55

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

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

        Grasscutter.getLogger().info(translate("messages.status.resources.finish"));
github-actions's avatar
github-actions committed
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    }

    public static void loadResources() {
        loadResources(false);
    }

    public static void loadResources(boolean doReload) {
        for (Class<?> resourceDefinition : getResourceDefClasses()) {
            ResourceType type = resourceDefinition.getAnnotation(ResourceType.class);

            if (type == null) {
                continue;
            }

            @SuppressWarnings("rawtypes")
            Int2ObjectMap map = GameData.getMapByResourceDef(resourceDefinition);

            if (map == null) {
                continue;
            }

            try {
                loadFromResource(resourceDefinition, type, map, doReload);
            } catch (Exception e) {
                Grasscutter.getLogger().error("Error loading resource file: " + Arrays.toString(type.name()), e);
            }
        }
    }

    @SuppressWarnings("rawtypes")
    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());
113
            Grasscutter.getLogger().debug("Loaded " + map.size() + " " + c.getSimpleName() + "s.");
github-actions's avatar
github-actions committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
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
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
303
304
305
306
307
308
309
310
311
        }
    }

    @SuppressWarnings({"rawtypes", "unchecked"})
    protected static void loadFromResource(Class<?> c, String fileName, Int2ObjectMap map) throws Exception {
        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);
            }
        }
    }

    private static void loadScenePoints() {
        Pattern pattern = Pattern.compile("(?<=scene)(.*?)(?=_point.json)");
        File folder = new File(RESOURCE("BinOutput/Scene/Point"));

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

        List<ScenePointEntry> scenePointList = new ArrayList<>();
        for (File file : Objects.requireNonNull(folder.listFiles())) {
            ScenePointConfig config; Integer sceneId;

            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);
                pointData.setId(Integer.parseInt(entry.getKey()));

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

                pointData.updateDailyDungeon();
            }

            for (ScenePointEntry entry : scenePointList) {
                GameData.getScenePointEntries().put(entry.getName(), entry);
            }
        }
    }

    private static void loadAbilityEmbryos() {
        List<AbilityEmbryoEntry> embryoList = null;

        // 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) {
            // Load from BinOutput
            Pattern pattern = Pattern.compile("(?<=ConfigAvatar_)(.*?)(?=.json)");

            embryoList = new LinkedList<>();
            File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Avatar/")));
            File[] files = folder.listFiles();
            if (files == null) {
                Grasscutter.getLogger().error("Error loading ability embryos: no files found in " + folder.getAbsolutePath());
                return;
            }

            for (File file : files) {
                AvatarConfig config;
                String avatarName;

                Matcher matcher = pattern.matcher(file.getName());
                if (matcher.find()) {
                    avatarName = matcher.group(0);
                } else {
                    continue;
                }

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

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

                int s = config.abilities.size();
                AbilityEmbryoEntry al = new AbilityEmbryoEntry(avatarName, config.abilities.stream().map(Object::toString).toArray(size -> new String[s]));
                embryoList.add(al);
            }

            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();
                }
            }
        }

        if (embryoList == null || embryoList.isEmpty()) {
            Grasscutter.getLogger().error("No embryos loaded!");
            return;
        }

        for (AbilityEmbryoEntry entry : embryoList) {
            GameData.getAbilityEmbryoInfo().put(entry.getName(), entry);
        }
    }

    private static void loadAbilityModifiers() {
        // Load from BinOutput
        File folder = new File(Utils.toFilePath(RESOURCE("BinOutput/Ability/Temp/AvatarAbilities/")));
        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) {
            List<AbilityConfigData> abilityConfigList;

            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);
            }
        }
    }

    private static void loadSpawnData() {
        String[] spawnDataNames = {"Spawns.json", "GadgetSpawns.json"};
        ArrayList<SpawnGroupEntry> spawnEntryMap = new ArrayList<>();
312
313
314

        for (String name : spawnDataNames) {
            // Load spawn entries from file
315
            try (InputStreamReader reader = DataLoader.loadReader(name)) {
316
                Type type = TypeToken.getParameterized(Collection.class, SpawnGroupEntry.class).getType();
317
                List<SpawnGroupEntry> list = Grasscutter.getGsonFactory().fromJson(reader, type);
318
319
320
321
322
323

                // Add spawns to group if it already exists in our spawn group map
                spawnEntryMap.addAll(list);
            } catch (Exception ignored) {}
        }

github-actions's avatar
github-actions committed
324
325
326
327
        if (spawnEntryMap.isEmpty()) {
            Grasscutter.getLogger().error("No spawn data loaded!");
            return;
        }
Melledy's avatar
Melledy committed
328

329
330
331
332
333
334
335
        HashMap<GridBlockId, ArrayList<SpawnDataEntry>> areaSort = new HashMap<>();
        //key = sceneId,x,z , value = ArrayList<SpawnDataEntry>
        for (SpawnGroupEntry entry : spawnEntryMap) {
            entry.getSpawns().forEach(
                s -> {
                    s.setGroup(entry);
                    GridBlockId point = s.getBlockId();
github-actions's avatar
github-actions committed
336
                    if (!areaSort.containsKey(point)) {
337
338
339
340
341
342
343
                        areaSort.put(point, new ArrayList<>());
                    }
                    areaSort.get(point).add(s);
                }
            );
        }
        GameDepot.addSpawnListById(areaSort);
github-actions's avatar
github-actions committed
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
    }

    private static void loadOpenConfig() {
        // Read from cached file if exists
        List<OpenConfigEntry> list = null;

        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) {
            Map<String, OpenConfigEntry> map = new TreeMap<>();
            java.lang.reflect.Type type = new TypeToken<Map<String, OpenConfigData[]>>() {}.getType();
            String[] folderNames = {"BinOutput/Talent/EquipTalents/", "BinOutput/Talent/AvatarTalents/"};

            for (String name : folderNames) {
                File folder = new File(Utils.toFilePath(RESOURCE(name)));
                File[] files = folder.listFiles();
                if (files == null) {
                    Grasscutter.getLogger().error("Error loading open config: no files found in " + folder.getAbsolutePath()); return;
                }

                for (File file : files) {
                    if (!file.getName().endsWith(".json")) {
                        continue;
                    }

                    Map<String, OpenConfigData[]> config;

                    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()) {
                        OpenConfigEntry entry = new OpenConfigEntry(e.getKey(), e.getValue());
                        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) {
            GameData.getOpenConfigEntries().put(entry.getName(), entry);
        }
    }

    private static void loadQuests() {
        File folder = new File(RESOURCE("BinOutput/Quest/"));

        if (!folder.exists()) {
            return;
        }

        for (File file : folder.listFiles()) {
            MainQuestData mainQuest = null;

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

            GameData.getMainQuestDataMap().put(mainQuest.getId(), mainQuest);
        }

        Grasscutter.getLogger().debug("Loaded " + GameData.getMainQuestDataMap().size() + " MainQuestDatas.");
    }

    @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().debug("Loaded " + GameData.getHomeworldDefaultSaveData().size() + " HomeworldDefaultSaveDatas.");
    }

    @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;
            }

            data.setIndex(SceneIndexManager.buildIndex(3, data.getBornPosList(), item -> item.getPos().toPoint()));
            GameData.getSceneNpcBornData().put(data.getSceneId(), data);
        }

        Grasscutter.getLogger().debug("Loaded " + GameData.getSceneNpcBornData().size() + " SceneNpcBornDatas.");
    }

    // BinOutput configs

    public static class AvatarConfig {
        @SerializedName(value="abilities", alternate={"targetAbilities"})
        public ArrayList<AvatarConfigAbility> abilities;
    }

    public static class AvatarConfigAbility {
        public String abilityName;
        public String toString() {
            return abilityName;
        }
    }

    private static class OpenConfig {
        public OpenConfigData[] data;
    }

    public static class OpenConfigData {
        public String $type;
        public String abilityName;

        @SerializedName(value="talentIndex", alternate={"OJOFFKLNAHN"})
        public int talentIndex;
488

github-actions's avatar
github-actions committed
489
490
        @SerializedName(value="skillID", alternate={"overtime"})
        public int skillID;
491

github-actions's avatar
github-actions committed
492
493
494
        @SerializedName(value="pointDelta", alternate={"IGEBKIHPOIF"})
        public int pointDelta;
    }
Melledy's avatar
Melledy committed
495
}