SyntaxTypeMatch CheckConstraintTypeMatch(const char *lval, Rval rval, DataType dt, const char *range, int level) { Rlist *rp; Item *checklist; /* Get type of lval */ switch (rval.type) { case RVAL_TYPE_SCALAR: switch (dt) { case CF_DATA_TYPE_STRING_LIST: case CF_DATA_TYPE_INT_LIST: case CF_DATA_TYPE_REAL_LIST: case CF_DATA_TYPE_CONTEXT_LIST: case CF_DATA_TYPE_OPTION_LIST: if (level == 0) { return SYNTAX_TYPE_MATCH_ERROR_GOT_SCALAR; } break; default: /* Only lists are incompatible with scalars */ break; } break; case RVAL_TYPE_LIST: switch (dt) { case CF_DATA_TYPE_STRING_LIST: case CF_DATA_TYPE_INT_LIST: case CF_DATA_TYPE_REAL_LIST: case CF_DATA_TYPE_CONTEXT_LIST: case CF_DATA_TYPE_OPTION_LIST: break; default: return SYNTAX_TYPE_MATCH_ERROR_GOT_LIST; } for (rp = (Rlist *) rval.item; rp != NULL; rp = rp->next) { SyntaxTypeMatch err = CheckConstraintTypeMatch(lval, rp->val, dt, range, 1); switch (err) { case SYNTAX_TYPE_MATCH_OK: case SYNTAX_TYPE_MATCH_ERROR_UNEXPANDED: break; default: return err; } } return SYNTAX_TYPE_MATCH_OK; case RVAL_TYPE_FNCALL: /* Fn-like objects are assumed to be parameterized bundles in these... */ checklist = SplitString("bundlesequence,edit_line,edit_xml,usebundle,service_bundle,home_bundle", ','); if (!IsItemIn(checklist, lval)) { SyntaxTypeMatch err = CheckFnCallType(RvalFnCallValue(rval)->name, dt); DeleteItemList(checklist); return err; } DeleteItemList(checklist); return SYNTAX_TYPE_MATCH_OK; case RVAL_TYPE_CONTAINER: break; case RVAL_TYPE_NOPROMISEE: return SYNTAX_TYPE_MATCH_ERROR_GOT_NULL; } /* If we get here, we have a literal scalar type */ switch (dt) { case CF_DATA_TYPE_STRING: case CF_DATA_TYPE_STRING_LIST: return CheckParseString(lval, (const char *) rval.item, range); case CF_DATA_TYPE_INT: case CF_DATA_TYPE_INT_LIST: return CheckParseInt(lval, (const char *) rval.item, range); case CF_DATA_TYPE_REAL: case CF_DATA_TYPE_REAL_LIST: return CheckParseReal(lval, (const char *) rval.item, range); case CF_DATA_TYPE_BODY: case CF_DATA_TYPE_BUNDLE: case CF_DATA_TYPE_CONTAINER: break; case CF_DATA_TYPE_OPTION: case CF_DATA_TYPE_OPTION_LIST: return CheckParseOpts(RvalScalarValue(rval), range); case CF_DATA_TYPE_CONTEXT: case CF_DATA_TYPE_CONTEXT_LIST: return CheckParseContext((const char *) rval.item, range); case CF_DATA_TYPE_INT_RANGE: return CheckParseIntRange(lval, (const char *) rval.item, range); case CF_DATA_TYPE_REAL_RANGE: return CheckParseRealRange(lval, (char *) rval.item, range); default: ProgrammingError("Unknown (unhandled) datatype for lval = %s (CheckConstraintTypeMatch)", lval); break; } return SYNTAX_TYPE_MATCH_OK; }
void CCodeView::OnPaint(wxPaintEvent& event) { // ------------------------- // General settings // ------------------------- std::unique_ptr<wxGraphicsContext> ctx(wxGraphicsContext::Create(wxPaintDC(this))); wxRect rc = GetClientRect(); ctx->SetFont(DebuggerFont, *wxBLACK); wxDouble w,h; ctx->GetTextExtent("0WJyq", &w, &h); if (h > m_rowHeight) m_rowHeight = h; ctx->GetTextExtent("W", &w, &h); int charWidth = w; struct branch { int src, dst, srcAddr; }; branch branches[256]; int numBranches = 0; // TODO: Add any drawing code here... int width = rc.width; int numRows = ((rc.height / m_rowHeight) / 2) + 2; // ------------ // ------------------------- // Colors and brushes // ------------------------- const wxColour bgColor = *wxWHITE; wxPen nullPen(bgColor); wxPen currentPen(*wxBLACK_PEN); wxPen selPen(*wxGREY_PEN); nullPen.SetStyle(wxTRANSPARENT); currentPen.SetStyle(wxSOLID); wxBrush currentBrush(*wxLIGHT_GREY_BRUSH); wxBrush pcBrush(*wxGREEN_BRUSH); wxBrush bpBrush(*wxRED_BRUSH); wxBrush bgBrush(bgColor); wxBrush nullBrush(bgColor); nullBrush.SetStyle(wxTRANSPARENT); ctx->SetPen(nullPen); ctx->SetBrush(bgBrush); ctx->DrawRectangle(0, 0, 16, rc.height); ctx->DrawRectangle(0, 0, rc.width, 5); // ------------ // ----------------------------- // Walk through all visible rows // ----------------------------- for (int i = -numRows; i <= numRows; i++) { unsigned int address = m_curAddress + (i * m_align); int rowY1 = (rc.height / 2) + (m_rowHeight * i) - (m_rowHeight / 2); int rowY2 = (rc.height / 2) + (m_rowHeight * i) + (m_rowHeight / 2); wxString temp = wxString::Format("%08x", address); u32 color = m_debugger->GetColor(address); wxBrush rowBrush(wxColour(color >> 16, color >> 8, color)); ctx->SetBrush(nullBrush); ctx->SetPen(nullPen); ctx->DrawRectangle(0, rowY1, 16, rowY2 - rowY1 + 2); if (m_selecting && (address == m_selection)) ctx->SetPen(selPen); else ctx->SetPen(i == 0 ? currentPen : nullPen); if (address == m_debugger->GetPC()) ctx->SetBrush(pcBrush); else ctx->SetBrush(rowBrush); ctx->DrawRectangle(16, rowY1, width, rowY2 - rowY1 + 1); ctx->SetBrush(currentBrush); if (!m_plain) { // the address text is dark red ctx->SetFont(DebuggerFont, wxColour("#600000")); ctx->DrawText(temp, 17, rowY1); ctx->SetFont(DebuggerFont, *wxBLACK); } // If running if (m_debugger->IsAlive()) { std::vector<std::string> dis; SplitString(m_debugger->Disassemble(address), '\t', dis); dis.resize(2); static const size_t VALID_BRANCH_LENGTH = 10; const std::string& opcode = dis[0]; const std::string& operands = dis[1]; std::string desc; // look for hex strings to decode branches std::string hex_str; size_t pos = operands.find("0x8"); if (pos != std::string::npos) { hex_str = operands.substr(pos); } if (hex_str.length() == VALID_BRANCH_LENGTH) { u32 offs = std::stoul(hex_str, nullptr, 16); branches[numBranches].src = rowY1 + (m_rowHeight / 2); branches[numBranches].srcAddr = (address / m_align); branches[numBranches++].dst = (int)(rowY1 + ((s64)(u32)offs - (s64)(u32)address) * m_rowHeight / m_align + m_rowHeight / 2); desc = StringFromFormat("-->%s", m_debugger->GetDescription(offs).c_str()); // the -> arrow illustrations are purple ctx->SetFont(DebuggerFont, wxTheColourDatabase->Find("PURPLE")); } else { ctx->SetFont(DebuggerFont, *wxBLACK); } ctx->DrawText(StrToWxStr(operands), 17 + 17*charWidth, rowY1); // ------------ // Show blr as its' own color if (opcode == "blr") ctx->SetFont(DebuggerFont, wxTheColourDatabase->Find("DARK GREEN")); else ctx->SetFont(DebuggerFont, wxTheColourDatabase->Find("VIOLET")); ctx->DrawText(StrToWxStr(opcode), 17 + (m_plain ? 1*charWidth : 9*charWidth), rowY1); if (desc.empty()) { desc = m_debugger->GetDescription(address); } if (!m_plain) { ctx->SetFont(DebuggerFont, *wxBLUE); //char temp[256]; //UnDecorateSymbolName(desc,temp,255,UNDNAME_COMPLETE); if (!desc.empty()) { ctx->DrawText(StrToWxStr(desc), 17 + 35 * charWidth, rowY1); } } // Show red breakpoint dot if (m_debugger->IsBreakpoint(address)) { ctx->SetBrush(bpBrush); ctx->DrawRectangle(2, rowY1 + 1, 11, 11); } } } // end of for // ------------ // ------------------------- // Colors and brushes // ------------------------- ctx->SetPen(currentPen); for (int i = 0; i < numBranches; i++) { int x = 17 + 49 * charWidth + (branches[i].srcAddr % 9) * 8; MoveTo(x-2, branches[i].src); if (branches[i].dst < rc.height + 400 && branches[i].dst > -400) { LineTo(ctx, x+2, branches[i].src); LineTo(ctx, x+2, branches[i].dst); LineTo(ctx, x-4, branches[i].dst); MoveTo(x, branches[i].dst - 4); LineTo(ctx, x-4, branches[i].dst); LineTo(ctx, x+1, branches[i].dst+5); } //else //{ // This can be re-enabled when there is a scrollbar or // something on the codeview (the lines are too long) //LineTo(ctx, x+4, branches[i].src); //MoveTo(x+2, branches[i].dst-4); //LineTo(ctx, x+6, branches[i].dst); //LineTo(ctx, x+1, branches[i].dst+5); //} //LineTo(ctx, x, branches[i].dst+4); //LineTo(ctx, x-2, branches[i].dst); } // ------------ }
void LoadPatchSection(const std::string& section, std::vector<Patch>& patches, IniFile& globalIni, IniFile& localIni) { // Load the name of all enabled patches std::string enabledSectionName = section + "_Enabled"; std::vector<std::string> enabledLines; std::set<std::string> enabledNames; localIni.GetLines(enabledSectionName, &enabledLines); for (const std::string& line : enabledLines) { if (!line.empty() && line[0] == '$') { std::string name = line.substr(1, line.size() - 1); enabledNames.insert(name); } } const IniFile* inis[2] = {&globalIni, &localIni}; for (const IniFile* ini : inis) { std::vector<std::string> lines; Patch currentPatch; ini->GetLines(section, &lines); for (std::string& line : lines) { if (line.empty()) continue; if (line[0] == '$') { // Take care of the previous code if (!currentPatch.name.empty()) { patches.push_back(currentPatch); } currentPatch.entries.clear(); // Set active and name currentPatch.name = line.substr(1, line.size() - 1); currentPatch.active = enabledNames.find(currentPatch.name) != enabledNames.end(); currentPatch.user_defined = (ini == &localIni); } else { std::string::size_type loc = line.find('='); if (loc != std::string::npos) { line[loc] = ':'; } const std::vector<std::string> items = SplitString(line, ':'); if (items.size() >= 3) { PatchEntry pE; bool success = true; success &= TryParse(items[0], &pE.address); success &= TryParse(items[2], &pE.value); const auto iter = std::find(s_patch_type_strings.begin(), s_patch_type_strings.end(), items[1]); pE.type = PatchType(std::distance(s_patch_type_strings.begin(), iter)); success &= (pE.type != (PatchType)3); if (success) { currentPatch.entries.push_back(pE); } } } } if (!currentPatch.name.empty() && !currentPatch.entries.empty()) { patches.push_back(currentPatch); } } }
StringList SplitString( const String& splitMe ) { return SplitString( splitMe, StringUtil_WhiteSpaceChars ); }
UINT32 StripRGBA(string colors) { vector<string> split = SplitString(colors, ' '); return ColorRGBA(atoi(split[0].c_str()), atoi(split[1].c_str()), atoi(split[2].c_str()), atoi(split[3].c_str())); }
void ImportSpells(SharedDatabase *db) { Log.Out(Logs::General, Logs::Status, "Importing Spells..."); FILE *f = fopen("import/spells_us.txt", "r"); if(!f) { Log.Out(Logs::General, Logs::Error, "Unable to open import/spells_us.txt to read, skipping."); return; } std::string query = "DELETE FROM spells_new"; db->QueryDatabase(query); int columns = GetSpellColumns(db); int spells_imported = 0; char buffer[2048]; while(fgets(buffer, 2048, f)) { for(int i = 0; i < 2048; ++i) { if(buffer[i] == '\n') { buffer[i] = 0; break; } } std::string escaped = ::EscapeString(buffer); auto split = SplitString(escaped, '^'); int line_columns = (int)split.size(); std::string sql; if(line_columns >= columns) { sql = "INSERT INTO spells_new VALUES("; for(int i = 0; i < columns; ++i) { if(i != 0) { sql += ", '"; } else { sql += "'"; } sql += split[i]; sql += "'"; } sql += ");"; } else { int i = 0; sql = "INSERT INTO spells_new VALUES("; for(; i < line_columns; ++i) { if(i != 0) { sql += ", '"; } else { sql += "'"; } sql += split[i]; sql += "'"; } for(; i < columns; ++i) { sql += ", '0'"; } sql += ");"; } db->QueryDatabase(sql); spells_imported++; if(spells_imported % 1000 == 0) { Log.Out(Logs::General, Logs::Status, "%d spells imported.", spells_imported); } } if(spells_imported % 1000 != 0) { Log.Out(Logs::General, Logs::Status, "%d spells imported.", spells_imported); } fclose(f); }
void CARCodeAddEdit::SaveCheatData(wxCommandEvent& WXUNUSED (event)) { std::vector<ActionReplay::AREntry> decryptedLines; std::vector<std::string> encryptedLines; // Split the entered cheat into lines. std::vector<std::string> userInputLines; SplitString(WxStrToStr(EditCheatCode->GetValue()), '\n', userInputLines); for (size_t i = 0; i < userInputLines.size(); i++) { // Make sure to ignore unneeded whitespace characters. std::string line_str = StripSpaces(userInputLines[i]); if (line_str == "") continue; // Let's parse the current line. Is it in encrypted or decrypted form? std::vector<std::string> pieces; SplitString(line_str, ' ', pieces); if (pieces.size() == 2 && pieces[0].size() == 8 && pieces[1].size() == 8) { // Decrypted code line. u32 addr = std::stoul(pieces[0], nullptr, 16); u32 value = std::stoul(pieces[1], nullptr, 16); decryptedLines.push_back(ActionReplay::AREntry(addr, value)); continue; } else if (pieces.size() == 1) { SplitString(line_str, '-', pieces); if (pieces.size() == 3 && pieces[0].size() == 4 && pieces[1].size() == 4 && pieces[2].size() == 5) { // Encrypted code line. We'll have to decode it later. encryptedLines.push_back(pieces[0] + pieces[1] + pieces[2]); continue; } } // If the above-mentioned conditions weren't met, then something went wrong. if (!PanicYesNoT("Unable to parse line %u of the entered AR code as a valid " "encrypted or decrypted code. Make sure you typed it correctly.\n" "Would you like to ignore this line and continue parsing?", (unsigned) (i + 1))) { return; } } // If the entered code was in encrypted form, we decode it here. if (encryptedLines.size()) { // TODO: what if both decrypted AND encrypted lines are entered into a single AR code? ActionReplay::DecryptARCode(encryptedLines, decryptedLines); } // Codes with no lines appear to be deleted/hidden from the list. Let's prevent that. if (!decryptedLines.size()) { WxUtils::ShowErrorDialog(_("The resulting decrypted AR code doesn't contain any lines.")); return; } if (selection == wxNOT_FOUND) { // Add a new AR cheat code. ActionReplay::ARCode newCheat; newCheat.name = WxStrToStr(EditCheatName->GetValue()); newCheat.ops = decryptedLines; newCheat.active = true; arCodes.push_back(newCheat); } else { // Update the currently-selected AR cheat code. arCodes.at(selection).name = WxStrToStr(EditCheatName->GetValue()); arCodes.at(selection).ops = decryptedLines; } AcceptAndClose(); }
vector<string> SplitString(const string &target, char ctoken) { string token(&ctoken); return SplitString(target, token); }
int main(int argc, char** argv) { #ifdef PIONEER_PROFILER Profiler::detect( argc, argv ); #endif RunMode mode = MODE_GAME; std::string modeopt; if (argc > 1) { const char switchchar = argv[1][0]; if (!(switchchar == '-' || switchchar == '/')) { mode = MODE_USAGE_ERROR; goto start; } modeopt = std::string(argv[1]).substr(1); if (modeopt == "game" || modeopt == "g") { mode = MODE_GAME; goto start; } if (modeopt == "modelviewer" || modeopt == "mv") { mode = MODE_MODELVIEWER; goto start; } if (modeopt == "galaxydump" || modeopt == "gd") { mode = MODE_GALAXYDUMP; goto start; } if (modeopt.find("skipmenu", 0, 8) != std::string::npos || modeopt.find("sm", 0, 2) != std::string::npos) { mode = MODE_SKIPMENU; goto start; } if (modeopt == "version" || modeopt == "v") { mode = MODE_VERSION; goto start; } if (modeopt == "help" || modeopt == "h" || modeopt == "?") { mode = MODE_USAGE; goto start; } mode = MODE_USAGE_ERROR; } start: int pos = 2; long int radius = 4; long int sx = 0, sy = 0, sz = 0; std::string filename; int startPlanet = 0; // zero is off switch (mode) { case MODE_GALAXYDUMP: { if (argc < 3) { Output("pioneer: galaxy dump requires a filename\n"); break; } filename = argv[pos]; ++pos; if (argc > pos) { // radius (optional) char* end = nullptr; radius = std::strtol(argv[pos], &end, 0); if (end == nullptr || *end != 0 || radius < 0 || radius > 10000) { Output("pioneer: invalid radius: %s\n", argv[pos]); break; } ++pos; } if (argc > pos) { // center of dump (three comma separated coordinates, optional) char* end = nullptr; sx = std::strtol(argv[pos], &end, 0); if (end == nullptr || *end != ',' || sx < -10000 || sx > 10000) { Output("pioneer: invalid center: %s\n", argv[pos]); break; } sy = std::strtol(end + 1, &end, 0); if (end == nullptr || *end != ',' || sy < -10000 || sy > 10000) { Output("pioneer: invalid center: %s\n", argv[pos]); break; } sz = std::strtol(end + 1, &end, 0); if (end == nullptr || *end != 0 || sz < -10000 || sz > 10000) { Output("pioneer: invalid center: %s\n", argv[pos]); break; } ++pos; } // fallthrough } case MODE_SKIPMENU: { // fallthrough protect if (mode == MODE_SKIPMENU) { // try to get start planet number std::vector<std::string> keyValue = SplitString(modeopt, "="); // if found value if (keyValue.size() == 2) { if (keyValue[1].empty()) { startPlanet = 0; } else { startPlanet = static_cast<int>(StrToSInt64(keyValue[1])); } } // if value not exists - load on Earth else startPlanet = 1; // set usual mode mode = MODE_GAME; } // fallthrough } case MODE_GAME: { std::map<std::string,std::string> options; // if arguments more than parsed already if (argc > pos) { static const std::string delim("="); // for each argument for (; pos < argc; pos++) { const std::string arg(argv[pos]); std::vector<std::string> keyValue = SplitString(arg, "="); // if there no key and value || key is empty || value is empty if (keyValue.size() != 2 || keyValue[0].empty() || keyValue[1].empty()) { Output("malformed option: %s\n", arg.c_str()); return 1; } // put key and value to config options[keyValue[0]] = keyValue[1]; } } Pi::Init(options, mode == MODE_GALAXYDUMP); if (mode == MODE_GAME) for (;;) { Pi::Start(startPlanet); startPlanet = 0; // Reset the start planet when coming back to the menu } else if (mode == MODE_GALAXYDUMP) { FILE* file = filename == "-" ? stdout : fopen(filename.c_str(), "w"); if (file == nullptr) { Output("pioneer: could not open \"%s\" for writing: %s\n", filename.c_str(), strerror(errno)); break; } RefCountedPtr<Galaxy> galaxy = GalaxyGenerator::Create(); galaxy->Dump(file, sx, sy, sz, radius); if (filename != "-" && fclose(file) != 0) { Output("pioneer: writing to \"%s\" failed: %s\n", filename.c_str(), strerror(errno)); } Pi::Quit(); } break; } case MODE_MODELVIEWER: { std::string modelName; if (argc > 2) modelName = argv[2]; ModelViewer::Run(modelName); break; } case MODE_VERSION: { std::string version(PIONEER_VERSION); if (strlen(PIONEER_EXTRAVERSION)) version += " (" PIONEER_EXTRAVERSION ")"; Output("pioneer %s\n", version.c_str()); break; } case MODE_USAGE_ERROR: Output("pioneer: unknown mode %s\n", argv[1]); // fall through case MODE_USAGE: Output( "usage: pioneer [mode] [options...]\n" "available modes:\n" " -game [-g] game (default)\n" " -modelviewer [-mv] model viewer\n" " -galaxydump [-gd] galaxy dumper\n" " -skipmenu [-sm] skip main menu\n" " -skipmenu=N [-sm=N] skip main menu and load planet 'N' where N: number\n" " -version [-v] show version\n" " -help [-h,-?] this help\n" ); break; } return 0; }
std::vector<std::string> SplitString(const std::string &s, char delim) { std::vector<std::string> elems; SplitString(s, delim, elems); return elems; }
bool hq_sum_change_rate_search_index::do_check_hq_sum_change_rate_ge(std::string &key, std::string &value, std::set<std::string> & search) { float end = 0; std::multimap<float, std::string>::iterator it_le, it_ge, it; std::map<std::string, std::multimap<float, std::string> > * search_index = current(); SETS_OP_TRPE tmp_ot; proc_data* p_data = proc_data::instance(); std::vector<std::string> tmp_vec; std::vector<std::set<std::string> > tmp_res_vec; if (strstr(key.c_str(), "|")) { SplitString(value.c_str(), '|', &tmp_vec, SPLIT_MODE_ALL); tmp_ot = SETS_OP_UNION; } else { SplitString(value.c_str(), '&', &tmp_vec, SPLIT_MODE_ALL); tmp_ot = SETS_OP_INTERSECTION; } if (!tmp_vec.size()) tmp_vec.push_back(value); for (uint32_t i = 0; i< tmp_vec.size(); i++) { std::vector<std::string> t_vec; SplitString(tmp_vec[i].c_str(), ':', &t_vec, SPLIT_MODE_ALL); std::string date; std::set<std::string> t_res; p_data->_hquoation_dict->current()->get_last_date(atoi(t_vec[0].c_str()), date); if (date.empty()) { tmp_res_vec.push_back(t_res); continue; } end = atof(t_vec[1].c_str()); auto ii = search_index->find(date); if (ii == search_index->end()) { tmp_res_vec.push_back(t_res); continue;; } it_le = ii->second.end(); it_ge = ii->second.begin(); it_ge = ii->second.lower_bound(end); for (it = it_ge; it != it_le; ++it) { t_res.insert(it->second); } tmp_res_vec.push_back(t_res); } if (tmp_ot == SETS_OP_INTERSECTION) get_intersection(tmp_res_vec, search); else get_union(tmp_res_vec, search); return true; }
int main(int argc, char **argv) { RegisterExecutablePlatform(ExePlatformSharedMemory); Log.LoadLogSettingsDefaults(); set_exception_handler(); Log.Out(Logs::General, Logs::Status, "Shared Memory Loader Program"); if(!EQEmuConfig::LoadConfig()) { Log.Out(Logs::General, Logs::Error, "Unable to load configuration file."); return 1; } auto Config = EQEmuConfig::get(); SharedDatabase database; Log.Out(Logs::General, Logs::Status, "Connecting to database..."); 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, "Unable to connect to the database, cannot continue without a " "database connection"); return 1; } /* Register Log System and Settings */ database.LoadLogSettings(Log.log_settings); Log.StartFileLogs(); database.LoadVariables(); /* If we're running shared memory and hotfix has no custom name, we probably want to start from scratch... */ std::string db_hotfix_name; if (database.GetVariable("hotfix_name", db_hotfix_name)) { if (!db_hotfix_name.empty() && strcasecmp("hotfix_", db_hotfix_name.c_str()) == 0) { Log.Out(Logs::General, Logs::Status, "Current hotfix in variables is the default %s, clearing out variable", db_hotfix_name.c_str()); std::string query = StringFormat("UPDATE `variables` SET `value`='' WHERE (`varname`='hotfix_name')"); database.QueryDatabase(query); } } std::string hotfix_name = ""; bool load_all = true; bool load_items = false; bool load_factions = false; bool load_loot = false; bool load_skill_caps = false; bool load_spells = false; bool load_bd = false; if(argc > 1) { for(int i = 1; i < argc; ++i) { switch(argv[i][0]) { case 'b': if(strcasecmp("base_data", argv[i]) == 0) { load_bd = true; load_all = false; } break; case 'i': if(strcasecmp("items", argv[i]) == 0) { load_items = true; load_all = false; } break; case 'f': if(strcasecmp("factions", argv[i]) == 0) { load_factions = true; load_all = false; } break; case 'l': if(strcasecmp("loot", argv[i]) == 0) { load_loot = true; load_all = false; } break; case 's': if(strcasecmp("skill_caps", argv[i]) == 0) { load_skill_caps = true; load_all = false; } else if(strcasecmp("spells", argv[i]) == 0) { load_spells = true; load_all = false; } break; case '-': { auto split = SplitString(argv[i], '='); if(split.size() >= 2) { auto command = split[0]; auto argument = split[1]; if(strcasecmp("-hotfix", command.c_str()) == 0) { hotfix_name = argument; load_all = true; } } break; } } } } if(hotfix_name.length() > 0) { Log.Out(Logs::General, Logs::Status, "Writing data for hotfix '%s'", hotfix_name.c_str()); } if(load_all || load_items) { Log.Out(Logs::General, Logs::Status, "Loading items..."); try { LoadItems(&database, hotfix_name); } catch(std::exception &ex) { Log.Out(Logs::General, Logs::Error, "%s", ex.what()); return 1; } } if(load_all || load_factions) { Log.Out(Logs::General, Logs::Status, "Loading factions..."); try { LoadFactions(&database, hotfix_name); } catch(std::exception &ex) { Log.Out(Logs::General, Logs::Error, "%s", ex.what()); return 1; } } if(load_all || load_loot) { Log.Out(Logs::General, Logs::Status, "Loading loot..."); try { LoadLoot(&database, hotfix_name); } catch(std::exception &ex) { Log.Out(Logs::General, Logs::Error, "%s", ex.what()); return 1; } } if(load_all || load_skill_caps) { Log.Out(Logs::General, Logs::Status, "Loading skill caps..."); try { LoadSkillCaps(&database, hotfix_name); } catch(std::exception &ex) { Log.Out(Logs::General, Logs::Error, "%s", ex.what()); return 1; } } if(load_all || load_spells) { Log.Out(Logs::General, Logs::Status, "Loading spells..."); try { LoadSpells(&database, hotfix_name); } catch(std::exception &ex) { Log.Out(Logs::General, Logs::Error, "%s", ex.what()); return 1; } } if(load_all || load_bd) { Log.Out(Logs::General, Logs::Status, "Loading base data..."); try { LoadBaseData(&database, hotfix_name); } catch(std::exception &ex) { Log.Out(Logs::General, Logs::Error, "%s", ex.what()); return 1; } } Log.CloseFileLogs(); return 0; }
static SyntaxTypeMatch CheckParseRealRange(const char *lval, const char *s, const char *range) { Item *split, *rangep, *ip; double max = (double) CF_LOWINIT, min = (double) CF_HIGHINIT, val; int n; if (*s == '[' || *s == '(') { return SYNTAX_TYPE_MATCH_ERROR_RANGE_BRACKETED; } if (strcmp(s, "inf") == 0) { return SYNTAX_TYPE_MATCH_ERROR_REAL_INF; } if (IsCf3VarString(s)) { return SYNTAX_TYPE_MATCH_ERROR_UNEXPANDED; } /* Numeric types are registered by range separated by comma str "min,max" */ split = SplitString(range, ','); if ((n = ListLen(split)) != 2) { ProgrammingError("Format specifier for real rvalues is not ok for lval %s - %d items", lval, n); } sscanf(split->name, "%lf", &min); sscanf(split->next->name, "%lf", &max); DeleteItemList(split); if (min == CF_HIGHINIT || max == CF_LOWINIT) { ProgrammingError("Could not parse format specifier for int rvalues for lval %s", lval); } rangep = SplitString(s, ','); if ((n = ListLen(rangep)) != 2) { return SYNTAX_TYPE_MATCH_ERROR_RANGE_MULTIPLE_ITEMS; } for (ip = rangep; ip != NULL; ip = ip->next) { if (!DoubleFromString(ip->name, &val)) { return SYNTAX_TYPE_MATCH_ERROR_REAL_OUT_OF_RANGE; } if (val > max || val < min) { return SYNTAX_TYPE_MATCH_ERROR_REAL_OUT_OF_RANGE; } } DeleteItemList(rangep); return SYNTAX_TYPE_MATCH_OK; }
static SyntaxTypeMatch CheckParseIntRange(const char *lval, const char *s, const char *range) { Item *split, *ip, *rangep; int n; long long max = CF_LOWINIT, min = CF_HIGHINIT; // Numeric types are registered by range separated by comma str "min,max" if (*s == '[' || *s == '(') { return SYNTAX_TYPE_MATCH_ERROR_RANGE_BRACKETED; } split = SplitString(range, ','); if ((n = ListLen(split)) != 2) { ProgrammingError("Format specifier %s for irange rvalues is not ok for lval %s - got %d items", range, lval, n); } sscanf(split->name, "%lld", &min); if (strcmp(split->next->name, "inf") == 0) { max = CF_INFINITY; } else { sscanf(split->next->name, "%lld", &max); } DeleteItemList(split); if (min == CF_HIGHINIT || max == CF_LOWINIT) { ProgrammingError("Could not parse irange format specifier for int rvalues for lval %s", lval); } if (IsCf3VarString(s)) { return SYNTAX_TYPE_MATCH_ERROR_UNEXPANDED; } rangep = SplitString(s, ','); if ((n = ListLen(rangep)) != 2) { return SYNTAX_TYPE_MATCH_ERROR_RANGE_MULTIPLE_ITEMS; } for (ip = rangep; ip != NULL; ip = ip->next) { long val = IntFromString(ip->name); if (val > max || val < min) { return SYNTAX_TYPE_MATCH_ERROR_INT_OUT_OF_RANGE; } } DeleteItemList(rangep); return SYNTAX_TYPE_MATCH_OK; }
std::vector<String> GetLines(const String& string) { return SplitString(string, "\n"); }
/*explicit*/ File::File(const std::string& path) : m_isDir(false) , m_exists(true) { char directory[2048]; GetCurrentDir(directory, 2048); std::vector<std::string> p = SplitString(path, '\\'); if(p.size() == 0) { m_file = ""; } else { m_file = p[0]; } for(uint32_t i = 1; i < p.size(); ++i) { m_file = m_file.append("/").append(p[i]); } std::string root = ""; #ifdef TARGET_OS_PC if(m_file.length() > 1 && m_file[1] != ':') { m_file = std::string(directory).append("/").append(m_file); root = m_file.substr(0, 2); } #else if(m_file.length() > 0 && m_file[0] != '/') { m_file = std::string(directory).append("/").append(m_file); } #endif // TARGET_OS_PC std::vector<std::string> hierarchy = SplitString(m_file, '/'); hierarchy.erase(hierarchy.begin()); for(std::vector<std::string>::iterator it = hierarchy.begin(); it != hierarchy.end(); ++it) { if(it->length() == 0 || 0 == it->compare(".")) { hierarchy.erase(it); it = hierarchy.begin(); } else if(0 == it->compare("..")) { if(it != hierarchy.begin()) { it->assign("."); --it; hierarchy.erase(it); it = hierarchy.begin(); } } } std::string m_file = root; for(std::vector<std::string>::iterator it = hierarchy.begin(); it != hierarchy.end(); ++it) { m_file = m_file.append("/").append(*it); } FILE* f = fopen(m_file.c_str(), "r"); if(f) { fclose(f); } else { DIR* d = opendir(m_file.c_str()); if(d) { closedir(d); m_isDir = true; } else { m_exists = false; } } }
void SplitStringByDelimiter(const StringPiece& full, const char* delim, std::vector<std::string>* result) { return SplitString(full, delim, result); }
nsValueList(nsString& aData) { mData.Assign(aData); SplitString(mData, mArray); }
int Process_ATOM(BUFFER Buffer, CHAIN **Chain, int *ChainNumber, BOOLEAN *First_ATOM, COMMAND *Cmd) { char *Field[MAX_FIELD]; BUFFER Tmp; int CC, NR, NA; static char LastRes[MAX_CHAIN][RES_FIELD]; RESIDUE *r; if( Cmd->NActive && !ChInStr(Cmd->Active,SpaceToDash(Buffer[21])) ) return(SUCCESS); if( Buffer[16] != 'A' && Buffer[16] != ' ' && Buffer[16] != '1' ) return(SUCCESS); if( *First_ATOM ) { for( CC=0; CC<MAX_CHAIN; CC++ ) strcpy(LastRes[CC],"XXXX"); *First_ATOM = NO; } for( CC=0; CC < *ChainNumber && Chain[CC]->Id != Buffer[21] ; CC++ ); if( CC == *ChainNumber ) { InitChain(&Chain[CC]); Chain[CC]->Id = Buffer[21]; (*ChainNumber)++; } else if( Chain[CC]->Ter == 1 ) return(SUCCESS); if( Buffer[34] != '.' || Buffer[42] != '.' || Buffer[50] != '.' ) return(escape(FAILURE,"File %s has no coordinates\n",Cmd->InputFile)); if( Cmd->Stringent && Buffer[63] != '.') return(escape(FAILURE,"File %s has no temperature factor\n",Cmd->InputFile)); SplitString(Buffer+22,Field,1); if( strcmp(Field[0],LastRes[CC]) ) { if( strcmp(LastRes[CC],"XXXX") && !FindAtom(Chain[CC],Chain[CC]->NRes,"CA",&NA) ) { free(Chain[CC]->Rsd[Chain[CC]->NRes]); Chain[CC]->NRes--; } if( strcmp(LastRes[CC],"XXXX") ) Chain[CC]->NRes++; NR = Chain[CC]->NRes; strcpy(LastRes[CC],Field[0]); Chain[CC]->Rsd[NR] = (RESIDUE *)ckalloc(sizeof(RESIDUE)); strcpy(Chain[CC]->Rsd[NR]->PDB_ResNumb,LastRes[CC]); Chain[CC]->Rsd[NR]->NAtom = 0; SplitString(Buffer+17,Field,1); strcpy(Chain[CC]->Rsd[NR]->ResType,Field[0]); } else NR = Chain[CC]->NRes; NA = Chain[CC]->Rsd[NR]->NAtom; if( Buffer[16] != ' ' ) { strcpy(Tmp,Buffer); Tmp[16] = ' '; SplitString(Tmp+12,Field,1); } else SplitString(Buffer+12,Field,1); r = Chain[CC]->Rsd[NR]; strcpy(r->AtomType[NA],Field[0]); strcpy(Tmp,Buffer); Buffer[38] = ' '; SplitString(Tmp+30,Field,1); r->Coord[NA][0] = atof(Field[0]); strcpy(Tmp,Buffer); Buffer[46] = ' '; SplitString(Tmp+38,Field,1); r->Coord[NA][1] = atof(Field[0]); strcpy(Tmp,Buffer); Buffer[54] = ' '; SplitString(Tmp+46,Field,1); r->Coord[NA][2] = atof(Field[0]); if( Buffer[57] == '.' ) { strcpy(Tmp,Buffer); Tmp[60] = ' '; SplitString(Tmp+54,Field,1); r->Occupancy[NA] = atof(Field[0]); } else r->Occupancy[NA] = -1.00; SplitString(Buffer+63,Field,1); r->TempFactor[NA] = atof(Field[0]); r->NAtom++; if( r->NAtom > MAX_AT_IN_RES-1 ) return(escape(FAILURE,"File %s has too many atoms in residue %s %s %c\n", Cmd->InputFile,r->ResType,r->PDB_ResNumb,Chain[CC]->Id)); return(SUCCESS); }
bool nsOEAddressIterator::BuildCard(const char16_t * pName, nsIMdbRow *newRow, LPMAILUSER pUser) { nsString lastName; nsString firstName; nsString eMail; nsString nickName; nsString middleName; PRTime birthDay = 0; LPSPropValue pProp = m_pWab->GetUserProperty(pUser, PR_EMAIL_ADDRESS); if (pProp) { m_pWab->GetValueString(pProp, eMail); SanitizeValue(eMail); m_pWab->FreeProperty(pProp); } pProp = m_pWab->GetUserProperty(pUser, PR_GIVEN_NAME); if (pProp) { m_pWab->GetValueString(pProp, firstName); SanitizeValue(firstName); m_pWab->FreeProperty(pProp); } pProp = m_pWab->GetUserProperty(pUser, PR_SURNAME); if (pProp) { m_pWab->GetValueString(pProp, lastName); SanitizeValue(lastName); m_pWab->FreeProperty(pProp); } pProp = m_pWab->GetUserProperty(pUser, PR_MIDDLE_NAME); if (pProp) { m_pWab->GetValueString(pProp, middleName); SanitizeValue(middleName); m_pWab->FreeProperty(pProp); } pProp = m_pWab->GetUserProperty(pUser, PR_NICKNAME); if (pProp) { m_pWab->GetValueString(pProp, nickName); SanitizeValue(nickName); m_pWab->FreeProperty(pProp); } // The idea here is that firstName and lastName cannot both be empty! if (firstName.IsEmpty() && lastName.IsEmpty()) firstName = pName; nsString displayName; pProp = m_pWab->GetUserProperty(pUser, PR_DISPLAY_NAME); if (pProp) { m_pWab->GetValueString(pProp, displayName); SanitizeValue(displayName); m_pWab->FreeProperty(pProp); } if (displayName.IsEmpty()) { if (firstName.IsEmpty()) displayName = pName; else { displayName = firstName; if (!middleName.IsEmpty()) { displayName.Append(char16_t(' ')); displayName.Append(middleName); } if (!lastName.IsEmpty()) { displayName.Append(char16_t(' ')); displayName.Append(lastName); } } } pProp = m_pWab->GetUserProperty(pUser, PR_BIRTHDAY); if (pProp) { m_pWab->GetValueTime(pProp, birthDay); m_pWab->FreeProperty(pProp); } // We now have the required fields // write them out followed by any optional fields! if (!displayName.IsEmpty()) m_database->AddDisplayName(newRow, NS_ConvertUTF16toUTF8(displayName).get()); if (!firstName.IsEmpty()) m_database->AddFirstName(newRow, NS_ConvertUTF16toUTF8(firstName).get()); if (!lastName.IsEmpty()) m_database->AddLastName(newRow, NS_ConvertUTF16toUTF8(lastName).get()); if (!nickName.IsEmpty()) m_database->AddNickName(newRow, NS_ConvertUTF16toUTF8(nickName).get()); if (!eMail.IsEmpty()) m_database->AddPrimaryEmail(newRow, NS_ConvertUTF16toUTF8(eMail).get()); if (birthDay) SetBirthDay(newRow, birthDay); // Do all of the extra fields! nsString value; nsString line2; nsresult rv; // Create a field map nsCOMPtr<nsIImportService> impSvc(do_GetService(NS_IMPORTSERVICE_CONTRACTID, &rv)); if (NS_SUCCEEDED(rv)) { nsIImportFieldMap * pFieldMap = nullptr; rv = impSvc->CreateNewFieldMap(&pFieldMap); if (NS_SUCCEEDED(rv) && pFieldMap) { int max = sizeof(gMapiFields) / sizeof(MAPIFields); for (int i = 0; i < max; i++) { pProp = m_pWab->GetUserProperty(pUser, gMapiFields[i].mapiTag); if (pProp) { m_pWab->GetValueString(pProp, value); m_pWab->FreeProperty(pProp); if (!value.IsEmpty()) { if (gMapiFields[i].multiLine == kNoMultiLine) { SanitizeValue(value); pFieldMap->SetFieldValue(m_database, newRow, gMapiFields[i].mozField, value.get()); } else if (gMapiFields[i].multiLine == kIsMultiLine) { pFieldMap->SetFieldValue(m_database, newRow, gMapiFields[i].mozField, value.get()); } else { line2.Truncate(); SplitString(value, line2); if (!value.IsEmpty()) pFieldMap->SetFieldValue(m_database, newRow, gMapiFields[i].mozField, value.get()); if (!line2.IsEmpty()) pFieldMap->SetFieldValue(m_database, newRow, gMapiFields[i].multiLine, line2.get()); } } } } // call fieldMap SetFieldValue based on the table of fields NS_RELEASE(pFieldMap); } } return true; }
void DoPopupWindow(const char *msg) { stringbank *bank = StringBank_Create (); const char *lines[30]; WIDGET_LABEL label; RECT r; STAMP s; FRAME F; CONTEXT oldContext; RECT oldRect; POPUP_STATE state; MENU_SOUND_FLAGS s0, s1; if (!bank) { log_add (log_Fatal, "FATAL: Memory exhaustion when preparing popup window"); exit (EXIT_FAILURE); } label.tag = WIDGET_TYPE_LABEL; label.parent = NULL; label.handleEvent = Widget_HandleEventIgnoreAll; label.receiveFocus = Widget_ReceiveFocusRefuseFocus; label.draw = Widget_DrawLabel; label.height = Widget_HeightLabel; label.width = Widget_WidthFullScreen; label.line_count = SplitString (msg, '\n', 30, lines, bank); label.lines = lines; LockMutex (GraphicsLock); oldContext = SetContext (ScreenContext); GetContextClipRect (&oldRect); SetContextClipRect (NULL_PTR); /* TODO: Better measure of dimensions than this */ r.extent.width = SCREEN_WIDTH; r.extent.height = SCREEN_HEIGHT; r.corner.x = (SCREEN_WIDTH - r.extent.width) >> 1; r.corner.y = (SCREEN_HEIGHT - r.extent.height) >> 1; F = CaptureDrawable (LoadDisplayPixmap (&r, (FRAME)0)); s.origin = r.corner; s.frame = F; DrawLabelAsWindow (&label); GetMenuSounds (&s0, &s1); SetMenuSounds (MENU_SOUND_NONE, MENU_SOUND_NONE); state.InputFunc = DoPopup; DoInput (&state, TRUE); DrawStamp (&s); DestroyDrawable (ReleaseDrawable (s.frame)); FlushInput (); SetContextClipRect (&oldRect); SetContext (oldContext); UnlockMutex (GraphicsLock); SetMenuSounds (s0, s1); StringBank_Free (bank); }
bool nsOutlookMail::BuildCard(const PRUnichar *pName, nsIAddrDatabase *pDb, nsIMdbRow *newRow, LPMAPIPROP pUser, nsIImportFieldMap *pFieldMap) { nsString lastName; nsString firstName; nsString eMail; nsString nickName; nsString middleName; nsString secondEMail; ULONG emailTag; LPSPropValue pProp = m_mapi.GetMapiProperty(pUser, PR_EMAIL_ADDRESS); if (!pProp) { emailTag = m_mapi.GetEmailPropertyTag(pUser, OUTLOOK_EMAIL1_MAPI_ID1); if (emailTag) { pProp = m_mapi.GetMapiProperty(pUser, emailTag); } } if (pProp) { m_mapi.GetStringFromProp(pProp, eMail); SanitizeValue(eMail); } // for secondary email emailTag = m_mapi.GetEmailPropertyTag(pUser, OUTLOOK_EMAIL2_MAPI_ID1); if (emailTag) { pProp = m_mapi.GetMapiProperty(pUser, emailTag); if (pProp) { m_mapi.GetStringFromProp(pProp, secondEMail); SanitizeValue(secondEMail); } } pProp = m_mapi.GetMapiProperty(pUser, PR_GIVEN_NAME); if (pProp) { m_mapi.GetStringFromProp(pProp, firstName); SanitizeValue(firstName); } pProp = m_mapi.GetMapiProperty(pUser, PR_SURNAME); if (pProp) { m_mapi.GetStringFromProp(pProp, lastName); SanitizeValue(lastName); } pProp = m_mapi.GetMapiProperty(pUser, PR_MIDDLE_NAME); if (pProp) { m_mapi.GetStringFromProp(pProp, middleName); SanitizeValue(middleName); } pProp = m_mapi.GetMapiProperty(pUser, PR_NICKNAME); if (pProp) { m_mapi.GetStringFromProp(pProp, nickName); SanitizeValue(nickName); } if (firstName.IsEmpty() && lastName.IsEmpty()) { firstName = pName; } nsString displayName; pProp = m_mapi.GetMapiProperty(pUser, PR_DISPLAY_NAME); if (pProp) { m_mapi.GetStringFromProp(pProp, displayName); SanitizeValue(displayName); } if (displayName.IsEmpty()) { if (firstName.IsEmpty()) displayName = pName; else { displayName = firstName; if (!middleName.IsEmpty()) { displayName.Append(PRUnichar(' ')); displayName.Append(middleName); } if (!lastName.IsEmpty()) { displayName.Append(PRUnichar(' ')); displayName.Append(lastName); } } } // We now have the required fields // write them out followed by any optional fields! if (!displayName.IsEmpty()) { pDb->AddDisplayName(newRow, NS_ConvertUTF16toUTF8(displayName).get()); } if (!firstName.IsEmpty()) { pDb->AddFirstName(newRow, NS_ConvertUTF16toUTF8(firstName).get()); } if (!lastName.IsEmpty()) { pDb->AddLastName(newRow, NS_ConvertUTF16toUTF8(lastName).get()); } if (!nickName.IsEmpty()) { pDb->AddNickName(newRow, NS_ConvertUTF16toUTF8(nickName).get()); } if (!eMail.IsEmpty()) { pDb->AddPrimaryEmail(newRow, NS_ConvertUTF16toUTF8(eMail).get()); } if (!secondEMail.IsEmpty()) { pDb->Add2ndEmail(newRow, NS_ConvertUTF16toUTF8(secondEMail).get()); } // Do all of the extra fields! nsString value; nsString line2; if (pFieldMap) { int max = sizeof(gMapiFields) / sizeof(MAPIFields); for (int i = 0; i < max; i++) { pProp = m_mapi.GetMapiProperty(pUser, gMapiFields[i].mapiTag); if (pProp) { m_mapi.GetStringFromProp(pProp, value); if (!value.IsEmpty()) { if (gMapiFields[i].multiLine == kNoMultiLine) { SanitizeValue(value); pFieldMap->SetFieldValue(pDb, newRow, gMapiFields[i].mozField, value.get()); } else if (gMapiFields[i].multiLine == kIsMultiLine) { pFieldMap->SetFieldValue(pDb, newRow, gMapiFields[i].mozField, value.get()); } else { line2.Truncate(); SplitString(value, line2); if (!value.IsEmpty()) pFieldMap->SetFieldValue(pDb, newRow, gMapiFields[i].mozField, value.get()); if (!line2.IsEmpty()) pFieldMap->SetFieldValue(pDb, newRow, gMapiFields[i].multiLine, line2.get()); } } } } } return true; }
bool SBMLModelSimulation::LoadSettings(const string& settingsFName) { string fName(settingsFName); if(!fName.size()) { Log(lError)<<"Empty file name for setings file"; return false; } else { map<string, string> settings; map<string, string>::iterator it; //Read each line in the settings file vector<string> lines = GetLinesInFile(fName); for(u_int i = 0; i < lines.size(); i++) { vector<string> line = SplitString(lines[i], ":"); if(line.size() == 2) { settings.insert( pair<string, string>(line[0], line[1])); } else { Log(lDebug2)<<"Empty line in settings file: "<<lines[i]; } } Log(lDebug3)<<"Settings File ============="; for (it = settings.begin() ; it != settings.end(); it++ ) { Log(lDebug) << (*it).first << " => " << (*it).second; } Log(lDebug)<<"==========================="; //Assign values it = settings.find("start"); mSettings.mStartTime = (it != settings.end()) ? ToDouble((*it).second) : 0; it = settings.find("duration"); mSettings.mDuration = (it != settings.end()) ? ToDouble((*it).second) : 0; it = settings.find("steps"); mSettings.mSteps = (it != settings.end()) ? ToInt((*it).second) : 50; it = settings.find("absolute"); mSettings.mAbsolute = (it != settings.end()) ? ToDouble((*it).second) : 1.e-7; it = settings.find("relative"); mSettings.mRelative = (it != settings.end()) ? ToDouble((*it).second) : 1.e-4; mSettings.mEndTime = mSettings.mStartTime + mSettings.mDuration; it = settings.find("variables"); if(it != settings.end()) { vector<string> vars = SplitString((*it).second, ","); for(int i=0; i < vars.size(); i++) { mSettings.mVariables.push_back(Trim(vars[i])); } } it = settings.find("amount"); if(it != settings.end()) { vector<string> vars = SplitString((*it).second, ","); for(int i=0; i < vars.size(); i++) { string rec = Trim(vars[i]); if(rec.size()) { mSettings.mAmount.push_back(rec); } } } it = settings.find("concentration"); if(it != settings.end()) { vector<string> vars = SplitString((*it).second, ","); for(int i=0; i < vars.size(); i++) { string rec = Trim(vars[i]); if(rec.size()) { mSettings.mConcentration.push_back(rec); } } } } if(mEngine) { mEngine->useSimulationSettings(mSettings); //This one creates the list of what we will look at in the result mEngine->createTimeCourseSelectionList(); } return true; }
PatchPieces( const wxString& param ) { SplitString( m_pieces, param, L"," ); if( m_pieces.Count() < 5 ) throw wxsFormat( L"Expected 5 data parameters; only found %d", m_pieces.Count() ); }
/////////////////////////////////////////////////////////////////////////////// // Execute /////////////////////////////////////////////////////////////////////////////// void cDbExplore::Execute( cFCODatabaseFileIter& dbIter ) { ASSERT( ! dbIter.Done() ); cDbDataSourceIter* pIter = new cDbDataSourceIter( &dbIter.GetDb(), dbIter.GetGenre() ); const iFCOPropDisplayer* pDisplayer = dbIter.GetGenreHeader().GetPropDisplayer(); //////////////////////////// // the main event loop... //////////////////////////// while( true ) { TSTRING verb, noun; TCOUT << _T(">>"); TCIN >> verb; // // ok, now we switch on the command... // //----------------------------------------------------------------- // quit //----------------------------------------------------------------- if( verb.compare( _T("quit") ) == 0 ) { // the quit command... break; } //----------------------------------------------------------------- // print //----------------------------------------------------------------- if( verb.compare( _T("print") ) == 0 ) { GetNoun(noun); if( SeekTo( pIter, noun ) ) { if( pIter->HasFCOData() ) { iFCO* pFCO = pIter->CreateFCO(); PrintFCO( pFCO, pDisplayer ); pFCO->Release(); } else { TCOUT << _T("Object has no data associated with it.") << std::endl; } } else { TCOUT << _T("Unable to find object ") << noun << std::endl; } } //----------------------------------------------------------------- // pwd //----------------------------------------------------------------- else if( verb.compare( _T("pwd") ) == 0 ) { TCOUT << iTWFactory::GetInstance()->GetNameTranslator()->ToStringDisplay( pIter->GetParentName() ) << std::endl; } //----------------------------------------------------------------- // ls //----------------------------------------------------------------- else if( verb.compare( _T("ls") ) == 0 ) { int cnt = 0; for( pIter->SeekBegin(); ! pIter->Done(); pIter->Next(), cnt++ ) { TCOUT << _T("[") << cnt ; if( pIter->CanDescend() ) { TCOUT << _T("]*\t") ; } else { TCOUT << _T("]\t") ; } TCOUT << pIter->GetShortName() << std::endl; } } //----------------------------------------------------------------- // cd //----------------------------------------------------------------- else if( verb.compare( _T("cd") ) == 0 ) { GetNoun(noun); std::vector<TSTRING> vDirs; SplitString( noun, pIter->GetParentName().GetDelimiter(), vDirs ); for( std::vector<TSTRING>::iterator i = vDirs.begin(); i != vDirs.end(); i++ ) { if( i->compare( _T("..") ) == 0 ) { if( pIter->AtRoot() ) { TCOUT << _T("Can't ascend above root.") << std::endl; break; } else { TCOUT << _T("Ascending...") << std::endl; pIter->Ascend(); } } else { if( SeekTo( pIter, *i ) ) { if( pIter->CanDescend() ) { TCOUT << _T("Descending into ") << *i << std::endl; pIter->Descend(); } else { TCOUT << *i << _T(" has no children; can't descend.") << std::endl; break; } } else { TCOUT << _T("Unable to find object ") << *i << std::endl; break; } } } } //----------------------------------------------------------------- // cg //----------------------------------------------------------------- else if( verb.compare( _T("cg") ) == 0 ) { GetNoun(noun); cGenre::Genre newGenre = cGenreSwitcher::GetInstance()->StringToGenre( noun.c_str() ); if (newGenre != cGenre::GENRE_INVALID) { dbIter.SeekToGenre( newGenre ); if( !dbIter.Done() ) { TCOUT << _T("Changing to Genre ") << noun << std::endl; // // create a new db iter for the new genre (db iters can only be // assocaited with a single genre :-( ) // delete pIter; pIter = new cDbDataSourceIter( &dbIter.GetDb(), newGenre ); } else { TCOUT << _T("Unable to find Genre ") << noun << std::endl; } } else { TCOUT << _T("Invalid Genre ") << noun << std::endl; } } //----------------------------------------------------------------- // pwg //----------------------------------------------------------------- else if( verb.compare( _T("pwg") ) == 0 ) { TCOUT << _T("Current Genre: ") << cGenreSwitcher::GetInstance()->GenreToString( (cGenre::Genre)dbIter.GetGenre(), true ) << std::endl; } //----------------------------------------------------------------- // help //----------------------------------------------------------------- if( verb.compare( _T("help") ) == 0 ) { TCOUT << _T("Commands: ") << std::endl << _T(" cd <dir_name>") << std::endl << _T(" pwd ") << std::endl << _T(" ls ") << std::endl << _T(" print <object_name>") << std::endl << _T(" cg (FS | NTFS | NTREG)")<< std::endl << _T(" pwg") << std::endl << _T(" quit") << std::endl; } // make sure the file is still valid... // /* #ifdef _BLOCKFILE_DEBUG db.AssertAllBlocksValid() ; #endif */ } delete pIter; TCOUT << _T("Exiting...") << std::endl; }
std::vector<String> SplitString(const String& string, const char delimiter) { return SplitString(string, String(1, delimiter)); }
// Main entry point int _tmain(int argc, _TCHAR* argv[]) { // Add command line alias' cl.AddAlias(L"h", L"?"); cl.AddAlias(L"help", L"?"); cl.AddAlias(L"x", L"extract"); cl.AddAlias(L"o", L"out"); // Parse command line cl.Parse(GetCommandLine(), true); // Display logo... if (!cl.GetSwitch(L"nologo")) { wprintf(L"Structured Ini File Compiler v1.1\nCopyright (C) 2007 Topten Software. All Rights Reserved\n\n"); } // Display help if (cl.GetSwitch(L"?")) { cl.BuildHelp(L"nologo", L"Suppress display of copyright and version info", NULL, clOptional); cl.BuildHelp(L"?|h|help", L"Display help information", NULL, clOptional); cl.BuildHelp(L"i", L"Include path", L"path", clMulti|clValue|clOptional); cl.BuildHelp(L"x|extract", L"Extract (decompile)", NULL, clOptional); cl.BuildHelp(L"unicode", L"Decompile to unicode", NULL, clOptional); cl.BuildHelp(L"flat", L"Decompile to flat", NULL, clOptional); cl.BuildHelp(L"o|out", L"Output File", NULL, clOptional); cl.BuildHelp(L"InputFile", L"File to be processed", NULL, clPlaced); cl.BuildHelp(L"crcstamp", L"CRC Stamp Module", NULL, clOptional); cl.BuildHelp(L"crcverify", L"Check Module CRC Stamp", NULL, clOptional); wprintf(cl.GetHelp(L"Sinic")); return 7; } // Get input value CUniString strInputFile; cl.GetPlacedValue(0, L"InputFile", strInputFile); strInputFile=QualifyPath(strInputFile); if (cl.GetSwitch(L"crcverify")) { if (!DoesFileExist(strInputFile)) { wprintf(L"Verifying %s... file doesn't exist, ignoring\n", strInputFile); return 0; } else { if (!CheckModuleCRC(strInputFile)) { CheckModuleCRCWithErrors(strInputFile); wprintf(L"************************************************************\n"); wprintf(L" Verifying %s... FAILED\n", strInputFile); wprintf(L"************************************************************\n"); return 7; } else { wprintf(L"Verifying %s... OK\n", strInputFile); return 0; } } } // Module CRC Stamp? if (cl.GetSwitch(L"crcstamp")) { // Work out output file CUniString strOutputFile; cl.GetValue(L"out", strOutputFile); if (strOutputFile.IsEmpty()) strOutputFile=strInputFile; // Error handling... cl.CheckNoUnknownArgs(); if (cl.HasError()) { wprintf(cl.GetErrorMessage()); wprintf(L"\n\n"); return 7; } // Open file for read/write FILE* pFile; if (_wfopen_s(&pFile, strInputFile, L"rb")!=0) { wprintf(L"Error: Can't open file '%s'\n", strInputFile); return 7; } // Get file size fseek(pFile, 0, SEEK_END); DWORD dwLength=ftell(pFile); fseek(pFile, 0, SEEK_SET); // Check has length if (dwLength==0) { fclose(pFile); wprintf(L"Error: Zero length file\n"); return 7; } // Load file into memory LPBYTE pFileData=(LPBYTE)malloc(dwLength); // Read data if (fread(pFileData, dwLength, 1, pFile)!=1) { free(pFileData); fclose(pFile); wprintf(L"Error: Error reading file\n"); return 7; } // Close the file fclose(pFile); if (CountCRCControlBlocks(pFileData, dwLength)>1) { free(pFileData); fclose(pFile); wprintf(L"Error: File contains multiple CRC Control blocks!\n"); return 7; } // Locate CRC Control block CRCCONTROLBLOCK* pCRCBlock=LocateCRCControlBlock(pFileData, dwLength); if (!pCRCBlock) { free(pFileData); fclose(pFile); wprintf(L"Error: File doesn't contain CRC Control block!\n"); return 7; } wprintf(L"CRC Control Block located at offset: 0x%.8x\n", reinterpret_cast<LPBYTE>(pCRCBlock)-pFileData); // Calculate the CRC upto start of control block pCRCBlock->dwCRC=CalculateModuleCRC(pFileData, dwLength, pCRCBlock); pCRCBlock->dwModuleLength=dwLength; wprintf(L"Module length: 0x%.8x\n", dwLength); wprintf(L"CRC: 0x%.8x\n", pCRCBlock->dwCRC); pFile=NULL; if (_wfopen_s(&pFile, strOutputFile, L"wb")!=0) { wprintf(L"Error: Can't open output file '%s'\n", strOutputFile); return 7; } if (!CheckModuleCRC(pFileData, dwLength)) { wprintf(L"Error: double check failed\n"); return 7; } // Write CRC stamped fwrite(pFileData, dwLength, 1, pFile); // Clean up free(pFileData); fclose(pFile); if (!CheckModuleCRC(strOutputFile)) { CheckModuleCRCWithErrors(strOutputFile); return 7; } wprintf(L"CRC Stamped %s - OK\n\n", strOutputFile); return 0; } // Compile or decompile bool bDecompile=cl.GetSwitch(L"extract"); bool bUnicode=cl.GetSwitch(L"unicode"); bool bFlat=cl.GetSwitch(L"flat"); // Get output file CUniString strOutputFile; cl.GetValue(L"out", strOutputFile); if (strOutputFile.IsEmpty()) { strOutputFile=ChangeFileExtension(strInputFile.IsEmpty() ? L"" : strInputFile, bDecompile ? L"sini" : L"bini"); } strOutputFile=QualifyPath(strOutputFile); // Setup file content provider with include paths CFileContentProvider fp; CVector<CUniString> vecIncludePaths; cl.GetMultiValue(L"i", vecIncludePaths); for (int i=0; i<vecIncludePaths.GetSize(); i++) { CUniString str=QualifyPath(vecIncludePaths[i]); fp.AddIncludePath(str); } // Get defines CVector<CUniString> vecDefines; cl.GetMultiValue(L"d", vecDefines); // Error handling... cl.CheckNoUnknownArgs(); if (cl.HasError()) { wprintf(cl.GetErrorMessage()); wprintf(L"\n\n"); return 7; } if (!bDecompile) { // Load the input file CProfileFile file; for (int i=0; i<vecDefines.GetSize(); i++) { CUniString strName, strValue; SplitString(vecDefines[i], L"=", strName, strValue); wprintf(L"#define %s %s\n", strName, strValue); file.Define(strName, strValue); } if (!file.Load(strInputFile, &fp)) { HRESULT hr=HRESULT_FROM_WIN32(GetLastError()); wprintf(file.GetParseError()); return 7; } // Extract encryption key DWORD dwEncryptionKey=0; CProfileSection* pSection=file.FindSection(L"Sinic"); if (pSection) { // Save the key dwEncryptionKey=pSection->GetIntValue(L"EncryptionKey", 0); // Remove the "sinic" section file.Remove(pSection); } // Create output file CFileStream OutStream; if (!OutStream.Create(strOutputFile)) { HRESULT hr=HRESULT_FROM_WIN32(GetLastError()); wprintf(L"Failed to create '%s' - %s (0x%.8x)\n\n", strOutputFile, FormatError(hr), hr); return 7; } // Save as binary file HRESULT hr; if (dwEncryptionKey) { CAutoPtr<IStream, SRefCounted> spEncStream; CreateCryptorStream(&OutStream, CCryptorKey(dwEncryptionKey), &spEncStream); hr=SaveBinaryProfile(file, spEncStream); } else { hr=SaveBinaryProfile(file, &OutStream); } OutStream.Close(); if (FAILED(hr)) { HRESULT hr=HRESULT_FROM_WIN32(GetLastError()); wprintf(L"Failed to save '%s' - %s (0x%.8x)\n\n", strOutputFile, FormatError(hr), hr); DeleteFile(strOutputFile); return 7; } } else { // Open stream CFileStream InStream; if (!InStream.Open(strInputFile)) { HRESULT hr=HRESULT_FROM_WIN32(GetLastError()); wprintf(L"Failed to open '%s' - %s (0x%.8x)\n\n", strInputFile, FormatError(hr), hr); return 7; } // Load profile CProfileFile file; HRESULT hr=LoadBinaryProfile(file, &InStream); if (FAILED(hr)) { if (hr!=E_UNEXPECTED) { wprintf(L"Failed to load '%s' - %s (0x%.8x)\n\n", strInputFile, FormatError(hr), hr); return 7; } else { wprintf(L"Failed to load '%s' - not a binary profile file\n\n", strInputFile); return 7; } } // Save as heirarchial if (!file.Save(strOutputFile, bUnicode, !bFlat)) { HRESULT hr=HRESULT_FROM_WIN32(GetLastError()); wprintf(L"Failed to save '%s' - %s (0x%.8x)\n\n", strInputFile, FormatError(hr), hr); return 7; } } wprintf(L"%s - OK\n\n", strOutputFile); return 0; }
std::vector<String> Tokenize(const String& string) { return SplitString(string, " \t\n"); }
void ReadPmd2Material(PMD2_MATERIAL* material, MEMORY_STREAM_PTR stream, size_t* data_size) { PMD2_MATERIAL_UNIT unit; const char *separator = "*"; const char *sph = ".sph"; const char *spa = ".spa"; char *texture; size_t name_length; (void)MemRead(unit.diffuse, sizeof(unit.diffuse), 1, stream); (void)MemRead(&unit.opacity, sizeof(unit.opacity), 1, stream); (void)MemRead(&unit.shininess, sizeof(unit.shininess), 1, stream); (void)MemRead(unit.specular, sizeof(unit.specular), 1, stream); (void)MemRead(unit.ambient, sizeof(unit.ambient), 1, stream); (void)MemRead(&unit.toon_texture_index, sizeof(unit.toon_texture_index), 1, stream); (void)MemRead(&unit.edge, sizeof(unit.edge), 1, stream); (void)MemRead(&unit.num_indices, sizeof(unit.num_indices), 1, stream); (void)MemRead(unit.texture_name, sizeof(unit.texture_name), 1, stream); texture = EncodeText(&material->application->encode, (char*)unit.texture_name, sizeof(unit.texture_name)); name_length = strlen(texture); if(strstr(texture, separator) != NULL) { size_t length; char *main_texture; int num_tokens; char **tokens = SplitString(texture, separator, &num_tokens); main_texture = tokens[0]; length = strlen(main_texture); if(length >= 4 && StringCompareIgnoreCase(&main_texture[length-4], sph) == 0) { material->interface_data.sphere_texture = MEM_STRDUP_FUNC(main_texture); material->interface_data.sphere_texture_render_mode = MATERIAL_MULTI_TEXTURE; } else { material->interface_data.main_texture = MEM_STRDUP_FUNC(main_texture); } Pmd2ModelAddTexture(material->model, main_texture); if(num_tokens == 2) { char *sub_texture = tokens[1]; length = strlen(sub_texture); if(StringCompareIgnoreCase(&sub_texture[length-4], sph) == 0) { material->interface_data.sphere_texture = MEM_STRDUP_FUNC(sub_texture); material->interface_data.sphere_texture_render_mode = MATERIAL_MULTI_TEXTURE; } else if(StringCompareIgnoreCase(&sub_texture[length-4], spa) == 0) { material->interface_data.sphere_texture = MEM_STRDUP_FUNC(sub_texture); material->interface_data.sphere_texture_render_mode = MATERIAL_ADD_TEXTURE; } } MEM_FREE_FUNC(tokens); } else if(StringCompareIgnoreCase(&texture[name_length-4], sph) == 0) { material->interface_data.sphere_texture = MEM_STRDUP_FUNC(texture); material->interface_data.sphere_texture_render_mode = MATERIAL_MULTI_TEXTURE; } else { material->interface_data.main_texture = MEM_STRDUP_FUNC(texture); } COPY_VECTOR3(material->ambient, unit.ambient); material->ambient[3] = 1; COPY_VECTOR3(material->diffuse, unit.diffuse); material->diffuse[3] = 1; COPY_VECTOR3(material->specular, unit.specular); material->specular[3] = 1; material->interface_data.index_range.count = unit.num_indices; material->enable_edge = unit.edge != 0; material->toon_texture_index = AdjustSharedToonTextureIndex(unit.toon_texture_index); *data_size = PMD2_MATERIAL_UNIT_SIZE; }
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; }