refactor: Переписана реализация конфигурации

- Загрузчик теперь имеет собственный конфиг *zotecore.yml*, в котором хранятся настройки ядра.
- Свойства можно получить, используя инстенс сервера, наккитовский сервер доступен отдельно.
- Устаревшие или неподдерживаемые методы по умолчанию логгируются в отладочный лог если он включен.
This commit is contained in:
MaXFeeD
2023-12-26 03:20:18 +03:00
parent 118ec09512
commit 61beb45a3e
21 changed files with 419 additions and 226 deletions
+47 -25
View File
@@ -1,37 +1,59 @@
# ZotCoreLoader # Zote Core Loader
ZotCoreLoader — серверное ядро предназначенное для inner core 1.16.201. __Zote Core__ — серверное ядро, основанное на Inner Core 1.26.200, созданное для создания уникального геймплея с модами.
Основой серверного ядра послужил [Nukkit-Mot](https://github.com/MemoriesOfTime/Nukkit-MOT), ZotCoreLoader сделан таким образом, чтобы Nukkit-Mot внутри ядра было легко обновлять.
![ZotCoreLoader](/.github/logo.png) Основой серверного ядра послужил [Nukkit-MOT](https://github.com/MemoriesOfTime/Nukkit-MOT), его можно легко обновить, заменив соответствующую библиотеку.
## server.properties ![Zote Core](/.github/logo.png)
**Настройки, добавляемые ядром**: ## Установка
* legacy.workbench — по умолчанию true (другое значение на данный момент не поддерживается) Поддерживается любая платформа, поддерживающая Java 17 или выше. Загрузите последний релиз серверного ядра, либо соберите репозиторий с помощью Gradle.
* inner_core.legacy_inventory — по умолчанию true (другое значение на данный момент не поддерживается)
* inner-core-version — числовая версия inner core
* inner-core-version-name — текстовая версия inner core
* inner-core-pack-name — имя пака inner core
* inner_core.runtime_exception — выдавать RuntimeException об использовании не поддерживаемых методов (по умолчанию false), рекомендуется только для отладки модов, во время игры выключайте
* eval-enable — вкл\выкл использование eval (по умолчанию true)
* develop-mode — режим разработки
## ПРЕДУПРЕЖДЕНИЕ Запустите собранное ядро, открыв консоль в папке с ним:
Использование `eval`, `requireGlobal` не рекомендуется! ```sh
Используйте эти методы с осторожностью! java -jar ZoteCore-SNAPSHOT.jar
Особенно не рекомендуется использвать в `Network` пакетах! ```
Это может использовать для получения полного контроля над сервером!
По умолчанию 'eval-enable' включён, лишь для обратной совместимости, при возможности рекомендуется держать его выключеным!
**Настройки, заблокированные ядром**: ## Конфигурация
* multiversion-min-protocol — ставит значение 422 (1.16.200) Настройки производятся посредством трех основных файлов: *server.properties*, *nukkit.yml* и *zotecore.yml*. Они будут созданы автоматически сразу же после запуска ядра, документация по первым двум доступна в репозитории Nukkit.
* multiversion-max-protocol — ставит значение 422 (1.16.200)
* xbox-auth — ставит значение false > Некоторые настройки Nukkit заблокированы загрузчиком, среди которых *multiversion-min/max-protocol* (422), *xbox-auth* (авторизация с помощью него не доступна) и *save-player-data-by-uuid* (false).
* save-player-data-by-uuid — ставит значение false
### zotecore.yml
Стандартные настройки ядра, которые можно использовать как основу:
```yml zotecore.yml
# Изменение информации пака, который клиент должен иметь для входа на сервер.
# Устаревшие или не реализованные методы, однако, добавлены не будут.
pack: Inner Core Test
pack-version: 2.3.0b115 test
pack-version-code: 152
# Использование ванильного интерфейса верстака, вместо кастомного.
# Внимание: в настоящее время не поддерживается и пользовательские рецепты не будут отображаться.
use-legacy-workbench-override: on
# Отключение исправления инвентаря для подключенных клиентов, устаревшие версии не
# работают должным образом с ним, не позволяя перемещать предметы по инвентарю.
use-legacy-inventory: on
# Переключение режима отладки для неподдерживаемых методов (например, клиентских).
# Может быть одним из: none, debug (по умолчанию), warning, raise.
unsupported-method-handling: debug
# Могут ли моды использовать небезопасные функции (например, вызов eval) или нет.
# Внимание: это может создать риск безопасности, однако, например, его запрет
# влияет на requireGlobal и часто может нарушить работу модов.
allow-unsafe-scripting: on
# Режим разработчика позволяет получать дополнительную информацию
# о работе ядра, а также профайлинг методов.
developer-mode: off
```
## Лицензия ## Лицензия
+135 -88
View File
@@ -4,6 +4,7 @@ import cn.nukkit.Server;
import cn.nukkit.plugin.PluginDescription; import cn.nukkit.plugin.PluginDescription;
import cn.nukkit.plugin.PluginManager; import cn.nukkit.plugin.PluginManager;
import com.google.common.base.Preconditions;
import com.reider745.api.CallbackHelper; import com.reider745.api.CallbackHelper;
import com.reider745.block.CustomBlock; import com.reider745.block.CustomBlock;
import com.reider745.commands.CommandsHelper; import com.reider745.commands.CommandsHelper;
@@ -36,6 +37,8 @@ import java.io.*;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.nio.file.*; import java.nio.file.*;
import java.nio.file.FileSystem;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
@@ -46,14 +49,21 @@ import java.util.zip.ZipEntry;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
public class InnerCoreServer { public class InnerCoreServer {
public enum MethodHandling {
NONE, DEBUG, WARNING, RAISE;
}
public static final int PROTOCOL = 422; public static final int PROTOCOL = 422;
public static final int EXIT_CODE_NO_INTERNAL_PACKAGE = 32; public static final int EXIT_CODE_NO_INTERNAL_PACKAGE = 32;
public static String dataPath;
public static InnerCoreServer singleton;
public static InnerCorePlugin plugin; public static InnerCorePlugin plugin;
public static String PATH; public InnerCoreServer() {
public static Server server; Preconditions.checkState(singleton == null, "Already initialized!");
public static InnerCoreServer ic_server; singleton = this;
}
public static String getStringParam(String name) { public static String getStringParam(String name) {
return switch (name) { return switch (name) {
@@ -64,33 +74,19 @@ public class InnerCoreServer {
} }
public static String getGameLanguage() { public static String getGameLanguage() {
final String lang = server.getLanguage().getLang(); final String langName = Server.getInstance().getLanguage().getLang();
final StringBuilder icLang = new StringBuilder(); final StringBuilder targetLang = new StringBuilder();
for (int i = 0; i < lang.length() - 1; i++) for (int i = 0; i < langName.length() - 1; i++) {
icLang.append(lang.charAt(i)); targetLang.append(langName.charAt(i));
return icLang.toString(); }
return targetLang.toString();
} }
public void left() { public void left() {
NativeCallback.onGameStopped(true); NativeCallback.onGameStopped(true);
NativeCallback.onMinecraftAppSuspended(); NativeCallback.onMinecraftAppSuspended();
} singleton = null;
public boolean isLegacyWorkbench() {
return server.getPropertyBoolean("legacy.workbench");
}
public static boolean canEvalEnable() {
return server.getPropertyBoolean("eval-enable", true);
}
public static boolean isDevelopMode() {
return server.getPropertyBoolean("develop-mode", false);
}
public static boolean isRuntimeException() {
return server.getPropertyBoolean("inner_core.runtime_exception", false);
} }
private static void processFile(ZipFile file, String uncompressedDirectory, ZipEntry entry) throws IOException { private static void processFile(ZipFile file, String uncompressedDirectory, ZipEntry entry) throws IOException {
@@ -190,8 +186,8 @@ public class InnerCoreServer {
try { try {
return unpackExistingResources(targetPath, outputPath); return unpackExistingResources(targetPath, outputPath);
} catch (IOException | SecurityException e) { } catch (IOException | SecurityException e) {
server.getLogger().warning("Failed to unpack '" + targetPath + "' or it was not found"); Server.getInstance().getLogger().warning("Failed to unpack '" + targetPath + "' or it was not found");
server.getLogger().debug("Failed to unpack '" + targetPath + "' or it was not found", e); Server.getInstance().getLogger().debug("Failed to unpack '" + targetPath + "' or it was not found", e);
} }
return null; return null;
} }
@@ -201,32 +197,31 @@ public class InnerCoreServer {
Thread.currentThread().setPriority(Thread.MAX_PRIORITY); Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
server.getLogger().info("Initiating target directory '" + server.getDataPath() + "'"); server.getLogger().info("Initiating target directory '" + server.getDataPath() + "'");
PATH = server.getDataPath(); dataPath = server.getDataPath();
InnerCoreServer.server = server; final File dataFolderFile = new File(dataPath);
InnerCoreServer.ic_server = this;
Logger.server = server;
CallbackHelper.init(); CallbackHelper.init();
NukkitIdConvertor.init(); NukkitIdConvertor.init();
HashMap<String, Object> description = new HashMap<>();
description.put("name", "ZoteCore");
description.put("version", "SNAPSHOT");
description.put("main", InnerCorePlugin.class.getName());
description.put("api", new ArrayList<String>());
plugin = new InnerCorePlugin(); plugin = new InnerCorePlugin();
plugin.setEnabled(true); plugin.init(null, server, new PluginDescription(description), dataFolderFile, dataFolderFile);
plugin.saveDefaultConfig();
plugin.onLoad();
plugin.setEnabled();
HashMap<String, Object> configs = new HashMap<>(); final File innerCoreDirectory = new File(dataPath, "innercore");
configs.put("name", "InnerCore");
configs.put("version", getVersionName());
configs.put("main", "cn.nukkit.plugin.InternalPlugin");
configs.put("api", null);
plugin.init(null, server, new PluginDescription(configs), null, null);
final File innerCoreDirectory = new File(PATH, "innercore");
if (!innerCoreDirectory.exists()) { if (!innerCoreDirectory.exists()) {
server.getLogger().info("Extracting internal package..."); server.getLogger().info("Extracting internal package...");
try { try {
File innercoreFile = unpackExistingResources("/innercore.zip", PATH); File innercoreFile = unpackExistingResources("/innercore.zip", dataPath);
try (final ZipFile zipFile = new ZipFile(innercoreFile)) { try (final ZipFile zipFile = new ZipFile(innercoreFile)) {
unzip(zipFile, PATH); unzip(zipFile, dataPath);
} }
} catch (IOException | SecurityException fileExc) { } catch (IOException | SecurityException fileExc) {
try { try {
@@ -246,7 +241,7 @@ public class InnerCoreServer {
} }
} }
unpackResources("/innercore_default_config.json", PATH); unpackResources("/innercore_default_config.json", dataPath);
// Required to be called before modpack instantiation // Required to be called before modpack instantiation
FileTools.init(); FileTools.init();
@@ -265,7 +260,7 @@ public class InnerCoreServer {
} }
} }
InnerCore innerCore = new InnerCore(new File(PATH)); InnerCore innerCore = new InnerCore(dataFolderFile);
innerCore.load(); innerCore.load();
innerCore.build(); innerCore.build();
LoadingStage.setStage(LoadingStage.STAGE_MCPE_STARTING); LoadingStage.setStage(LoadingStage.STAGE_MCPE_STARTING);
@@ -290,10 +285,11 @@ public class InnerCoreServer {
} }
public void afterload() { public void afterload() {
server.getLogger().info("Registering Nukkit-MOT containment..."); Server.getInstance().getLogger().info("Registering Nukkit-MOT containment...");
PluginManager pluginManager = Server.getInstance().getPluginManager();
pluginManager.getPlugins().put(plugin.getDescription().getName(), plugin);
Logger.info("Registering ZoteCore events..."); Logger.info("Registering ZoteCore events...");
PluginManager pluginManager = server.getPluginManager();
pluginManager.registerEvents(new EventListener(), plugin); pluginManager.registerEvents(new EventListener(), plugin);
pluginManager.registerEvents(new SnowfallEverywhere(), plugin); pluginManager.registerEvents(new SnowfallEverywhere(), plugin);
@@ -308,67 +304,118 @@ public class InnerCoreServer {
NativeCallback.onLevelCreated(); NativeCallback.onLevelCreated();
} }
public void reload() {
plugin.setEnabled();
PluginManager pluginManager = Server.getInstance().getPluginManager();
pluginManager.getPlugins().put(plugin.getDescription().getName(), plugin);
pluginManager.registerEvents(new EventListener(), plugin);
pluginManager.registerEvents(new SnowfallEverywhere(), plugin);
}
public void start() { public void start() {
} }
public static int getVersionCode() { public Object getProperty(String variable) {
return server.getPropertyInt("inner-core-version", 152); return getProperty(variable, (Object) null);
} }
public static String getVersionName() { public Object getProperty(String variable, Object defaultValue) {
return server.getPropertyString("inner-core-version-name", "2.3.1b115 test"); return plugin.getConfig().exists(variable) ? plugin.getConfig().get(variable) : defaultValue;
}
public String getPropertyString(String key) {
return getPropertyString(key, (String) null);
}
public String getPropertyString(String key, String defaultValue) {
return plugin.getConfig().exists(key) ? String.valueOf(plugin.getConfig().get(key)) : defaultValue;
}
public int getPropertyInt(String variable) {
return getPropertyInt(variable, (Integer) null);
}
public int getPropertyInt(String variable, Integer defaultValue) {
return plugin.getConfig().exists(variable) ? (!plugin.getConfig().get(variable).equals("")
? Integer.parseInt(String.valueOf(plugin.getConfig().get(variable)))
: defaultValue) : defaultValue;
}
public boolean getPropertyBoolean(String variable) {
return getPropertyBoolean(variable, (Object) null);
}
public boolean getPropertyBoolean(String variable, Object defaultValue) {
Object value = plugin.getConfig().exists(variable) ? plugin.getConfig().get(variable) : defaultValue;
if (value instanceof Boolean) {
return (Boolean) value;
} else {
return switch (String.valueOf(value)) {
case "on", "true", "1", "yes" -> true;
default -> false;
};
}
}
public static boolean isLegacyWorkbench() {
return singleton.getPropertyBoolean("use-legacy-workbench-override", true);
}
public static boolean isUnsafeScriptingAllowed() {
return singleton.getPropertyBoolean("allow-unsafe-scripting", true);
}
public static boolean isDeveloperMode() {
return singleton.getPropertyBoolean("developer-mode", false);
}
public static MethodHandling getUnsupportedMethodHandling() {
try {
return MethodHandling
.valueOf(singleton.getPropertyString("unsupported-method-handling", "debug").toUpperCase());
} catch (IllegalArgumentException exc) {
return MethodHandling.DEBUG;
}
} }
public static String getName() { public static String getName() {
return server.getPropertyString("inner-core-pack-name", "Inner Core Test"); return singleton.getPropertyString("pack", "Inner Core Test");
}
public static String getVersionName() {
return singleton.getPropertyString("pack-version", "2.3.1b115 test");
}
public static int getVersionCode() {
return singleton.getPropertyInt("pack-version-code", 152);
}
private static void handleUnsupportedMethod(String message) {
MethodHandling handling = getUnsupportedMethodHandling();
if (handling != MethodHandling.NONE) {
switch (handling) {
case DEBUG -> Logger.message(message);
case WARNING -> Logger.warning(message);
case RAISE -> throw new RuntimeException(message);
default -> throw new UnsupportedOperationException();
}
}
} }
public static void useNotSupport(String name) { public static void useNotSupport(String name) {
if (!isDevelopMode()) { handleUnsupportedMethod("Usage of unavailable multiplayer method " + name);
return;
}
String message = "Use not support multiplayer method " + name;
if (isRuntimeException()) {
throw new RuntimeException(message);
} else {
Logger.warning(message);
}
} }
public static void useClientMethod(String name) { public static void useClientMethod(String name) {
if (!isDevelopMode()) { handleUnsupportedMethod("Usage of client method " + name);
return;
}
String message = "Use client method " + name;
if (isRuntimeException()) {
throw new RuntimeException(message);
} else {
Logger.warning(message);
}
} }
public static void useNotCurrentSupport(String name) { public static void useNotCurrentSupport(String name) {
if (!isDevelopMode()) { handleUnsupportedMethod("Usage of method " + name + " currently is not supported");
return;
}
String message = "The " + name + " method is currently not supported";
if (isRuntimeException()) {
throw new RuntimeException(message);
} else {
Logger.warning(message);
}
} }
public static void useIncomprehensibleMethod(String name) { public static void useIncomprehensibleMethod(String name) {
if (!isDevelopMode()) { handleUnsupportedMethod("I don't really understand what this method does (" + name
return; + "), which is why you're reading this right now");
}
String message = "I don't really understand what this method does (" + name
+ "), which is why you're reading this right now";
if (isRuntimeException()) {
throw new RuntimeException(message);
} else {
Logger.warning(message);
}
} }
} }
-7
View File
@@ -1,7 +0,0 @@
package com.reider745;
public interface Logger {
void debug(String str);
void info(String str);
void error(String str, Exception e);
}
+24 -33
View File
@@ -2,6 +2,7 @@ package com.reider745;
import cn.nukkit.Server; import cn.nukkit.Server;
import cn.nukkit.network.Network; import cn.nukkit.network.Network;
import com.reider745.api.hooks.JarEditor; import com.reider745.api.hooks.JarEditor;
import com.reider745.hooks.*; import com.reider745.hooks.*;
import com.reider745.network.InnerCorePacket; import com.reider745.network.InnerCorePacket;
@@ -35,41 +36,31 @@ public class Main {
} }
} }
/* // @Hooks(className = "org.example.Perlin2D")
* @Hooks(class_name = "org.example.Perlin2D") // public static class TestHook {
* public static class TestHook {
* // @Inject
* @Inject(controller = false) // public static float lerp(Object perlin, float a, float b, float t) {
* public static float lerp(Object perlin, float a, float b, float t){ // return a + (b - a) * t;
* return a + (b - a) * t; // /*
*//* // * Arguments arguments = controller.getArguments();
* Arguments arguments = controller.getArguments(); // * float a = arguments.arg("a");
* float a = arguments.arg("a"); // * float b = arguments.arg("b");
* float b = arguments.arg("b"); // * float t = arguments.arg("t");
* float t = arguments.arg("t"); // */
*//* // }
* }
*//* // @Inject(argumentMap = ArgumentTypes.PARAMETERS)
* @Inject(arguments_map = true) // public static float lerp(HookController controller) {
* public static float lerp(HookController controller){ // Arguments arguments = controller.getArguments();
* Arguments arguments = controller.getArguments(); // float a = arguments.arg("a");
* float a = arguments.arg("a"); // float b = arguments.arg("b");
* float b = arguments.arg("b"); // float t = arguments.arg("t");
* float t = arguments.arg("t"); // return a + (b - a) * t;
* return a + (b - a) * t; // }
* } // }
*//*
* }
*/
public static void main(String[] args) throws Throwable { public static void main(String[] args) throws Throwable {
/*
* JarFileLoader loader = new
* JarFileLoader("C:\\vs\\untitled1\\build\\libs\\untitled1-1.0-SNAPSHOT.jar");
* loader.registerHooksForClass(TestHook.class);
* loader.run("org.example.Main", args);
*/
JarEditor loader = new JarEditor(); JarEditor loader = new JarEditor();
loader.registerHooksInitializationForClass(NetworkHooks.class); loader.registerHooksInitializationForClass(NetworkHooks.class);
@@ -1,11 +1,11 @@
package com.reider745.commands; package com.reider745.commands;
import cn.nukkit.Server;
import cn.nukkit.command.SimpleCommandMap; import cn.nukkit.command.SimpleCommandMap;
import com.reider745.InnerCoreServer;
public class CommandsHelper { public class CommandsHelper {
public static void init(){ public static void init(){
final SimpleCommandMap map = InnerCoreServer.server.getCommandMap(); final SimpleCommandMap map = Server.getInstance().getCommandMap();
final String fallbackPrefix = "inner_core"; final String fallbackPrefix = "inner_core";
map.register(fallbackPrefix, new ModsListCommand()); map.register(fallbackPrefix, new ModsListCommand());
@@ -1,6 +1,7 @@
package com.reider745.entity; package com.reider745.entity;
import cn.nukkit.Player; import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.entity.BaseEntity; import cn.nukkit.entity.BaseEntity;
import cn.nukkit.entity.Entity; import cn.nukkit.entity.Entity;
import cn.nukkit.entity.EntityHuman; import cn.nukkit.entity.EntityHuman;
@@ -18,15 +19,13 @@ import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.NBTIO; import cn.nukkit.nbt.NBTIO;
import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.CompoundTag;
import cn.nukkit.potion.Effect; import cn.nukkit.potion.Effect;
import com.reider745.InnerCoreServer;
import com.reider745.api.ReflectHelper; import com.reider745.api.ReflectHelper;
import com.reider745.hooks.ItemUtils; import com.reider745.hooks.ItemUtils;
import com.reider745.item.CustomProjectileItem;
import com.reider745.world.BlockSourceMethods; import com.reider745.world.BlockSourceMethods;
public class EntityMethod { public class EntityMethod {
public static Entity getEntityToLong(long ent){ public static Entity getEntityToLong(long ent){
for (Level level : InnerCoreServer.server.getLevels().values()) for (Level level : Server.getInstance().getLevels().values())
for (Entity entity : level.getEntities()) for (Entity entity : level.getEntities())
if(entity.getId() == ent) if(entity.getId() == ent)
return entity; return entity;
@@ -34,7 +33,7 @@ public class EntityMethod {
} }
public static Player getPlayerToLong(long ent){ public static Player getPlayerToLong(long ent){
for (Level level : InnerCoreServer.server.getLevels().values()) for (Level level : Server.getInstance().getLevels().values())
for (Player entity : level.getPlayers().values()) for (Player entity : level.getPlayers().values())
if(entity.getId() == ent) if(entity.getId() == ent)
return entity; return entity;
@@ -42,7 +41,7 @@ public class EntityMethod {
} }
public static EntityHuman getEntityHumanToLong(long ent){ public static EntityHuman getEntityHumanToLong(long ent){
for (Level level : InnerCoreServer.server.getLevels().values()) for (Level level : Server.getInstance().getLevels().values())
for (Entity entity : level.getEntities()) for (Entity entity : level.getEntities())
if(entity.getId() == ent && entity instanceof EntityHuman) if(entity.getId() == ent && entity instanceof EntityHuman)
return (EntityHuman) entity; return (EntityHuman) entity;
@@ -123,7 +122,7 @@ public class EntityMethod {
} }
public static boolean isValidEntity(long ent){ public static boolean isValidEntity(long ent){
for (Level level : InnerCoreServer.server.getLevels().values()) for (Level level : Server.getInstance().getLevels().values())
for (Entity entity : level.getEntities()) for (Entity entity : level.getEntities())
if(entity.getId() == ent) if(entity.getId() == ent)
return true; return true;
@@ -224,7 +223,7 @@ public class EntityMethod {
} }
public static void removeEntity(long unwrapEntity) { public static void removeEntity(long unwrapEntity) {
for (Level level : InnerCoreServer.server.getLevels().values()) for (Level level : Server.getInstance().getLevels().values())
for (Entity entity : level.getEntities()) for (Entity entity : level.getEntities())
if(entity.getId() == unwrapEntity) if(entity.getId() == unwrapEntity)
level.removeEntity(entity); level.removeEntity(entity);
@@ -2,20 +2,20 @@ package com.reider745.entity;
import cn.nukkit.Player; import cn.nukkit.Player;
import cn.nukkit.PlayerFood; import cn.nukkit.PlayerFood;
import cn.nukkit.inventory.PlayerInventory; import cn.nukkit.Server;
import cn.nukkit.item.Item; import cn.nukkit.item.Item;
import cn.nukkit.level.Level; import cn.nukkit.level.Level;
import cn.nukkit.math.Vector3; import cn.nukkit.math.Vector3;
import com.reider745.InnerCoreServer;
import com.reider745.hooks.ItemUtils; import com.reider745.hooks.ItemUtils;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.Collection; import java.util.Collection;
public class PlayerActorMethods { public class PlayerActorMethods {
@Nullable @Nullable
public static Player constructNew(long entity){ public static Player constructNew(long entity){
Collection<Player> collection = InnerCoreServer.server.getOnlinePlayers().values(); Collection<Player> collection = Server.getInstance().getOnlinePlayers().values();
for(Player player : collection) for(Player player : collection)
if(player.getId() == entity) if(player.getId() == entity)
return player; return player;
@@ -1,10 +1,131 @@
package com.reider745.event; package com.reider745.event;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.regex.Pattern;
import org.snakeyaml.engine.v2.api.Load;
import org.snakeyaml.engine.v2.api.LoadSettings;
import cn.nukkit.Server;
import cn.nukkit.plugin.Plugin;
import cn.nukkit.plugin.PluginBase; import cn.nukkit.plugin.PluginBase;
import cn.nukkit.plugin.PluginDescription;
import cn.nukkit.plugin.PluginLoader;
import cn.nukkit.utils.Config;
import cn.nukkit.utils.Utils;
public class InnerCorePlugin extends PluginBase implements PluginLoader {
private File configFile;
private Config config;
public class InnerCorePlugin extends PluginBase {
@Override @Override
public String getName() { public Config getConfig() {
return "Inner Core"; if (this.config == null) {
this.reloadConfig();
}
return this.config;
}
protected File getConfigFile() {
if (this.configFile == null) {
if (!isInitialized()) {
throw new UnsupportedOperationException("Plugin should be initialized before getting config file!");
}
this.configFile = new File(getDataFolder(), "zotecore.yml");
}
return this.configFile;
}
@Override
@SuppressWarnings("unchecked")
public void reloadConfig() {
final InputStream configStream = getResource("zotecore.yml");
if (configStream != null) {
final LoadSettings settings = LoadSettings.builder().setParseComments(false).build();
final Load yaml = new Load(settings);
try {
this.config = new Config(getConfigFile(), -1,
(LinkedHashMap<String, Object>) yaml.loadFromString(Utils.readFile(getConfigFile())));
} catch (IOException exc) {
Server.getInstance().getLogger().logException(exc);
}
}
if (this.config == null) {
this.config = new Config(getConfigFile());
}
}
@Override
public void saveDefaultConfig() {
final File configFile = getConfigFile();
if (!configFile.exists()) {
saveResource("zotecore.yml", configFile.getName(), false);
}
}
@Override
public PluginLoader getPluginLoader() {
return this;
}
@Override
public void disablePlugin(Plugin plugin) {
if (plugin.equals(this)) {
setEnabled(false);
return;
}
throw new UnsupportedOperationException();
}
@Override
public void enablePlugin(Plugin plugin) {
if (plugin.equals(this)) {
setEnabled();
return;
}
throw new UnsupportedOperationException();
}
@Override
public PluginDescription getPluginDescription(String name) {
if (getName().equals(name)) {
return getDescription();
}
return null;
}
@Override
public PluginDescription getPluginDescription(File file) {
if (getFile().equals(file)) {
return getDescription();
}
return null;
}
@Override
public Pattern[] getPluginFilters() {
return new Pattern[0];
}
@Override
public Plugin loadPlugin(String name) throws Exception {
if (getName().equals(name)) {
return this;
}
throw new UnsupportedOperationException();
}
@Override
public Plugin loadPlugin(File file) throws Exception {
if (getFile().equals(file)) {
return this;
}
throw new UnsupportedOperationException();
} }
} }
@@ -8,7 +8,6 @@ import cn.nukkit.item.ItemBlock;
import cn.nukkit.item.ItemID; import cn.nukkit.item.ItemID;
import cn.nukkit.item.RuntimeItems; import cn.nukkit.item.RuntimeItems;
import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.CompoundTag;
import com.reider745.api.ReflectHelper;
import com.reider745.api.hooks.HookClass; import com.reider745.api.hooks.HookClass;
import com.reider745.api.hooks.HookController; import com.reider745.api.hooks.HookController;
import com.reider745.api.hooks.TypeHook; import com.reider745.api.hooks.TypeHook;
@@ -22,11 +21,9 @@ import com.reider745.item.Repairs;
import com.zhekasmirnov.innercore.api.NativeFurnaceRegistry; import com.zhekasmirnov.innercore.api.NativeFurnaceRegistry;
import com.zhekasmirnov.innercore.api.NativeItemInstanceExtra; import com.zhekasmirnov.innercore.api.NativeItemInstanceExtra;
import com.zhekasmirnov.innercore.api.unlimited.IDRegistry; import com.zhekasmirnov.innercore.api.unlimited.IDRegistry;
import it.unimi.dsi.fastutil.objects.ObjectArrayList;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt; import java.util.OptionalInt;
import java.util.function.Supplier; import java.util.function.Supplier;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@@ -37,14 +37,14 @@ public class PlayerHooks implements HookClass {
} }
@Inject(type = TypeHook.AFTER) @Inject(type = TypeHook.AFTER)
public static void completeLoginSequence(Player self) { public static void completeLoginSequence(Player player) {
if (getForPlayer(self) == null) if (getForPlayer(player) == null)
self.kick("Failed to connection Inner Core 1.16.201"); player.kick("Failed to connection Inner Core 1.16.201");
} }
@Inject @Inject
public static void close(Player self, TextContainer message, String reason, boolean notify) { public static void close(Player player, TextContainer message, String reason, boolean notify) {
ConnectedClient client = getForPlayer(self); ConnectedClient client = getForPlayer(player);
try { try {
if (client != null) if (client != null)
client.getChannelInterface().close(); client.getChannelInterface().close();
@@ -5,6 +5,7 @@ import cn.nukkit.utils.Config;
import com.reider745.InnerCoreServer; import com.reider745.InnerCoreServer;
import com.reider745.Main; import com.reider745.Main;
import com.reider745.api.hooks.HookClass; import com.reider745.api.hooks.HookClass;
import com.reider745.api.hooks.TypeHook;
import com.reider745.api.hooks.annotation.Inject; import com.reider745.api.hooks.annotation.Inject;
import com.reider745.api.hooks.annotation.Hooks; import com.reider745.api.hooks.annotation.Hooks;
import com.zhekasmirnov.innercore.api.NativeCallback; import com.zhekasmirnov.innercore.api.NativeCallback;
@@ -60,4 +61,9 @@ public class ServerHooks implements HookClass {
public static void forceShutdown(Server server, String reason) throws Exception { public static void forceShutdown(Server server, String reason) throws Exception {
Main.LoadingStages.stop(server); Main.LoadingStages.stop(server);
} }
@Inject(type = TypeHook.AFTER)
public static void reload(Server server) {
InnerCoreServer.singleton.reload();
}
} }
@@ -1,29 +1,24 @@
package com.reider745.world; package com.reider745.world;
import cn.nukkit.Player; import cn.nukkit.Player;
import cn.nukkit.Server;
import cn.nukkit.block.Block; import cn.nukkit.block.Block;
import cn.nukkit.blockentity.BlockEntity; import cn.nukkit.blockentity.BlockEntity;
import cn.nukkit.entity.Entity; import cn.nukkit.entity.Entity;
import cn.nukkit.entity.item.EntityItem; import cn.nukkit.entity.item.EntityItem;
import cn.nukkit.entity.item.EntityXPOrb;
import cn.nukkit.event.entity.EntityExplosionPrimeEvent;
import cn.nukkit.event.entity.ExplosionPrimeEvent; import cn.nukkit.event.entity.ExplosionPrimeEvent;
import cn.nukkit.item.Item; import cn.nukkit.item.Item;
import cn.nukkit.level.Explosion; import cn.nukkit.level.Explosion;
import cn.nukkit.level.Level; import cn.nukkit.level.Level;
import cn.nukkit.level.Position; import cn.nukkit.level.Position;
import cn.nukkit.level.biome.Biome;
import cn.nukkit.level.format.anvil.palette.BiomePalette;
import cn.nukkit.level.particle.DestroyBlockParticle; import cn.nukkit.level.particle.DestroyBlockParticle;
import cn.nukkit.math.BlockVector3; import cn.nukkit.math.BlockVector3;
import cn.nukkit.math.Vector3; import cn.nukkit.math.Vector3;
import cn.nukkit.nbt.tag.CompoundTag; import cn.nukkit.nbt.tag.CompoundTag;
import com.reider745.InnerCoreServer;
import com.reider745.hooks.GlobalBlockPalette; import com.reider745.hooks.GlobalBlockPalette;
import com.reider745.hooks.ItemUtils; import com.reider745.hooks.ItemUtils;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Map; import java.util.Map;
public class BlockSourceMethods { public class BlockSourceMethods {
@@ -42,14 +37,14 @@ public class BlockSourceMethods {
public static Level getLevelForDimension(int dimension) { public static Level getLevelForDimension(int dimension) {
if (dimension >= 0 && dimension <= 2) { if (dimension >= 0 && dimension <= 2) {
return InnerCoreServer.server.getLevelByName(switch (dimension) { return Server.getInstance().getLevelByName(switch (dimension) {
case 0 -> "world"; case 0 -> "world";
case 1 -> "nether"; case 1 -> "nether";
case 2 -> "the_end"; case 2 -> "the_end";
default -> throw new UnsupportedOperationException(); default -> throw new UnsupportedOperationException();
}); });
} }
return InnerCoreServer.server.getLevel(dimension); return Server.getInstance().getLevel(dimension);
} }
public static void destroyBlock(Level pointer, int x, int y, int z, boolean drop, int updateType, public static void destroyBlock(Level pointer, int x, int y, int z, boolean drop, int updateType,
@@ -141,7 +136,6 @@ public class BlockSourceMethods {
public static void setBlockByRuntimeId(Level pointer, int x, int y, int z, int runtimeId, boolean allowUpdate, public static void setBlockByRuntimeId(Level pointer, int x, int y, int z, int runtimeId, boolean allowUpdate,
int updateType) { int updateType) {
Block block = pointer.getBlock(x, y, z);
int legacyId = GlobalBlockPalette.getLegacyFullId(runtimeId); int legacyId = GlobalBlockPalette.getLegacyFullId(runtimeId);
setBlock(pointer, x, y, z, legacyId >> 6, legacyId & 0x3F, allowUpdate, updateType); setBlock(pointer, x, y, z, legacyId >> 6, legacyId & 0x3F, allowUpdate, updateType);
} }
@@ -183,9 +177,8 @@ public class BlockSourceMethods {
} }
public static void explode(Level pointer, float x, float y, float z, float power, boolean fire) { public static void explode(Level pointer, float x, float y, float z, float power, boolean fire) {
ExplosionPrimeEvent event = new ExplosionPrimeEvent(null, power); ExplosionPrimeEvent event = new ExplosionPrimeEvent(null, power);
InnerCoreServer.server.getPluginManager().callEvent(event); Server.getInstance().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
return; return;
} }
@@ -1,12 +1,13 @@
package com.reider745.world; package com.reider745.world;
import cn.nukkit.Server;
import cn.nukkit.level.Level; import cn.nukkit.level.Level;
import com.reider745.InnerCoreServer; import com.reider745.InnerCoreServer;
public class WorldMethod { public class WorldMethod {
private static Level getLevel(){ private static Level getLevel(){
return InnerCoreServer.server.getDefaultLevel(); return Server.getInstance().getDefaultLevel();
} }
public static long getTime() { public static long getTime() {
@@ -23,7 +24,7 @@ public class WorldMethod {
} }
public static int getGameMode() { public static int getGameMode() {
return InnerCoreServer.server.getGamemode(); return Server.getInstance().getGamemode();
} }
public static void setGameMode(int mode) { public static void setGameMode(int mode) {
@@ -31,11 +32,11 @@ public class WorldMethod {
} }
public static int getDifficulty() { public static int getDifficulty() {
return InnerCoreServer.server.getDifficulty(); return Server.getInstance().getDifficulty();
} }
public static void setDifficulty(int difficulty) { public static void setDifficulty(int difficulty) {
InnerCoreServer.server.setDifficulty(difficulty); Server.getInstance().setDifficulty(difficulty);
} }
public static double getRainLevel() { public static double getRainLevel() {
@@ -25,6 +25,6 @@ public class Apparatus {
} }
public static boolean isDevelop() { public static boolean isDevelop() {
return InnerCoreServer.isDevelopMode(); return InnerCoreServer.isDeveloperMode();
} }
} }
@@ -1,14 +1,12 @@
package com.zhekasmirnov.apparatus.mcpe; package com.zhekasmirnov.apparatus.mcpe;
import cn.nukkit.Server;
import cn.nukkit.entity.Entity; import cn.nukkit.entity.Entity;
import cn.nukkit.level.Level; import cn.nukkit.level.Level;
import com.reider745.InnerCoreServer;
import com.zhekasmirnov.apparatus.Apparatus;
import com.zhekasmirnov.innercore.api.mod.adaptedscript.AdaptedScriptAPI;
public class NativeStaticUtils { public class NativeStaticUtils {
public static boolean isExistingEntity(long entityUid){ public static boolean isExistingEntity(long entityUid){
for (Level level : InnerCoreServer.server.getLevels().values()) for (Level level : Server.getInstance().getLevels().values())
for (Entity entity : level.getEntities()) for (Entity entity : level.getEntities())
if (entity.getId() == entityUid) if (entity.getId() == entityUid)
return true; return true;
@@ -6,104 +6,102 @@ import java.io.StringWriter;
import cn.nukkit.Server; import cn.nukkit.Server;
import org.mozilla.javascript.RhinoException; import org.mozilla.javascript.RhinoException;
public class Logger { public class Logger {
public static Server server;
public static void message(String message) { public static void message(String message) {
server.getLogger().debug(message); Server.getInstance().getLogger().debug(message);
} }
public static void message(String tag, String message) { public static void message(String tag, String message) {
server.getLogger().debug("[" + tag + "] " + message); Server.getInstance().getLogger().debug("[" + tag + "] " + message);
} }
public static void message(String message, Throwable exc) { public static void message(String message, Throwable exc) {
server.getLogger().debug(message + ": ", exc); Server.getInstance().getLogger().debug(message + ": ", exc);
} }
public static void message(String tag, String message, Throwable exc) { public static void message(String tag, String message, Throwable exc) {
server.getLogger().debug("[" + tag + "] " + message, exc); Server.getInstance().getLogger().debug("[" + tag + "] " + message, exc);
} }
public static void debug(String message) { public static void debug(String message) {
server.getLogger().info(message); Server.getInstance().getLogger().info(message);
} }
public static void debug(String tag, String message) { public static void debug(String tag, String message) {
server.getLogger().info("[" + tag + "] " + message); Server.getInstance().getLogger().info("[" + tag + "] " + message);
} }
public static void debug(String message, Throwable exc) { public static void debug(String message, Throwable exc) {
server.getLogger().info(message + ": ", exc); Server.getInstance().getLogger().info(message + ": ", exc);
} }
public static void debug(String tag, String message, Throwable exc) { public static void debug(String tag, String message, Throwable exc) {
server.getLogger().info("[" + tag + "] " + message, exc); Server.getInstance().getLogger().info("[" + tag + "] " + message, exc);
} }
public static void error(String message) { public static void error(String message) {
server.getLogger().error(message); Server.getInstance().getLogger().error(message);
} }
public static void error(String tag, String message) { public static void error(String tag, String message) {
server.getLogger().error("[" + tag + "] " + message); Server.getInstance().getLogger().error("[" + tag + "] " + message);
} }
public static void error(String message, Throwable exc) { public static void error(String message, Throwable exc) {
server.getLogger().error(message + ": ", exc); Server.getInstance().getLogger().error(message + ": ", exc);
} }
public static void error(String tag, String message, Throwable exc) { public static void error(String tag, String message, Throwable exc) {
server.getLogger().error("[" + tag + "] " + message, exc); Server.getInstance().getLogger().error("[" + tag + "] " + message, exc);
} }
public static void info(String message) { public static void info(String message) {
server.getLogger().info(message); Server.getInstance().getLogger().info(message);
} }
public static void info(String tag, String message) { public static void info(String tag, String message) {
server.getLogger().info("[" + tag + "] " + message); Server.getInstance().getLogger().info("[" + tag + "] " + message);
} }
public static void info(String message, Throwable exc) { public static void info(String message, Throwable exc) {
server.getLogger().info(message + ": ", exc); Server.getInstance().getLogger().info(message + ": ", exc);
} }
public static void info(String tag, String message, Throwable exc) { public static void info(String tag, String message, Throwable exc) {
server.getLogger().info("[" + tag + "] " + message, exc); Server.getInstance().getLogger().info("[" + tag + "] " + message, exc);
} }
public static void warning(String message) { public static void warning(String message) {
server.getLogger().warning(message); Server.getInstance().getLogger().warning(message);
} }
public static void warning(String tag, String message) { public static void warning(String tag, String message) {
server.getLogger().warning("[" + tag + "] " + message); Server.getInstance().getLogger().warning("[" + tag + "] " + message);
} }
public static void warning(String message, Throwable exc) { public static void warning(String message, Throwable exc) {
server.getLogger().warning(message + ": ", exc); Server.getInstance().getLogger().warning(message + ": ", exc);
} }
public static void warning(String tag, String message, Throwable exc) { public static void warning(String tag, String message, Throwable exc) {
server.getLogger().warning("[" + tag + "] " + message, exc); Server.getInstance().getLogger().warning("[" + tag + "] " + message, exc);
} }
public static void critical(String message) { public static void critical(String message) {
server.getLogger().critical(message); Server.getInstance().getLogger().critical(message);
} }
public static void critical(String tag, String message) { public static void critical(String tag, String message) {
server.getLogger().warning("[" + tag + "] " + message); Server.getInstance().getLogger().warning("[" + tag + "] " + message);
} }
public static void critical(String message, Throwable exc) { public static void critical(String message, Throwable exc) {
server.getLogger().critical(message + ": ", exc); Server.getInstance().getLogger().critical(message + ": ", exc);
} }
public static void critical(String tag, String message, Throwable exc) { public static void critical(String tag, String message, Throwable exc) {
server.getLogger().critical("[" + tag + "] " + message, exc); Server.getInstance().getLogger().critical("[" + tag + "] " + message, exc);
} }
public static String getStackTrace(Throwable err) { public static String getStackTrace(Throwable err) {
@@ -24,7 +24,7 @@ public class NativeAPI {
} }
public static String executeCommand(String command, int x, int y, int z, long blockSource) { public static String executeCommand(String command, int x, int y, int z, long blockSource) {
if (InnerCoreServer.server.getCommandMap().dispatch(InnerCoreServer.server.getConsoleSender(), command)) { if (Server.getInstance().getCommandMap().dispatch(Server.getInstance().getConsoleSender(), command)) {
return "TODO"; return "TODO";
} }
return null; return null;
@@ -1,6 +1,7 @@
package com.zhekasmirnov.innercore.api; package com.zhekasmirnov.innercore.api;
import android.util.Pair; import android.util.Pair;
import cn.nukkit.Server;
import cn.nukkit.level.Level; import cn.nukkit.level.Level;
import com.reider745.InnerCoreServer; import com.reider745.InnerCoreServer;
@@ -74,7 +75,7 @@ public class NativeCallback {
} }
public static void onCopyrightCheck() { public static void onCopyrightCheck() {
InnerCoreServer.server.getLogger() Server.getInstance().getLogger()
.info("Inner Core is developed fully and only by zheka_smirnov (zheka2304), all rights are reserved."); .info("Inner Core is developed fully and only by zheka_smirnov (zheka2304), all rights are reserved.");
} }
@@ -179,7 +179,7 @@ public class Executable implements Runnable {
scriptScope.put("__modpack__", scriptScope, scriptScope.put("__modpack__", scriptScope,
Context.javaToJS(ModPackContext.getInstance().assureJsAdapter(), scriptScope)); Context.javaToJS(ModPackContext.getInstance().assureJsAdapter(), scriptScope));
if (!InnerCoreServer.canEvalEnable()) { if (!InnerCoreServer.isUnsafeScriptingAllowed()) {
scriptScope.put("eval", scriptScope, new ScriptableFunctionImpl() { scriptScope.put("eval", scriptScope, new ScriptableFunctionImpl() {
@Override @Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
@@ -32,7 +32,7 @@ public class FileTools {
// } // }
public static void init() { public static void init() {
DIR_ROOT = DIR_HORIZON = DIR_PACK = DIR_MINECRAFT = InnerCoreServer.PATH + "/"; DIR_ROOT = DIR_HORIZON = DIR_PACK = DIR_MINECRAFT = InnerCoreServer.dataPath + "/";
DIR_WORK = DIR_ROOT + "innercore/"; DIR_WORK = DIR_ROOT + "innercore/";
checkdirs(); checkdirs();
} }
+26
View File
@@ -0,0 +1,26 @@
# Change resolution of pack that client should have to log into server.
# However, no deprecated or unimplemented methods will be added.
pack: Inner Core Test
pack-version: 2.3.0b115 test
pack-version-code: 152
# Use vanilla crafting table interface, instead of custom one.
# Attention: currently not supported and custom recipes will not be dislayed.
# use-legacy-workbench-override: off
# Disabling inventory fix for connected clients, outdated versions do not
# work properly with it, not allowing moving items around inventory.
# use-legacy-inventory: off
# Switches the debugging mode for unsupported methods (e.g., client-side).
# Might be one of: none, debug (default), warning, raise.
# unsupported-method-handling: raise
# Can mods use unsafe features (e.g., calling eval) or not.
# Attention: can create a security risk, however, for example,
# using requireGlobal can often disrupt operation of mods.
# allow-unsafe-scripting: off
# Developer mode allows you to receive additional information
# about engine operation, as well as profiling of methods.
# developer-mode: on