package dev.l2essence.gameserver;
import dev.l2essence.Config;
import dev.l2essence.commons.concurrent.ThreadPool;
import dev.l2essence.commons.database.DatabaseFactory;
import dev.l2essence.commons.enums.ServerMode;
import dev.l2essence.commons.util.DeadLockDetector;
import dev.l2essence.gameserver.cache.HtmCache;
import dev.l2essence.gameserver.data.EventDroplist;
import dev.l2essence.gameserver.data.ItemTable;
import dev.l2essence.gameserver.data.SchemeBufferTable;
import dev.l2essence.gameserver.data.sql.*;
import dev.l2essence.gameserver.data.xml.*;
import dev.l2essence.gameserver.discord.DiscordBotManager;
import dev.l2essence.gameserver.discord.webhook.DiscordWebhookManager;
import dev.l2essence.gameserver.geoengine.GeoEngine;
import dev.l2essence.gameserver.handler.ConditionHandler;
import dev.l2essence.gameserver.handler.DailyMissionHandler;
import dev.l2essence.gameserver.handler.EffectHandler;
import dev.l2essence.gameserver.handler.SkillConditionHandler;
import dev.l2essence.gameserver.instancemanager.*;
import dev.l2essence.gameserver.instancemanager.events.GoldFestival.GoldFestivalEvent;
import dev.l2essence.gameserver.instancemanager.games.MonsterRace;
import dev.l2essence.gameserver.model.World;
import dev.l2essence.gameserver.model.events.EventDispatcher;
import dev.l2essence.gameserver.model.olympiad.Hero;
import dev.l2essence.gameserver.model.olympiad.Olympiad;
import dev.l2essence.gameserver.model.votereward.VoteSystem;
import dev.l2essence.gameserver.network.ClientPacketHandler;
import dev.l2essence.gameserver.network.GameClient;
import dev.l2essence.gameserver.network.loginserver.LoginServerNetworkManager;
import dev.l2essence.gameserver.scripting.ScriptEngineManager;
import dev.l2essence.gameserver.taskmanager.*;
import dev.l2essence.gameserver.telegram.TelegramBotApi;
import dev.l2essence.gameserver.util.Broadcast;
import io.github.joealisson.mmocore.ConnectionBuilder;
import io.github.joealisson.mmocore.ConnectionHandler;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.InetSocketAddress;
import java.time.Duration;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class GameServer {
public static final Calendar dateTimeServerStarted = Calendar.getInstance();
private static final Logger LOGGER = Logger.getLogger(GameServer.class.getName());
private static GameServer INSTANCE;
private final DeadLockDetector _deadDetectThread;
private final ConnectionHandler<GameClient> connectionHandler;
public GameServer() throws Exception {
final long serverLoadStart = System.currentTimeMillis();
// GUI
if (!GraphicsEnvironment.isHeadless()) {
// System.out.println("GameServer: Running in GUI mode.");
// new Gui();
}
// Create log folder
final File logFolder = new File(".", "log");
logFolder.mkdir();
// Create input stream for log file -- or store file data into memory
try (InputStream is = new FileInputStream(new File("./log.cfg"))) {
LogManager.getLogManager().readConfiguration(is);
}
// Initialize config
Config.load(ServerMode.GAME);
printSection("Database");
DatabaseFactory.init();
printSection("ThreadPool");
ThreadPool.init();
printSection("IdManager");
IdManager.getInstance();
if (!IdManager.hasInitialized()) {
LOGGER.severe(getClass().getSimpleName() + ": Could not read object IDs from database. Please check your configuration.");
throw new Exception("Could not initialize the ID factory!");
}
// load script engines
printSection("Scripting Engine");
EventDispatcher.getInstance();
ScriptEngineManager.getInstance();
printSection("World");
// start game time control early
GameTimeController.init();
World.getInstance();
MapRegionManager.getInstance();
ZoneManager.getInstance();
DoorData.getInstance();
FenceData.getInstance();
AnnouncementsTable.getInstance();
GlobalVariables.getInstance();
printSection("Data");
ActionData.getInstance();
CategoryData.getInstance();
SecondaryAuthData.getInstance();
CombinationItemsData.getInstance();
SayuneData.getInstance();
DailyMissionHandler.getInstance().executeScript();
DailyMissionData.getInstance();
ElementalSpiritData.getInstance();
TranscendentInstanceData.getInstance();
printSection("Skills");
SkillConditionHandler.getInstance().executeScript();
EffectHandler.getInstance().executeScript();
EnchantSkillGroupsData.getInstance();
SkillTreeData.getInstance();
SkillData.getInstance();
PetSkillData.getInstance();
printSection("Items");
ConditionHandler.getInstance().executeScript();
ItemTable.getInstance();
EnchantItemGroupsData.getInstance();
EnchantItemData.getInstance();
EnchantItemOptionsData.getInstance();
EnchantChallengePointsData.getInstance();
ItemCrystallizationData.getInstance();
OptionData.getInstance();
VariationData.getInstance();
EnsoulData.getInstance();
EnchantItemHPBonusData.getInstance();
BuyListData.getInstance();
MultisellData.getInstance();
EquipmentUpgradeNormalData.getInstance();
RecipeData.getInstance();
ArmorSetData.getInstance();
FishingData.getInstance();
HennaData.getInstance();
DyePotentialData.getInstance();
PrimeShopData.getInstance();
LCoinShopData.getInstance();
PcCafePointsManager.getInstance();
AppearanceItemData.getInstance();
CommissionManager.getInstance();
LuckyGameData.getInstance();
AttendanceRewardData.getInstance();
ClientWeaponTypesData.getInstance();
BlessItemData.getInstance();
CollectionData.getInstance();
ItemDeletionData.getInstance();
RaidDropAnnounceData.getInstance();
NicknameItemData.getInstance();
printSection("Characters");
ClassListData.getInstance();
InitialEquipmentData.getInstance();
InitialShortcutData.getInstance();
ExperienceData.getInstance();
PlayerXpPercentLostData.getInstance();
KarmaData.getInstance();
HitConditionBonusData.getInstance();
PlayerTemplateData.getInstance();
CharNameTable.getInstance();
AdminData.getInstance();
PetDataTable.getInstance();
PetExtractData.getInstance();
CubicData.getInstance();
CharSummonTable.getInstance().init();
BeautyShopData.getInstance();
MentorManager.getInstance();
ResurrectionFeesData.getInstance();
if (Config.PREMIUM_SYSTEM_ENABLED) {
LOGGER.info("PremiumManager: Premium system is enabled.");
PremiumManager.getInstance();
}
RandomCraftPremiumManager.getInstance();
printSection("Clans");
ClanTable.getInstance();
ResidenceFunctionsData.getInstance();
ClanHallData.getInstance();
ClanHallAuctionManager.getInstance();
ClanEntryManager.getInstance();
ClanExperienceData.getInstance();
printSection("Geodata");
GeoEngine.getInstance();
printSection("NPCs");
NpcData.getInstance();
SpawnData.getInstance();
StaticObjectData.getInstance();
ItemAuctionManager.getInstance();
CastleManager.getInstance().loadInstances();
SchemeBufferTable.getInstance();
GrandBossManager.getInstance();
RaidTeleportData.getInstance();
RaidSpawnData.getInstance();
RaidSpawnManager.getInstance();
EventDroplist.getInstance();
printSection("Instance");
InstanceManager.getInstance();
printSection("Olympiad");
Olympiad.getInstance();
Hero.getInstance();
// Call to load caches
printSection("Cache");
HtmCache.getInstance();
CrestTable.getInstance();
TeleportListData.getInstance();
TeleporterData.getInstance();
MatchingRoomManager.getInstance();
PetitionManager.getInstance();
CursedWeaponsManager.getInstance();
TransformData.getInstance();
RankManager.getInstance();
PurgeData.getInstance();
if (Config.SELLBUFF_ENABLED) {
SellBuffsManager.getInstance();
}
printSection("Scripts");
QuestManager.getInstance();
BoatManager.getInstance();
AirShipManager.getInstance();
ShuttleData.getInstance();
try {
LOGGER.info(getClass().getSimpleName() + ": Loading server scripts:");
ScriptEngineManager.getInstance().executeScript(ScriptEngineManager.MASTER_HANDLER_FILE);
ScriptEngineManager.getInstance().executeScriptList();
} catch (Exception e) {
LOGGER.log(Level.WARNING, getClass().getSimpleName() + ": Failed to execute script list!", e);
}
SpawnData.getInstance().init();
DBSpawnManager.getInstance();
printSection("Event Engine");
EventEngineData.getInstance();
LetterCollectorData.getInstance();
GoldFestivalEvent.getInstance();
MableGameEventData.getInstance();
VoteSystem.initialize();
printSection("Siege");
SiegeManager.getInstance().getSieges();
CastleManager.getInstance().activateInstances();
FortManager.getInstance().loadInstances();
FortManager.getInstance().activateInstances();
FortSiegeManager.getInstance();
SiegeScheduleData.getInstance();
CastleManorManager.getInstance();
SiegeGuardManager.getInstance();
QuestManager.getInstance().report();
if (Config.SAVE_DROPPED_ITEM) {
ItemsOnGroundManager.getInstance();
}
if ((Config.AUTODESTROY_ITEM_AFTER > 0) || (Config.HERB_AUTO_DESTROY_TIME > 0)) {
ItemsAutoDestroy.getInstance();
}
MonsterRace.getInstance();
TaskManager.getInstance();
AntiFeedManager.getInstance().registerEvent(AntiFeedManager.GAME_ID);
if (Config.ALLOW_MAIL) {
MailManager.getInstance();
}
if (Config.CUSTOM_MAIL_MANAGER_ENABLED) {
CustomMailManager.getInstance();
}
PunishmentManager.getInstance();
Runtime.getRuntime().addShutdownHook(Shutdown.getInstance());
LOGGER.info("IdManager: Free ObjectID's remaining: " + IdManager.size());
if ((Config.OFFLINE_TRADE_ENABLE || Config.OFFLINE_CRAFT_ENABLE) && Config.RESTORE_OFFLINERS) {
OfflineTraderTable.getInstance().restoreOfflineTraders();
}
if (Config.SERVER_RESTART_SCHEDULE_ENABLED) {
ServerRestartManager.getInstance();
}
if (Config.PRECAUTIONARY_RESTART_ENABLED) {
PrecautionaryRestartManager.getInstance();
}
if (Config.DEADLOCK_DETECTOR) {
_deadDetectThread = new DeadLockDetector(Duration.ofSeconds(Config.DEADLOCK_CHECK_INTERVAL), () ->
{
if (Config.RESTART_ON_DEADLOCK) {
Broadcast.toAllOnlinePlayers("Server has stability issues - restarting now.");
Shutdown.getInstance().startShutdown(null, 60, true);
}
});
_deadDetectThread.setDaemon(true);
_deadDetectThread.start();
} else {
_deadDetectThread = null;
}
SpecialHuntingZoneData.getInstance();
RandomCraftData.getInstance();
RandomCraftExtractionData.getInstance();
VengeanceManager.getInstance();
L2PassData.getInstance();
MissionLevelData.getInstance();
PrivateStoreHistoryManager.getInstance().restore();
SteadyBoxTaskManager.getInstance();
DelayedItemsManager.getInstance();
DeathDisconnectionManager.getInstance();
PromoCodeManager.getInstance();
AdditionalSaveTaskManager.getInstance();
printSection("Fake Players");
FakePlayerHennaData.getInstance();
FakePlayerItemData.getInstance();
FakePlayerSkillData.getInstance();
FakePlayerNameData.getInstance();
FakePlayerShopNameData.getInstance();
FakePlayerTownData.getInstance();
FakePlayerZoneData.getInstance();
FakePlayerManager.getInstance();
if (Config.DISCORD_ENABLED) {
DiscordBotManager.getInstance();
DiscordWebhookManager.getInstance();
}
if (Config.TELEGRAM_ENABLED) {
TelegramBotApi.getInstance();
}
UniqueOnlineManager.getInstance();
System.gc();
final long totalMem = Runtime.getRuntime().maxMemory() / 1048576;
LOGGER.info(getClass().getSimpleName() + ": Started, using " + getUsedMemoryMB() + " of " + totalMem + " MB total memory.");
LOGGER.info(getClass().getSimpleName() + ": Maximum number of connected players is " + Config.MAXIMUM_ONLINE_USERS + ".");
LOGGER.info(getClass().getSimpleName() + ": Server loaded in " + ((System.currentTimeMillis() - serverLoadStart) / 1000) + " seconds.");
System.setProperty("async-mmocore.configurationFile", "config/async-mmocore.ini");
connectionHandler =
ConnectionBuilder.create(new InetSocketAddress(Config.PORT_GAME), GameClient::new, new ClientPacketHandler(), ThreadPool::execute).disableAutoReading(!Config.ASYNC_MMOCORE_AUTO_READ).fairnessBuckets(Config.ASYNC_MMOCORE_FAIRNESS_BUCKETS).dropPacketThreshold(Config.ASYNC_MMOCORE_DROP_PACKET_THRESHOLD).build();
connectionHandler.start();
if (Boolean.getBoolean("newLoginServer")) {
LoginServerNetworkManager.getInstance().connect();
} else {
LoginServerThread.getInstance().start();
}
QueueManager.getInstance();
Toolkit.getDefaultToolkit().beep();
}
public static void main(String[] args) throws Exception {
INSTANCE = new GameServer();
}
public static GameServer getInstance() {
return INSTANCE;
}
public long getUsedMemoryMB() {
return (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1048576;
}
public DeadLockDetector getDeadLockDetectorThread() {
return _deadDetectThread;
}
public ConnectionHandler<GameClient> getConnectionHandler() {
return connectionHandler;
}
public long getStartedTime() {
return ManagementFactory.getRuntimeMXBean().getStartTime();
}
public String getUptime() {
final long uptime = ManagementFactory.getRuntimeMXBean().getUptime() / 1000;
final long hours = uptime / 3600;
final long mins = (uptime - (hours * 3600)) / 60;
final long secs = ((uptime - (hours * 3600)) - (mins * 60));
if (hours > 0) {
return hours + "hrs " + mins + "mins " + secs + "secs";
}
return mins + "mins " + secs + "secs";
}
private void printSection(String section) {
String s = "=[ " + section + " ]";
while (s.length() < 61) {
s = "-" + s;
}
LOGGER.info(s);
}
}