-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathModCore.java
More file actions
557 lines (481 loc) · 21.1 KB
/
ModCore.java
File metadata and controls
557 lines (481 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
113
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
package cam72cam.mod;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import net.minecraft.client.resources.ClientResourcePackInfo;
import net.minecraft.resources.*;
import net.minecraft.resources.data.IMetadataSectionSerializer;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.fml.ModList;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cam72cam.mod.config.ConfigFile;
import cam72cam.mod.entity.ModdedEntity;
import cam72cam.mod.entity.sync.EntitySync;
import cam72cam.mod.event.ClientEvents;
import cam72cam.mod.input.Mouse;
import cam72cam.mod.net.Packet;
import cam72cam.mod.net.PacketDirection;
import cam72cam.mod.render.Light;
import cam72cam.mod.resource.Identifier;
import cam72cam.mod.text.Command;
import cam72cam.mod.util.MinecraftFiles;
import cam72cam.mod.util.ModCoreCommand;
import cam72cam.mod.world.ChunkManager;
import net.minecraft.client.Minecraft;
import net.minecraft.util.Unit;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLLoadCompleteEvent;
import net.minecraftforge.fml.event.lifecycle.InterModEnqueueEvent;
import net.minecraftforge.fml.event.server.FMLServerStartedEvent;
import net.minecraftforge.fml.event.server.FMLServerStartingEvent;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.loading.FMLPaths;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.lwjgl.opengl.GL11;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/** UMC Mod, do not touch... */
@net.minecraftforge.fml.common.Mod(ModCore.MODID)
public class ModCore {
public static final String MODID = "universalmodcore";
public static final String NAME = "UniversalModCore";
public static final String VERSION = "1.2.3";
public static ModCore instance;
public static boolean hasResources;
private static boolean isInReload;
private static List<Mod> mods = new ArrayList<>();
private Logger logger;
/** Register a mod, must happen before UMC is loaded! */
public static void register(Mod ctr) {
mods.add(ctr);
}
/** Called during Mod Construction phase */
public ModCore() {
System.out.println("Welcome to UniversalModCore!");
instance = this;
ModCore.register(new Internal());
proxy.setup();
proxy.event(ModEvent.CONSTRUCT);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::preInit);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::init);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::postInit);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::serverStarting);
FMLJavaModLoadingContext.get().getModEventBus().addListener(this::serverStarted);
MinecraftForge.EVENT_BUS.register(this);
}
/** INIT Phase (Forge) */
public void preInit(FMLCommonSetupEvent event) {
logger = LogManager.getLogger();
proxy.event(ModEvent.INITIALIZE);
hasResources = true;
}
/** SETUP Phase (Forge) */
public void init(InterModEnqueueEvent event) {
proxy.event(ModEvent.SETUP);
}
/** FINALIZE Phase (Forge) */
public void postInit(FMLLoadCompleteEvent event) {
proxy.event(ModEvent.FINALIZE);
for (Mod mod : mods) {
File modDir = cacheFile(new Identifier(mod.modID(), "foo")).getParentFile();
if (modDir.exists() && modDir.isDirectory()) {
for (File file : modDir.listFiles()) {
if (!usedCacheFiles.contains(file)) {
ModCore.warn("Removing file cache entry: %s", file);
FileUtils.deleteQuietly(file);
}
}
}
}
}
@SubscribeEvent
public void serverStarting(FMLServerStartingEvent event) {
Command.registration(event.getCommandDispatcher());
}
/** START Phase (Forge) */
public void serverStarted(FMLServerStartedEvent event) {
proxy.event(ModEvent.START);
}
/** Implement this to create a UMC mod */
public static abstract class Mod {
public abstract String modID();
/** Called both server and client side with a given event */
public abstract void commonEvent(ModEvent event);
/** Called client side with a given event */
public abstract void clientEvent(ModEvent event);
/** Called server side with a given event */
public abstract void serverEvent(ModEvent event);
/** Get config file for filename */
public final Path getConfig(String fname) {
return Paths.get(FMLPaths.CONFIGDIR.get().toString(), fname);
}
/* Standard logging functions */
public static void debug(String msg, Object...params) {
ModCore.debug(msg, params);
}
public static void info(String msg, Object...params) {
ModCore.info(msg, params);
}
public static void warn(String msg, Object...params) {
ModCore.warn(msg, params);
}
public static void error(String msg, Object...params) {
ModCore.error(msg, params);
}
public static void catching(Throwable ex) {
ModCore.catching(ex);
}
}
private static Proxy proxy = DistExecutor.runForDist(() -> ClientProxy::new, () -> ServerProxy::new);
/** Hooked into forge's proxy system and fires off corresponding events */
public static class Proxy {
public Proxy() {
proxy = this;
}
public void event(ModEvent event) {
instance.mods.forEach(m -> event(event, m));
}
public void event(ModEvent event, Mod m) {
m.commonEvent(event);
}
public void setup() {
}
}
public static class ClientProxy extends Proxy {
static int MaxTextureSize = -1;
public ClientProxy() {
super();
try {
throw new Exception();
} catch (Exception ex) {
if (Arrays.toString(ex.getStackTrace()).contains("net.minecraftforge.fml.ModLoader.runDataGenerator")) {
ModCore.warn("Skipping MaxTextureSize detection during data generation");
return;
}
}
if (FMLPaths.CONFIGDIR.get() != null) { /* not a test environment */
MaxTextureSize = GL11.glGetInteger(GL11.GL_MAX_TEXTURE_SIZE);
ModCore.info("Detected GL_MAX_TEXTURE_SIZE as: %s", MaxTextureSize);
}
}
@Override
public void setup() {
if (Minecraft.getInstance() == null) {
// Instance can be null during data gen
return;
}
Config.getMaxTextureSize(); //populate
List<ResourcePack> packs = new ArrayList<>();
packs.add(new TranslationResourcePack());
for (Mod m : mods) {
ResourcePack modPack = createPack(ModList.get().getModFileById(m.modID()).getFile().getFilePath().toFile());
packs.add(modPack);
String configDir = FMLPaths.CONFIGDIR.get().toString();
new File(configDir).mkdirs();
File folder = new File(configDir + File.separator + m.modID());
if (folder.exists()) {
if (folder.isDirectory()) {
File[] files = folder.listFiles((dir, name) -> name.endsWith(".zip"));
for (File file : files) {
packs.add(createPack(file));
}
File[] folders = folder.listFiles((dir, name) -> dir.isDirectory());
for (File dir : folders) {
packs.add(createPack(dir));
}
}
} else {
folder.mkdirs();
}
packs.add(modPack);
}
// Force first and last (and inject mod time) BUG: sounds can still be overridden by resource packs
Minecraft.getInstance().getResourcePackList().addPackFinder(new IPackFinder() {
@Override
public <T extends ResourcePackInfo> void addPackInfosToMap(Map<String, T> nameToPackMap, ResourcePackInfo.IFactory<T> packInfoFactory) {
for (ResourcePack pack : packs) {
//noinspection unchecked
nameToPackMap.put(pack.getName(), (T) new ClientResourcePackInfo(pack.getName(),
true,
() -> pack,
new StringTextComponent(""),
new StringTextComponent(""),
PackCompatibility.COMPATIBLE,
ResourcePackInfo.Priority.TOP,
true,
null,
true));
}
}
});
}
@Override
public void event(ModEvent event, Mod m) {
super.event(event, m);
m.clientEvent(event);
}
private static class TranslationResourcePack extends ResourcePack {
public TranslationResourcePack() {
super(null);
}
private ResourceLocation toLang(String path) {
// assets/mod/location
//return String.format("%s/%s/%s", type.getDirectoryName(), location.getNamespace(), location.getPath());
String[] parts = path.split("/");
String type = parts[0];
String namespace = parts[1];
String prefix = String.format("%s/%s/", type, namespace);
path = path.replace(prefix, "").replace(".json", ".lang");
String lang = path.split("_")[1].replace(".lang", "");
path = path.replace("_" + lang, "_" + lang.toUpperCase(Locale.ROOT));
return new ResourceLocation(namespace, path.toLowerCase(Locale.ROOT)) {
@Override
public String getPath() {
// Very evil...
return path;
}
};
}
@Override
public boolean resourceExists(String resourcePath) {
if (resourcePath.contains("/lang/") && resourcePath.endsWith(".json")) {
ResourceLocation lang = toLang(resourcePath);
return Minecraft.getInstance().getResourceManager().hasResource(lang);
}
return false;
}
@Override
public InputStream getInputStream(String resourcePath) throws IOException {
if (resourcePath.contains("/lang/") && resourcePath.endsWith(".json")) {
// Magical Translations!
ResourceLocation lang = toLang(resourcePath);
if (Minecraft.getInstance().getResourceManager().hasResource(lang)) {
Map<String, String> translationMap = new HashMap<>();
for (IResource resource : Minecraft.getInstance().getResourceManager().getAllResources(lang)) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
//Remove comment
line = line.trim();
int comment = line.indexOf("#");
if (line.isEmpty() || comment == 0) {
continue;
}
String[] splits = line.split("=", 2);
if (splits.length == 2) {
translationMap.put(splits[0].trim(), splits[1].trim());
}
}
}
}
Set<String> translations = new HashSet<>();
translationMap.forEach((key, value) -> {
if (!key.isEmpty()) {
translations.add(String.format("\"%s\": \"%s\"", key, value));
translations.add(String.format("\"%s\": \"%s\"", key.replace(":", "."), value));
translations.add(String.format("\"%s\": \"%s\"", key.replace(".name", ""), value));
translations.add(String.format("\"%s\": \"%s\"", key.replace(".name", "").replace(":", "."), value));
}
});
String output = "{" + String.join(",", translations) + "}";
return new ByteArrayInputStream(output.getBytes(StandardCharsets.UTF_8));
}
}
return null;
}
@Override
public Collection<ResourceLocation> getAllResourceLocations(ResourcePackType type, String pathIn, int maxDepth, Predicate<String> filter) {
return Collections.emptyList();
}
@Override
public Set<String> getResourceNamespaces(ResourcePackType type) {
return mods.stream().map(Mod::modID).collect(Collectors.toSet());
}
@Override
public void close() throws IOException {
}
@Override
public String getName() {
return "Translation Hackery";
}
@Nullable
@Override
public <T> T getMetadata(IMetadataSectionSerializer<T> p_195760_1_) throws IOException {
return getResourceMetadata(p_195760_1_, new ByteArrayInputStream("{}".getBytes()));
}
}
private static class UMCFolderPack extends FolderPack {
public UMCFolderPack(File folder) {
super(folder);
}
@Override
public InputStream getInputStream(String name) throws IOException {
InputStream stream = super.getInputStream(name);
File file = this.getFile(name);
return new Identifier.InputStreamMod(stream, file.lastModified());
}
@Override
public boolean resourceExists(String resourcePath) {
return super.resourceExists(resourcePath);
}
}
private static class UMCFilePack extends FilePack {
private final File path;
public UMCFilePack(File fileIn) {
super(fileIn);
this.path = fileIn;
}
@Override
public InputStream getInputStream(String name) throws IOException {
return new Identifier.InputStreamMod(super.getInputStream(name), path.lastModified());
}
}
private static ResourcePack createPack(File path) {
if (path.isDirectory()) {
return new UMCFolderPack(path);
} else {
return new UMCFilePack(path);
}
}
}
public static class ServerProxy extends Proxy {
@Override
public void event(ModEvent event, Mod m) {
super.event(event, m);
m.serverEvent(event);
}
}
public static boolean isInReload() {
return isInReload;
}
public static class Internal extends Mod {
@Override
public String modID() {
return "universalmodcore";
}
@Override
public void commonEvent(ModEvent event) {
switch (event) {
case CONSTRUCT:
Packet.register(EntitySync.EntitySyncPacket::new, PacketDirection.ServerToClient);
Packet.register(ModdedEntity.PassengerPositionsPacket::new, PacketDirection.ServerToClient);
Packet.register(ModdedEntity.PassengerSeatPacket::new, PacketDirection.ServerToClient);
Packet.register(Mouse.MousePressPacket::new, PacketDirection.ClientToServer);
Command.register(new ModCoreCommand());
ConfigFile.sync(Config.class);
break;
case INITIALIZE:
break;
case SETUP:
// CommonEvents.World.LOAD.subscribe(w -> w.increaseMaxEntityRadius(32));
break;
case FINALIZE:
ChunkManager.setup();
break;
case START:
break;
}
}
@Override
public void clientEvent(ModEvent event) {
switch (event) {
case CONSTRUCT:
// Instance can be null during data gen
if (Minecraft.getInstance() != null) {
((IReloadableResourceManager) Minecraft.getInstance().getResourceManager()).addReloadListener((stage, resourceManager, preparationsProfiler, reloadProfiler, backgroundExecutor, gameExecutor) ->
stage.markCompleteAwaitingOthers(Unit.INSTANCE).thenRun(ClientEvents::fireReload));
Light.register();
}
case SETUP:
try {
Minecraft.getInstance().populateSearchTreeManager();
} catch (Exception ex) {
ModCore.catching(ex);
}
//BlockRender.onPostColorSetup();
//ClientEvents.fireReload();
break;
}
}
@Override
public void serverEvent(ModEvent event) {
}
}
public static void debug(String msg, Object... params) {
if (Config.DebugLogging) {
if (instance == null || instance.logger == null) {
System.out.println("DEBUG: " + String.format(msg, params));
return;
}
if (params.length != 0) {
instance.logger.info(String.format(msg, params));
} else {
instance.logger.info(msg);
}
}
}
public static void info(String msg, Object... params) {
if (instance == null || instance.logger == null) {
System.out.println("INFO: " + String.format(msg, params));
return;
}
instance.logger.info(String.format(msg, params));
}
public static void warn(String msg, Object... params) {
if (instance == null || instance.logger == null) {
System.out.println("WARN: " + String.format(msg, params));
return;
}
instance.logger.warn(String.format(msg, params));
}
public static void error(String msg, Object... params) {
if (instance == null || instance.logger == null) {
System.out.println("ERROR: " + String.format(msg, params));
return;
}
instance.logger.error(String.format(msg, params));
}
public static void catching(Throwable ex, String msg, Object... params) {
error(msg, params);
catching(ex);
}
public static void catching(Throwable ex) {
if (instance == null || instance.logger == null) {
ex.printStackTrace();
return;
}
instance.logger.error("Exception", ex);
}
private static final List<File> usedCacheFiles = new ArrayList<>();
/** Get a file for name in the UMC cache dir */
public static synchronized File cacheFile(Identifier id) {
Path configDir = MinecraftFiles.getConfigDir().toPath();
File cacheDir = Paths.get(configDir.getParent().toFile().getPath(), "cache", id.getDomain()).toFile();
cacheDir.mkdirs();
// https://stackoverflow.com/questions/1155107/is-there-a-cross-platform-java-method-to-remove-filename-special-chars#comment96425990_17745189
String path = id.getPath().replaceAll("(?U)[^\\w\\._]+", ".");
if (SystemUtils.IS_OS_WINDOWS) {
// In a world with linux, who needs windows or gates?
path = StringUtils.right(path, 250 - cacheDir.getAbsolutePath().length()); // Windows default max *Path* len is 256
} else {
path = StringUtils.right(path, 250); // Most FS's allow up to 255
}
File f = new File(cacheDir, path);
usedCacheFiles.add(f);
return f;
}
}