bool ZMatrixCalculator::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin ZMatrixCalculator member initialisation mAtom1Edit = NULL; mAtom2Edit = NULL; mAtom3Edit = NULL; mAtom4Edit = NULL; mBondLength = NULL; mBondAngle = NULL; mDihedralAngle = NULL; ////@end ZMatrixCalculator member initialisation ////@begin ZMatrixCalculator creation SetExtraStyle(GetExtraStyle()|wxWS_EX_BLOCK_EVENTS); wxDialog::Create( parent, id, caption, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end ZMatrixCalculator creation UpdateWindowTitle(); return true; }
CustomWindow::CustomWindow(QWidget *parent) : QWidget(parent), m_MainLayout(this), m_TitleBar (this), m_SizeGrip (this), m_Cache (NULL) { connect(this , SIGNAL(WindowTitleChanged()), &m_TitleBar, SLOT (UpdateWindowTitle ())); resize(512, 512); setWindowTitle(tr("Tutorial Qt: CustomWindow")); setWindowFlags(Qt::FramelessWindowHint); setAttribute(Qt::WA_TranslucentBackground); m_SizeGrip.setStyleSheet("image: none"); m_MainLayout.setMargin (0); // No space between window's element and the window's border m_MainLayout.setSpacing(0); // No space between window's element setLayout(&m_MainLayout); m_MainLayout.addWidget(&m_TitleBar, 0, 0, 1, 1); m_MainLayout.setRowStretch(1, 1); // Put the title bar at the top of the window }
/** * Updates the current {@link CScene} title * @param title new title for the {@link CScene} */ void CFortEdit::UpdateSceneTitle(const QString& title) { if (DScene) { DScene->SetTitle(title); UpdateWindowTitle(); } }
void CMSourceDirector::DisplayFile ( const JCharacter* fileName, const JIndex lineNumber, const JBoolean markLine ) { assert( !JStringEmpty(fileName) ); if (!itsCurrentFile.IsEmpty() && JSameDirEntry(fileName, itsCurrentFile)) { DisplayLine(lineNumber, markLine); UpdateWindowTitle(NULL); } else if (JFileReadable(fileName)) { itsCurrentFile = fileName; JTextEditor::PlainTextFormat format; itsText->ReadPlainText(itsCurrentFile, &format); // Assembly must not end with newline, so we have to enforce this for // source code, too. const JString& text = itsText->GetText(); JIndex i = text.GetLength(); while (text.GetCharacter(i) == '\n') { i--; } if (i < text.GetLength()) { itsText->SetSelection(i+1, text.GetLength()); itsText->DeleteSelection(); } itsText->SetCaretLocation(1); DisplayLine(lineNumber, markLine); itsFileDisplay->SetText(itsCurrentFile); UpdateFileType(); UpdateWindowTitle(NULL); } }
void CheckEQEMuErrorAndPause() { #ifdef _WINDOWS if (CheckEQEMuError()) { fprintf(stdout, "Hit any key to exit\n"); UpdateWindowTitle("Error"); getch(); } #endif }
/** * Updates the window title and map properties if a {@link CScene} is loaded */ void CFortEdit::UpdateUi() { if (!DScene) { return; } UpdateWindowTitle(); UpdateMapProperties(); }
void CMSourceDirector::DisplayDisassembly ( const CMLocation& loc ) { const JString& fnName = loc.GetFunctionName(); const JString& addr = loc.GetMemoryAddress(); assert( !JStringEmpty(fnName) ); assert( !JStringEmpty(addr) ); if (fnName == itsCurrentFn) { JIndex i; if (dynamic_cast<CMLineAddressTable*>(itsTable)->FindAddressLineNumber(addr, &i)) { DisplayLine(i); } else { itsTable->SetCurrentLine(0); } UpdateWindowTitle(NULL); } else { itsCurrentFn = fnName; if (itsGetAssemblyCmd == NULL) { itsGetAssemblyCmd = (CMGetLink())->CreateGetAssembly(this); } if (itsGetAssemblyCmd != NULL) { itsAsmLocation = loc; itsGetAssemblyCmd->Send(); } UpdateWindowTitle(NULL); } }
void CMRegistersDir::Receive ( JBroadcaster* sender, const Message& message ) { if (sender == CMGetLink() && (message.Is(CMLink::kProgramFinished) || message.Is(CMLink::kCoreCleared) || message.Is(CMLink::kDetachedFromProcess))) { Update(""); } else if (sender == CMGetLink() && (message.Is(CMLink::kProgramStopped) || CMVarNode::ShouldUpdate(message))) { itsNeedsUpdateFlag = kJTrue; Update(); } else if (sender == CMGetLink() && message.Is(CMLink::kSymbolsLoaded)) { const CMLink::SymbolsLoaded* info = dynamic_cast<const CMLink::SymbolsLoaded*>(&message); assert( info != NULL ); UpdateWindowTitle(info->GetProgramName()); } else if (sender == itsFileMenu && message.Is(JXMenu::kNeedsUpdate)) { UpdateFileMenu(); } else if (sender == itsFileMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleFileMenu(selection->GetIndex()); } else if (sender == itsHelpMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleHelpMenu(selection->GetIndex()); } else { JXWindowDirector::Receive(sender, message); } }
void CMSourceDirector::ClearDisplay() { itsTable->ClearLineNumbers(); itsText->SetText(""); itsFileDisplay->SetText(""); itsCurrentFile.Clear(); itsCurrentFn.Clear(); UpdateWindowTitle(NULL); UpdateFileType(); }
void Treenity::SaveAs() { QString fileName = QFileDialog::getSaveFileName(this, "Save Project", "", "World File (*.world)"); if (fileName != "") { m_currentProjectFile = fileName; UpdateWindowTitle(); m_projectManager->Export(fileName); } }
void Treenity::OpenProject() { QString fileName = QFileDialog::getOpenFileName(this, "Open Project", "", "World File (*.world)"); if (fileName != "") { m_currentProjectFile = fileName; UpdateWindowTitle(); m_engineInterface->ClearScene(); m_projectManager->Import(fileName); m_engineInterface->AddDefaultEntities(); m_engineInterface->InitializeScene(); } }
void CMSourceDirector::ClearDisplay() { CMLineAddressTable* table = dynamic_cast<CMLineAddressTable*>(itsTable); if (table != NULL) { table->ClearLineNumbers(); } itsText->SetText(""); itsFileDisplay->SetText(""); itsCurrentFile.Clear(); itsCurrentFn.Clear(); UpdateWindowTitle(NULL); UpdateFileType(); }
void SolveSpaceUI::AfterNewFile(void) { // Clear out the traced point, which is no longer valid traced.point = Entity::NO_ENTITY; traced.path.l.Clear(); // and the naked edges nakedEdges.Clear(); // Quit export mode justExportedInfo.draw = false; exportMode = false; // GenerateAll() expects the view to be valid, because it uses that to // fill in default values for extrusion depths etc. (which won't matter // here, but just don't let it work on garbage) SS.GW.offset = Vector::From(0, 0, 0); SS.GW.projRight = Vector::From(1, 0, 0); SS.GW.projUp = Vector::From(0, 1, 0); GenerateAll(GENERATE_REGEN); TW.Init(); GW.Init(); unsaved = false; int w, h; GetGraphicsWindowSize(&w, &h); GW.width = w; GW.height = h; // The triangles haven't been generated yet, but zoom to fit the entities // roughly in the window, since that sets the mesh tolerance. Consider // invisible entities, so we still get something reasonable if the only // thing visible is the not-yet-generated surfaces. GW.ZoomToFit(true); GenerateAll(GENERATE_ALL); SS.ScheduleShowTW(); // Then zoom to fit again, to fit the triangles GW.ZoomToFit(false); // Create all the default styles; they'll get created on the fly anyways, // but can't hurt to do it now. Style::CreateAllDefaultStyles(); UpdateWindowTitle(); }
int Run( T* pApp ) { printf("Application started.\n"); MSG msg; msg.message = WM_NULL; PeekMessage(&msg, NULL, 0U, 0U, PM_NOREMOVE); while (msg.message != WM_QUIT) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else { pApp->Render(); UpdateWindowTitle(); } } return (int) msg.wParam; }
void CTaskDialog::LayoutWindow(void) { // customize post-creation window styles EnableSystemClose(HasFlag(TDF_ALLOW_DIALOG_CANCELLATION)); // create and position controls GenerateControlIDs(); LayoutControls(); SetFontControls(); SetZOrderControls(); // update various graphical items UpdateMainIcon(MainIcon()); UpdateWindowTitle(WindowTitle()); UpdateFooterIcon(FooterIcon()); // set the keyboard focus to the default button // and select the default radio button SetControlFocus(config_.iDefaultButton); if (!HasFlag(TDF_NO_DEFAULT_RADIO_BUTTON) && config_.nDefaultRadioButton != 0) CheckDlgButton(config_.nDefaultRadioButton, BST_CHECKED); // position dialog if (HasFlag(TDF_POSITION_RELATIVE_TO_WINDOW)) CenterWindow(Parent()); else CenterWindow(::GetDesktopWindow()); if (HasFlag(TDF_CALLBACK_TIMER)) CreateCallbackTimer(); Callback(TDN_DIALOG_CONSTRUCTED); }
WindowTitleBar::WindowTitleBar(QWidget *parent) : QWidget(parent), m_Cache (NULL), m_Title (this), m_Minimize(WindowButton::BUTTON_MINIMIZE, this), m_Maximize(WindowButton::BUTTON_MAXIMIZE, this), m_Close (WindowButton::BUTTON_CLOSE , this) { setFixedHeight(33); setAttribute(Qt::WA_TranslucentBackground); m_Title.setStyleSheet("color: white; font-family: Sans; font-weight: bold; font-size: 14px"); UpdateWindowTitle(); connect(&m_Minimize, SIGNAL(clicked ()), this , SLOT (Minimized())); connect(&m_Maximize, SIGNAL(clicked ()), this, SLOT (Maximized())); connect(&m_Close , SIGNAL(clicked ()), this , SLOT (Quit ())); }
bool FrequenciesDialog::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) { ////@begin FrequenciesDialog member initialisation editMenu = NULL; mFreqListBox = NULL; fGraph = NULL; ////@end FrequenciesDialog member initialisation ////@begin FrequenciesDialog creation wxFrame::Create( parent, id, caption, pos, size, style ); CreateControls(); if (GetSizer()) { GetSizer()->SetSizeHints(this); } Centre(); ////@end FrequenciesDialog creation UpdateWindowTitle(); RegenData(); return true; }
void D3D12HeterogeneousMultiadapter::OnInit() { LoadPipeline(); LoadAssets(); UpdateWindowTitle(); }
void CMArray1DDir::Receive ( JBroadcaster* sender, const Message& message ) { if (sender == itsExprInput && (message.Is(JXWidget::kLostFocus) || message.Is(CMArrayExprInput::kReturnKeyPressed))) { if (itsExprInput->GetText() != itsExpr) { itsExpr = itsExprInput->GetText(); UpdateWindowTitle(); itsDisplayRange.SetToEmptyAt(0); BeginCreateNodes(); } } else if (sender == itsStartIndex && (message.Is(JXWidget::kLostFocus) || message.Is(CMArrayIndexInput::kReturnKeyPressed))) { JInteger value; if (itsStartIndex->GetValue(&value) && value != itsRequestRange.first) { itsRequestRange.first = value; BeginCreateNodes(); } } else if (sender == itsEndIndex && (message.Is(JXWidget::kLostFocus) || message.Is(CMArrayIndexInput::kReturnKeyPressed))) { JInteger value; if (itsEndIndex->GetValue(&value) && value != itsRequestRange.last) { itsRequestRange.last = value; BeginCreateNodes(); } } else if (sender == itsTree && message.Is(JTree::kNodeChanged)) { const JTree::NodeChanged* info = dynamic_cast<const JTree::NodeChanged*>(&message); assert(info != NULL); if (info->GetNode() == itsCurrentNode) { itsCurrentNode = NULL; CreateNextNode(); } } else if (sender == itsStopButton && message.Is(JXButton::kPushed)) { itsRequestRange = itsDisplayRange; itsStartIndex->SetValue(itsRequestRange.first); itsEndIndex->SetValue(itsRequestRange.last); CreateNodesFinished(); } else if (sender == itsLink && message.Is(CMLink::kDebuggerRestarted)) { itsWaitingForReloadFlag = kJTrue; } else if (sender == itsLink && message.Is(CMLink::kDebuggerStarted)) { if (!itsWaitingForReloadFlag) { JXCloseDirectorTask::Close(this); // close after bcast is finished } itsWaitingForReloadFlag = kJFalse; } else if (sender == itsFileMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleFileMenu(selection->GetIndex()); } else if (sender == itsActionMenu && message.Is(JXMenu::kNeedsUpdate)) { UpdateActionMenu(); } else if (sender == itsActionMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleActionMenu(selection->GetIndex()); } else if (sender == itsHelpMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleHelpMenu(selection->GetIndex()); } else { JXWindowDirector::Receive(sender, message); } }
int main(int argc, char** argv) { #ifdef _DEBUG _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); // _crtBreakAlloc = 2025; #endif srand(time(NULL)); for (int logs = 0; logs < EQEMuLog::MaxLogID; logs++) { LogFile->write((EQEMuLog::LogIDs)logs, "CURRENT_ZONE_VERSION: %s", CURRENT_ZONE_VERSION); } if (argc != 5) { cerr << "Usage: zone zone_name address port worldaddress" << endl; exit(0); } char* filename = argv[0]; char* zone_name = argv[1]; char* address = argv[2]; int32 port = atoi(argv[3]); char* worldaddress = argv[4]; if (strlen(address) <= 0) { cerr << "Invalid address" << endl; exit(0); } if (port <= 0) { cerr << "Bad port specified" << endl; exit(0); } if (strlen(worldaddress) <= 0) { cerr << "Invalid worldaddress" << endl; exit(0); } if (signal(SIGINT, CatchSignal) == SIG_ERR) { cerr << "Could not set signal handler" << endl; return 0; } #ifndef WIN32 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { cerr << "Could not set signal handler" << endl; return 0; } #endif net.SaveInfo(address, port, worldaddress,filename); LogFile->write(EQEMuLog::Status, "Loading Variables"); database.LoadVariables(); LogFile->write(EQEMuLog::Status, "Loading zone names"); database.LoadZoneNames(); LogFile->write(EQEMuLog::Status, "Loading items"); if (!database.LoadItems()) { LogFile->write(EQEMuLog::Error, "Loading items FAILED!"); cout << "Failed. But ignoring error and going on..." << endl; } LogFile->write(EQEMuLog::Status, "Loading npcs"); if (!database.LoadNPCTypes()) { LogFile->write(EQEMuLog::Error, "Loading npcs FAILED!"); CheckEQEMuErrorAndPause(); return 0; } #ifdef SHAREMEM LogFile->write(EQEMuLog::Status, "Loading npc faction lists"); if (!database.LoadNPCFactionLists()) { LogFile->write(EQEMuLog::Error, "Loading npcs faction lists FAILED!"); CheckEQEMuErrorAndPause(); return 0; } #endif LogFile->write(EQEMuLog::Status, "Loading loot tables"); if (!database.LoadLoot()) { LogFile->write(EQEMuLog::Error, "Loading loot FAILED!"); CheckEQEMuErrorAndPause(); return 0; } #ifdef SHAREMEM LogFile->write(EQEMuLog::Status, "Loading doors"); database.LoadDoors(); #endif LoadSPDat(); #ifdef GUILDWARS LogFile->write(EQEMuLog::Status, "Loading guild alliances"); //database.LoadGuildAlliances(); #endif // New Load function. keeping it commented till I figure out why its not working correctly in linux. Trump. // NewLoadSPDat(); LogFile->write(EQEMuLog::Status, "Loading guilds"); database.LoadGuilds(guilds); LogFile->write(EQEMuLog::Status, "Loading factions"); database.LoadFactionData(); LogFile->write(EQEMuLog::Status, "Loading corpse timers"); database.GetDecayTimes(npcCorpseDecayTimes); LogFile->write(EQEMuLog::Status, "Loading what ever is left"); database.ExtraOptions(); AutoDelete<Parser> ADparse(&parse, new Parser); #ifdef ADDONCMD LogFile->write(EQEMuLog::Status, "Looding addon commands from dll"); if ( !addonCmd.openLib() ) { LogFile->write(EQEMuLog::Error, "Loading addons failed =("); } #endif if (!worldserver.Connect()) { LogFile->write(EQEMuLog::Error, "worldserver.Connect() FAILED!"); } if (strcmp(zone_name, ".") == 0 || strcasecmp(zone_name, "sleep") == 0) { LogFile->write(EQEMuLog::Status, "Entering sleep mode"); } else if (!Zone::Bootup(database.GetZoneID(zone_name), true)) { LogFile->write(EQEMuLog::Error, "Zone bootup FAILED!"); zone = 0; } Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect UpdateWindowTitle(); bool worldwasconnected = worldserver.Connected(); EQNetworkConnection* eqnc; while(RunLoops) { Timer::SetCurrentTime(); while ((eqnc = eqns.NewQueuePop())) { struct in_addr in; in.s_addr = eqnc->GetrIP(); LogFile->write(EQEMuLog::Status, "%i New client from ip:%s port:%i", Timer::GetCurrentTime(), inet_ntoa(in), ntohs(eqnc->GetrPort())); Client* client = new Client(eqnc); entity_list.AddClient(client); } #ifdef CATCH_CRASH try{ #endif worldserver.Process(); #ifdef CATCH_CRASH } catch(...){ error = 1; adverrornum = worldserver.GetErrorNumber(); worldserver.Disconnect(); worldwasconnected = false; } #endif if (worldserver.Connected()) { worldwasconnected = true; } else { if (worldwasconnected && ZoneLoaded) entity_list.ChannelMessageFromWorld(0, 0, 6, 0, 0, "WARNING: World server connection lost"); worldwasconnected = false; } if (ZoneLoaded) { { #ifdef CATCH_CRASH try{ #endif entity_list.Process(); #ifdef CATCH_CRASH } catch(...){ error = 4; } try{ #endif zoneprocess= zone->Process(); if (!zoneprocess) { Zone::Shutdown(); } #ifdef CATCH_CRASH } catch(...){ error = 2; } #endif } } DBAsyncWork* dbaw = 0; while ((dbaw = MTdbafq->Pop())) { DispatchFinishedDBAsync(dbaw); } if (InterserverTimer.Check() #ifdef CATCH_CRASH && !error #endif ) { #ifdef CATCH_CRASH try{ #endif InterserverTimer.Start(); database.ping(); AsyncLoadVariables(); // NPC::GetAILevel(true); entity_list.UpdateWho(); if (worldserver.TryReconnect() && (!worldserver.Connected())) worldserver.AsyncConnect(); #ifdef CATCH_CRASH } catch(...) { error = 16; RunLoops = false; } #endif } #ifdef CATCH_CRASH if (error){ RunLoops = false; } #endif #if defined(_DEBUG) && defined(DEBUG_PC) QueryPerformanceCounter(&tmp3); mainloop_time += tmp3.QuadPart - tmp2.QuadPart; if (!--tmp0) { tmp0 = 200; printf("Elapsed Tics : %9.0f (%1.4f sec)\n", (double)mainloop_time, ((double)mainloop_time/tmp.QuadPart)); printf("NPCAI Tics : %9.0f (%1.2f%%)\n", (double)npcai_time, ((double)npcai_time/mainloop_time)*100); printf("FindSpell Tics: %9.0f (%1.2f%%)\n", (double)findspell_time, ((double)findspell_time/mainloop_time)*100); printf("AtkAllowd Tics: %9.0f (%1.2f%%)\n", (double)IsAttackAllowed_time, ((double)IsAttackAllowed_time/mainloop_time)*100); printf("ClientPro Tics: %9.0f (%1.2f%%)\n", (double)clientprocess_time, ((double)clientprocess_time/mainloop_time)*100); printf("ClientAtk Tics: %9.0f (%1.2f%%)\n", (double)clientattack_time, ((double)clientattack_time/mainloop_time)*100); mainloop_time = 0; npcai_time = 0; findspell_time = 0; IsAttackAllowed_time = 0; clientprocess_time = 0; clientattack_time = 0; } #endif Sleep(1); } #ifdef CATCH_CRASH if (error) FilePrint("eqemudebug.log",true,true,"Zone %i crashed. Errorcode: %i/%i. Current zone loaded:%s. Current clients:%i. Caused by: %s",net.GetZonePort(), error,adverrornum, zone->GetShortName(), numclients,errorname); try{ entity_list.Message(0, 15, "ZONEWIDE_MESSAGE: This zone caused a fatal error and will shut down now. Your character will be restored to the last saved status. We are sorry for any inconvenience!"); } catch(...){} if (error){ #ifdef WIN32 ExitProcess(error); #else entity_list.Clear(); safe_delete(zone); #endif } #endif entity_list.Clear(); if (zone != 0 #ifdef CATCH_CRASH & !error #endif ) Zone::Shutdown(true); //Fix for Linux world server problem. eqns.Close(); worldserver.Disconnect(); dbasync->CommitWrites(); dbasync->StopThread(); #ifdef NEW_LoadSPDat safe_delete(spells_delete); #endif CheckEQEMuErrorAndPause(); return 0; }
int main(int argc, char** argv) { RegisterExecutablePlatform(ExePlatformZone); LogSys.LoadLogSettingsDefaults(); set_exception_handler(); #ifdef USE_MAP_MMFS if (argc == 3 && strcasecmp(argv[1], "convert_map") == 0) { if (!ZoneConfig::LoadConfig()) return 1; Config = ZoneConfig::get(); std::string mapfile = argv[2]; std::transform(mapfile.begin(), mapfile.end(), mapfile.begin(), ::tolower); std::string filename = Config->MapDir; filename += mapfile; auto m = new Map(); auto success = m->Load(filename, true); delete m; std::cout << mapfile.c_str() << " conversion " << (success ? "succeeded" : "failed") << std::endl; return 0; } #endif /*USE_MAP_MMFS*/ QServ = new QueryServ; Log(Logs::General, Logs::Zone_Server, "Loading server configuration.."); if (!ZoneConfig::LoadConfig()) { Log(Logs::General, Logs::Error, "Loading server configuration failed."); return 1; } Config = ZoneConfig::get(); const char *zone_name; uint32 instance_id = 0; std::string z_name; if (argc == 4) { instance_id = atoi(argv[3]); worldserver.SetLauncherName(argv[2]); auto zone_port = SplitString(argv[1], ':'); if (!zone_port.empty()) { z_name = zone_port[0]; } if (zone_port.size() > 1) { std::string p_name = zone_port[1]; Config->SetZonePort(atoi(p_name.c_str())); } worldserver.SetLaunchedName(z_name.c_str()); if (strncmp(z_name.c_str(), "dynamic_", 8) == 0) { zone_name = "."; } else { zone_name = z_name.c_str(); } } else if (argc == 3) { worldserver.SetLauncherName(argv[2]); auto zone_port = SplitString(argv[1], ':'); if (!zone_port.empty()) { z_name = zone_port[0]; } if (zone_port.size() > 1) { std::string p_name = zone_port[1]; Config->SetZonePort(atoi(p_name.c_str())); } worldserver.SetLaunchedName(z_name.c_str()); if (strncmp(z_name.c_str(), "dynamic_", 8) == 0) { zone_name = "."; } else { zone_name = z_name.c_str(); } } else if (argc == 2) { worldserver.SetLauncherName("NONE"); auto zone_port = SplitString(argv[1], ':'); if (!zone_port.empty()) { z_name = zone_port[0]; } if (zone_port.size() > 1) { std::string p_name = zone_port[1]; Config->SetZonePort(atoi(p_name.c_str())); } worldserver.SetLaunchedName(z_name.c_str()); if (strncmp(z_name.c_str(), "dynamic_", 8) == 0) { zone_name = "."; } else { zone_name = z_name.c_str(); } } else { zone_name = "."; worldserver.SetLaunchedName("."); worldserver.SetLauncherName("NONE"); } Log(Logs::General, Logs::Zone_Server, "Connecting to MySQL..."); if (!database.Connect( Config->DatabaseHost.c_str(), Config->DatabaseUsername.c_str(), Config->DatabasePassword.c_str(), Config->DatabaseDB.c_str(), Config->DatabasePort)) { Log(Logs::General, Logs::Error, "Cannot continue without a database connection."); return 1; } #ifdef BOTS if (!botdb.Connect( Config->DatabaseHost.c_str(), Config->DatabaseUsername.c_str(), Config->DatabasePassword.c_str(), Config->DatabaseDB.c_str(), Config->DatabasePort)) { Log(Logs::General, Logs::Error, "Cannot continue without a bots database connection."); return 1; } #endif /* Register Log System and Settings */ LogSys.OnLogHookCallBackZone(&Zone::GMSayHookCallBackProcess); database.LoadLogSettings(LogSys.log_settings); LogSys.StartFileLogs(); /* Guilds */ guild_mgr.SetDatabase(&database); GuildBanks = nullptr; /** * NPC Scale Manager */ npc_scale_manager = new NpcScaleManager; npc_scale_manager->LoadScaleData(); #ifdef _EQDEBUG _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif Log(Logs::General, Logs::Zone_Server, "CURRENT_VERSION: %s", CURRENT_VERSION); /* * Setup nice signal handlers */ if (signal(SIGINT, CatchSignal) == SIG_ERR) { Log(Logs::General, Logs::Error, "Could not set signal handler"); return 1; } if (signal(SIGTERM, CatchSignal) == SIG_ERR) { Log(Logs::General, Logs::Error, "Could not set signal handler"); return 1; } #ifndef WIN32 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { Log(Logs::General, Logs::Error, "Could not set signal handler"); return 1; } #endif Log(Logs::General, Logs::Zone_Server, "Mapping Incoming Opcodes"); MapOpcodes(); Log(Logs::General, Logs::Zone_Server, "Loading Variables"); database.LoadVariables(); std::string hotfix_name; if (database.GetVariable("hotfix_name", hotfix_name)) { if (!hotfix_name.empty()) { Log(Logs::General, Logs::Zone_Server, "Current hotfix in use: '%s'", hotfix_name.c_str()); } } Log(Logs::General, Logs::Zone_Server, "Loading zone names"); database.LoadZoneNames(); Log(Logs::General, Logs::Zone_Server, "Loading items"); if (!database.LoadItems(hotfix_name)) { Log(Logs::General, Logs::Error, "Loading items FAILED!"); Log(Logs::General, Logs::Error, "Failed. But ignoring error and going on..."); } Log(Logs::General, Logs::Zone_Server, "Loading npc faction lists"); if (!database.LoadNPCFactionLists(hotfix_name)) { Log(Logs::General, Logs::Error, "Loading npcs faction lists FAILED!"); return 1; } Log(Logs::General, Logs::Zone_Server, "Loading loot tables"); if (!database.LoadLoot(hotfix_name)) { Log(Logs::General, Logs::Error, "Loading loot FAILED!"); return 1; } Log(Logs::General, Logs::Zone_Server, "Loading skill caps"); if (!database.LoadSkillCaps(std::string(hotfix_name))) { Log(Logs::General, Logs::Error, "Loading skill caps FAILED!"); return 1; } Log(Logs::General, Logs::Zone_Server, "Loading spells"); if (!database.LoadSpells(hotfix_name, &SPDAT_RECORDS, &spells)) { Log(Logs::General, Logs::Error, "Loading spells FAILED!"); return 1; } Log(Logs::General, Logs::Zone_Server, "Loading base data"); if (!database.LoadBaseData(hotfix_name)) { Log(Logs::General, Logs::Error, "Loading base data FAILED!"); return 1; } Log(Logs::General, Logs::Zone_Server, "Loading guilds"); guild_mgr.LoadGuilds(); Log(Logs::General, Logs::Zone_Server, "Loading factions"); database.LoadFactionData(); Log(Logs::General, Logs::Zone_Server, "Loading titles"); title_manager.LoadTitles(); Log(Logs::General, Logs::Zone_Server, "Loading tributes"); database.LoadTributes(); Log(Logs::General, Logs::Zone_Server, "Loading corpse timers"); database.GetDecayTimes(npcCorpseDecayTimes); Log(Logs::General, Logs::Zone_Server, "Loading profanity list"); if (!EQEmu::ProfanityManager::LoadProfanityList(&database)) Log(Logs::General, Logs::Error, "Loading profanity list FAILED!"); Log(Logs::General, Logs::Zone_Server, "Loading commands"); int retval = command_init(); if (retval<0) Log(Logs::General, Logs::Error, "Command loading FAILED"); else Log(Logs::General, Logs::Zone_Server, "%d commands loaded", retval); //rules: { std::string tmp; if (database.GetVariable("RuleSet", tmp)) { Log(Logs::General, Logs::Zone_Server, "Loading rule set '%s'", tmp.c_str()); if (!RuleManager::Instance()->LoadRules(&database, tmp.c_str(), false)) { Log(Logs::General, Logs::Error, "Failed to load ruleset '%s', falling back to defaults.", tmp.c_str()); } } else { if (!RuleManager::Instance()->LoadRules(&database, "default", false)) { Log(Logs::General, Logs::Zone_Server, "No rule set configured, using default rules"); } else { Log(Logs::General, Logs::Zone_Server, "Loaded default rule set 'default'", tmp.c_str()); } } EQEmu::InitializeDynamicLookups(); Log(Logs::General, Logs::Zone_Server, "Initialized dynamic dictionary entries"); } #ifdef BOTS Log(Logs::General, Logs::Zone_Server, "Loading bot commands"); int botretval = bot_command_init(); if (botretval<0) Log(Logs::General, Logs::Error, "Bot command loading FAILED"); else Log(Logs::General, Logs::Zone_Server, "%d bot commands loaded", botretval); Log(Logs::General, Logs::Zone_Server, "Loading bot spell casting chances"); if (!botdb.LoadBotSpellCastingChances()) Log(Logs::General, Logs::Error, "Bot spell casting chances loading FAILED"); #endif if (RuleB(TaskSystem, EnableTaskSystem)) { Log(Logs::General, Logs::Tasks, "[INIT] Loading Tasks"); taskmanager = new TaskManager; taskmanager->LoadTasks(); } parse = new QuestParserCollection(); #ifdef LUA_EQEMU parse->RegisterQuestInterface(LuaParser::Instance(), "lua"); #endif #ifdef EMBPERL auto perl_parser = new PerlembParser(); parse->RegisterQuestInterface(perl_parser, "pl"); /* Load Perl Event Export Settings */ parse->LoadPerlEventExportSettings(parse->perl_event_export_settings); #endif //now we have our parser, load the quests Log(Logs::General, Logs::Zone_Server, "Loading quests"); parse->ReloadQuests(); worldserver.Connect(); Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect #ifdef EQPROFILE #ifdef PROFILE_DUMP_TIME Timer profile_dump_timer(PROFILE_DUMP_TIME * 1000); profile_dump_timer.Start(); #endif #endif if (!strlen(zone_name) || !strcmp(zone_name, ".")) { Log(Logs::General, Logs::Zone_Server, "Entering sleep mode"); } else if (!Zone::Bootup(database.GetZoneID(zone_name), instance_id, true)) { Log(Logs::General, Logs::Error, "Zone Bootup failed :: Zone::Bootup"); zone = 0; } //register all the patches we have avaliable with the stream identifier. EQStreamIdentifier stream_identifier; RegisterAllPatches(stream_identifier); #ifndef WIN32 Log(Logs::Detail, Logs::None, "Main thread running with thread id %d", pthread_self()); #endif Timer quest_timers(100); UpdateWindowTitle(); bool worldwasconnected = worldserver.Connected(); std::shared_ptr<EQStreamInterface> eqss; EQStreamInterface *eqsi; bool eqsf_open = false; std::unique_ptr<EQ::Net::EQStreamManager> eqsm; std::chrono::time_point<std::chrono::system_clock> frame_prev = std::chrono::system_clock::now(); auto loop_fn = [&](EQ::Timer* t) { //Advance the timer to our current point in time Timer::SetCurrentTime(); //Calculate frame time std::chrono::time_point<std::chrono::system_clock> frame_now = std::chrono::system_clock::now(); frame_time = std::chrono::duration_cast<std::chrono::duration<double>>(frame_now - frame_prev).count(); frame_prev = frame_now; if (!eqsf_open && Config->ZonePort != 0) { Log(Logs::General, Logs::Zone_Server, "Starting EQ Network server on port %d", Config->ZonePort); EQ::Net::EQStreamManagerOptions opts(Config->ZonePort, false, true); opts.daybreak_options.resend_delay_ms = RuleI(Network, ResendDelayBaseMS); opts.daybreak_options.resend_delay_factor = RuleR(Network, ResendDelayFactor); opts.daybreak_options.resend_delay_min = RuleI(Network, ResendDelayMinMS); opts.daybreak_options.resend_delay_max = RuleI(Network, ResendDelayMaxMS); eqsm.reset(new EQ::Net::EQStreamManager(opts)); eqsf_open = true; eqsm->OnNewConnection([&stream_identifier](std::shared_ptr<EQ::Net::EQStream> stream) { stream_identifier.AddStream(stream); LogF(Logs::Detail, Logs::World_Server, "New connection from IP {0}:{1}", stream->RemoteEndpoint(), ntohs(stream->GetRemotePort())); }); } //give the stream identifier a chance to do its work.... stream_identifier.Process(); //check the stream identifier for any now-identified streams while ((eqsi = stream_identifier.PopIdentified())) { //now that we know what patch they are running, start up their client object struct in_addr in; in.s_addr = eqsi->GetRemoteIP(); Log(Logs::Detail, Logs::World_Server, "New client from %s:%d", inet_ntoa(in), ntohs(eqsi->GetRemotePort())); auto client = new Client(eqsi); entity_list.AddClient(client); } if (worldserver.Connected()) { worldwasconnected = true; } else { if (worldwasconnected && is_zone_loaded) { entity_list.ChannelMessageFromWorld(0, 0, 6, 0, 0, "WARNING: World server connection lost"); worldwasconnected = false; } } if (is_zone_loaded) { { if (net.group_timer.Enabled() && net.group_timer.Check()) entity_list.GroupProcess(); if (net.door_timer.Enabled() && net.door_timer.Check()) entity_list.DoorProcess(); if (net.object_timer.Enabled() && net.object_timer.Check()) entity_list.ObjectProcess(); if (net.corpse_timer.Enabled() && net.corpse_timer.Check()) entity_list.CorpseProcess(); if (net.trap_timer.Enabled() && net.trap_timer.Check()) entity_list.TrapProcess(); if (net.raid_timer.Enabled() && net.raid_timer.Check()) entity_list.RaidProcess(); entity_list.Process(); entity_list.MobProcess(); entity_list.BeaconProcess(); entity_list.EncounterProcess(); if (zone) { if (!zone->Process()) { Zone::Shutdown(); } } if (quest_timers.Check()) quest_manager.Process(); } } if (InterserverTimer.Check()) { InterserverTimer.Start(); database.ping(); entity_list.UpdateWho(); } }; EQ::Timer process_timer(loop_fn); bool is_boat_zone = strstr(zone_name, "erudnext") != NULL || strstr(zone_name, "freporte") != NULL || strstr(zone_name, "qeynos") != NULL || strstr(zone_name, "oot") != NULL || strstr(zone_name, "timorous") != NULL || strstr(zone_name, "erudsxing") != NULL || strstr(zone_name, "firiona") != NULL || strstr(zone_name, "butcher") != NULL || strstr(zone_name, "overthere") != NULL || strstr(zone_name, "oasis") != NULL || strstr(zone_name, "nro") != NULL || strstr(zone_name, "iceclad") != NULL; if (!is_boat_zone) process_timer.Start(1000, true); else process_timer.Start(100, true); while (RunLoops) { if (!is_boat_zone) { bool previous_loaded = is_zone_loaded && numclients > 0; EQ::EventLoop::Get().Process(); bool current_loaded = is_zone_loaded && numclients > 0; if (previous_loaded && !current_loaded) { process_timer.Stop(); process_timer.Start(1000, true); } else if (!previous_loaded && current_loaded) { process_timer.Stop(); process_timer.Start(32, true); } if (current_loaded) { Sleep(1); } else { Sleep(10); } } else { bool previous_loaded = is_zone_loaded; EQ::EventLoop::Get().Process(); bool current_loaded = is_zone_loaded; if (previous_loaded && !current_loaded) { process_timer.Stop(); process_timer.Start(100, true); if (zone && zone->GetZoneID() && zone->GetInstanceVersion()) { uint32 shutdown_timer = database.getZoneShutDownDelay(zone->GetZoneID(), zone->GetInstanceVersion()); zone->StartShutdownTimer(shutdown_timer); } } else if (!previous_loaded && current_loaded) { process_timer.Stop(); process_timer.Start(10, true); } Sleep(1); } } entity_list.Clear(); entity_list.RemoveAllEncounters(); // gotta do it manually or rewrite lots of shit :P parse->ClearInterfaces(); #ifdef EMBPERL safe_delete(perl_parser); #endif safe_delete(Config); if (zone != 0) Zone::Shutdown(true); //Fix for Linux world server problem. safe_delete(taskmanager); command_deinit(); #ifdef BOTS bot_command_deinit(); #endif safe_delete(parse); Log(Logs::General, Logs::Zone_Server, "Proper zone shutdown complete."); LogSys.CloseFileLogs(); return 0; }
void MainWidget::loggedInData(LPConnection::Result res) { UpdateWindowTitle(); }
void CMLocalVarsDir::Receive ( JBroadcaster* sender, const Message& message ) { if (sender == itsLink && (message.Is(CMLink::kValueChanged) || message.Is(CMLink::kThreadChanged) || message.Is(CMLink::kFrameChanged) || message.Is(CMLink::kCoreLoaded) || message.Is(CMLink::kAttachedToProcess))) { Rebuild(); } else if (sender == itsLink && message.Is(CMLink::kProgramStopped)) { const CMLink::ProgramStopped& info = dynamic_cast<const CMLink::ProgramStopped&>(message); const CMLocation* loc; if (info.GetLocation(&loc) && !(loc->GetFileName()).IsEmpty()) { Rebuild(); } } else if (sender == itsLink && (message.Is(CMLink::kProgramFinished) || message.Is(CMLink::kCoreCleared) || message.Is(CMLink::kDetachedFromProcess))) { // can't listen for CMLink::kProgramRunning because this happens // every time the user executes another line of code FlushOldData(); } else if (sender == itsLink && message.Is(CMLink::kSymbolsLoaded)) { const CMLink::SymbolsLoaded* info = dynamic_cast<const CMLink::SymbolsLoaded*>(&message); assert( info != NULL ); UpdateWindowTitle(info->GetProgramName()); } else if (sender == itsFileMenu && message.Is(JXMenu::kNeedsUpdate)) { UpdateFileMenu(); } else if (sender == itsFileMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleFileMenu(selection->GetIndex()); } else if (sender == itsActionMenu && message.Is(JXMenu::kNeedsUpdate)) { UpdateActionMenu(); } else if (sender == itsActionMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleActionMenu(selection->GetIndex()); } else if (sender == itsHelpMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleHelpMenu(selection->GetIndex()); } else if (sender == GetWindow() && message.Is(JXWindow::kDeiconified)) { Update(); } else { JXWindowDirector::Receive(sender, message); } }
MainWidget::MainWidget(QWidget *parent) : QWidget(parent) { QString hostname="localhost"; unsigned port=LPCORE_CONNECTION_TCP_PORT; QString username; QString password; bool track_state=false; bool ok=false; // // Fonts // QFont label_font("helvetica",12,QFont::Bold); label_font.setPixelSize(12); // // Read Command Options // LPCmdSwitch *cmd= new LPCmdSwitch(qApp->argc(),qApp->argv(),"lpcore",LPCORE_USAGE); for(unsigned i=0;i<cmd->keys();i++) { if(cmd->key(i)=="--hostname") { hostname=cmd->value(i); cmd->setProcessed(i,true); } if(cmd->key(i)=="--port") { port=cmd->value(i).toUInt(&ok); if((!ok)||(port>0xFFFF)) { fprintf(stderr,"invalid port value\n"); exit(256); } cmd->setProcessed(i,true); } if(cmd->key(i)=="--username") { username=cmd->value(i); cmd->setProcessed(i,true); } if(cmd->key(i)=="--password") { password=cmd->value(i); cmd->setProcessed(i,true); } if(cmd->key(i)=="--track-state") { track_state=true; cmd->setProcessed(i,true); } if(!cmd->processed(i)) { fprintf(stderr,"unknown option \"%s\"\n", (const char *)cmd->key(i).toAscii()); exit(256); } } delete cmd; // // Open Syslog // openlog("lpcore",LOG_PERROR,LOG_USER); // // Connection // lp_connection=new LPConnection(track_state,this); connect(lp_connection,SIGNAL(messageReceived(const LPMessage &)), this,SLOT(messageReceivedData(const LPMessage &))); connect(lp_connection,SIGNAL(watchdogStateChanged(bool)), this,SLOT(watchdogStateChangedData(bool))); connect(lp_connection,SIGNAL(loggedIn(LPConnection::Result)), this,SLOT(loggedInData(LPConnection::Result))); connect(lp_connection, SIGNAL(socketError(QAbstractSocket::SocketError,const QString &)), this, SLOT(socketErrorData(QAbstractSocket::SocketError,const QString &))); // // Context Selector // lp_context_label=new QLabel(tr("Context")+":",this); lp_context_label->setFont(label_font); lp_context_label->setAlignment(Qt::AlignRight|Qt::AlignVCenter); lp_context_box=new QComboBox(this); lp_context_box->insertItem(-1,tr("Global")); lp_context_box->insertItem(-1,tr("Isolated")); lp_context_box->setCurrentIndex(1); connect(lp_context_box,SIGNAL(activated(int)), this,SLOT(contextChangedData(int))); lp_clear_button=new QPushButton(tr("Clear"),this); lp_clear_button->setFont(label_font); // // Send Widget // lp_send_edit=new QLineEdit(this); lp_send_edit->setDisabled(true); connect(lp_send_edit,SIGNAL(returnPressed()),this,SLOT(returnPressedData())); // // Receive Widget // lp_recv_edit=new QTextEdit(this); lp_recv_edit->setReadOnly(true); connect(lp_clear_button,SIGNAL(clicked()),lp_recv_edit,SLOT(clear())); contextChangedData(lp_context_box->currentIndex()); lp_connection->connectToHost(hostname,port,username,password); UpdateWindowTitle(); }
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: if (!DoesVersionMatchWindows(6, 0, 0, 0, true)) { // Remove the D3D11 choice on versions below XP RemoveMenu(GetMenu(hWnd), ID_OPTIONS_DIRECT3D11, MF_BYCOMMAND); } break; case WM_GETMINMAXINFO: { MINMAXINFO *minmax = reinterpret_cast<MINMAXINFO *>(lParam); RECT rc = { 0 }; bool portrait = g_Config.IsPortrait(); rc.right = portrait ? 272 : 480; rc.bottom = portrait ? 480 : 272; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, TRUE); minmax->ptMinTrackSize.x = rc.right - rc.left; minmax->ptMinTrackSize.y = rc.bottom - rc.top; } return 0; case WM_ACTIVATE: { bool pause = true; if (wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE) { WindowsRawInput::GainFocus(); if (!IsIconic(GetHWND())) { InputDevice::GainFocus(); } g_activeWindow = WINDOW_MAINWINDOW; pause = false; } if (!noFocusPause && g_Config.bPauseOnLostFocus && GetUIState() == UISTATE_INGAME) { if (pause != Core_IsStepping()) { // != is xor for bools if (disasmWindow[0]) SendMessage(disasmWindow[0]->GetDlgHandle(), WM_COMMAND, IDC_STOPGO, 0); else Core_EnableStepping(pause); } } if (wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE) { NativeMessageReceived("got_focus", ""); hasFocus = true; trapMouse = true; } if (wParam == WA_INACTIVE) { NativeMessageReceived("lost_focus", ""); WindowsRawInput::LoseFocus(); InputDevice::LoseFocus(); hasFocus = false; trapMouse = false; } } break; case WM_ERASEBKGND: // This window is always covered by DisplayWindow. No reason to erase. return 1; case WM_MOVE: SavePosition(); break; case WM_ENTERSIZEMOVE: inResizeMove = true; break; case WM_EXITSIZEMOVE: inResizeMove = false; HandleSizeChange(SIZE_RESTORED); break; case WM_SIZE: switch (wParam) { case SIZE_RESTORED: case SIZE_MAXIMIZED: if (g_IgnoreWM_SIZE) { return DefWindowProc(hWnd, message, wParam, lParam); } else if (!inResizeMove) { HandleSizeChange(wParam); } if (hasFocus) { InputDevice::GainFocus(); } break; case SIZE_MINIMIZED: Core_NotifyWindowHidden(true); if (!g_Config.bPauseWhenMinimized) { NativeMessageReceived("window minimized", "true"); } InputDevice::LoseFocus(); break; default: break; } break; case WM_TIMER: // Hack: Take the opportunity to also show/hide the mouse cursor in fullscreen mode. switch (wParam) { case TIMER_CURSORUPDATE: CorrectCursor(); return 0; case TIMER_CURSORMOVEUPDATE: hideCursor = true; KillTimer(hWnd, TIMER_CURSORMOVEUPDATE); return 0; } break; // For some reason, need to catch this here rather than in DisplayProc. case WM_MOUSEWHEEL: { int wheelDelta = (short)(wParam >> 16); KeyInput key; key.deviceId = DEVICE_ID_MOUSE; if (wheelDelta < 0) { key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN; wheelDelta = -wheelDelta; } else { key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP; } // There's no separate keyup event for mousewheel events, let's pass them both together. // This also means it really won't work great for key mapping :( Need to build a 1 frame delay or something. key.flags = KEY_DOWN | KEY_UP | KEY_HASWHEELDELTA | (wheelDelta << 16); NativeKey(key); } break; case WM_COMMAND: { if (!MainThread_Ready()) return DefWindowProc(hWnd, message, wParam, lParam); MainWindowMenu_Process(hWnd, wParam); } break; case WM_USER_TOGGLE_FULLSCREEN: ToggleFullscreen(hwndMain, wParam ? true : false); break; case WM_INPUT: return WindowsRawInput::Process(hWnd, wParam, lParam); // TODO: Could do something useful with WM_INPUT_DEVICE_CHANGE? // Not sure why we are actually getting WM_CHAR even though we use RawInput, but alright.. case WM_CHAR: return WindowsRawInput::ProcessChar(hWnd, wParam, lParam); case WM_DEVICECHANGE: #ifndef _M_ARM DinputDevice::CheckDevices(); #endif return DefWindowProc(hWnd, message, wParam, lParam); case WM_VERYSLEEPY_MSG: switch (wParam) { case VERYSLEEPY_WPARAM_SUPPORTED: return TRUE; case VERYSLEEPY_WPARAM_GETADDRINFO: { VerySleepy_AddrInfo *info = (VerySleepy_AddrInfo *)lParam; const u8 *ptr = (const u8 *)info->addr; std::string name; if (MIPSComp::jit && MIPSComp::jit->DescribeCodePtr(ptr, name)) { swprintf_s(info->name, L"Jit::%S", name.c_str()); return TRUE; } if (gpu && gpu->DescribeCodePtr(ptr, name)) { swprintf_s(info->name, L"GPU::%S", name.c_str()); return TRUE; } } return FALSE; default: return FALSE; } break; case WM_DROPFILES: { if (!MainThread_Ready()) return DefWindowProc(hWnd, message, wParam, lParam); HDROP hdrop = (HDROP)wParam; int count = DragQueryFile(hdrop,0xFFFFFFFF,0,0); if (count != 1) { MessageBox(hwndMain,L"You can only load one file at a time",L"Error",MB_ICONINFORMATION); } else { TCHAR filename[512]; if (DragQueryFile(hdrop, 0, filename, 512) != 0) { const std::string utf8_filename = ReplaceAll(ConvertWStringToUTF8(filename), "\\", "/"); NativeMessageReceived("boot", utf8_filename.c_str()); Core_EnableStepping(false); } } } break; case WM_CLOSE: InputDevice::StopPolling(); WindowsRawInput::Shutdown(); return DefWindowProc(hWnd,message,wParam,lParam); case WM_DESTROY: KillTimer(hWnd, TIMER_CURSORUPDATE); KillTimer(hWnd, TIMER_CURSORMOVEUPDATE); PostQuitMessage(0); break; case WM_USER + 1: if (disasmWindow[0]) disasmWindow[0]->NotifyMapLoaded(); if (memoryWindow[0]) memoryWindow[0]->NotifyMapLoaded(); if (disasmWindow[0]) disasmWindow[0]->UpdateDialog(); SetForegroundWindow(hwndMain); break; case WM_USER_SAVESTATE_FINISH: SetCursor(LoadCursor(0, IDC_ARROW)); break; case WM_USER_UPDATE_UI: TranslateMenus(hwndMain, menu); // Update checked status immediately for accelerators. UpdateMenus(); break; case WM_USER_WINDOW_TITLE_CHANGED: UpdateWindowTitle(); break; case WM_USER_BROWSE_BOOT_DONE: BrowseAndBootDone(); break; case WM_USER_BROWSE_BG_DONE: BrowseBackgroundDone(); break; case WM_USER_RESTART_EMUTHREAD: NativeSetRestarting(); InputDevice::StopPolling(); MainThread_Stop(); coreState = CORE_POWERUP; UpdateUIState(UISTATE_MENU); MainThread_Start(g_Config.iGPUBackend == (int)GPUBackend::OPENGL); InputDevice::BeginPolling(); break; case WM_MENUSELECT: // Called when a menu is opened. Also when an item is selected, but meh. UpdateMenus(true); WindowsRawInput::NotifyMenu(); trapMouse = false; break; case WM_EXITMENULOOP: // Called when menu is closed. trapMouse = true; break; // Turn off the screensaver. // Note that if there's a screensaver password, this simple method // doesn't work on Vista or higher. case WM_SYSCOMMAND: { switch (wParam) { case SC_SCREENSAVE: return 0; case SC_MONITORPOWER: return 0; } return DefWindowProc(hWnd, message, wParam, lParam); } default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
void CMSourceDirector::Receive ( JBroadcaster* sender, const Message& message ) { if (IsMainSourceWindow() && sender == itsLink && message.Is(CMLink::kDebuggerStarted)) { ClearDisplay(); } else if (sender == itsLink && message.Is(CMLink::kPrepareToLoadSymbols)) { if (!itsCurrentFile.IsEmpty()) // reload file, in case it changed { const JString fileName = itsCurrentFile; const JIndex lineIndex = itsText->HasSelection() ? itsText->GetLineForChar(itsText->GetInsertionIndex()) : itsTable->GetCurrentLine(); itsCurrentFile.Clear(); // force reload DisplayFile(fileName, lineIndex); } } else if (IsMainSourceWindow() && sender == itsLink && message.Is(CMLink::kSymbolsLoaded)) { const CMLink::SymbolsLoaded* info = dynamic_cast<const CMLink::SymbolsLoaded*>(&message); assert( info != NULL ); UpdateWindowTitle(info->GetProgramName()); } else if (IsMainSourceWindow() && sender == itsLink && message.Is(CMLink::kProgramStopped)) { const CMLink::ProgramStopped* info = dynamic_cast<const CMLink::ProgramStopped*>(&message); assert( info != NULL); const CMLocation* loc; const JBoolean hasFile = info->GetLocation(&loc); if (itsType == kMainSourceType && hasFile) { DisplayFile(loc->GetFileName(), loc->GetLineNumber()); } else if (itsType == kMainAsmType && !loc->GetFunctionName().IsEmpty() && !loc->GetMemoryAddress().IsEmpty()) { DisplayDisassembly(*loc); } else if (itsType == kMainAsmType) { // wait for kProgramStopped2 } else { #ifdef _J_OLD_OSX itsTable->SetCurrentLine(0); // we get blank location the first time #else ClearDisplay(); (CMGetCommandDirector())->GetStackDir()->Activate(); #endif } } else if (itsType == kMainAsmType && sender == itsLink && message.Is(CMLink::kProgramStopped2)) { const CMLink::ProgramStopped2* info = dynamic_cast<const CMLink::ProgramStopped2*>(&message); assert( info != NULL); const CMLocation* loc; info->GetLocation(&loc); if (!loc->GetFunctionName().IsEmpty() && !loc->GetMemoryAddress().IsEmpty()) { DisplayDisassembly(*loc); } else { ClearDisplay(); } } else if (sender == itsLink && (message.Is(CMLink::kProgramFinished) || message.Is(CMLink::kCoreCleared) || message.Is(CMLink::kDetachedFromProcess))) { if (itsSrcMainCmd != NULL) { itsSrcMainCmd->CMCommand::Send(); } else if (itsType == kMainAsmType) { ClearDisplay(); } } else if (sender == itsFileMenu && message.Is(JXMenu::kNeedsUpdate)) { UpdateFileMenu(); } else if (sender == itsFileMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleFileMenu(selection->GetIndex()); } else if (sender == itsDebugMenu && message.Is(JXMenu::kNeedsUpdate)) { itsCommandDir->UpdateDebugMenu(itsDebugMenu, itsText, NULL); } else if (sender == itsDebugMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); itsCommandDir->HandleDebugMenu(itsDebugMenu, selection->GetIndex(), itsText, NULL); } else if (sender == itsPrefsMenu && message.Is(JXMenu::kNeedsUpdate)) { UpdatePrefsMenu(); } else if (sender == itsPrefsMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandlePrefsMenu(selection->GetIndex()); } else if (sender == itsHelpMenu && message.Is(JXMenu::kItemSelected)) { const JXMenu::ItemSelected* selection = dynamic_cast<const JXMenu::ItemSelected*>(&message); assert( selection != NULL ); HandleHelpMenu(selection->GetIndex()); } else if (sender == CMGetPrefsManager() && message.Is(CMPrefsManager::kFileTypesChanged)) { UpdateFileType(); } else if (sender == CMGetPrefsManager() && message.Is(CMPrefsManager::kCustomCommandsChanged)) { itsCommandDir->AdjustDebugMenu(itsDebugMenu); } else { JXWindowDirector::Receive(sender,message); } }
int main(int argc, char** argv) { RegisterExecutablePlatform(ExePlatformZone); Log.LoadLogSettingsDefaults(); set_exception_handler(); QServ = new QueryServ; Log.Out(Logs::General, Logs::Zone_Server, "Loading server configuration.."); if(!ZoneConfig::LoadConfig()) { Log.Out(Logs::General, Logs::Error, "Loading server configuration failed."); return 1; } Config = ZoneConfig::get(); const char *zone_name; uint32 instance_id = 0; std::string z_name; if(argc == 4) { instance_id = atoi(argv[3]); worldserver.SetLauncherName(argv[2]); auto zone_port = SplitString(argv[1], ':'); if(!zone_port.empty()) { z_name = zone_port[0]; } if(zone_port.size() > 1) { std::string p_name = zone_port[1]; Config->SetZonePort(atoi(p_name.c_str())); } worldserver.SetLaunchedName(z_name.c_str()); if(strncmp(z_name.c_str(), "dynamic_", 8) == 0) { zone_name = "."; } else { zone_name = z_name.c_str(); } } else if(argc == 3) { worldserver.SetLauncherName(argv[2]); auto zone_port = SplitString(argv[1], ':'); if(!zone_port.empty()) { z_name = zone_port[0]; } if(zone_port.size() > 1) { std::string p_name = zone_port[1]; Config->SetZonePort(atoi(p_name.c_str())); } worldserver.SetLaunchedName(z_name.c_str()); if(strncmp(z_name.c_str(), "dynamic_", 8) == 0) { zone_name = "."; } else { zone_name = z_name.c_str(); } } else if (argc == 2) { worldserver.SetLauncherName("NONE"); auto zone_port = SplitString(argv[1], ':'); if(!zone_port.empty()) { z_name = zone_port[0]; } if(zone_port.size() > 1) { std::string p_name = zone_port[1]; Config->SetZonePort(atoi(p_name.c_str())); } worldserver.SetLaunchedName(z_name.c_str()); if(strncmp(z_name.c_str(), "dynamic_", 8) == 0) { zone_name = "."; } else { zone_name = z_name.c_str(); } } else { zone_name = "."; worldserver.SetLaunchedName("."); worldserver.SetLauncherName("NONE"); } worldserver.SetPassword(Config->SharedKey.c_str()); Log.Out(Logs::General, Logs::Zone_Server, "Connecting to MySQL..."); if (!database.Connect( Config->DatabaseHost.c_str(), Config->DatabaseUsername.c_str(), Config->DatabasePassword.c_str(), Config->DatabaseDB.c_str(), Config->DatabasePort)) { Log.Out(Logs::General, Logs::Error, "Cannot continue without a database connection."); return 1; } #ifdef BOTS if (!botdb.Connect( Config->DatabaseHost.c_str(), Config->DatabaseUsername.c_str(), Config->DatabasePassword.c_str(), Config->DatabaseDB.c_str(), Config->DatabasePort)) { Log.Out(Logs::General, Logs::Error, "Cannot continue without a bots database connection."); return 1; } #endif /* Register Log System and Settings */ Log.OnLogHookCallBackZone(&Zone::GMSayHookCallBackProcess); database.LoadLogSettings(Log.log_settings); Log.StartFileLogs(); /* Guilds */ guild_mgr.SetDatabase(&database); GuildBanks = nullptr; #ifdef _EQDEBUG _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); #endif Log.Out(Logs::General, Logs::Zone_Server, "CURRENT_VERSION: %s", CURRENT_VERSION); /* * Setup nice signal handlers */ if (signal(SIGINT, CatchSignal) == SIG_ERR) { Log.Out(Logs::General, Logs::Error, "Could not set signal handler"); return 1; } if (signal(SIGTERM, CatchSignal) == SIG_ERR) { Log.Out(Logs::General, Logs::Error, "Could not set signal handler"); return 1; } #ifndef WIN32 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { Log.Out(Logs::General, Logs::Error, "Could not set signal handler"); return 1; } #endif Log.Out(Logs::General, Logs::Zone_Server, "Mapping Incoming Opcodes"); MapOpcodes(); Log.Out(Logs::General, Logs::Zone_Server, "Loading Variables"); database.LoadVariables(); std::string hotfix_name; if(database.GetVariable("hotfix_name", hotfix_name)) { if(!hotfix_name.empty()) { Log.Out(Logs::General, Logs::Zone_Server, "Current hotfix in use: '%s'", hotfix_name.c_str()); } } Log.Out(Logs::General, Logs::Zone_Server, "Loading zone names"); database.LoadZoneNames(); Log.Out(Logs::General, Logs::Zone_Server, "Loading items"); if(!database.LoadItems(hotfix_name)) { Log.Out(Logs::General, Logs::Error, "Loading items FAILED!"); Log.Out(Logs::General, Logs::Error, "Failed. But ignoring error and going on..."); } Log.Out(Logs::General, Logs::Zone_Server, "Loading npc faction lists"); if(!database.LoadNPCFactionLists(hotfix_name)) { Log.Out(Logs::General, Logs::Error, "Loading npcs faction lists FAILED!"); return 1; } Log.Out(Logs::General, Logs::Zone_Server, "Loading loot tables"); if(!database.LoadLoot(hotfix_name)) { Log.Out(Logs::General, Logs::Error, "Loading loot FAILED!"); return 1; } Log.Out(Logs::General, Logs::Zone_Server, "Loading skill caps"); if(!database.LoadSkillCaps(std::string(hotfix_name))) { Log.Out(Logs::General, Logs::Error, "Loading skill caps FAILED!"); return 1; } Log.Out(Logs::General, Logs::Zone_Server, "Loading spells"); if(!database.LoadSpells(hotfix_name, &SPDAT_RECORDS, &spells)) { Log.Out(Logs::General, Logs::Error, "Loading spells FAILED!"); return 1; } Log.Out(Logs::General, Logs::Zone_Server, "Loading base data"); if(!database.LoadBaseData(hotfix_name)) { Log.Out(Logs::General, Logs::Error, "Loading base data FAILED!"); return 1; } Log.Out(Logs::General, Logs::Zone_Server, "Loading guilds"); guild_mgr.LoadGuilds(); Log.Out(Logs::General, Logs::Zone_Server, "Loading factions"); database.LoadFactionData(); Log.Out(Logs::General, Logs::Zone_Server, "Loading titles"); title_manager.LoadTitles(); Log.Out(Logs::General, Logs::Zone_Server, "Loading tributes"); database.LoadTributes(); Log.Out(Logs::General, Logs::Zone_Server, "Loading corpse timers"); database.GetDecayTimes(npcCorpseDecayTimes); Log.Out(Logs::General, Logs::Zone_Server, "Loading commands"); int retval=command_init(); if(retval<0) Log.Out(Logs::General, Logs::Error, "Command loading FAILED"); else Log.Out(Logs::General, Logs::Zone_Server, "%d commands loaded", retval); //rules: { std::string tmp; if (database.GetVariable("RuleSet", tmp)) { Log.Out(Logs::General, Logs::Zone_Server, "Loading rule set '%s'", tmp.c_str()); if(!RuleManager::Instance()->LoadRules(&database, tmp.c_str())) { Log.Out(Logs::General, Logs::Error, "Failed to load ruleset '%s', falling back to defaults.", tmp.c_str()); } } else { if(!RuleManager::Instance()->LoadRules(&database, "default")) { Log.Out(Logs::General, Logs::Zone_Server, "No rule set configured, using default rules"); } else { Log.Out(Logs::General, Logs::Zone_Server, "Loaded default rule set 'default'", tmp.c_str()); } } } #ifdef BOTS Log.Out(Logs::General, Logs::Zone_Server, "Loading bot commands"); int botretval = bot_command_init(); if (botretval<0) Log.Out(Logs::General, Logs::Error, "Bot command loading FAILED"); else Log.Out(Logs::General, Logs::Zone_Server, "%d bot commands loaded", botretval); #endif if(RuleB(TaskSystem, EnableTaskSystem)) { Log.Out(Logs::General, Logs::Tasks, "[INIT] Loading Tasks"); taskmanager = new TaskManager; taskmanager->LoadTasks(); } parse = new QuestParserCollection(); #ifdef LUA_EQEMU auto lua_parser = new LuaParser(); parse->RegisterQuestInterface(lua_parser, "lua"); #endif #ifdef EMBPERL auto perl_parser = new PerlembParser(); parse->RegisterQuestInterface(perl_parser, "pl"); /* Load Perl Event Export Settings */ parse->LoadPerlEventExportSettings(parse->perl_event_export_settings); #endif //now we have our parser, load the quests Log.Out(Logs::General, Logs::Zone_Server, "Loading quests"); parse->ReloadQuests(); if (!worldserver.Connect()) { Log.Out(Logs::General, Logs::Error, "Worldserver Connection Failed :: worldserver.Connect()"); } Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect #ifdef EQPROFILE #ifdef PROFILE_DUMP_TIME Timer profile_dump_timer(PROFILE_DUMP_TIME*1000); profile_dump_timer.Start(); #endif #endif if (!strlen(zone_name) || !strcmp(zone_name,".")) { Log.Out(Logs::General, Logs::Zone_Server, "Entering sleep mode"); } else if (!Zone::Bootup(database.GetZoneID(zone_name), instance_id, true)) { Log.Out(Logs::General, Logs::Error, "Zone Bootup failed :: Zone::Bootup"); zone = 0; } //register all the patches we have avaliable with the stream identifier. EQStreamIdentifier stream_identifier; RegisterAllPatches(stream_identifier); #ifndef WIN32 Log.Out(Logs::Detail, Logs::None, "Main thread running with thread id %d", pthread_self()); #endif Timer quest_timers(100); UpdateWindowTitle(); bool worldwasconnected = worldserver.Connected(); std::shared_ptr<EQStream> eqss; EQStreamInterface *eqsi; uint8 IDLEZONEUPDATE = 200; uint8 ZONEUPDATE = 10; Timer zoneupdate_timer(ZONEUPDATE); zoneupdate_timer.Start(); while(RunLoops) { { //profiler block to omit the sleep from times //Advance the timer to our current point in time Timer::SetCurrentTime(); worldserver.Process(); if (!eqsf.IsOpen() && Config->ZonePort != 0) { Log.Out(Logs::General, Logs::Zone_Server, "Starting EQ Network server on port %d", Config->ZonePort); if (!eqsf.Open(Config->ZonePort)) { Log.Out(Logs::General, Logs::Error, "Failed to open port %d", Config->ZonePort); ZoneConfig::SetZonePort(0); worldserver.Disconnect(); worldwasconnected = false; } } //check the factory for any new incoming streams. while ((eqss = eqsf.Pop())) { //pull the stream out of the factory and give it to the stream identifier //which will figure out what patch they are running, and set up the dynamic //structures and opcodes for that patch. struct in_addr in; in.s_addr = eqss->GetRemoteIP(); Log.Out(Logs::Detail, Logs::World_Server, "New connection from %s:%d", inet_ntoa(in), ntohs(eqss->GetRemotePort())); stream_identifier.AddStream(eqss); //takes the stream } //give the stream identifier a chance to do its work.... stream_identifier.Process(); //check the stream identifier for any now-identified streams while((eqsi = stream_identifier.PopIdentified())) { //now that we know what patch they are running, start up their client object struct in_addr in; in.s_addr = eqsi->GetRemoteIP(); Log.Out(Logs::Detail, Logs::World_Server, "New client from %s:%d", inet_ntoa(in), ntohs(eqsi->GetRemotePort())); auto client = new Client(eqsi); entity_list.AddClient(client); } if ( numclients < 1 && zoneupdate_timer.GetDuration() != IDLEZONEUPDATE ) zoneupdate_timer.SetTimer(IDLEZONEUPDATE); else if ( numclients > 0 && zoneupdate_timer.GetDuration() == IDLEZONEUPDATE ) { zoneupdate_timer.SetTimer(ZONEUPDATE); zoneupdate_timer.Trigger(); } //check for timeouts in other threads timeout_manager.CheckTimeouts(); if (worldserver.Connected()) { worldwasconnected = true; } else { if (worldwasconnected && is_zone_loaded) entity_list.ChannelMessageFromWorld(0, 0, 6, 0, 0, "WARNING: World server connection lost"); worldwasconnected = false; } if (is_zone_loaded && zoneupdate_timer.Check()) { { if(net.group_timer.Enabled() && net.group_timer.Check()) entity_list.GroupProcess(); if(net.door_timer.Enabled() && net.door_timer.Check()) entity_list.DoorProcess(); if(net.object_timer.Enabled() && net.object_timer.Check()) entity_list.ObjectProcess(); if(net.corpse_timer.Enabled() && net.corpse_timer.Check()) entity_list.CorpseProcess(); if(net.trap_timer.Enabled() && net.trap_timer.Check()) entity_list.TrapProcess(); if(net.raid_timer.Enabled() && net.raid_timer.Check()) entity_list.RaidProcess(); entity_list.Process(); entity_list.MobProcess(); entity_list.BeaconProcess(); entity_list.EncounterProcess(); if (zone) { if(!zone->Process()) { Zone::Shutdown(); } } if(quest_timers.Check()) quest_manager.Process(); } } if (InterserverTimer.Check()) { InterserverTimer.Start(); database.ping(); // AsyncLoadVariables(dbasync, &database); entity_list.UpdateWho(); if (worldserver.TryReconnect() && (!worldserver.Connected())) worldserver.AsyncConnect(); } #ifdef EQPROFILE #ifdef PROFILE_DUMP_TIME if(profile_dump_timer.Check()) { DumpZoneProfile(); } #endif #endif } //end extra profiler block Sleep(ZoneTimerResolution); } entity_list.Clear(); parse->ClearInterfaces(); #ifdef EMBPERL safe_delete(perl_parser); #endif #ifdef LUA_EQEMU safe_delete(lua_parser); #endif safe_delete(Config); if (zone != 0) Zone::Shutdown(true); //Fix for Linux world server problem. eqsf.Close(); worldserver.Disconnect(); safe_delete(taskmanager); command_deinit(); #ifdef BOTS bot_command_deinit(); #endif safe_delete(parse); Log.Out(Logs::General, Logs::Zone_Server, "Proper zone shutdown complete."); Log.CloseFileLogs(); return 0; }
// Update frame-based values. void D3D12HeterogeneousMultiadapter::OnUpdate() { // Add the oldest timestamp data to our moving average counters. // Use the oldest timestamp index to limit CPU waits. { // The oldest frame is the current frame index and it will always be complete due to the wait in MoveToNextFrame(). const UINT oldestFrameIndex = m_frameIndex; assert(m_frameFenceValues[oldestFrameIndex] <= m_frameFence->GetCompletedValue()); // Get the timestamp values from the result buffers. D3D12_RANGE readRange = {}; const D3D12_RANGE emptyRange = {}; UINT64* ppMovingAverage[] = { m_drawTimes, m_blurTimes }; for (UINT i = 0; i < GraphicsAdaptersCount; i++) { readRange.Begin = 2 * oldestFrameIndex * sizeof(UINT64); readRange.End = readRange.Begin + 2 * sizeof(UINT64); void* pData = nullptr; ThrowIfFailed(m_timestampResultBuffers[i]->Map(0, &readRange, &pData)); const UINT64* pTimestamps = reinterpret_cast<UINT64*>(static_cast<UINT8*>(pData) + readRange.Begin); const UINT64 timeStampDelta = pTimestamps[1] - pTimestamps[0]; // Unmap with an empty range (written range). m_timestampResultBuffers[i]->Unmap(0, &emptyRange); // Calculate the GPU execution time in microseconds. const UINT64 gpuTimeUS = (timeStampDelta * 1000000) / m_directCommandQueueTimestampFrequencies[i]; ppMovingAverage[i][m_currentTimesIndex] = gpuTimeUS; } // Move to the next index. m_currentTimesIndex = (m_currentTimesIndex + 1) % MovingAverageFrameCount; } // Dynamically change the workload on the primary adapter. This is a VERY naive implementation. // The point here is to show that applications have a choice with how to spend their extra cycles. // Note: If copies take longer then you should take that into account as well. { static UINT64 framesSinceLastUpdate = 0; framesSinceLastUpdate++; if (framesSinceLastUpdate > MovingAverageFrameCount) { // Calculate the average draw and blur times for last few frames. m_drawTimeMovingAverage = 0; m_blurTimeMovingAverage = 0; for (UINT i = 0; i < MovingAverageFrameCount; i++) { m_drawTimeMovingAverage += m_drawTimes[i]; m_blurTimeMovingAverage += m_blurTimes[i]; } m_drawTimeMovingAverage /= MovingAverageFrameCount; m_blurTimeMovingAverage /= MovingAverageFrameCount; framesSinceLastUpdate = 0; // Adjust the shader blur time to be at least 20ms/frame. // Note: This is just done to show that we can reach ~100% utilization of both adapters. if (AllowShaderDynamicWorkload) { const UINT64 desiredBlurPSTimeUS = 20000; // 20 ms if (m_blurTimeMovingAverage < desiredBlurPSTimeUS || m_blurPSLoopCount != 0) { // Adjust the PS blur time based on the moving average. const float timeDelta = (static_cast<float>(desiredBlurPSTimeUS) - static_cast<float>(m_blurTimeMovingAverage)) / static_cast<float>(m_blurTimeMovingAverage); if (timeDelta < -.05f || timeDelta > .01f) { const float stepSize = max(1.0f, m_blurPSLoopCount); m_blurPSLoopCount += static_cast<INT>(stepSize * timeDelta); } } } // Adjust the render time to be greater than the blur time. { const UINT64 desiredDrawPSTimeUS = m_blurTimeMovingAverage + static_cast<UINT64>(m_blurTimeMovingAverage * .10f); const float timeDelta = (static_cast<float>(desiredDrawPSTimeUS) - static_cast<float>(m_drawTimeMovingAverage)) / static_cast<float>(m_drawTimeMovingAverage); if (timeDelta < -.10f || timeDelta > .01f) { if (AllowDrawDynamicWorkload) { // Adjust the number of triangles drawn. const float stepSize = max(1.0f, m_triangleCount); m_triangleCount = min(m_triangleCount + static_cast<INT>(stepSize * timeDelta), MaxTriangleCount); } else if (AllowShaderDynamicWorkload) { // Adjust the number of the PS loop count based on the moving average. const float stepSize = max(1.0f, m_psLoopCount); m_psLoopCount += static_cast<INT>(stepSize * timeDelta); } } } } // Conditionally update the window's title. if (framesSinceLastUpdate % WindowTextUpdateFrequency == 0) { UpdateWindowTitle(); } } // Update the workloads. { WorkloadConstantBufferData* pWorkloadDst = m_pWorkloadCbvDataBegin + m_frameIndex; WorkloadConstantBufferData* pWorkloadSrc = &m_workloadConstantBufferData; pWorkloadSrc->loopCount = m_psLoopCount; memcpy(pWorkloadDst, pWorkloadSrc, sizeof(WorkloadConstantBufferData)); WorkloadConstantBufferData* pBlurWorkloadDst = m_pBlurWorkloadCbvDataBegin + m_frameIndex; WorkloadConstantBufferData* pBlurWorkloadSrc = &m_blurWorkloadConstantBufferData; pBlurWorkloadSrc->loopCount = m_blurPSLoopCount; memcpy(pBlurWorkloadDst, pBlurWorkloadSrc, sizeof(WorkloadConstantBufferData)); } // Update the triangles. { const float offsetBounds = 2.5f; for (UINT n = 0; n < m_triangleCount; n++) { // Animate the triangles. m_constantBufferData[n].offset.x += m_constantBufferData[n].velocity.x; if (m_constantBufferData[n].offset.x > offsetBounds) { m_constantBufferData[n].velocity.x = GetRandomFloat(0.01f, 0.02f); m_constantBufferData[n].offset.x = -offsetBounds; } } ConstantBufferData* dst = m_pCbvDataBegin + (m_frameIndex * MaxTriangleCount); memcpy(dst, &m_constantBufferData[0], m_triangleCount * sizeof(ConstantBufferData)); } }
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: break; case WM_GETMINMAXINFO: { MINMAXINFO *minmax = reinterpret_cast<MINMAXINFO *>(lParam); RECT rc = { 0 }; bool portrait = g_Config.IsPortrait(); rc.right = portrait ? 272 : 480; rc.bottom = portrait ? 480 : 272; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, TRUE); minmax->ptMinTrackSize.x = rc.right - rc.left; minmax->ptMinTrackSize.y = rc.bottom - rc.top; } return 0; case WM_ACTIVATE: { bool pause = true; if (wParam == WA_ACTIVE || wParam == WA_CLICKACTIVE) { WindowsRawInput::GainFocus(); InputDevice::GainFocus(); g_activeWindow = WINDOW_MAINWINDOW; pause = false; } if (!noFocusPause && g_Config.bPauseOnLostFocus && GetUIState() == UISTATE_INGAME) { if (pause != Core_IsStepping()) { // != is xor for bools if (disasmWindow[0]) SendMessage(disasmWindow[0]->GetDlgHandle(), WM_COMMAND, IDC_STOPGO, 0); else Core_EnableStepping(pause); } } if (wParam == WA_ACTIVE) { NativeMessageReceived("got_focus", ""); } if (wParam == WA_INACTIVE) { NativeMessageReceived("lost_focus", ""); WindowsRawInput::LoseFocus(); InputDevice::LoseFocus(); } } break; case WM_ERASEBKGND: // This window is always covered by DisplayWindow. No reason to erase. return 1; case WM_MOVE: SavePosition(); break; case WM_SIZE: switch (wParam) { case SIZE_RESTORED: case SIZE_MAXIMIZED: if (g_IgnoreWM_SIZE) { return DefWindowProc(hWnd, message, wParam, lParam); } else { SavePosition(); Core_NotifyWindowHidden(false); if (!g_Config.bPauseWhenMinimized) { NativeMessageReceived("window minimized", "false"); } int width = 0, height = 0; RECT rc; GetClientRect(hwndMain, &rc); width = rc.right - rc.left; height = rc.bottom - rc.top; // Moves the internal display window to match the inner size of the main window. MoveWindow(hwndDisplay, 0, 0, width, height, TRUE); // Setting pixelWidth to be too small could have odd consequences. if (width >= 4 && height >= 4) { // The framebuffer manager reads these once per frame, hopefully safe enough.. should really use a mutex or some // much better mechanism. PSP_CoreParameter().pixelWidth = width; PSP_CoreParameter().pixelHeight = height; } UpdateRenderResolution(); if (UpdateScreenScale(width, height, IsWindowSmall())) { NativeMessageReceived("gpu resized", ""); } // Don't save the window state if fullscreen. if (!g_Config.bFullScreen) { g_WindowState = wParam; } } break; case SIZE_MINIMIZED: Core_NotifyWindowHidden(true); if (!g_Config.bPauseWhenMinimized) { NativeMessageReceived("window minimized", "true"); } break; default: break; } break; case WM_TIMER: // Hack: Take the opportunity to also show/hide the mouse cursor in fullscreen mode. switch (wParam) { case TIMER_CURSORUPDATE: CorrectCursor(); return 0; case TIMER_CURSORMOVEUPDATE: hideCursor = true; KillTimer(hWnd, TIMER_CURSORMOVEUPDATE); return 0; } break; // For some reason, need to catch this here rather than in DisplayProc. case WM_MOUSEWHEEL: { int wheelDelta = (short)(wParam >> 16); KeyInput key; key.deviceId = DEVICE_ID_MOUSE; if (wheelDelta < 0) { key.keyCode = NKCODE_EXT_MOUSEWHEEL_DOWN; wheelDelta = -wheelDelta; } else { key.keyCode = NKCODE_EXT_MOUSEWHEEL_UP; } // There's no separate keyup event for mousewheel events, let's pass them both together. // This also means it really won't work great for key mapping :( Need to build a 1 frame delay or something. key.flags = KEY_DOWN | KEY_UP | KEY_HASWHEELDELTA | (wheelDelta << 16); NativeKey(key); } break; case WM_COMMAND: { if (!EmuThread_Ready()) return DefWindowProc(hWnd, message, wParam, lParam); MainWindowMenu_Process(hWnd, wParam); } break; case WM_USER_TOGGLE_FULLSCREEN: ToggleFullscreen(hwndMain, !g_Config.bFullScreen); break; case WM_INPUT: return WindowsRawInput::Process(hWnd, wParam, lParam); // TODO: Could do something useful with WM_INPUT_DEVICE_CHANGE? // Not sure why we are actually getting WM_CHAR even though we use RawInput, but alright.. case WM_CHAR: return WindowsRawInput::ProcessChar(hWnd, wParam, lParam); case WM_VERYSLEEPY_MSG: switch (wParam) { case VERYSLEEPY_WPARAM_SUPPORTED: return TRUE; case VERYSLEEPY_WPARAM_GETADDRINFO: { VerySleepy_AddrInfo *info = (VerySleepy_AddrInfo *)lParam; const u8 *ptr = (const u8 *)info->addr; std::string name; if (MIPSComp::jit && MIPSComp::jit->DescribeCodePtr(ptr, name)) { swprintf_s(info->name, L"Jit::%S", name.c_str()); return TRUE; } if (gpu && gpu->DescribeCodePtr(ptr, name)) { swprintf_s(info->name, L"GPU::%S", name.c_str()); return TRUE; } } return FALSE; default: return FALSE; } break; case WM_DROPFILES: { if (!EmuThread_Ready()) return DefWindowProc(hWnd, message, wParam, lParam); HDROP hdrop = (HDROP)wParam; int count = DragQueryFile(hdrop,0xFFFFFFFF,0,0); if (count != 1) { MessageBox(hwndMain,L"You can only load one file at a time",L"Error",MB_ICONINFORMATION); } else { TCHAR filename[512]; DragQueryFile(hdrop,0,filename,512); TCHAR *type = filename+_tcslen(filename)-3; NativeMessageReceived("boot", ConvertWStringToUTF8(filename).c_str()); Core_EnableStepping(false); } } break; case WM_CLOSE: EmuThread_Stop(); InputDevice::StopPolling(); WindowsRawInput::Shutdown(); return DefWindowProc(hWnd,message,wParam,lParam); case WM_DESTROY: KillTimer(hWnd, TIMER_CURSORUPDATE); KillTimer(hWnd, TIMER_CURSORMOVEUPDATE); PostQuitMessage(0); break; case WM_USER + 1: if (disasmWindow[0]) disasmWindow[0]->NotifyMapLoaded(); if (memoryWindow[0]) memoryWindow[0]->NotifyMapLoaded(); if (disasmWindow[0]) disasmWindow[0]->UpdateDialog(); SetForegroundWindow(hwndMain); break; case WM_USER_SAVESTATE_FINISH: SetCursor(LoadCursor(0, IDC_ARROW)); break; case WM_USER_UPDATE_UI: TranslateMenus(hwndMain, menu); break; case WM_USER_UPDATE_SCREEN: ShowScreenResolution(); break; case WM_USER_WINDOW_TITLE_CHANGED: UpdateWindowTitle(); break; case WM_USER_BROWSE_BOOT_DONE: BrowseAndBootDone(); break; case WM_MENUSELECT: // Unfortunately, accelerate keys (hotkeys) shares the same enabled/disabled states // with corresponding menu items. UpdateMenus(); WindowsRawInput::NotifyMenu(); break; // Turn off the screensaver. // Note that if there's a screensaver password, this simple method // doesn't work on Vista or higher. case WM_SYSCOMMAND: { switch (wParam) { case SC_SCREENSAVE: return 0; case SC_MONITORPOWER: return 0; } return DefWindowProc(hWnd, message, wParam, lParam); } default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
int main(int argc, char** argv) { RegisterExecutablePlatform(ExePlatformWorld); LogSys.LoadLogSettingsDefaults(); set_exception_handler(); /* Database Version Check */ uint32 Database_Version = CURRENT_BINARY_DATABASE_VERSION; uint32 Bots_Database_Version = CURRENT_BINARY_BOTS_DATABASE_VERSION; if (argc >= 2) { if (strcasecmp(argv[1], "db_version") == 0) { std::cout << "Binary Database Version: " << Database_Version << " : " << Bots_Database_Version << std::endl; return 0; } } // Load server configuration Log(Logs::General, Logs::World_Server, "Loading server configuration.."); if (!WorldConfig::LoadConfig()) { Log(Logs::General, Logs::World_Server, "Loading server configuration failed."); return 1; } Config = WorldConfig::get(); Log(Logs::General, Logs::World_Server, "CURRENT_VERSION: %s", CURRENT_VERSION); if (signal(SIGINT, CatchSignal) == SIG_ERR) { Log(Logs::General, Logs::World_Server, "Could not set signal handler"); return 1; } if (signal(SIGTERM, CatchSignal) == SIG_ERR) { Log(Logs::General, Logs::World_Server, "Could not set signal handler"); return 1; } #ifndef WIN32 if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) { Log(Logs::General, Logs::World_Server, "Could not set signal handler"); return 1; } #endif // add login server config to list if (Config->LoginCount == 0) { if (Config->LoginHost.length()) { loginserverlist.Add(Config->LoginHost.c_str(), Config->LoginPort, Config->LoginAccount.c_str(), Config->LoginPassword.c_str(), Config->LoginLegacy); Log(Logs::General, Logs::World_Server, "Added loginserver %s:%i", Config->LoginHost.c_str(), Config->LoginPort); } } else { LinkedList<LoginConfig*> loginlist = Config->loginlist; LinkedListIterator<LoginConfig*> iterator(loginlist); iterator.Reset(); while (iterator.MoreElements()) { loginserverlist.Add(iterator.GetData()->LoginHost.c_str(), iterator.GetData()->LoginPort, iterator.GetData()->LoginAccount.c_str(), iterator.GetData()->LoginPassword.c_str(), iterator.GetData()->LoginLegacy); Log(Logs::General, Logs::World_Server, "Added loginserver %s:%i", iterator.GetData()->LoginHost.c_str(), iterator.GetData()->LoginPort); iterator.Advance(); } } Log(Logs::General, Logs::World_Server, "Connecting to MySQL..."); if (!database.Connect( Config->DatabaseHost.c_str(), Config->DatabaseUsername.c_str(), Config->DatabasePassword.c_str(), Config->DatabaseDB.c_str(), Config->DatabasePort)) { Log(Logs::General, Logs::World_Server, "Cannot continue without a database connection."); return 1; } guild_mgr.SetDatabase(&database); /* Register Log System and Settings */ database.LoadLogSettings(LogSys.log_settings); LogSys.StartFileLogs(); bool ignore_db = false; if (argc >= 2) { std::string tmp; if (strcasecmp(argv[1], "help") == 0 || strcasecmp(argv[1], "?") == 0 || strcasecmp(argv[1], "/?") == 0 || strcasecmp(argv[1], "-?") == 0 || strcasecmp(argv[1], "-h") == 0 || strcasecmp(argv[1], "-help") == 0) { std::cout << "Worldserver command line commands:" << std::endl; std::cout << "adduser username password flag - adds a user account" << std::endl; std::cout << "flag username flag - sets GM flag on the account" << std::endl; std::cout << "startzone zoneshortname - sets the starting zone" << std::endl; std::cout << "-holdzones - reboots lost zones" << std::endl; return 0; } else if (strcasecmp(argv[1], "-holdzones") == 0) { std::cout << "Reboot Zones mode ON" << std::endl; holdzones = true; } else if (database.GetVariable("disablecommandline", tmp)) { if (tmp.length() == 1) { if (tmp[0] == '1') { std::cerr << "Command line disabled in database... exiting" << std::endl; return 1; } } } else if (strcasecmp(argv[1], "adduser") == 0) { if (argc == 5) { if (Seperator::IsNumber(argv[4])) { if (atoi(argv[4]) >= 0 && atoi(argv[4]) <= 255) { if (database.CreateAccount(argv[2], argv[3], atoi(argv[4])) == 0) { std::cerr << "database.CreateAccount failed." << std::endl; return 1; } else { std::cout << "Account created: Username='******', Password='******', status=" << argv[4] << std::endl; return 0; } } } } std::cout << "Usage: world adduser username password flag" << std::endl; std::cout << "flag = 0, 1 or 2" << std::endl; return 0; } else if (strcasecmp(argv[1], "flag") == 0) { if (argc == 4) { if (Seperator::IsNumber(argv[3])) { if (atoi(argv[3]) >= 0 && atoi(argv[3]) <= 255) { if (database.SetAccountStatus(argv[2], atoi(argv[3]))) { std::cout << "Account flagged: Username='******', status=" << argv[3] << std::endl; return 0; } else { std::cerr << "database.SetAccountStatus failed." << std::endl; return 1; } } } } std::cout << "Usage: world flag username flag" << std::endl; std::cout << "flag = 0-200" << std::endl; return 0; } else if (strcasecmp(argv[1], "startzone") == 0) { if (argc == 3) { if (strlen(argv[2]) < 3) { std::cerr << "Error: zone name too short" << std::endl; return 1; } else if (strlen(argv[2]) > 15) { std::cerr << "Error: zone name too long" << std::endl; return 1; } else { if (database.SetVariable("startzone", argv[2])) { std::cout << "Starting zone changed: '" << argv[2] << "'" << std::endl; return 0; } else { std::cerr << "database.SetVariable failed." << std::endl; return 1; } } } std::cout << "Usage: world startzone zoneshortname" << std::endl; return 0; } else if (strcasecmp(argv[1], "ignore_db") == 0) { ignore_db = true; } else { std::cerr << "Error, unknown command line option" << std::endl; return 1; } } if (!ignore_db) { Log(Logs::General, Logs::World_Server, "Checking Database Conversions.."); database.CheckDatabaseConversions(); } Log(Logs::General, Logs::World_Server, "Loading variables.."); database.LoadVariables(); std::string hotfix_name; if (database.GetVariable("hotfix_name", hotfix_name)) { if (!hotfix_name.empty()) { Log(Logs::General, Logs::Zone_Server, "Current hotfix in use: '%s'", hotfix_name.c_str()); } } Log(Logs::General, Logs::World_Server, "Loading zones.."); database.LoadZoneNames(); Log(Logs::General, Logs::World_Server, "Clearing groups.."); database.ClearGroup(); Log(Logs::General, Logs::World_Server, "Clearing raids.."); database.ClearRaid(); database.ClearRaidDetails(); database.ClearRaidLeader(); Log(Logs::General, Logs::World_Server, "Clearing inventory snapshots.."); database.ClearInvSnapshots(); Log(Logs::General, Logs::World_Server, "Loading items.."); if (!database.LoadItems(hotfix_name)) Log(Logs::General, Logs::World_Server, "Error: Could not load item data. But ignoring"); Log(Logs::General, Logs::World_Server, "Loading skill caps.."); if (!database.LoadSkillCaps(std::string(hotfix_name))) Log(Logs::General, Logs::World_Server, "Error: Could not load skill cap data. But ignoring"); Log(Logs::General, Logs::World_Server, "Loading guilds.."); guild_mgr.LoadGuilds(); //rules: { std::string tmp; if (database.GetVariable("RuleSet", tmp)) { Log(Logs::General, Logs::World_Server, "Loading rule set '%s'", tmp.c_str()); if (!RuleManager::Instance()->LoadRules(&database, tmp.c_str())) { Log(Logs::General, Logs::World_Server, "Failed to load ruleset '%s', falling back to defaults.", tmp.c_str()); } } else { if (!RuleManager::Instance()->LoadRules(&database, "default")) { Log(Logs::General, Logs::World_Server, "No rule set configured, using default rules"); } else { Log(Logs::General, Logs::World_Server, "Loaded default rule set 'default'", tmp.c_str()); } } } if (RuleB(World, ClearTempMerchantlist)) { Log(Logs::General, Logs::World_Server, "Clearing temporary merchant lists.."); database.ClearMerchantTemp(); } RuleManager::Instance()->SaveRules(&database); Log(Logs::General, Logs::World_Server, "Loading EQ time of day.."); TimeOfDay_Struct eqTime; time_t realtime; eqTime = database.LoadTime(realtime); zoneserver_list.worldclock.SetCurrentEQTimeOfDay(eqTime, realtime); Timer EQTimeTimer(600000); EQTimeTimer.Start(600000); Log(Logs::General, Logs::World_Server, "Loading launcher list.."); launcher_list.LoadList(); std::string tmp; database.GetVariable("holdzones", tmp); if (tmp.length() == 1 && tmp[0] == '1') { holdzones = true; } Log(Logs::General, Logs::World_Server, "Reboot zone modes %s", holdzones ? "ON" : "OFF"); Log(Logs::General, Logs::World_Server, "Deleted %i stale player corpses from database", database.DeleteStalePlayerCorpses()); Log(Logs::General, Logs::World_Server, "Loading adventures..."); if (!adventure_manager.LoadAdventureTemplates()) { Log(Logs::General, Logs::World_Server, "Unable to load adventure templates."); } if (!adventure_manager.LoadAdventureEntries()) { Log(Logs::General, Logs::World_Server, "Unable to load adventure templates."); } adventure_manager.Load(); adventure_manager.LoadLeaderboardInfo(); Log(Logs::General, Logs::World_Server, "Purging expired instances"); database.PurgeExpiredInstances(); Timer PurgeInstanceTimer(450000); PurgeInstanceTimer.Start(450000); Log(Logs::General, Logs::World_Server, "Loading char create info..."); database.LoadCharacterCreateAllocations(); database.LoadCharacterCreateCombos(); std::unique_ptr<EQ::Net::ConsoleServer> console; if (Config->TelnetEnabled) { Log(Logs::General, Logs::World_Server, "Console (TCP) listener started."); console.reset(new EQ::Net::ConsoleServer(Config->TelnetIP, Config->TelnetTCPPort)); RegisterConsoleFunctions(console); } std::unique_ptr<EQ::Net::ServertalkServer> server_connection; server_connection.reset(new EQ::Net::ServertalkServer()); EQ::Net::ServertalkServerOptions server_opts; server_opts.port = Config->WorldTCPPort; server_opts.ipv6 = false; server_opts.credentials = Config->SharedKey; server_connection->Listen(server_opts); Log(Logs::General, Logs::World_Server, "Server (TCP) listener started."); server_connection->OnConnectionIdentified("Zone", [&console](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "New Zone Server connection from {2} at {0}:{1}", connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID()); numzones++; zoneserver_list.Add(new ZoneServer(connection, console.get())); }); server_connection->OnConnectionRemoved("Zone", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "Removed Zone Server connection from {0}", connection->GetUUID()); numzones--; zoneserver_list.Remove(connection->GetUUID()); }); server_connection->OnConnectionIdentified("Launcher", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "New Launcher connection from {2} at {0}:{1}", connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID()); launcher_list.Add(connection); }); server_connection->OnConnectionRemoved("Launcher", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "Removed Launcher connection from {0}", connection->GetUUID()); launcher_list.Remove(connection); }); server_connection->OnConnectionIdentified("QueryServ", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "New Query Server connection from {2} at {0}:{1}", connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID()); QSLink.AddConnection(connection); }); server_connection->OnConnectionRemoved("QueryServ", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "Removed Query Server connection from {0}", connection->GetUUID()); QSLink.RemoveConnection(connection); }); server_connection->OnConnectionIdentified("UCS", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "New UCS Server connection from {2} at {0}:{1}", connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID()); UCSLink.SetConnection(connection); }); server_connection->OnConnectionRemoved("UCS", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "Removed Query Server connection from {0}", connection->GetUUID()); UCSLink.SetConnection(nullptr); }); server_connection->OnConnectionIdentified("WebInterface", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "New WebInterface Server connection from {2} at {0}:{1}", connection->Handle()->RemoteIP(), connection->Handle()->RemotePort(), connection->GetUUID()); web_interface.AddConnection(connection); }); server_connection->OnConnectionRemoved("WebInterface", [](std::shared_ptr<EQ::Net::ServertalkServerConnection> connection) { LogF(Logs::General, Logs::World_Server, "Removed WebInterface Server connection from {0}", connection->GetUUID()); web_interface.RemoveConnection(connection); }); EQ::Net::EQStreamManagerOptions opts(9000, false, false); EQ::Net::EQStreamManager eqsm(opts); //register all the patches we have avaliable with the stream identifier. EQStreamIdentifier stream_identifier; RegisterAllPatches(stream_identifier); zoneserver_list.shutdowntimer = new Timer(60000); zoneserver_list.shutdowntimer->Disable(); zoneserver_list.reminder = new Timer(20000); zoneserver_list.reminder->Disable(); Timer InterserverTimer(INTERSERVER_TIMER); // does MySQL pings and auto-reconnect InterserverTimer.Trigger(); uint8 ReconnectCounter = 100; std::shared_ptr<EQStreamInterface> eqs; EQStreamInterface *eqsi; eqsm.OnNewConnection([&stream_identifier](std::shared_ptr<EQ::Net::EQStream> stream) { stream_identifier.AddStream(stream); LogF(Logs::Detail, Logs::World_Server, "New connection from IP {0}:{1}", stream->RemoteEndpoint(), ntohs(stream->GetRemotePort())); }); while (RunLoops) { Timer::SetCurrentTime(); eqs = nullptr; //give the stream identifier a chance to do its work.... stream_identifier.Process(); //check the stream identifier for any now-identified streams while ((eqsi = stream_identifier.PopIdentified())) { //now that we know what patch they are running, start up their client object struct in_addr in; in.s_addr = eqsi->GetRemoteIP(); if (RuleB(World, UseBannedIPsTable)) { //Lieka: Check to see if we have the responsibility for blocking IPs. Log(Logs::Detail, Logs::World_Server, "Checking inbound connection %s against BannedIPs table", inet_ntoa(in)); if (!database.CheckBannedIPs(inet_ntoa(in))) { //Lieka: Check inbound IP against banned IP table. Log(Logs::Detail, Logs::World_Server, "Connection %s PASSED banned IPs check. Processing connection.", inet_ntoa(in)); auto client = new Client(eqsi); // @merth: client->zoneattempt=0; client_list.Add(client); } else { Log(Logs::General, Logs::World_Server, "Connection from %s FAILED banned IPs check. Closing connection.", inet_ntoa(in)); eqsi->Close(); //Lieka: If the inbound IP is on the banned table, close the EQStream. } } if (!RuleB(World, UseBannedIPsTable)) { Log(Logs::Detail, Logs::World_Server, "New connection from %s:%d, processing connection", inet_ntoa(in), ntohs(eqsi->GetRemotePort())); auto client = new Client(eqsi); // @merth: client->zoneattempt=0; client_list.Add(client); } } client_list.Process(); if (PurgeInstanceTimer.Check()) { database.PurgeExpiredInstances(); } if (EQTimeTimer.Check()) { TimeOfDay_Struct tod; zoneserver_list.worldclock.GetCurrentEQTimeOfDay(time(0), &tod); if (!database.SaveTime(tod.minute, tod.hour, tod.day, tod.month, tod.year)) Log(Logs::General, Logs::World_Server, "Failed to save eqtime."); else Log(Logs::Detail, Logs::World_Server, "EQTime successfully saved."); } zoneserver_list.Process(); launcher_list.Process(); LFPGroupList.Process(); adventure_manager.Process(); if (InterserverTimer.Check()) { InterserverTimer.Start(); database.ping(); std::string window_title = StringFormat("World: %s Clients: %i", Config->LongName.c_str(), client_list.GetClientCount()); UpdateWindowTitle(window_title); } EQ::EventLoop::Get().Process(); Sleep(5); } Log(Logs::General, Logs::World_Server, "World main loop completed."); Log(Logs::General, Logs::World_Server, "Shutting down zone connections (if any)."); zoneserver_list.KillAll(); Log(Logs::General, Logs::World_Server, "Zone (TCP) listener stopped."); Log(Logs::General, Logs::World_Server, "Signaling HTTP service to stop..."); LogSys.CloseFileLogs(); return 0; }