BlueMap/implementations/fabric-1.16.2/src/main/java/de/bluecolored/bluemap/fabric/FabricMod.java

257 lines
8.7 KiB
Java
Raw Normal View History

/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
2020-05-11 20:07:39 +02:00
package de.bluecolored.bluemap.fabric;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
2020-05-11 20:07:39 +02:00
import de.bluecolored.bluemap.common.plugin.Plugin;
import de.bluecolored.bluemap.common.plugin.commands.Commands;
import de.bluecolored.bluemap.common.plugin.serverinterface.Player;
2020-05-11 20:07:39 +02:00
import de.bluecolored.bluemap.common.plugin.serverinterface.ServerEventListener;
import de.bluecolored.bluemap.common.plugin.serverinterface.ServerInterface;
import de.bluecolored.bluemap.core.BlueMap;
2020-08-25 15:07:42 +02:00
import de.bluecolored.bluemap.core.MinecraftVersion;
2020-05-11 20:07:39 +02:00
import de.bluecolored.bluemap.core.logger.Logger;
import de.bluecolored.bluemap.core.resourcepack.ParseResourceException;
2020-08-08 16:50:47 +02:00
import de.bluecolored.bluemap.fabric.events.PlayerJoinCallback;
import de.bluecolored.bluemap.fabric.events.PlayerLeaveCallback;
2020-05-11 20:07:39 +02:00
import net.fabricmc.api.ModInitializer;
2020-08-03 15:38:28 +02:00
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
2020-08-16 15:18:55 +02:00
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.minecraft.server.MinecraftServer;
2020-08-08 16:50:47 +02:00
import net.minecraft.server.network.ServerPlayerEntity;
2020-05-11 20:07:39 +02:00
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.WorldSavePath;
2020-08-03 15:38:28 +02:00
import net.minecraft.world.dimension.DimensionType;
2021-05-23 10:12:34 +02:00
import org.apache.logging.log4j.LogManager;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
2020-05-11 20:07:39 +02:00
public class FabricMod implements ModInitializer, ServerInterface {
private Plugin pluginInstance = null;
2020-08-08 16:50:47 +02:00
private MinecraftServer serverInstance = null;
2020-05-11 20:07:39 +02:00
private Map<File, UUID> worldUUIDs;
private FabricEventForwarder eventForwarder;
2020-05-11 20:07:39 +02:00
private LoadingCache<ServerWorld, UUID> worldUuidCache;
2020-08-08 16:50:47 +02:00
private int playerUpdateIndex = 0;
private Map<UUID, Player> onlinePlayerMap;
private List<FabricPlayer> onlinePlayerList;
public FabricMod() {
2020-05-11 20:07:39 +02:00
Logger.global = new Log4jLogger(LogManager.getLogger(Plugin.PLUGIN_NAME));
2020-08-08 16:50:47 +02:00
this.onlinePlayerMap = new ConcurrentHashMap<>();
this.onlinePlayerList = Collections.synchronizedList(new ArrayList<>());
2021-05-23 10:12:34 +02:00
pluginInstance = new Plugin(new MinecraftVersion(1, 16, 2), "fabric-1.16.2", this);
this.worldUUIDs = new ConcurrentHashMap<>();
this.eventForwarder = new FabricEventForwarder(this);
this.worldUuidCache = Caffeine.newBuilder()
.executor(BlueMap.THREAD_POOL)
.weakKeys()
.maximumSize(1000)
.build(this::loadUUIDForWorld);
}
@Override
public void onInitialize() {
2020-05-11 20:07:39 +02:00
//register commands
2020-08-03 15:38:28 +02:00
CommandRegistrationCallback.EVENT.register((dispatcher, dedicated) -> {
new Commands<>(pluginInstance, dispatcher, fabricSource -> new FabricCommandSource(this, pluginInstance, fabricSource));
});
2020-08-03 15:38:28 +02:00
ServerLifecycleEvents.SERVER_STARTED.register((MinecraftServer server) -> {
2020-08-08 16:50:47 +02:00
this.serverInstance = server;
new Thread(()->{
2020-08-16 15:18:55 +02:00
Logger.global.logInfo("Loading BlueMap...");
try {
pluginInstance.load();
if (pluginInstance.isLoaded()) Logger.global.logInfo("BlueMap loaded!");
} catch (IOException | ParseResourceException e) {
Logger.global.logError("Failed to load bluemap!", e);
2020-08-19 20:31:20 +02:00
pluginInstance.unload();
}
}).start();
});
2020-08-03 15:38:28 +02:00
ServerLifecycleEvents.SERVER_STOPPING.register((MinecraftServer server) -> {
pluginInstance.unload();
Logger.global.logInfo("BlueMap unloaded!");
2020-05-11 20:07:39 +02:00
});
2020-08-08 16:50:47 +02:00
PlayerJoinCallback.EVENT.register(this::onPlayerJoin);
PlayerLeaveCallback.EVENT.register(this::onPlayerLeave);
2020-08-16 15:18:55 +02:00
ServerTickEvents.END_SERVER_TICK.register((MinecraftServer server) -> {
2020-08-08 16:50:47 +02:00
if (server == this.serverInstance) this.updateSomePlayers();
});
2020-05-11 20:07:39 +02:00
}
@Override
public void registerListener(ServerEventListener listener) {
eventForwarder.addEventListener(listener);
2020-05-11 20:07:39 +02:00
}
@Override
public void unregisterAllListeners() {
eventForwarder.removeAllListeners();
2020-05-11 20:07:39 +02:00
}
@Override
public UUID getUUIDForWorld(File worldFolder) throws IOException {
worldFolder = worldFolder.getCanonicalFile();
UUID uuid = worldUUIDs.get(worldFolder);
if (uuid == null) {
uuid = UUID.randomUUID();
worldUUIDs.put(worldFolder, uuid);
}
return uuid;
}
public UUID getUUIDForWorld(ServerWorld world) throws IOException {
try {
return worldUuidCache.get(world);
} catch (RuntimeException e) {
Throwable cause = e.getCause();
if (cause instanceof IOException) throw (IOException) cause;
else throw new IOException(cause);
}
}
private UUID loadUUIDForWorld(ServerWorld world) throws IOException {
2020-08-03 15:38:28 +02:00
MinecraftServer server = world.getServer();
File worldFolder = world.getServer().getRunDirectory().toPath().resolve(server.getSavePath(WorldSavePath.ROOT)).toFile();
2020-08-03 15:38:28 +02:00
File dimensionFolder = DimensionType.getSaveDirectory(world.getRegistryKey(), worldFolder);
File dimensionDir = dimensionFolder.getCanonicalFile();
return getUUIDForWorld(dimensionDir);
2020-05-11 20:07:39 +02:00
}
@Override
public boolean persistWorldChanges(UUID worldUUID) throws IOException, IllegalArgumentException {
final CompletableFuture<Boolean> taskResult = new CompletableFuture<>();
serverInstance.execute(() -> {
try {
for (ServerWorld world : serverInstance.getWorlds()) {
if (getUUIDForWorld(world).equals(worldUUID)) {
world.save(null, true, false);
}
}
taskResult.complete(true);
} catch (Exception e) {
taskResult.completeExceptionally(e);
}
});
try {
return taskResult.get();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException(e);
} catch (ExecutionException e) {
Throwable t = e.getCause();
if (t instanceof IOException) throw (IOException) t;
if (t instanceof IllegalArgumentException) throw (IllegalArgumentException) t;
throw new IOException(t);
}
}
2020-05-11 20:07:39 +02:00
@Override
public File getConfigFolder() {
return new File("config/bluemap");
2020-05-11 20:07:39 +02:00
}
2020-08-08 16:50:47 +02:00
public void onPlayerJoin(MinecraftServer server, ServerPlayerEntity playerInstance) {
if (this.serverInstance != server) return;
FabricPlayer player = new FabricPlayer(this, playerInstance.getUuid());
2020-08-08 16:50:47 +02:00
onlinePlayerMap.put(player.getUuid(), player);
onlinePlayerList.add(player);
}
public void onPlayerLeave(MinecraftServer server, ServerPlayerEntity player) {
if (this.serverInstance != server) return;
UUID playerUUID = player.getUuid();
onlinePlayerMap.remove(playerUUID);
synchronized (onlinePlayerList) {
onlinePlayerList.removeIf(p -> p.getUuid().equals(playerUUID));
}
}
public MinecraftServer getServer() {
return this.serverInstance;
}
@Override
public Collection<Player> getOnlinePlayers() {
2020-08-08 16:50:47 +02:00
return onlinePlayerMap.values();
}
@Override
public Optional<Player> getPlayer(UUID uuid) {
2020-08-08 16:50:47 +02:00
return Optional.ofNullable(onlinePlayerMap.get(uuid));
}
/**
* Only update some of the online players each tick to minimize performance impact on the server-thread.
* Only call this method on the server-thread.
*/
private void updateSomePlayers() {
int onlinePlayerCount = onlinePlayerList.size();
if (onlinePlayerCount == 0) return;
int playersToBeUpdated = onlinePlayerCount / 20; //with 20 tps, each player is updated once a second
if (playersToBeUpdated == 0) playersToBeUpdated = 1;
for (int i = 0; i < playersToBeUpdated; i++) {
playerUpdateIndex++;
if (playerUpdateIndex >= 20 && playerUpdateIndex >= onlinePlayerCount) playerUpdateIndex = 0;
if (playerUpdateIndex < onlinePlayerCount) {
onlinePlayerList.get(playerUpdateIndex).update();
2020-08-08 16:50:47 +02:00
}
}
}
2020-05-11 20:07:39 +02:00
}