void GlobalGroupFlag::AddFlag(const char *flag_id) { const unsigned int hash_id = djb2_hash((unsigned char *) flag_id); std::multimap<const unsigned int, FlagAccessSwitch, ltint>::iterator p; flag_list.insert(std::make_pair(hash_id, FlagAccessSwitch(flag_id, true))); }
int pk_send(int id, Packet * pckt, int nbytes) { int n, len; struct sockaddr * addr; UdpPacket udp_pckt; memcpy(&(udp_pckt.pckt), pckt, sizeof(Packet)); udp_pckt.checksum = djb2_hash((char *) pckt, sizeof(Packet)); if (id == SRV_ID) { // sending from client to server addr = (struct sockaddr *) &srvaddr; len = sizeof srvaddr; } else { // sending from server to client addr = (struct sockaddr *) &cliaddr; len = sizeof cliaddr; } n = sendto(sockfd, &udp_pckt, sizeof udp_pckt, 0, addr, len); if (n == -1) { printf("Error sending packet.\n"); return -1; } return n; }
bool PersonalFlag::IsFlagSet(const char *class_type, const char *flag_id) { if (!flag_list.empty()) { const unsigned int hash_id = djb2_hash((unsigned char *) class_type, (unsigned char *)flag_id); typedef std::multimap<const unsigned int, ClassFlagAccess, ltint>::iterator RangeType; std::pair<RangeType, RangeType> range = flag_list.equal_range(hash_id); for (RangeType i = range.first; i != range.second; i++) { if (strcmp(i->second.GetFlagID(), flag_id) == 0 && strcmp(i->second.GetClassType(), class_type) == 0) { if (i->second.IsEnabled()) { return true; } return false; } } } return false; }
int main(void) { gnrc_netreg_entry_t ne; uint8_t cpuid[CPUID_LEN]; cpuid_get(cpuid); conn_test_id = djb2_hash(cpuid, CPUID_LEN); random_init(conn_test_id); ne.pid = thread_create(_stack, sizeof(_stack), THREAD_PRIORITY_MAIN - 1, THREAD_CREATE_STACKTEST, _listener, NULL, "listener"); ne.demux_ctx = GNRC_NETREG_DEMUX_CTX_ALL; gnrc_netreg_register(GNRC_NETTYPE_UNDEF, &ne); puts("Connectivity Test program!"); printf("MY ID: %08lX\n", (unsigned long) conn_test_id); unsigned res = CONN_TEST_CHAN; if (gnrc_netapi_set(CONN_TEST_NETIF, NETOPT_CHANNEL, 0, (uint16_t *)&res, sizeof(uint16_t)) < 0) { puts("main: error setting channel"); } unsigned int addr_len = 8; if (gnrc_netapi_set(CONN_TEST_NETIF, NETOPT_SRC_LEN, 0, (uint16_t *)&addr_len, sizeof(uint16_t)) < 0) { printf("main: error setting addressing mode\n"); } xtimer_set_msg(&ct_timer, (SEC_IN_USEC * 3) + (random_uint32() & 0x001FFFFF), &ct_m, ne.pid); char line_buf[SHELL_DEFAULT_BUFSIZE]; shell_run(shell_commands, line_buf, SHELL_DEFAULT_BUFSIZE); return 0; }
bool CharacterDB::del_name_validation_set( uint32 characterID ) { CharIdNameMapItr helper_itr = mIdNameContainer.find(characterID); /* if we are unable to find the entry... return. * @note we do risk keeping the name in the name validation. * which I am willing to take. */ if (helper_itr == mIdNameContainer.end()) return false; const char* name = helper_itr->second.c_str(); if (name == NULL || *name == '\0') return false; uint32 hash = djb2_hash(name); CharValidationSetItr name_itr = mNameValidation.find(hash); if (name_itr != mNameValidation.end()) { // we found the name hash... deleting mNameValidation.erase(name_itr); mIdNameContainer.erase(helper_itr); return true; } else { /* normally this should never happen... */ printf("CharacterDB::del_name_validation_set: unable to remove: %s as its not in the set", name); return false; } }
void CharacterDB::load_name_validation_set() { DBQueryResult res; if(!sDatabase.RunQuery(res, "SELECT" " characterID, itemName AS characterName" " FROM character_" " JOIN entity ON characterID = itemID" )) { codelog(SERVICE__ERROR, "Error in query for %s", res.error.c_str()); return; } DBResultRow row; while(res.GetRow(row) == true) { uint32 characterID = row.GetUInt(0); const char* name = row.GetText(1); //printf("initializing name validation: %s\n", name); uint32 hash = djb2_hash(name); mNameValidation.insert(hash); mIdNameContainer.insert(std::make_pair(characterID, name)); } }
int pk_receive(int id, Packet * pckt, int nbytes) { int n, len; struct sockaddr * addr; UdpPacket udp_pckt; if (id != SRV_ID) { // client receiving len = sizeof srvaddr; addr = (struct sockaddr *) &srvaddr; } else { // server receiving len = sizeof cliaddr; addr = (struct sockaddr *) &cliaddr; } n = recvfrom(sockfd, &udp_pckt, sizeof udp_pckt, 0, addr, (socklen_t *) &len); if (n == -1) { printf("Error receiving packet.\n"); return -1; } unsigned long checksum; checksum = djb2_hash((char *) &(udp_pckt.pckt), sizeof(Packet)); if (checksum == udp_pckt.checksum) { memcpy(pckt, &(udp_pckt.pckt), sizeof(Packet)); } else { return -1; } return n; }
int snippet_library::add_snippet( const std::string &category, const std::string &text ) { int hash = djb2_hash( ( const unsigned char * )text.c_str() ); snippets.insert( std::pair<int, std::string>( hash, text ) ); categories.insert( std::pair<std::string, int>( category, hash ) ); return hash; }
/* Finds the address where the pointer should be (whether or not it is there) * So that we can add it if we want * returns 0 if it exists, 1 otherwise */ static int __get_bucket_addr(hash h, char* key, bucket** ret) { char* lower_key = str_to_lower(key); unsigned int i = djb2_hash(lower_key) % (h -> size); free(lower_key); int found = 0; bucket* it = &(h -> table)[i]; bucket* head = it; // try to find it in the current bucket while(*it && !found) { if( strcasecmp( (*it) -> key, key) == 0 ) found = 1; else it = &( (*it) -> next ); } // if we found a bucket, we need to return it if(*it) *ret = it; else *ret = head; // otherwise return where it should be (head of the bucket) // returning the flag return found; }
void PersonalFlag::SetFlag(const char *class_type, const char *flag_id, const bool enable) { bool found = false; if (!flag_list.empty()) { const unsigned int hash_id = djb2_hash((unsigned char *) class_type, (unsigned char *)flag_id); typedef std::multimap<const unsigned int, ClassFlagAccess, ltint>::iterator RangeType; std::pair<RangeType, RangeType> range = flag_list.equal_range(hash_id); for (RangeType i = range.first; i != range.second; i++) { if (strcmp(i->second.GetFlagID(), flag_id) == 0 && strcmp(i->second.GetClassType(), class_type) == 0) { i->second.SetEnabled(enable); found = true; break; } } } if (!found) { this->AddFlag(class_type, flag_id); } }
const struct macro *definition(struct token name) { struct macro *ref; unsigned long hash, pos; if (name.token != IDENTIFIER) return NULL; hash = djb2_hash(name.strval); pos = hash % HASH_TABLE_LENGTH; ref = ¯o_hash_table[pos]; if (!ref->name.strval) { return NULL; } while ((ref->hash.val != hash || strcmp(ref->name.strval, name.strval)) && ref->hash.next) ref = ref->hash.next; if (ref->hash.val == hash && !strcmp(ref->name.strval, name.strval)) { if (!strcmp(ref->name.strval, "__LINE__")) { ref->replacement[0].token.intval = current_file.line; } return ref; } return NULL; }
/* adrpo: see the comment above about djb2 hash */ modelica_integer stringHashDjb2(metamodelica_string_const s) { const char* str = MMC_STRINGDATA(s); long res = djb2_hash((const unsigned char*)str); res = labs(res); /* fprintf(stderr, "stringHashDjb2 %s-> %ld %ld %ld\n", str, res, mmc_mk_icon(res), mmc_unbox_integer(mmc_mk_icon(res))); */ return res; }
void snippet_library::load_snippet(JsonObject &jsobj) { std::string category = jsobj.get_string("category"); std::string text = _(jsobj.get_string("text").c_str()); int hash = djb2_hash( (const unsigned char*)text.c_str() ); snippets.insert( std::pair<int, std::string>(hash, text) ); categories.insert( std::pair<std::string, int>(category, hash) ); }
static unsigned int relation_salt_cpp(const td_scanner *scanner) { int i, count; unsigned int hash = 0; for (i = 0, count = scanner->path_count; i < count; ++i) { hash ^= (unsigned int) djb2_hash(scanner->include_paths[i]->path); } return hash; }
void PersonalFlag::SetAll(const char *class_type, FlagDescList *flag_list_ptr) { this->Kill(); const DualStrKey *key_value = NULL; for (const char *flag_id = flag_list_ptr->FindFirst(class_type, &key_value); flag_id != NULL; flag_id = flag_list_ptr->FindNext(class_type, &key_value)) { const unsigned int hash_id = djb2_hash((unsigned char *) class_type, (unsigned char *) flag_id); flag_list.insert(std::pair<const unsigned int, ClassFlagAccess> (hash_id, ClassFlagAccess(class_type, flag_id, true))); } }
/* adrpo: see the comment above about djb2 hash */ modelica_integer stringHashDjb2Mod(metamodelica_string_const s, modelica_integer mod) { const char* str = MMC_STRINGDATA(s); long res; if (mod == 0) { MMC_THROW(); } res = djb2_hash((const unsigned char*)str) % (unsigned int) mod; res = labs(res); /* fprintf(stderr, "stringHashDjb2Mod %s %ld-> %ld %ld %ld\n", str, mod, res, mmc_mk_icon(res), mmc_unbox_integer(mmc_mk_icon(res))); */ return res; }
entry *findName(char lastname[], entry *pHead[]) { unsigned long i; i = djb2_hash((unsigned char *)lastname)%SIZE_OF_TABLE; entry *e = pHead[i]; while (e != NULL) { if (strcasecmp(lastname, e->lastName) == 0) return e; e = e->pNext; } return NULL; }
void define(struct macro macro) { static int clean_on_exit; struct macro *ref; unsigned long hash = djb2_hash(macro.name.strval), pos = hash % HASH_TABLE_LENGTH; if (!clean_on_exit) { atexit(cleanup); clean_on_exit = 1; } ref = ¯o_hash_table[pos]; if (!ref->name.strval) { *ref = macro; ref->hash.val = hash; return; } while ((ref->hash.val != hash || strcmp(ref->name.strval, macro.name.strval)) && ref->hash.next) ref = ref->hash.next; if (ref->hash.val == hash && !strcmp(ref->name.strval, macro.name.strval)) { if (macrocmp(ref, ¯o)) { error("Redefinition of macro '%s' with different substitution.", macro.name.strval); exit(1); } /* Already have this definition, but need to clean up memory that we * took ownership of. */ if (macro.size) { free(macro.replacement); } return; } assert(!ref->hash.next); ref->hash.next = calloc(1, sizeof(*ref)); ref = ref->hash.next; *ref = macro; ref->hash.val = hash; }
bool CharacterDB::add_name_validation_set( const char* name, uint32 characterID ) { if (name == NULL || *name == '\0') return false; uint32 hash = djb2_hash(name); /* check if the name is already present ( this should not be possible but we all know how hackers are ) */ if (mNameValidation.find(hash) != mNameValidation.end()) { printf("CharacterDB::add_name_validation_set: unable to add: %s as its a dupe", name); return false; } mNameValidation.insert(hash); mIdNameContainer.insert(std::make_pair(characterID, name)); return true; }
bool CharacterDB::ValidateCharName(const char *name) { if (name == NULL || *name == '\0') return false; /* hash the name */ uint32 hash = djb2_hash(name); /* check if its in our std::set */ CharValidationSetItr itr = mNameValidation.find(hash); /* if itr is not equal to the end of the set it means that the same hash has been found */ if (itr != mNameValidation.end()) return false; /* if we got here the name is "new" */ return true; }
void undef(struct token name) { struct macro *ref, *prev; unsigned long hash, pos; if (name.token != IDENTIFIER) return; hash = djb2_hash(name.strval); pos = hash % HASH_TABLE_LENGTH; ref = ¯o_hash_table[pos]; prev = ref; if (!ref->name.strval) { return; } /* Special case if found in static buffer. */ if (ref->hash.val == hash && !strcmp(ref->name.strval, name.strval)) { prev = ref->hash.next; if (ref->replacement) free(ref->replacement); memset(ref, 0, sizeof(*ref)); if (prev) { *ref = *prev; free(prev); } return; } /* Get pointer to match, and predecessor. */ while ((ref->hash.val != hash || strcmp(ref->name.strval, name.strval)) && ref->hash.next) { prev = ref; ref = ref->hash.next; } /* Remove node in middle of list. */ if (ref->hash.val == hash && !strcmp(ref->name.strval, name.strval)) { assert(ref != prev); prev->hash.next = ref->hash.next; hash_node_free(ref); } }
void append(entry *pHead[],char lastName[]) { entry *e; unsigned long i; i = djb2_hash((unsigned char *)lastName)%SIZE_OF_TABLE; if(pHead[i]==NULL) { pHead[i] = (entry *) malloc(sizeof(entry)); pHead[i]->pNext = NULL; strcpy(pHead[i]->lastName,lastName); pHead[i]->pDetail = NULL; } else { for(e=pHead[i]; e->pNext!=NULL; e=e->pNext); e->pNext = (entry *) malloc(sizeof(entry)); e = e->pNext; strcpy(e->lastName, lastName); e->pNext = NULL; e->pDetail = NULL; } }
bool GlobalGroupFlag::IsFlagSet(const char *flag_id) { const unsigned int hash_id = djb2_hash((unsigned char *)flag_id); typedef std::multimap<const unsigned int, FlagAccessSwitch, ltint>::iterator RangeType; std::pair<RangeType, RangeType> range = flag_list.equal_range(hash_id); for (RangeType i = range.first; i != range.second; i++) { if (strcmp(i->second.GetFlagID(), flag_id) == 0) { if (i->second.IsEnabled()) { return true; } return false; } } return false; }
void snippet_library::load() throw (std::string) { catajson snippetRaw("data/raw/snippets.json"); if(!json_good()) throw (std::string)"Could not read data/raw/snippets.json"; catajson snippetList = snippetRaw.get("snippets"); for( snippetList.set_begin(); snippetList.has_curr(); snippetList.next() ) { const catajson curr = snippetList.curr(); // required fields const std::string category = curr.get("category").as_string(); const std::string text = curr.get("text").as_string(); const int hash = djb2_hash( (const unsigned char*)text.c_str() ); snippets.insert( std::pair<int, std::string>(hash, text) ); categories.insert( std::pair<std::string, int>(category, hash) ); } if(!json_good()) throw (std::string)"There was an error reading data/raw/snippets.json"; }
void GlobalGroupFlag::SetFlag(const char *flag_id, const bool enable) { const unsigned int hash_id = djb2_hash((unsigned char *)flag_id); bool found = false; typedef std::multimap<const unsigned int, FlagAccessSwitch, ltint>::iterator RangeType; std::pair<RangeType, RangeType> range = flag_list.equal_range(hash_id); for (RangeType i = range.first; i != range.second; i++) { if (strcmp(i->second.GetFlagID(), flag_id) == 0) { i->second.SetEnabled(enable); found = true; break; } } if (!found) { this->AddFlag(flag_id); } }
static int hash_index(hash_table_t * hash, const char *key) { return djb2_hash((const unsigned char *)key) % hash->n_buckets; }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif #ifdef ENABLE_LOGGING setupDebug(); #endif int seed = time(NULL); // set locale to system default setlocale(LC_ALL, ""); #ifdef LOCALIZE bindtextdomain("cataclysm-dda", "lang/mo"); bind_textdomain_codeset("cataclysm-dda", "UTF-8"); textdomain("cataclysm-dda"); #endif //args: world seeding only. argc--; argv++; while (argc){ if(std::string(argv[0]) == "--seed"){ argc--; argv++; if(argc){ seed = djb2_hash((unsigned char*)argv[0]); argc--; argv++; } } else // ignore unknown args. argc--; argv++; } // ncurses stuff initOptions(); load_options(); // For getting size options initscr(); // Initialize ncurses #ifdef SDLTILES init_tiles(); #endif // SDLTILES noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers init_colors(); // See color.cpp // curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); bool quit_game = false; g = new game; g->init_data(); if(g->game_error()) exit_handler(-999); g->init_ui(); MAPBUFFER.set_game(g); if(g->game_error()) exit_handler(-999); curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif do { if(!g->opening_screen()) { quit_game = true; } while (!g->do_turn()) ; if (g->game_quit() || g->game_error()) quit_game = true; } while (!quit_game); exit_handler(-999); return 0; }
void PersonalFlag::AddFlag(const char *class_type, const char *flag_id) { const unsigned int hash_id = djb2_hash((unsigned char *) class_type, (unsigned char *) flag_id); flag_list.insert(std::pair<const unsigned int, ClassFlagAccess> (hash_id, ClassFlagAccess(class_type, flag_id, true))); }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif int seed = time(NULL); bool verifyexit = false; bool check_all_mods = false; // Set default file paths #ifdef PREFIX #define Q(STR) #STR #define QUOTE(STR) Q(STR) init_base_path(std::string(QUOTE(PREFIX))); #else PATH_INFO::init_base_path(""); #endif #ifdef USE_HOME_DIR PATH_INFO::init_user_dir(); #else PATH_INFO::init_user_dir("./"); #endif PATH_INFO::set_standart_filenames(); MAP_SHARING::setDefaults(); // Process CLI arguments int saved_argc = --argc; // skip program name char **saved_argv = ++argv; while (argc) { if(std::string(argv[0]) == "--seed") { argc--; argv++; if(argc) { seed = djb2_hash((unsigned char *)argv[0]); argc--; argv++; } } else if(std::string(argv[0]) == "--jsonverify") { argc--; argv++; verifyexit = true; } else if(std::string(argv[0]) == "--check-mods") { argc--; argv++; check_all_mods = true; } else if(std::string(argv[0]) == "--basepath") { argc--; argv++; if(argc) { PATH_INFO::init_base_path(std::string(argv[0])); PATH_INFO::set_standart_filenames(); argc--; argv++; } } else if(std::string(argv[0]) == "--userdir") { argc--; argv++; if (argc) { PATH_INFO::init_user_dir( argv[0] ); PATH_INFO::set_standart_filenames(); argc--; argv++; } } else if(std::string(argv[0]) == "--username") { argc--; argv++; if (argc) { MAP_SHARING::setUsername(std::string(argv[0])); argc--; argv++; } } else if(std::string(argv[0]) == "--addadmin") { argc--; argv++; if (argc) { MAP_SHARING::addAdmin(std::string(argv[0])); argc--; argv++; } } else if(std::string(argv[0]) == "--adddebugger") { argc--; argv++; if (argc) { MAP_SHARING::addDebugger(std::string(argv[0])); argc--; argv++; } } else if(std::string(argv[0]) == "--shared") { argc--; argv++; MAP_SHARING::setSharing(true); MAP_SHARING::setCompetitive(true); MAP_SHARING::setWorldmenu(false); } else if(std::string(argv[0]) == "--competitive") { argc--; argv++; MAP_SHARING::setCompetitive(true); } else { // Skipping other options. argc--; argv++; } } while (saved_argc) { if(std::string(saved_argv[0]) == "--worldmenu") { saved_argc--; saved_argv++; MAP_SHARING::setWorldmenu(true); } else if(std::string(saved_argv[0]) == "--datadir") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("datadir", std::string(saved_argv[0])); PATH_INFO::update_datadir(); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--savedir") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("savedir", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--configdir") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("config_dir", std::string(saved_argv[0])); PATH_INFO::update_config_dir(); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--optionfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("options", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--keymapfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("keymap", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--autopickupfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("autopickup", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else if(std::string(saved_argv[0]) == "--motdfile") { saved_argc--; saved_argv++; if(saved_argc) { PATH_INFO::update_pathname("motd", std::string(saved_argv[0])); saved_argc--; saved_argv++; } } else { // ignore unknown args. saved_argc--; saved_argv++; } } // setup debug loggind #ifdef ENABLE_LOGGING setupDebug(); #endif // set locale to system default setlocale(LC_ALL, ""); #ifdef LOCALIZE const char *locale_dir; #ifdef __linux__ if (!FILENAMES["base_path"].empty()) { locale_dir = std::string(FILENAMES["base_path"] + "share/locale").c_str(); } else { locale_dir = "lang/mo"; } #else locale_dir = "lang/mo"; #endif // __linux__ bindtextdomain("cataclysm-dda", locale_dir); bind_textdomain_codeset("cataclysm-dda", "UTF-8"); textdomain("cataclysm-dda"); #endif // LOCALIZE // ncurses stuff initOptions(); load_options(); // For getting size options #ifdef LOCALIZE setlocale(LC_ALL, OPTIONS["USE_LANG"].getValue().c_str()); #endif // LOCALIZE if (initscr() == NULL) { // Initialize ncurses DebugLog() << "initscr failed!\n"; return 1; } init_interface(); noecho(); // Don't echo keypresses cbreak(); // C-style breaks (e.g. ^C to SIGINT) keypad(stdscr, true); // Numpad is numbers #if !(defined TILES || defined _WIN32 || defined WINDOWS) // For tiles or windows, this is handled already in initscr(). init_colors(); #endif // curs_set(0); // Invisible cursor set_escdelay(10); // Make escape actually responsive std::srand(seed); g = new game; // First load and initialize everything that does not // depend on the mods. try { if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) { debugmsg("Can't open or create %s. Check permissions.", FILENAMES["user_dir"].c_str()); exit_handler(-999); } g->load_static_data(); if (verifyexit) { if(g->game_error()) { exit_handler(-999); } exit_handler(0); } if (check_all_mods) { // Here we load all the mods and check their // consistency (both is done in check_all_mod_data). g->init_ui(); popup_nowait("checking all mods"); g->check_all_mod_data(); if(g->game_error()) { exit_handler(-999); } // At this stage, the mods (and core game data) // are find and we could start playing, but this // is only for verifying that stage, so we exit. exit_handler(0); } } catch(std::string &error_message) { if(!error_message.empty()) { debugmsg("%s", error_message.c_str()); } exit_handler(-999); } // Now we do the actuall game g->init_ui(); if(g->game_error()) { exit_handler(-999); } curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif bool quit_game = false; do { if(!g->opening_screen()) { quit_game = true; } while (!quit_game && !g->do_turn()) ; if (g->game_quit() || g->game_error()) { quit_game = true; } } while (!quit_game); exit_handler(-999); return 0; }
int APIENTRY WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int argc = __argc; char **argv = __argv; #else int main(int argc, char *argv[]) { #endif int seed = time(NULL); bool verifyexit = false; bool check_mods = false; std::string dump; dump_mode dmode = dump_mode::TSV; std::vector<std::string> opts; std::string world; /** if set try to load first save in this world on startup */ // Set default file paths #ifdef PREFIX #define Q(STR) #STR #define QUOTE(STR) Q(STR) PATH_INFO::init_base_path(std::string(QUOTE(PREFIX))); #else PATH_INFO::init_base_path(""); #endif #if (defined USE_HOME_DIR || defined USE_XDG_DIR) PATH_INFO::init_user_dir(); #else PATH_INFO::init_user_dir("./"); #endif PATH_INFO::set_standard_filenames(); MAP_SHARING::setDefaults(); { const char *section_default = nullptr; const char *section_map_sharing = "Map sharing"; const char *section_user_directory = "User directories"; const std::array<arg_handler, 12> first_pass_arguments = {{ { "--seed", "<string of letters and or numbers>", "Sets the random number generator's seed value", section_default, [&seed](int num_args, const char **params) -> int { if (num_args < 1) return -1; const unsigned char *hash_input = (const unsigned char *) params[0]; seed = djb2_hash(hash_input); return 1; } }, { "--jsonverify", nullptr, "Checks the cdda json files", section_default, [&verifyexit](int, const char **) -> int { verifyexit = true; return 0; } }, { "--check-mods", "[mods...]", "Checks the json files belonging to cdda mods", section_default, [&check_mods,&opts]( int n, const char *params[] ) -> int { check_mods = true; test_mode = true; for( int i = 0; i < n; ++i ) { opts.emplace_back( params[ i ] ); } return 0; } }, { "--dump-stats", "<what> [mode = TSV] [opts...]", "Dumps item stats", section_default, [&dump,&dmode,&opts](int n, const char *params[]) -> int { if( n < 1 ) { return -1; } test_mode = true; dump = params[ 0 ]; for( int i = 2; i < n; ++i ) { opts.emplace_back( params[ i ] ); } if( n >= 2 ) { if( !strcmp( params[ 1 ], "TSV" ) ) { dmode = dump_mode::TSV; return 0; } else if( !strcmp( params[ 1 ], "HTML" ) ) { dmode = dump_mode::HTML; return 0; } else { return -1; } } return 0; } }, { "--world", "<name>", "Load world", section_default, [&world](int n, const char *params[]) -> int { if( n < 1 ) { return -1; } world = params[0]; return 1; } }, { "--basepath", "<path>", "Base path for all game data subdirectories", section_default, [](int num_args, const char **params) { if (num_args < 1) return -1; PATH_INFO::init_base_path(params[0]); PATH_INFO::set_standard_filenames(); return 1; } }, { "--shared", nullptr, "Activates the map-sharing mode", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setSharing(true); MAP_SHARING::setCompetitive(true); MAP_SHARING::setWorldmenu(false); return 0; } }, { "--username", "<name>", "Instructs map-sharing code to use this name for your character.", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::setUsername(params[0]); return 1; } }, { "--addadmin", "<username>", "Instructs map-sharing code to use this name for your character and give you " "access to the cheat functions.", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::addAdmin(params[0]); return 1; } }, { "--adddebugger", "<username>", "Informs map-sharing code that you're running inside a debugger", section_map_sharing, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; MAP_SHARING::addDebugger(params[0]); return 1; } }, { "--competitive", nullptr, "Instructs map-sharing code to disable access to the in-game cheat functions", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setCompetitive(true); return 0; } }, { "--userdir", "<path>", "Base path for user-overrides to files from the ./data directory and named below", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::init_user_dir(params[0]); PATH_INFO::set_standard_filenames(); return 1; } } }}; // The following arguments are dependent on one or more of the previous flags and are run // in a second pass. const std::array<arg_handler, 9> second_pass_arguments = {{ { "--worldmenu", nullptr, "Enables the world menu in the map-sharing code", section_map_sharing, [](int, const char **) -> int { MAP_SHARING::setWorldmenu(true); return true; } }, { "--datadir", "<directory name>", "Sub directory from which game data is loaded", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("datadir", params[0]); PATH_INFO::update_datadir(); return 1; } }, { "--savedir", "<directory name>", "Subdirectory for game saves", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("savedir", params[0]); return 1; } }, { "--configdir", "<directory name>", "Subdirectory for game configuration", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("config_dir", params[0]); PATH_INFO::update_config_dir(); return 1; } }, { "--memorialdir", "<directory name>", "Subdirectory for memorials", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("memorialdir", params[0]); return 1; } }, { "--optionfile", "<filename>", "Name of the options file within the configdir", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("options", params[0]); return 1; } }, { "--keymapfile", "<filename>", "Name of the keymap file within the configdir", section_user_directory, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("keymap", params[0]); return 1; } }, { "--autopickupfile", "<filename>", "Name of the autopickup options file within the configdir", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("autopickup", params[0]); return 1; } }, { "--motdfile", "<filename>", "Name of the message of the day file within the motd directory", nullptr, [](int num_args, const char **params) -> int { if (num_args < 1) return -1; PATH_INFO::update_pathname("motd", params[0]); return 1; } }, }}; // Process CLI arguments. const size_t num_first_pass_arguments = sizeof(first_pass_arguments) / sizeof(first_pass_arguments[0]); const size_t num_second_pass_arguments = sizeof(second_pass_arguments) / sizeof(second_pass_arguments[0]); int saved_argc = --argc; // skip program name const char **saved_argv = (const char **)++argv; while (argc) { if(!strcmp(argv[0], "--help")) { printHelpMessage(first_pass_arguments.data(), num_first_pass_arguments, second_pass_arguments.data(), num_second_pass_arguments); return 0; } else { bool arg_handled = false; for (size_t i = 0; i < num_first_pass_arguments; ++i) { auto &arg_handler = first_pass_arguments[i]; if (!strcmp(argv[0], arg_handler.flag)) { argc--; argv++; int args_consumed = arg_handler.handler(argc, (const char **)argv); if (args_consumed < 0) { printf("Failed parsing parameter '%s'\n", *(argv - 1)); exit(1); } argc -= args_consumed; argv += args_consumed; arg_handled = true; break; } } // Skip other options. if (!arg_handled) { --argc; ++argv; } } } while (saved_argc) { bool arg_handled = false; for (size_t i = 0; i < num_second_pass_arguments; ++i) { auto &arg_handler = second_pass_arguments[i]; if (!strcmp(saved_argv[0], arg_handler.flag)) { --saved_argc; ++saved_argv; int args_consumed = arg_handler.handler(saved_argc, saved_argv); if (args_consumed < 0) { printf("Failed parsing parameter '%s'\n", *(argv - 1)); exit(1); } saved_argc -= args_consumed; saved_argv += args_consumed; arg_handled = true; break; } } // Ingore unknown options. if (!arg_handled) { --saved_argc; ++saved_argv; } } } if (!assure_dir_exist(FILENAMES["user_dir"].c_str())) { printf("Can't open or create %s. Check permissions.\n", FILENAMES["user_dir"].c_str()); exit(1); } setupDebug(); /** * OS X does not populate locale env vars correctly (they usually default to * "C") so don't bother trying to set the locale based on them. */ #if (!defined MACOSX) if (setlocale(LC_ALL, "") == NULL) { DebugLog(D_WARNING, D_MAIN) << "Error while setlocale(LC_ALL, '')."; } else { #endif try { std::locale::global( std::locale( "" ) ); } catch( const std::exception& ) { // if user default locale retrieval isn't implemented by system try{ // default to basic C locale std::locale::global( std::locale::classic() ); } catch( const std::exception &err ) { debugmsg( "%s", err.what() ); exit_handler(-999); } } #if (!defined MACOSX) } #endif get_options().init(); get_options().load(); set_language(); // in test mode don't initialize curses to avoid escape sequences being inserted into output stream if( !test_mode ) { try { catacurses::init_interface(); } catch( const std::exception &err ) { // can't use any curses function as it has not been initialized std::cerr << "Error while initializing the interface: " << err.what() << std::endl; DebugLog( D_ERROR, DC_ALL ) << "Error while initializing the interface: " << err.what() << "\n"; return 1; } } srand(seed); g = new game; // First load and initialize everything that does not // depend on the mods. try { g->load_static_data(); if (verifyexit) { exit_handler(0); } if( !dump.empty() ) { init_colors(); exit( g->dump_stats( dump, dmode, opts ) ? 0 : 1 ); } if( check_mods ) { init_colors(); loading_ui ui( false ); exit( g->check_mod_data( opts, ui ) && !test_dirty ? 0 : 1 ); } } catch( const std::exception &err ) { debugmsg( "%s", err.what() ); exit_handler(-999); } // Now we do the actual game. g->init_ui(); curs_set(0); // Invisible cursor here, because MAPBUFFER.load() is crash-prone #if (!(defined _WIN32 || defined WINDOWS)) struct sigaction sigIntHandler; sigIntHandler.sa_handler = exit_handler; sigemptyset(&sigIntHandler.sa_mask); sigIntHandler.sa_flags = 0; sigaction(SIGINT, &sigIntHandler, NULL); #endif #ifdef LOCALIZE std::string lang = ""; #if (defined _WIN32 || defined WINDOWS) lang = getLangFromLCID( GetUserDefaultLCID() ); #else const char *v = setlocale( LC_ALL, NULL ); if( v != NULL ) { lang = v; if( lang == "C" ) { lang = "en"; } } #endif if( get_option<std::string>( "USE_LANG" ).empty() && ( lang.empty() || !isValidLanguage( lang ) ) ) { select_language(); set_language(); } #endif while( true ) { if( !world.empty() ) { if( !g->load( world ) ) { break; } world.clear(); // ensure quit returns to opening screen } else { main_menu menu; if( !menu.opening_screen() ) { break; } } while( !g->do_turn() ); }; exit_handler(-999); return 0; }