diff --git a/code/menuui/mainhallmenu.cpp b/code/menuui/mainhallmenu.cpp index ed50cd57aec..7d755322b06 100644 --- a/code/menuui/mainhallmenu.cpp +++ b/code/menuui/mainhallmenu.cpp @@ -975,8 +975,9 @@ void main_hall_do(float frametime) if (Num_recent_missions > 0) { strcpy_s(Game_current_mission_filename, Recent_missions[0]); } else { - if (mission_load_up_campaign()) { + if (mission_load_up_campaign() || Campaign.missions.empty()) { main_hall_set_notify_string(XSTR( "Campaign file is currently unavailable", 1606)); + break; } strcpy_s(Game_current_mission_filename, Campaign.missions[0].name); } diff --git a/code/menuui/readyroom.cpp b/code/menuui/readyroom.cpp index 073759a5940..9dd8140a80e 100644 --- a/code/menuui/readyroom.cpp +++ b/code/menuui/readyroom.cpp @@ -36,8 +36,6 @@ -#define MAX_MISSIONS 1024 - int Mission_list_coords[GR_NUM_RESOLUTIONS][4] = { { // GR_640 33, 108, 402, 279 @@ -198,17 +196,13 @@ static struct { } sim_room_lines[MAX_LINES]; static char Cur_campaign[MAX_FILENAME_LEN]; -static char *Mission_filenames[MAX_MISSIONS] = { NULL }; -static char *Standalone_mission_names[MAX_MISSIONS] = { NULL }; -static int Standalone_mission_flags[MAX_MISSIONS]; -static char *Campaign_missions[MAX_MISSIONS] = { NULL }; -static char *Campaign_mission_names[MAX_CAMPAIGN_MISSIONS] = { NULL }; -static int Campaign_mission_flags[MAX_MISSIONS]; +static SCP_vector Mission_filenames; +static SCP_vector> Standalone_mission_names; +static SCP_vector Campaign_missions; +static SCP_vector> Campaign_mission_names; static int Simroom_show_all = 0; static int Standalone_mission_names_inited = 0; static int Campaign_mission_names_inited = 0; -static int Num_standalone_missions; -static int Num_campaign_missions; //static int Num_player_missions; static int Scroll_offset; static int Selected_line; @@ -364,8 +358,8 @@ int build_campaign_mission_filename_hash_table() { int rval; // Go through all campaign missions - for (int i=0; i 0) { // sanity check - if (strlen(Mission_filenames[Num_standalone_missions_with_info]) < MAX_FILENAME_LEN - 4) { // sanity check? - // tack on an extension - auto filename = cf_add_ext(Mission_filenames[Num_standalone_missions_with_info], FS_MISSION_FILE_EXT); - - // update popup - sprintf(popup_str, XSTR("Single Mission\n\n%s", 989), filename); - popup_change_text(popup_str.c_str()); - - // activate tstrings check - Lcl_unexpected_tstring_check = &lcl_weirdness; - - // check if we can list the mission, if loading basic info didn't return an error code, and if we didn't find an XSTR mismatch - bool condition = !mission_is_ignored(filename) && !get_mission_info(filename) && !lcl_weirdness; - - // maybe log - if (lcl_weirdness) - mprintf(("Skipping %s due to XSTR mismatch\n", filename)); - - // deactivate tstrings check - Lcl_unexpected_tstring_check = nullptr; - - if (condition) { - Standalone_mission_names[Num_standalone_missions_with_info] = vm_strdup(The_mission.name.c_str()); - Standalone_mission_flags[Num_standalone_missions_with_info] = The_mission.game_type; - int y = Num_lines * (font_height + 2); - - //Add mission data to the API - if (API_Access) { - sim_mission api_mission; - api_mission.name = The_mission.name; - api_mission.filename = filename; - api_mission.mission_desc = The_mission.mission_desc; - api_mission.author = The_mission.author; - api_mission.visible = 1; - - Sim_Missions.push_back(std::move(api_mission)); - } + Standalone_mission_names[Num_standalone_missions_with_info].reset(); - // determine some extra information - int flags = 0; - auto fb = game_find_builtin_mission(filename); - if((fb != NULL) && (fb->flags & FSB_FROM_VOLITION)){ - flags |= READYROOM_FLAG_FROM_VOLITION; - } + if (Mission_filenames[Num_standalone_missions_with_info].size() < MAX_FILENAME_LEN - 4) { // sanity check? + // tack on an extension + auto filename = cf_add_ext(Mission_filenames[Num_standalone_missions_with_info].c_str(), FS_MISSION_FILE_EXT); + + // update popup + sprintf(popup_str, XSTR("Single Mission\n\n%s", 989), filename); + popup_change_text(popup_str.c_str()); + + // activate tstrings check + Lcl_unexpected_tstring_check = &lcl_weirdness; + + // check if we can list the mission, if loading basic info didn't return an error code, and if we didn't find an XSTR mismatch + bool condition = !mission_is_ignored(filename) && !get_mission_info(filename) && !lcl_weirdness; + + // maybe log + if (lcl_weirdness) + mprintf(("Skipping %s due to XSTR mismatch\n", filename)); + + // deactivate tstrings check + Lcl_unexpected_tstring_check = nullptr; + + if (condition) { + Standalone_mission_names[Num_standalone_missions_with_info].reset(vm_strdup(The_mission.name.c_str())); + int y = Num_lines * (font_height + 2); + + //Add mission data to the API + if (API_Access) { + sim_mission api_mission; + api_mission.name = The_mission.name; + api_mission.filename = filename; + api_mission.mission_desc = The_mission.mission_desc; + api_mission.author = The_mission.author; + api_mission.visible = 1; - // add the line - sim_room_line_add(READYROOM_LINE_MISSION, Standalone_mission_names[Num_standalone_missions_with_info], Mission_filenames[Num_standalone_missions_with_info], list_x1 + M_TEXT_X, y, flags); + Sim_Missions.push_back(std::move(api_mission)); + } + + // determine some extra information + int flags = 0; + auto fb = game_find_builtin_mission(filename); + if((fb != nullptr) && (fb->flags & FSB_FROM_VOLITION)){ + flags |= READYROOM_FLAG_FROM_VOLITION; } - } - Num_standalone_missions_with_info++; + // add the line + sim_room_line_add(READYROOM_LINE_MISSION, Standalone_mission_names[Num_standalone_missions_with_info].get(), Mission_filenames[Num_standalone_missions_with_info].c_str(), list_x1 + M_TEXT_X, y, flags); + } } - if (Num_standalone_missions_with_info == Num_standalone_missions) { + Num_standalone_missions_with_info++; + + if (Num_standalone_missions_with_info == sz2i(Mission_filenames.size())) { Standalone_mission_names_inited = 1; return 1; } else { @@ -544,7 +532,7 @@ int build_campaign_mission_list_do_frame(bool API_Access) static int valid_missions_with_info = 0; // we use this to avoid blank entries in the mission list // When no campaign files in data directory - if (Campaign.num_missions == 0) { + if (Campaign.missions.empty()) { Campaign_mission_names_inited = 1; return 1; } @@ -553,9 +541,14 @@ int build_campaign_mission_list_do_frame(bool API_Access) sprintf(popup_str, XSTR("Campaign Mission\n\n%s", 990), Campaign.missions[Num_campaign_missions_with_info].name); popup_change_text(popup_str.c_str()); + // Ensure storage matches the number of missions we are about to process + if (Campaign_mission_names.size() != Campaign.missions.size()) { + Campaign_mission_names.clear(); + Campaign_mission_names.resize(Campaign.missions.size()); + } + // Set global variable so we we'll have list available next time - Campaign_mission_names[Num_campaign_missions_with_info] = NULL; - Campaign_mission_flags[Num_campaign_missions_with_info] = 0; + Campaign_mission_names[Num_campaign_missions_with_info].reset(); // Only allow missions already completed if (Campaign.missions[Num_campaign_missions_with_info].completed || (Simroom_show_all || API_Access)) @@ -565,8 +558,7 @@ int build_campaign_mission_list_do_frame(bool API_Access) auto filename = Campaign.missions[Num_campaign_missions_with_info].name; // add to list - Campaign_mission_names[Num_campaign_missions_with_info] = vm_strdup(The_mission.name.c_str()); - Campaign_mission_flags[Num_campaign_missions_with_info] = The_mission.game_type; + Campaign_mission_names[Num_campaign_missions_with_info].reset(vm_strdup(The_mission.name.c_str())); int y = valid_missions_with_info * (font_height + 2); // Add mission data to the API @@ -589,14 +581,14 @@ int build_campaign_mission_list_do_frame(bool API_Access) flags |= READYROOM_FLAG_FROM_VOLITION; } - sim_room_line_add(READYROOM_LINE_CMISSION, Campaign_mission_names[Num_campaign_missions_with_info], Campaign.missions[Num_campaign_missions_with_info].name, list_x1 + C_SUBTEXT_X, y, flags); + sim_room_line_add(READYROOM_LINE_CMISSION, Campaign_mission_names[Num_campaign_missions_with_info].get(), Campaign.missions[Num_campaign_missions_with_info].name, list_x1 + C_SUBTEXT_X, y, flags); valid_missions_with_info++; } } Num_campaign_missions_with_info++; - if (Num_campaign_missions_with_info == Campaign.num_missions) { + if (Num_campaign_missions_with_info == sz2i(Campaign.missions.size())) { valid_missions_with_info = 0; Campaign_mission_names_inited = 1; return 1; @@ -629,13 +621,13 @@ void sim_room_build_listing() if (Standalone_mission_names[i]) { // determine some extra information int flags = 0; - auto full_filename = cf_add_ext(Mission_filenames[i], FS_MISSION_FILE_EXT); + auto full_filename = cf_add_ext(Mission_filenames[i].c_str(), FS_MISSION_FILE_EXT); auto fb = game_find_builtin_mission(full_filename); if((fb != NULL) && (fb->flags & FSB_FROM_VOLITION)){ flags |= READYROOM_FLAG_FROM_VOLITION; } - sim_room_line_add(READYROOM_LINE_MISSION, Standalone_mission_names[i], Mission_filenames[i], list_x1 + M_TEXT_X, y, flags); + sim_room_line_add(READYROOM_LINE_MISSION, Standalone_mission_names[i].get(), Mission_filenames[i].c_str(), list_x1 + M_TEXT_X, y, flags); y += font_height + 2; } } @@ -662,7 +654,7 @@ void sim_room_build_listing() flags |= READYROOM_FLAG_FROM_VOLITION; } - sim_room_line_add(READYROOM_LINE_CMISSION, Campaign_mission_names[i], Campaign.missions[i].name, list_x1 + C_SUBTEXT_X, y, flags); + sim_room_line_add(READYROOM_LINE_CMISSION, Campaign_mission_names[i].get(), Campaign.missions[i].name, list_x1 + C_SUBTEXT_X, y, flags); y += font_height + 2; // Goober5000 - added +2 to conform with above } } @@ -683,13 +675,7 @@ void sim_room_reset_campaign_listing() if (!Campaign_mission_names_inited) return; - - for (int i=0; i= 0) bm_release(Background_bitmap); - if (Standalone_mission_names_inited){ - for (i=0; iflags & FSB_FROM_VOLITION) { flags |= READYROOM_FLAG_FROM_VOLITION; } } - sim_room_line_add(READYROOM_LINE_CAMPAIGN, Campaign_names[i], Campaign_file_names[i], Cr_list_coords[gr_screen.res][0], y, flags); + sim_room_line_add(READYROOM_LINE_CAMPAIGN, Campaign_names[i].c_str(), Campaign_file_names[i].c_str(), Cr_list_coords[gr_screen.res][0], y, flags); y += font_height + 2; } } @@ -1540,13 +1480,11 @@ void campaign_room_build_listing() void set_new_campaign_line(int n) { - char *str; - Selected_campaign_index = n; - str = Campaign_descs[Selected_campaign_index]; + const auto &desc = Campaign_descs[Selected_campaign_index]; Num_info_lines = 0; - if (str) { - Num_info_lines = split_str(str, Cr_info_coords[gr_screen.res][2], Info_text_line_size, Info_text_ptrs, MAX_INFO_LINES, MAX_INFO_LINE_LEN); + if (!desc.empty()) { + Num_info_lines = split_str(desc.c_str(), Cr_info_coords[gr_screen.res][2], Info_text_line_size, Info_text_ptrs, MAX_INFO_LINES, MAX_INFO_LINE_LEN); Assert(Num_info_lines >= 0); } @@ -1661,7 +1599,7 @@ int campaign_room_button_pressed(int n) */ case CR_RESET_BUTTON: - if ( (Active_campaign_index < 0) || (Active_campaign_index >= Num_campaigns) ) + if ( !Campaign_file_names.in_bounds(Active_campaign_index) ) gamesnd_play_iface(InterfaceSounds::GENERAL_FAIL); else if (campaign_room_reset_campaign(Active_campaign_index)) gamesnd_play_iface(InterfaceSounds::GENERAL_FAIL); @@ -1680,7 +1618,7 @@ bool campaign_build_campaign_list() { mission_campaign_next_mission(); } else { Campaign.filename[0] = 0; - Campaign.num_missions = 0; + Campaign.missions.clear(); mission_campaign_load_failure_popup(); } @@ -1784,12 +1722,13 @@ void campaign_room_init() Selected_campaign_index = Active_campaign_index = -1; if (!load_failed) { - for (i=0; i= Num_campaigns)) { + if (!Campaign_file_names.in_bounds(Active_campaign_index)) { // Player is trying to use a regular pilot in the demo. - if (Num_campaigns < 1) { + if (Campaign_file_names.empty()) { // If there are no campaigns loaded, there's really nothing left to do. popup_game_feature_not_in_demo(); return; @@ -1870,7 +1809,7 @@ void campaign_room_do_frame(float /*frametime*/) switch (k) { case KEY_DOWN: // scroll list down - if (Selected_campaign_index < Num_campaigns - 1) { + if (Selected_campaign_index < sz2i(Campaign_file_names.size()) - 1) { set_new_campaign_line(Selected_campaign_index + 1); gamesnd_play_iface(InterfaceSounds::SCROLL); @@ -1979,7 +1918,7 @@ void campaign_room_do_frame(float /*frametime*/) i++; } - if (Num_campaigns < 1) { + if (Campaign_file_names.empty()) { popup(PF_USE_AFFIRMATIVE_ICON, 1, POPUP_OK, XSTR( "No campaigns are available!", 1613)); Campaign_room_no_campaigns = true; gameseq_post_event(GS_EVENT_MAIN_MENU); diff --git a/code/mission/missioncampaign.cpp b/code/mission/missioncampaign.cpp index 8c7f47e3d2c..f01c0b73f2e 100644 --- a/code/mission/missioncampaign.cpp +++ b/code/mission/missioncampaign.cpp @@ -58,10 +58,9 @@ int Campaign_ending_via_supernova = 0; // stuff for selecting campaigns. We need to keep both arrays around since we display the // list of campaigns by name, but must load campaigns by filename -char *Campaign_names[MAX_CAMPAIGNS] = { NULL }; -char *Campaign_file_names[MAX_CAMPAIGNS] = { NULL }; -char *Campaign_descs[MAX_CAMPAIGNS] = { NULL }; -int Num_campaigns; +SCP_vector Campaign_names; +SCP_vector Campaign_file_names; +SCP_vector Campaign_descs; bool Campaign_file_missing = false; int Campaign_load_failure = 0; int Campaign_names_inited = 0; @@ -96,11 +95,11 @@ campaign Campaign; /** - * Returns a string (which is malloced in this routine) of the name of the given freespace campaign file. - * In the type field, we return if the campaign is a single player or multiplayer campaign. - * The type field will only be valid if the name returned is non-NULL + * Gets the name and type (single or multiplayer) of the given campaign file, and optionally its + * max players, description, and (for multiplayer campaigns) first mission. + * Returns false on failure. */ -bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type, int *max_players, char **desc, char **first_mission) +bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type, int *max_players, SCP_string *desc, SCP_string *first_mission) { int i, success = false; SCP_string campaign_type; @@ -117,11 +116,11 @@ bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type } if (desc) { - *desc = nullptr; + desc->clear(); } if (first_mission) { - *first_mission = nullptr; + first_mission->clear(); } strncpy(fname, filename, MAX_FILENAME_LEN - 1); @@ -161,10 +160,11 @@ bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type if (desc) { if (optional_string("+Description:")) { - *desc = stuff_and_malloc_string(F_MULTITEXT, NULL); + stuff_string(*desc, F_MULTITEXT); + drop_white_space(*desc); } else { - *desc = NULL; + desc->clear(); } } @@ -175,7 +175,8 @@ bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type // Cyborg17 - and the first mission name if we want it, too if (first_mission) { skip_to_string("$Mission:"); - *first_mission = stuff_and_malloc_string(F_NAME, nullptr); + stuff_string(*first_mission, F_NAME); + drop_white_space(*first_mission); } } @@ -195,13 +196,14 @@ bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type } /** - * Parses campaign and returns a list of missions in it. - * @return Number of missions added to the 'list', and up to 'max' missions may be added to 'list'. + * Parses campaign and appends the missions in it to 'list'. + * @return Number of missions added to the 'list'. * @return Negative on error. */ -int mission_campaign_get_mission_list(const char *filename, char **list, int max) +int mission_campaign_get_mission_list(const char *filename, SCP_vector &list) { - int i, num = 0; + int num = 0; + const size_t original_size = list.size(); char name[MAX_FILENAME_LEN]; filename = cf_add_ext(filename, FS_CAMPAIGN_FILE_EXT); @@ -214,19 +216,16 @@ int mission_campaign_get_mission_list(const char *filename, char **list, int max while (skip_to_string("$Mission:") > 0) { stuff_string(name, F_NAME, MAX_FILENAME_LEN); - if (num < max) - list[num++] = vm_strdup(name); - else - Warning(LOCATION, "Maximum number of missions exceeded (%d)!", max); + list.emplace_back(name); + num++; } } catch (const parse::ParseException& e) { mprintf(("MISSIONCAMPAIGN: Unable to parse '%s'! Error message = %s.\n", filename, e.what())); - // since we can't return count of allocated elements, free them instead - for (i = 0; i 0) { - for (i = incr; i < Num_campaigns; i++) { + for (i = incr; i < num_campaigns; i++) { j = i - incr; while (j >= 0) { - char *name1 = Campaign_names[j]; - char *name2 = Campaign_names[j + incr]; - // if we hit this then a coder probably did something dumb (like not needing to sort) - if ( (name1 == NULL) || (name2 == NULL) ) { + if ( Campaign_names[j].empty() || Campaign_names[j + incr].empty() ) { Int3(); break; } + const char *name1 = Campaign_names[j].c_str(); + const char *name2 = Campaign_names[j + incr].c_str(); + if ( !strnicmp(name1, "the ", 4) ) name1 += 4; @@ -355,21 +338,13 @@ void mission_campaign_build_list(bool desc, bool sort, bool multiplayer) if (stricmp(name1, name2) > 0) { // first, do filenames - t = Campaign_file_names[j]; - Campaign_file_names[j] = Campaign_file_names[j + incr]; - Campaign_file_names[j + incr] = t; + std::swap(Campaign_file_names[j], Campaign_file_names[j + incr]); // next, actual names - t = Campaign_names[j]; - Campaign_names[j] = Campaign_names[j + incr]; - Campaign_names[j + incr] = t; + std::swap(Campaign_names[j], Campaign_names[j + incr]); // finally, do descriptions - if (desc) { - t = Campaign_descs[j]; - Campaign_descs[j] = Campaign_descs[j + incr]; - Campaign_descs[j + incr] = t; - } + std::swap(Campaign_descs[j], Campaign_descs[j + incr]); j -= incr; } else { @@ -525,44 +500,44 @@ int mission_campaign_load(const char* filename, const char* full_path, player* p // parse the mission file and actually read in the mission stuff while ( required_string_either("#End", "$Mission:") ) { - cmission *cm; - required_string("$Mission:"); stuff_string(name, F_NAME, NAME_LENGTH); - cm = &Campaign.missions[Campaign.num_missions]; - cm->name = vm_strdup(name); - cm->notes = NULL; + const int this_mission_idx = sz2i(Campaign.missions.size()); + cmission& cm = Campaign.missions.emplace_back(); + cm.name = vm_strdup(name); + + cm.notes = nullptr; - cm->briefing_cutscene[0] = 0; + cm.briefing_cutscene[0] = 0; if ( optional_string("+Briefing Cutscene:") ) - stuff_string( cm->briefing_cutscene, F_NAME, NAME_LENGTH ); + stuff_string( cm.briefing_cutscene, F_NAME, NAME_LENGTH ); - cm->flags = 0; + cm.flags = 0; if (optional_string("+Flags:")) - stuff_int(&cm->flags); + stuff_int(&cm.flags); - cm->main_hall = "0"; + cm.main_hall = "0"; // deal with previous campaign versions - if (cm->flags & CMISSION_FLAG_BASTION) { - cm->main_hall = "1"; + if (cm.flags & CMISSION_FLAG_BASTION) { + cm.main_hall = "1"; } // clear any other flag bits to prevent bogus values causing surprises - cm->flags &= CMISSION_EXTERNAL_FLAG_MASK; + cm.flags &= CMISSION_EXTERNAL_FLAG_MASK; // Goober5000 - new main hall stuff! // Updated by CommanderDJ if (optional_string("+Main Hall:")) { stuff_string(temp, F_RAW, 32); - cm->main_hall = temp; + cm.main_hall = temp; } // Goober5000 - substitute main hall (like substitute music) - cm->substitute_main_hall = ""; + cm.substitute_main_hall = ""; if (optional_string("+Substitute Main Hall:")) { stuff_string(temp, F_RAW, 32); - cm->substitute_main_hall = temp; + cm.substitute_main_hall = temp; // if we're running FRED, keep the halls separate (so we can save the campaign file), // but if we're running FS, replace the main hall with the substitute right now @@ -570,7 +545,7 @@ int mission_campaign_load(const char* filename, const char* full_path, player* p // see if this main hall exists main_hall_defines* mhd = main_hall_get_pointer(temp); if (mhd != nullptr) { - cm->main_hall = temp; + cm.main_hall = temp; } else { mprintf(("Substitute main hall '%s' not found\n", temp)); } @@ -578,19 +553,19 @@ int mission_campaign_load(const char* filename, const char* full_path, player* p } // Goober5000 - new debriefing persona stuff! - cm->debrief_persona_index = 0; + cm.debrief_persona_index = 0; if (optional_string("+Debriefing Persona Index:")) - stuff_ubyte(&cm->debrief_persona_index); + stuff_ubyte(&cm.debrief_persona_index); - cm->formula = -1; + cm.formula = -1; if ( optional_string("+Formula:") ) { - cm->formula = get_sexp_main(); + cm.formula = get_sexp_main(); if ( !Fred_running ) { - Assert ( cm->formula != -1 ); - sexp_mark_persistent( cm->formula ); + Assert ( cm.formula != -1 ); + sexp_mark_persistent( cm.formula ); } else { - if ( cm->formula == -1 ){ + if ( cm.formula == -1 ){ Campaign_load_failure = CAMPAIGN_ERROR_SEXP_EXHAUSTED; return CAMPAIGN_ERROR_SEXP_EXHAUSTED; } @@ -599,69 +574,67 @@ int mission_campaign_load(const char* filename, const char* full_path, player* p // Do mission branching stuff if ( optional_string("+Mission Loop:") ) { - cm->flags |= CMISSION_FLAG_HAS_LOOP; + cm.flags |= CMISSION_FLAG_HAS_LOOP; } else if ( optional_string("+Mission Fork:") ) { - cm->flags |= CMISSION_FLAG_HAS_FORK; + cm.flags |= CMISSION_FLAG_HAS_FORK; } - cm->mission_branch_desc = NULL; + cm.mission_branch_desc = nullptr; if ( optional_string("+Mission Loop Text:") || optional_string("+Mission Fork Text:") ) { - cm->mission_branch_desc = stuff_and_malloc_string(F_MULTITEXT, NULL); + cm.mission_branch_desc = stuff_and_malloc_string(F_MULTITEXT, nullptr); } - cm->mission_branch_brief_anim = NULL; + cm.mission_branch_brief_anim = nullptr; if ( optional_string("+Mission Loop Brief Anim:") || optional_string("+Mission Fork Brief Anim:") ) { ignore_white_space(); // it might be on the next line - cm->mission_branch_brief_anim = stuff_and_malloc_string(F_FILESPEC, nullptr); + cm.mission_branch_brief_anim = stuff_and_malloc_string(F_FILESPEC, nullptr); (void)optional_string("$end_multi_text"); // consume the unneeded ending token } - cm->mission_branch_brief_sound = NULL; + cm.mission_branch_brief_sound = nullptr; if ( optional_string("+Mission Loop Brief Sound:") || optional_string("+Mission Fork Brief Sound:") ) { ignore_white_space(); // it might be on the next line - cm->mission_branch_brief_sound = stuff_and_malloc_string(F_FILESPEC, nullptr); + cm.mission_branch_brief_sound = stuff_and_malloc_string(F_FILESPEC, nullptr); (void)optional_string("$end_multi_text"); // consume the unneeded ending token } - cm->mission_loop_formula = -1; + cm.mission_loop_formula = -1; if ( optional_string("+Formula:") ) { - cm->mission_loop_formula = get_sexp_main(); + cm.mission_loop_formula = get_sexp_main(); if ( !Fred_running ) { - Assert ( cm->mission_loop_formula != -1 ); - sexp_mark_persistent( cm->mission_loop_formula ); + Assert ( cm.mission_loop_formula != -1 ); + sexp_mark_persistent( cm.mission_loop_formula ); } else { - if ( cm->mission_loop_formula == -1 ){ + if ( cm.mission_loop_formula == -1 ){ Campaign_load_failure = CAMPAIGN_ERROR_SEXP_EXHAUSTED; return CAMPAIGN_ERROR_SEXP_EXHAUSTED; } } } - cm->level = 0; + cm.level = 0; if (optional_string("+Level:")) { - stuff_int( &cm->level ); - if ( cm->level == 0 ) // check if the top (root) of the whole tree - Campaign.next_mission = Campaign.num_missions; + stuff_int( &cm.level ); + if ( cm.level == 0 ) // check if the top (root) of the whole tree + Campaign.next_mission = this_mission_idx; } else Campaign.realign_required = 1; - cm->pos = 0; + cm.pos = 0; if (optional_string("+Position:")) - stuff_int( &cm->pos ); + stuff_int( &cm.pos ); else Campaign.realign_required = 1; - cm->goals.clear(); - cm->events.clear(); - cm->variables.clear(); - cm->flags |= CMISSION_FLAG_FRED_LOAD_PENDING; - - Campaign.num_missions++; + cm.goals.clear(); + cm.events.clear(); + cm.variables.clear(); + cm.flags |= CMISSION_FLAG_FRED_LOAD_PENDING; } - if ((Game_mode & GM_MULTIPLAYER) && Campaign.num_missions > UINT8_MAX) + if ((Game_mode & GM_MULTIPLAYER) && Campaign.missions.size() > UINT8_MAX) throw parse::ParseException("Number of campaign missions is too high and breaks multi!"); } catch (const parse::FileOpenException& foe) @@ -669,7 +642,7 @@ int mission_campaign_load(const char* filename, const char* full_path, player* p mprintf(("Error opening '%s'\r\nError message = %s.\r\n", filename, foe.what())); Campaign.filename[0] = 0; - Campaign.num_missions = 0; + Campaign.missions.clear(); Campaign_file_missing = true; Campaign_load_failure = CAMPAIGN_ERROR_MISSING; @@ -680,7 +653,7 @@ int mission_campaign_load(const char* filename, const char* full_path, player* p mprintf(("Error parsing '%s'\r\nError message = %s.\r\n", filename, pe.what())); Campaign.filename[0] = 0; - Campaign.num_missions = 0; + Campaign.missions.clear(); Campaign_file_missing = true; Campaign_load_failure = CAMPAIGN_ERROR_CORRUPT; @@ -701,7 +674,7 @@ int mission_campaign_load(const char* filename, const char* full_path, player* p // but if the data is invalid for the savefile then it is fatal if ( Pilot.is_invalid() ) { Campaign.filename[0] = 0; - Campaign.num_missions = 0; + Campaign.missions.clear(); Campaign_load_failure = CAMPAIGN_ERROR_SAVEFILE; return CAMPAIGN_ERROR_SAVEFILE; } @@ -825,7 +798,7 @@ int mission_campaign_next_mission() if ((Campaign.next_mission == -1) || (Campaign.name[0] == '\0')) // will be set to -1 when there is no next mission return -1; - if (Campaign.num_missions < 1) + if (Campaign.missions.empty()) return -2; Campaign.current_mission = Campaign.next_mission; @@ -1217,43 +1190,24 @@ void mission_campaign_free_mission_strings(cmission &cm) */ void mission_campaign_clear() { - int i; - Campaign.description.clear(); // be sure to remove all old malloced strings of Mission_names // we must also free any goal stuff that was from a previous campaign - for ( i=0; i &dest) { // read the mission file and get the list of mission filenames try @@ -1296,10 +1247,11 @@ int mission_campaign_get_filenames(char *filename, char dest[][NAME_LENGTH], int advance_to_eoln(NULL); // parse the mission file and actually read in the mission stuff - *num = 0; + dest.clear(); while ( skip_to_string("$Mission:") == 1 ) { - stuff_string(dest[*num], F_NAME, NAME_LENGTH); - (*num)++; + char name_buf[NAME_LENGTH]; + stuff_string(name_buf, F_NAME, NAME_LENGTH); + dest.emplace_back(name_buf); } } catch (const parse::ParseException& e) @@ -1344,7 +1296,7 @@ void read_mission_goal_list(int num) char *filename, notes[NOTES_LENGTH]; int z; - Assertion(num >= 0 && num < Campaign.num_missions, "mission number out of range!"); + Assertion(Campaign.missions.in_bounds(num), "mission number out of range!"); filename = Campaign.missions[num].name; if (Campaign.missions[num].notes) { @@ -1446,7 +1398,7 @@ int mission_campaign_find_mission( const char *name ) sprintf(realname, NOX("%s%s"), name, FS_MISSION_FILE_EXT ); } - for (i = 0; i < Campaign.num_missions; i++ ) { + for (i = 0; i < sz2i(Campaign.missions.size()); i++) { if ( !stricmp(realname, Campaign.missions[i].name) ){ return i; } @@ -1626,22 +1578,22 @@ int mission_load_up_campaign(bool fall_back_from_current) // no descriptions, no sorting mission_campaign_build_list(false, false); - for (idx = 0; (idx < Num_campaigns) && (rc < 0); idx++) { - if ( (Campaign_file_names[idx] == NULL) || !strlen(Campaign_file_names[idx]) ) { + for (idx = 0; (idx < sz2i(Campaign_file_names.size())) && (rc < 0); idx++) { + if ( Campaign_file_names[idx].empty() ) { continue; } // skip current and builtin since they already didn't work - if ( !stricmp(Campaign_file_names[idx], pl->current_campaign) ) { + if ( !stricmp(Campaign_file_names[idx].c_str(), pl->current_campaign) ) { continue; } - if ( !stricmp(Campaign_file_names[idx], BUILTIN_CAMPAIGN) ) { + if ( !stricmp(Campaign_file_names[idx].c_str(), BUILTIN_CAMPAIGN) ) { continue; } // try to load it, whatever "it" is - rc = mission_campaign_load(Campaign_file_names[idx], nullptr, pl); + rc = mission_campaign_load(Campaign_file_names[idx].c_str(), nullptr, pl); } mission_campaign_free_list(); @@ -1724,7 +1676,7 @@ void mission_campaign_skip_to_next() // (e.g. if is-previous-goal-false or is-previous-event-false is used without the optional argument), so this is a failsafe if (Campaign.next_mission == Campaign.current_mission) { Campaign.next_mission++; - if (Campaign.next_mission < Campaign.num_missions) { + if (Campaign.next_mission < sz2i(Campaign.missions.size())) { Warning(LOCATION, "mission_campaign_skip_to_next() could not determine the next mission! Choosing the next-in-sequence mission as a failsafe..."); } else { Warning(LOCATION, "mission_campaign_skip_to_next() could not determine the next mission!"); @@ -1798,7 +1750,7 @@ bool mission_campaign_jump_to_mission(const char* filename, bool no_skip, bool p strcat_s(dest_filename, ".fs2"); // search for our mission - for (i = 0; i < Campaign.num_missions; i++) { + for (i = 0; i < sz2i(Campaign.missions.size()); i++) { if ((Campaign.missions[i].name != nullptr) && !stricmp(Campaign.missions[i].name, dest_filename)) { mission_num = i; break; @@ -1839,7 +1791,7 @@ SCP_vector mission_campaign_get_valid_next_missions() // This can be queried from UI states outside active mission gameplay // where GM_CAMPAIGN_MODE may not be set even though a campaign is loaded. - if (Campaign.name[0] == '\0' || Campaign.num_missions <= 0) { + if (Campaign.name[0] == '\0' || Campaign.missions.empty()) { return valid_missions; } @@ -1853,10 +1805,10 @@ SCP_vector mission_campaign_get_valid_next_missions() branch_source_mission = Campaign.current_mission; } - if (branch_source_mission < 0 || branch_source_mission >= Campaign.num_missions) { + if (!Campaign.missions.in_bounds(branch_source_mission)) { // Campaigns that haven't started yet can have both current_mission and prev_mission // unset. In that case, next_mission is the only available entry point. - if (Campaign.next_mission >= 0 && Campaign.next_mission < Campaign.num_missions) { + if (Campaign.missions.in_bounds(Campaign.next_mission)) { valid_missions.emplace_back(Campaign.missions[Campaign.next_mission].name); } return valid_missions; @@ -1899,7 +1851,7 @@ SCP_vector mission_campaign_get_valid_next_missions() actions = CDR(actions); } - if (Campaign.next_mission >= 0 && Campaign.next_mission < Campaign.num_missions && Campaign.next_mission != branch_source_mission) { + if (Campaign.missions.in_bounds(Campaign.next_mission) && Campaign.next_mission != branch_source_mission) { const auto& mission_name = Campaign.missions[Campaign.next_mission].name; if (std::find(valid_missions.begin(), valid_missions.end(), mission_name) == valid_missions.end()) { valid_missions.emplace_back(mission_name); diff --git a/code/mission/missioncampaign.h b/code/mission/missioncampaign.h index 41d7042023e..7ab75efe320 100644 --- a/code/mission/missioncampaign.h +++ b/code/mission/missioncampaign.h @@ -22,8 +22,6 @@ struct sexp_variable; // name of the builtin campaign. #define BUILTIN_CAMPAIGN "FreeSpace2" -#define MAX_CAMPAIGN_MISSIONS 100 // maximum number of missions in a campaign - #define CAMPAIGN_ERROR_CORRUPT -1 #define CAMPAIGN_ERROR_SEXP_EXHAUSTED -2 #define CAMPAIGN_ERROR_MISSING -3 @@ -90,24 +88,24 @@ typedef struct mevent { class cmission { public: - char *name; // name of the mission - char *notes; // mission notes for mission (used by Fred) - char briefing_cutscene[NAME_LENGTH]; // name of the cutscene to be played before this mission - int formula; // sexpression used to determine mission branching. - int completed; // has the player completed this mission + char *name = nullptr; // name of the mission + char *notes = nullptr; // mission notes for mission (used by Fred) + char briefing_cutscene[NAME_LENGTH] = {}; // name of the cutscene to be played before this mission + int formula = -1; // sexpression used to determine mission branching. + int completed = 0; // has the player completed this mission SCP_vector goals; // vector of mgoals which has the goal completion status SCP_vector events; // vector of mevents which has the event completion status SCP_vector variables; // vector of sexp_variables (of num_variables size) containing mission-persistent variables - Goober5000 - int mission_loop_formula; // formula to determine whether to allow a side loop - char *mission_branch_desc; // message in popup - char *mission_branch_brief_anim; - char *mission_branch_brief_sound; - int level; // what level of the tree it's on (Fred) - int pos; // what x position on level it's on (Fred) - int flags; + int mission_loop_formula = -1; // formula to determine whether to allow a side loop + char *mission_branch_desc = nullptr; // message in popup + char *mission_branch_brief_anim = nullptr; + char *mission_branch_brief_sound = nullptr; + int level = 0; // what level of the tree it's on (Fred) + int pos = 0; // what x position on level it's on (Fred) + int flags = 0; SCP_string main_hall; // which main hall the player is in - converted to SCP_string by CommanderDJ SCP_string substitute_main_hall; // really only needed for FRED - ubyte debrief_persona_index; // which persona is used for ranks/badges - Goober5000 + ubyte debrief_persona_index = 0; // which persona is used for ranks/badges - Goober5000 scoring_struct stats; }; @@ -119,7 +117,6 @@ class campaign SCP_string description; // unlimited length description of campaign int type; // type of campaign int flags; // flags - Goober5000 - int num_missions; // number of missions in the campaign int num_missions_completed; // number of missions in the campaign that have been flown int current_mission; // the current mission that the player is playing. Only valid during the mission int next_mission; // number of the next mission to fly when continuing the campaign. Always valid @@ -131,7 +128,7 @@ class campaign int num_players; // valid in multiplayer campaigns -- number of players campaign supports. SCP_set ships_allowed; // class indices of ships the player can use; absent = not allowed SCP_set weapons_allowed; // class indices of weapons the player can use; absent = not allowed - cmission missions[MAX_CAMPAIGN_MISSIONS]; // decription of the missions + SCP_vector missions; // decription of the missions SCP_vector persistent_variables; // These variables will be saved at the end of a mission SCP_vector red_alert_variables; // state of the variables in the previous mission of a Red Alert scenario. SCP_vector persistent_containers; // These containers will be saved at the end of a mission @@ -139,7 +136,6 @@ class campaign SCP_map custom_data; // Custom data for the campaign campaign() - : num_missions(0) { name[0] = 0; filename[0] = 0; @@ -153,11 +149,9 @@ extern int Campaign_ending_via_supernova; // extern'ed so the mission loading can get a list of campains. Only use this // data after mission_campaign_build_list() is called -#define MAX_CAMPAIGNS 128 -extern char *Campaign_names[MAX_CAMPAIGNS]; -extern char *Campaign_file_names[MAX_CAMPAIGNS]; -extern char *Campaign_descs[MAX_CAMPAIGNS]; -extern int Num_campaigns; +extern SCP_vector Campaign_names; +extern SCP_vector Campaign_file_names; +extern SCP_vector Campaign_descs; extern int Campaign_names_inited; extern SCP_vector Ignored_campaigns; @@ -218,10 +212,10 @@ extern void mission_campaign_save_persistent( int type, int index ); // execute the corresponding mission_campaign_savefile functions. // get name and type of specified campaign file -bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type, int *max_players, char **desc = nullptr, char **first_mission = nullptr); +bool mission_campaign_get_info(const char *filename, SCP_string &name, int *type, int *max_players, SCP_string *desc = nullptr, SCP_string *first_mission = nullptr); // get a listing of missions in a campaign -int mission_campaign_get_mission_list(const char *filename, char **list, int max); +int mission_campaign_get_mission_list(const char *filename, SCP_vector &list); // load up a campaign for the current player. int mission_load_up_campaign(bool fall_back_from_current = false); diff --git a/code/mission/missionload.cpp b/code/mission/missionload.cpp index 79e13169ad3..51fb54e144e 100644 --- a/code/mission/missionload.cpp +++ b/code/mission/missionload.cpp @@ -159,8 +159,8 @@ UI_LISTBOX campaign_filter; UI_BUTTON mlm_ok, mlm_cancel; char * mlm_missions[MLM_MAX_MISSIONS]; char * recent_missions[MAX_RECENT_MISSIONS]; -char * campaign_names[MAX_CAMPAIGNS+2]; -char * campaign_missions[MAX_CAMPAIGN_MISSIONS]; +SCP_vector campaign_names; +SCP_vector campaign_missions; int mlm_nfiles = 0; static int last_recent_current = -1; static int last_mlm_current = -1; @@ -192,12 +192,11 @@ void ml_change_listbox() } } -static char Campaign_missions[MAX_CAMPAIGN_MISSIONS][NAME_LENGTH]; -static char Campaign_name_list[MAX_CAMPAIGNS+2][NAME_LENGTH]; -static int Num_campaign_missions; +static SCP_vector Campaign_missions; +static SCP_vector Campaign_name_list; // get the mission filenames that make up a campaign -extern int mission_campaign_get_filenames(char *filename, char dest[][NAME_LENGTH], int *num); +extern int mission_campaign_get_filenames(const char *filename, SCP_vector &dest); void mission_load_menu_init() { @@ -232,25 +231,26 @@ void mission_load_menu_init() mission_campaign_build_list(0); - for ( i = 0; i < Num_campaigns; i++ ) { - strcpy_s(Campaign_name_list[i+1], Campaign_names[i]); + Campaign_name_list.clear(); + Campaign_name_list.emplace_back(NOX("All campaigns")); + Campaign_name_list.emplace_back(NOX("Player Missions")); + Campaign_name_list.insert(Campaign_name_list.end(), Campaign_names.begin(), Campaign_names.end()); + + campaign_names.clear(); + campaign_names.reserve(Campaign_name_list.size()); + for (auto& name : Campaign_name_list) { + campaign_names.push_back(name.data()); } - strcpy_s(Campaign_name_list[0], NOX("All campaigns")); - strcpy_s(Campaign_name_list[1], NOX("Player Missions")); - for ( i = 0; i < Num_campaigns+2; i++ ) { - campaign_names[i] = Campaign_name_list[i]; - } - - campaign_filter.create( &mlm_window, 50, 150, 150, 200, Num_campaigns+2, campaign_names ); + campaign_filter.create( &mlm_window, 50, 150, 150, 200, sz2i(campaign_names.size()), campaign_names.data() ); Campaign_filter_index = 0; campaign_filter.set_current(Campaign_filter_index); } void mission_load_menu_do() { - int selected, key_in, recent_current, mlm_current, use_recent_flag, i; - + int selected, key_in, recent_current, mlm_current, use_recent_flag; + Assert( mlm_active == 1 ); @@ -289,16 +289,18 @@ void mission_load_menu_do() Campaign_filter_index = campaign_filter.current(); if ( Campaign_filter_index > 1 ) { - mission_campaign_get_filenames(Campaign_file_names[Campaign_filter_index-2], Campaign_missions, &Num_campaign_missions); + mission_campaign_get_filenames(Campaign_file_names[Campaign_filter_index-2].c_str(), Campaign_missions); - for ( i = 0; i < Num_campaign_missions; i++ ) { - campaign_missions[i] = Campaign_missions[i]; + campaign_missions.clear(); + campaign_missions.reserve(Campaign_missions.size()); + for (auto& name : Campaign_missions) { + campaign_missions.push_back(name.data()); } - mlm_mission_list.set_new_list(Num_campaign_missions, campaign_missions); + mlm_mission_list.set_new_list(sz2i(campaign_missions.size()), campaign_missions.data()); } else if ( Campaign_filter_index == 0 ) { mlm_mission_list.set_new_list(mlm_nfiles, mlm_missions); } else if ( Campaign_filter_index == 1 ) { - mlm_mission_list.set_new_list(jtmp_nfiles, jtmp_missions); + mlm_mission_list.set_new_list(jtmp_nfiles, jtmp_missions); } } @@ -353,7 +355,7 @@ void mission_load_menu_do() } else if (Campaign_filter_index == 1 ) { strcpy_s( mission_name, jtmp_missions[selected]); } else { - strcpy_s(mission_name, Campaign_missions[selected]); + strcpy_s(mission_name, Campaign_missions[selected].c_str()); } strncpy( mission_name_final, mission_name, MAX_FILENAME_LEN ); } diff --git a/code/missioneditor/campaignsave.cpp b/code/missioneditor/campaignsave.cpp index a36b02e05b2..f0155c51030 100644 --- a/code/missioneditor/campaignsave.cpp +++ b/code/missioneditor/campaignsave.cpp @@ -105,7 +105,7 @@ int Fred_campaign_save::save_campaign_file(const char* pathname, const SCP_vecto fout(" )"); fred_parse_flag = 0; - for (int i = 0; i < Campaign.num_missions; i++) { + for (int i = 0; i < sz2i(Campaign.missions.size()); i++) { // Expect to get Campaign.missions ordered from FRED cmission& cm = Campaign.missions[i]; diff --git a/code/missioneditor/sexp_tree_opf.cpp b/code/missioneditor/sexp_tree_opf.cpp index dc29f09fa04..b805a5363e9 100644 --- a/code/missioneditor/sexp_tree_opf.cpp +++ b/code/missioneditor/sexp_tree_opf.cpp @@ -2688,7 +2688,7 @@ int SexpTreeOPF::query_default_argument_available(int op, int i) const return 1; } - if (Campaign.num_missions > 0) + if (!Campaign.missions.empty()) return 1; return 0; diff --git a/code/missionui/missiondebrief.cpp b/code/missionui/missiondebrief.cpp index acd4a06937b..00c3fac31ae 100644 --- a/code/missionui/missiondebrief.cpp +++ b/code/missionui/missiondebrief.cpp @@ -403,8 +403,8 @@ typedef struct voice_map { int persona_index; } voice_map; -voice_map Debrief_promotion_voice_mapping[NUM_VOLITION_CAMPAIGNS][MAX_CAMPAIGN_MISSIONS] = { - { // FreeSpace2 campaign +voice_map Debrief_promotion_voice_mapping[NUM_VOLITION_CAMPAIGNS][35] = { + { // FreeSpace2 campaign { "SM1-01.fs2", 1 }, { "SM1-02.fs2", 1 }, { "SM1-03.fs2", 1 }, @@ -437,7 +437,7 @@ voice_map Debrief_promotion_voice_mapping[NUM_VOLITION_CAMPAIGNS][MAX_CAMPAIGN_M { "SM3-08.fs2", 9 }, { "SM3-09.fs2", 9 }, { "SM3-10.fs2", 9 }, // no debriefing for 3-10 - + { "loop1-1.fs2", 4 }, { "loop1-2.fs2", 4 }, { "loop1-3.fs2", 5 }, @@ -885,7 +885,7 @@ int debrief_find_persona_index() { int i, j; - if ((Campaign.current_mission >= 0) && (Campaign.missions[Campaign.current_mission].name)) + if (Campaign.missions.in_bounds(Campaign.current_mission) && (Campaign.missions[Campaign.current_mission].name)) { // Goober5000 - first see if the campaign supplied a persona index // (0 means use the Volition default) diff --git a/code/network/multi_campaign.cpp b/code/network/multi_campaign.cpp index 2f89aa7303d..b6d86fe779c 100644 --- a/code/network/multi_campaign.cpp +++ b/code/network/multi_campaign.cpp @@ -355,15 +355,15 @@ void multi_campaign_process_update(ubyte *data, header *hinfo) // clear the campaign multi_campaign_client_start(); - // read in the # of missions + // read in the # of missions and size the missions vector to match GET_DATA(val); - Campaign.num_missions = val; + Campaign.missions.resize(val); break; case MC_CODE_MISSION_NAMES: GET_DATA(item_count); GET_DATA(starting_num); - Assert(starting_num + item_count <= Campaign.num_missions); + Assert(starting_num + item_count <= sz2i(Campaign.missions.size())); for (idx = starting_num; idx < (starting_num + item_count); ++idx) { GET_STRING(fname); Campaign.missions[idx].name = vm_strdup(fname); @@ -516,7 +516,7 @@ void multi_campaign_send_start(net_player *pl) val = MC_CODE_START; ADD_DATA(val); - val = static_cast(Campaign.num_missions); + val = static_cast(Campaign.missions.size()); ADD_DATA(val); if (pl != nullptr) { @@ -539,7 +539,7 @@ void multi_campaign_send_start(net_player *pl) starting_num = 0; ADD_DATA(starting_num); - for (idx = 0; idx < Campaign.num_missions; idx++) { + for (idx = 0; idx < sz2i(Campaign.missions.size()); idx++) { Assert(Campaign.missions[idx].name != NULL); ADD_STRING(Campaign.missions[idx].name); ++item_count; @@ -598,7 +598,7 @@ void multi_campaign_send_ingame_start( net_player *pl ) packet_type = MC_JIP_INITIAL_PACKET; ADD_DATA(packet_type); - val = static_cast(Campaign.num_missions); + val = static_cast(Campaign.missions.size()); ADD_DATA(val); multi_io_send_reliable(pl, data, packet_size); @@ -616,7 +616,7 @@ void multi_campaign_send_ingame_start( net_player *pl ) starting_num = 0; ADD_DATA(starting_num); - for (i = 0; i < Campaign.num_missions; i++) { + for (i = 0; i < sz2i(Campaign.missions.size()); i++) { Assert(Campaign.missions[i].name != NULL); ADD_STRING(Campaign.missions[i].name); ++item_count; @@ -644,7 +644,7 @@ void multi_campaign_send_ingame_start( net_player *pl ) multi_io_send_reliable(pl, data, packet_size); // send the number and status of all goals event for all previous missions - for (i = 0; i < Campaign.num_missions; i++ ) { + for (i = 0; i < sz2i(Campaign.missions.size()); i++) { ubyte status; // don't do anything if mission hasn't been completed @@ -680,7 +680,7 @@ void multi_campaign_send_ingame_start( net_player *pl ) } // send the goal/event names. - for ( i = 0; i < Campaign.num_missions; i++ ) { + for (i = 0; i < sz2i(Campaign.missions.size()); i++) { ubyte goal_count, starting_goal_num; // first the goal names @@ -732,7 +732,7 @@ void multi_campaign_send_ingame_start( net_player *pl ) } // send the goal/event names. - for ( i = 0; i < Campaign.num_missions; i++ ) { + for (i = 0; i < sz2i(Campaign.missions.size()); i++) { ushort event_count, starting_event_num; // first the goal names @@ -809,7 +809,7 @@ void multi_campaign_process_ingame_start( ubyte *data, header *hinfo ) // get the number of missions GET_DATA(mission_num); - Campaign.num_missions = mission_num; + Campaign.missions.resize(mission_num); break; case MC_JIP_GE_STATUS: @@ -860,7 +860,7 @@ void multi_campaign_process_ingame_start( ubyte *data, header *hinfo ) case MC_JIP_MISSION_NAMES: GET_DATA(num_missions); GET_DATA(starting_num); - Assert(starting_num + num_missions <= Campaign.num_missions); + Assert(starting_num + num_missions <= sz2i(Campaign.missions.size())); for (i = starting_num; i < (starting_num + num_missions); ++i) { GET_STRING(fname); Campaign.missions[i].name = vm_strdup(fname); diff --git a/code/network/multiui.cpp b/code/network/multiui.cpp index a282a4a8e5d..96d5b322869 100644 --- a/code/network/multiui.cpp +++ b/code/network/multiui.cpp @@ -4732,7 +4732,7 @@ void multi_create_list_set_item(int abs_index, int mode) { netgame_info* ng; multi_create_info* mcip = NULL; - char* campaign_desc = nullptr; + SCP_string campaign_desc; // if not on the standalone server if (Net_player->flags & NETINFO_FLAG_AM_MASTER) { @@ -4824,7 +4824,7 @@ void multi_create_list_set_item(int abs_index, int mode) { } break; case MULTI_CREATE_SHOW_CAMPAIGNS: - char* first_mission = nullptr; + SCP_string first_mission; mission* mp = &The_mission; // if not on the standalone server @@ -4851,7 +4851,7 @@ void multi_create_list_set_item(int abs_index, int mode) { // Cyborg17 - Now that we can have both descriptions, markers in the text are helpful. Multi_netgame_common_description = PRE_CAMPAIGN_DESC; - if (campaign_desc) { + if (!campaign_desc.empty()) { Multi_netgame_common_description += campaign_desc; } else { Multi_netgame_common_description += "No description available."; @@ -4860,7 +4860,7 @@ void multi_create_list_set_item(int abs_index, int mode) { Multi_netgame_common_description += DOUBLE_NEW_LINE; Multi_netgame_common_description += PRE_MISSION_DESC; - int rc = get_mission_info(first_mission, mp, true); + int rc = get_mission_info(first_mission.c_str(), mp, true); if (!rc && strlen(mp->mission_desc)) { Multi_netgame_common_description += mp->mission_desc; @@ -4870,15 +4870,6 @@ void multi_create_list_set_item(int abs_index, int mode) { multi_common_set_text(Multi_netgame_common_description.c_str()); - // free the malloc'ed strings from mission_campaign_get_info() - if (campaign_desc != nullptr) { - vm_free(campaign_desc); - } - - if (first_mission != nullptr) { - vm_free(first_mission); - } - // standalones should now be able to request the info. } else { send_netgame_descript_packet(&Netgame.server_addr, 0); diff --git a/code/parse/sexp.cpp b/code/parse/sexp.cpp index 2ac42ba0db2..63aa1094283 100644 --- a/code/parse/sexp.cpp +++ b/code/parse/sexp.cpp @@ -3273,15 +3273,16 @@ int check_sexp_syntax(int node, int desired_return_type, int recursive, int *bad if (Fred_running) { if (mode == sexp_mode::CAMPAIGN) { - for (i=0; i= Campaign.missions[Sexp_useful_number].level)) return SEXP_CHECK_INVALID_LEVEL; break; } + } - if (i == Campaign.num_missions) + if (i == sz2i(Campaign.missions.size())) return SEXP_CHECK_INVALID_MISSION_NAME; } else { @@ -3326,7 +3327,7 @@ int check_sexp_syntax(int node, int desired_return_type, int recursive, int *bad } // look for mission - count = count_items_with_string(Campaign.missions, i2sz(Campaign.num_missions), &cmission::name, CTEXT(z)); + count = count_items_with_string(Campaign.missions, &cmission::name, CTEXT(z)); // only check for a missing mission -- it's ok if the same mission appears multiple times in the campaign if (count == 0) { @@ -15677,7 +15678,7 @@ void sexp_next_mission(int n) Error( LOCATION, "Mission name is NULL in campaign file for next-mission command!"); } - for (int i = 0; i < Campaign.num_missions; ++i) { + for (int i = 0; i < sz2i(Campaign.missions.size()); ++i) { if ( !stricmp(Campaign.missions[i].name, mission_name) ) { Campaign.next_mission = i; return; diff --git a/code/pilotfile/csg.cpp b/code/pilotfile/csg.cpp index 09a969b0330..4ed705eb759 100644 --- a/code/pilotfile/csg.cpp +++ b/code/pilotfile/csg.cpp @@ -38,6 +38,10 @@ enum class TechroomState : ubyte REMOVED = 2 }; +// set when the campaign data in memory was loaded from a savefile for a different campaign than the one loaded; +// file-level because every pilotfile instance shares Campaign, and a save through Pilot must see a load through any other instance +static bool Csg_campaign_mismatch = false; + void pilotfile::csg_read_flags() { // tips? @@ -144,7 +148,7 @@ void pilotfile::csg_read_info() // check that the next mission won't be greater than the total number of missions // though ensure we only flag if campaign exists and has been loaded - if (Campaign.num_missions > 0 && Campaign.next_mission >= Campaign.num_missions) { + if (!Csg_campaign_mismatch && !Campaign.missions.empty() && !Campaign.missions.in_bounds(Campaign.next_mission) && (Campaign.next_mission != -1)) { Campaign.next_mission = 0; // Prevent trying to load from invalid mission data downstream m_data_invalid = true; // Causes a warning popup to be displayed } @@ -266,6 +270,7 @@ void pilotfile::csg_read_missions() { int i, j, idx, list_size; cmission *missionp; + cmission discarded_mission; if ( !m_have_info ) { throw "Missions before Info!"; @@ -273,7 +278,14 @@ void pilotfile::csg_read_missions() for (i = 0; i < Campaign.num_missions_completed; i++) { idx = cfread_int(cfp); - missionp = &Campaign.missions[idx]; + if (Csg_campaign_mismatch) { + missionp = &discarded_mission; + } else if (Campaign.missions.in_bounds(idx)) { + missionp = &Campaign.missions[idx]; + } else { + mprintf(("CSG => Discarding data for invalid mission index %d\n", idx)); + missionp = &discarded_mission; + } missionp->completed = 1; @@ -362,7 +374,7 @@ void pilotfile::csg_write_missions() startSection(Section::Missions); - for (idx = 0; idx < MAX_CAMPAIGN_MISSIONS; idx++) { + for (idx = 0; idx < sz2i(Campaign.missions.size()); idx++) { if (Campaign.missions[idx].completed) { missionp = &Campaign.missions[idx]; @@ -1600,9 +1612,6 @@ void pilotfile::csg_write_container(const sexp_container &container) void pilotfile::csg_reset_data(bool reset_ships_and_weapons) { - int idx; - cmission *missionp; - // internals m_have_flags = false; m_have_info = false; @@ -1639,14 +1648,14 @@ void pilotfile::csg_reset_data(bool reset_ships_and_weapons) Red_alert_wing_status.clear(); // clear out mission stuff - for (idx = 0; idx < MAX_CAMPAIGN_MISSIONS; idx++) { - missionp = &Campaign.missions[idx]; - - missionp->goals.clear(); - missionp->events.clear(); - missionp->variables.clear(); + if (!Csg_campaign_mismatch) { + for (auto& cm : Campaign.missions) { + cm.goals.clear(); + cm.events.clear(); + cm.variables.clear(); - missionp->stats.init(); + cm.stats.init(); + } } } @@ -1727,6 +1736,12 @@ bool pilotfile::load_savefile(player *_p, const char *campaign) mprintf(("CSG => Loading '%s' with version %d...\n", filename.c_str(), (int)csg_ver)); + // mission data is stored by index, so it only applies to the campaign it was saved from + Csg_campaign_mismatch = (stricmp(base, util::get_file_part(Campaign.filename)) != 0); + if (Csg_campaign_mismatch) { + mprintf(("CSG => '%s' does not match the loaded campaign; discarding its mission data\n", filename.c_str())); + } + csg_reset_data(true); // the point of all this: read in the CSG contents @@ -1886,6 +1901,10 @@ bool pilotfile::save_savefile() mprintf(("CSG => Skipping save of '%s' due to invalid data check!\n", filename.c_str())); return false; } + if (Csg_campaign_mismatch) { + mprintf(("CSG => Skipping save of '%s' because the last savefile loaded was for a different campaign!\n", filename.c_str())); + return false; + } // validate the number of red alert entries // assertion before writing so that we don't corrupt the .csg by asserting halfway through writing @@ -1962,6 +1981,7 @@ void pilotfile::clear_savefile(bool reset_ships_and_weapons) Assert((Player_num >= 0) && (Player_num < MAX_PLAYERS)); p = &Players[Player_num]; + Csg_campaign_mismatch = false; csg_reset_data(reset_ships_and_weapons); } diff --git a/code/playerman/managepilot.cpp b/code/playerman/managepilot.cpp index fda8d8b4dfd..1fc78929d3d 100644 --- a/code/playerman/managepilot.cpp +++ b/code/playerman/managepilot.cpp @@ -166,98 +166,62 @@ void init_new_pilot(player *p, int reset) } } -int local_num_campaigns = 0; - -int campaign_file_list_filter(const char *filename) -{ - SCP_string name; - int type, max_players; - - if ( mission_campaign_get_info( filename, name, &type, &max_players) ) { - if ( type == CAMPAIGN_TYPE_SINGLE) { - Campaign_names[local_num_campaigns] = vm_strdup(name.c_str()); - local_num_campaigns++; - return 1; - } - } - - return 0; -} - -//Generates a list of available campaigns. Sets active campaign to "freespace2.fc2", or if that is unavailable, the first campaign found +// Sets the starting campaign to the default campaign, or if that is unavailable, the single-player campaign whose title sorts first void pilot_set_start_campaign(player* p) { char wild_card[10]; - int i, j, incr = 0; - char *t = NULL; - int rc = 0; - char *campaign_file_list[MAX_CAMPAIGNS]; + SCP_vector campaign_file_list; + SCP_string title; + + // note that this also grabs the title + auto is_single_player_campaign = [&title](const SCP_string &campaign_file) + { + int type, max_players; + return mission_campaign_get_info(campaign_file.c_str(), title, &type, &max_players) && (type == CAMPAIGN_TYPE_SINGLE); + }; memset(wild_card, 0, sizeof(wild_card)); strcpy_s(wild_card, NOX("*")); strcat_s(wild_card, FS_CAMPAIGN_FILE_EXT); - // set filter for cf_get_file_list() if there isn't one set already (the simroom has a special one) - if (Get_file_list_filter == NULL) - Get_file_list_filter = campaign_file_list_filter; - - // now get the list of all campaign names - // NOTE: we don't do sorting here, but we assume CF_SORT_NAME, and do it manually below - rc = cf_get_file_list(MAX_CAMPAIGNS, campaign_file_list, CF_TYPE_MISSIONS, wild_card, CF_SORT_NONE); + cf_get_file_list(campaign_file_list, CF_TYPE_MISSIONS, wild_card, CF_SORT_NONE); - for (i = 0; i < rc; i++) + for (const auto &campaign_file : campaign_file_list) { - if (!stricmp(campaign_file_list[i], Default_campaign_file_name)) + if (!stricmp(campaign_file.c_str(), Default_campaign_file_name)) { - strcpy_s(p->current_campaign, campaign_file_list[i]); - return; + if (is_single_player_campaign(campaign_file)) + { + strcpy_s(p->current_campaign, campaign_file.c_str()); + return; + } + break; } } - // now sort everything - incr = local_num_campaigns / 2; + const SCP_string *best_file = nullptr; + SCP_string best_title; - while (incr > 0) { - for (i = incr; i < local_num_campaigns; i++) { - j = i - incr; - - while (j >= 0) { - char *name1 = Campaign_names[j]; - char *name2 = Campaign_names[j + incr]; - - // if we hit this then a coder probably did something dumb (like not needing to sort) - if ( (name1 == NULL) || (name2 == NULL) ) { - Int3(); - break; - } - - if ( !strnicmp(name1, "the ", 4) ) - name1 += 4; - - if ( !strnicmp(name2, "the ", 4) ) - name2 += 4; - - if (stricmp(name1, name2) > 0) { - // first, do filenames - t = campaign_file_list[j]; - campaign_file_list[j] = campaign_file_list[j + incr]; - campaign_file_list[j + incr] = t; - - j -= incr; - } else { - break; - } - } - } + for (const auto &campaign_file : campaign_file_list) + { + if (!is_single_player_campaign(campaign_file)) + continue; - incr /= 2; + const char *sort_title = title.c_str(); + if (!strnicmp(sort_title, "the ", 4)) + sort_title += 4; + + if (best_file == nullptr || stricmp(sort_title, best_title.c_str()) < 0) + { + best_file = &campaign_file; + best_title = sort_title; + } } - if (rc > 0) - strcpy_s(p->current_campaign, campaign_file_list[0]); + if (best_file != nullptr) + strcpy_s(p->current_campaign, best_file->c_str()); else strcpy_s(p->current_campaign, ""); - } void pilot_set_short_callsign(player *p, int max_width) diff --git a/code/scripting/api/libs/mission.cpp b/code/scripting/api/libs/mission.cpp index 36a8081b1fb..54003f6fdb4 100644 --- a/code/scripting/api/libs/mission.cpp +++ b/code/scripting/api/libs/mission.cpp @@ -3268,7 +3268,7 @@ ADE_LIB(l_Campaign, "Campaign", "ca", "Campaign Library"); ADE_FUNC(getNextMissionFilename, l_Campaign, NULL, "Gets next mission filename", "string", "Next mission filename, or nil if the next mission is invalid") { - if (Campaign.next_mission < 0 || Campaign.next_mission >= MAX_CAMPAIGN_MISSIONS) { + if (!Campaign.missions.in_bounds(Campaign.next_mission)) { return ADE_RETURN_NIL; } return ade_set_args(L, "s", Campaign.missions[Campaign.next_mission].name); @@ -3276,7 +3276,7 @@ ADE_FUNC(getNextMissionFilename, l_Campaign, NULL, "Gets next mission filename", ADE_FUNC(getPrevMissionFilename, l_Campaign, NULL, "Gets previous mission filename", "string", "Previous mission filename, or nil if the previous mission is invalid") { - if (Campaign.prev_mission < 0 || Campaign.prev_mission >= MAX_CAMPAIGN_MISSIONS) { + if (!Campaign.missions.in_bounds(Campaign.prev_mission)) { return ADE_RETURN_NIL; } return ade_set_args(L, "s", Campaign.missions[Campaign.prev_mission].name); diff --git a/code/scripting/api/libs/ui.cpp b/code/scripting/api/libs/ui.cpp index 2e74b980232..3b438f0bfe9 100644 --- a/code/scripting/api/libs/ui.cpp +++ b/code/scripting/api/libs/ui.cpp @@ -627,12 +627,10 @@ ADE_FUNC(getCampaignList, luacpp::LuaTable fileNameTable = luacpp::LuaTable::create(L); luacpp::LuaTable descriptionTable = luacpp::LuaTable::create(L); - for (int i = 0; i < Num_campaigns; ++i) { - nameTable.addValue(i + 1, Campaign_names[i]); - fileNameTable.addValue(i + 1, Campaign_file_names[i]); - - auto description = Campaign_descs[i]; - descriptionTable.addValue(i + 1, description ? description : ""); + for (int i = 0; i < sz2i(Campaign_file_names.size()); ++i) { + nameTable.addValue(i + 1, Campaign_names[i].c_str()); + fileNameTable.addValue(i + 1, Campaign_file_names[i].c_str()); + descriptionTable.addValue(i + 1, Campaign_descs[i].c_str()); } // We actually do not need this anymore now so free it immediately diff --git a/code/scripting/api/objs/loop_brief.cpp b/code/scripting/api/objs/loop_brief.cpp index 9748b5d0649..b1f69ba592f 100644 --- a/code/scripting/api/objs/loop_brief.cpp +++ b/code/scripting/api/objs/loop_brief.cpp @@ -9,7 +9,7 @@ cmission_h::cmission_h(int stage) : l_stage(stage) {} bool cmission_h::isValid() const { - return l_stage >= 0; + return Campaign.missions.in_bounds(l_stage); } cmission* cmission_h::getStage() const diff --git a/code/scripting/api/objs/player.cpp b/code/scripting/api/objs/player.cpp index 249b82d794b..85e3858bc90 100644 --- a/code/scripting/api/objs/player.cpp +++ b/code/scripting/api/objs/player.cpp @@ -245,10 +245,9 @@ ADE_FUNC(getMainHallName, l_Player, NULL, "Gets player's current main hall name" { SCP_string hallname; // FS2-->Lua - if (Campaign.next_mission == -1) { - hallname = Campaign.missions[0].main_hall; - } else { - hallname = Campaign.missions[Campaign.next_mission].main_hall; + int idx = (Campaign.next_mission == -1) ? 0 : Campaign.next_mission; + if (Campaign.missions.in_bounds(idx)) { + hallname = Campaign.missions[idx].main_hall; } return ade_set_args(L, "s", hallname.c_str()); @@ -259,10 +258,11 @@ ADE_FUNC(getMainHallIndex, l_Player, NULL, "Gets player's current main hall numb { int hallnum = 0; //FS2-->Lua - if (Campaign.next_mission == -1) { - hallnum = main_hall_get_index(Campaign.missions[0].main_hall); + int idx = (Campaign.next_mission == -1) ? 0 : Campaign.next_mission; + if (Campaign.missions.in_bounds(idx)) { + hallnum = main_hall_get_index(Campaign.missions[idx].main_hall); } else { - hallnum = main_hall_get_index(Campaign.missions[Campaign.next_mission].main_hall); + hallnum = main_hall_get_index(""); } return ade_set_args(L, "i", hallnum); diff --git a/fred2/campaigneditordlg.cpp b/fred2/campaigneditordlg.cpp index cbe2cb608a4..50d987473ac 100644 --- a/fred2/campaigneditordlg.cpp +++ b/fred2/campaigneditordlg.cpp @@ -65,13 +65,13 @@ campaign_editor::campaign_editor() int campaign_editor::onRootDeleted(int formula_node) { int i; - for (i = 0; i < Total_links; i++) { + for (i = 0; i < sz2i(Links.size()); i++) { if ((Links[i].from == Cur_campaign_mission) && (Links[i].node == formula_node)) { break; } } - if (i < Total_links) { + if (i < sz2i(Links.size())) { Campaign_tree_viewp->delete_link(i); m_num_links--; } @@ -89,7 +89,7 @@ SCP_vector campaign_editor::getMissionNames() // only list missions the player could have already played: the current mission and // any mission at an earlier level in the campaign tree - for (int i = 0; i < Campaign.num_missions; i++) + for (int i = 0; i < sz2i(Campaign.missions.size()); i++) { if ((i == Cur_campaign_mission) || (Campaign.missions[i].level < Campaign.missions[Cur_campaign_mission].level)) list.emplace_back(Campaign.missions[i].name); @@ -400,7 +400,7 @@ void campaign_editor::update() // set the number of players in a multiplayer mission equal to the number of players in the first mission if ( Campaign.type != CAMPAIGN_TYPE_SINGLE ) { - if ( Campaign.num_missions == 0 ) { + if (Campaign.missions.empty()) { Campaign.num_players = 0; } else { mission a_mission; @@ -451,7 +451,7 @@ void campaign_editor::load_tree(int save_first) GetDlgItem(IDC_LOOP_BRIEF_BROWSE)->EnableWindow(FALSE); GetDlgItem(IDC_LOOP_BRIEF_SOUND_BROWSE)->EnableWindow(FALSE); - for (i=0; i= 0) { save_tree(); - for (i=0; iSetFocus(); } -void campaign_editor::OnMoveDown() +void campaign_editor::OnMoveDown() { int i, j; - campaign_tree_link temp; HTREEITEM h1, h2; if (Cur_campaign_link >= 0) { save_tree(); - for (i=0; i Level_counts; +SCP_vector Sorted; +SCP_vector Elements; +SCP_vector Links; LOCAL CRect Dragging_rect; LOCAL CSize Rect_offset, Last_draw_size; @@ -164,7 +163,7 @@ void campaign_tree_view::OnDraw(CDC* pDC) // draw text boxes and text - for (i=0; iTextOut(x, y - By / 2 + 2, str, (int)strlen(str)); } - for (i=0; i= 0 && mission_num < Campaign.num_missions); + Assert(Campaign.missions.in_bounds(mission_num)); if (formula >= 0) { if (!stricmp(CTEXT(formula), "cond")) { @@ -272,30 +271,34 @@ void stuff_link_with_formula(int *link_idx, int formula, int mission_num) node = CDR(formula); free_one_sexp(formula); while (node != -1) { - init_link(Links[*link_idx], mission_num); + Links.emplace_back(); + init_link(Links.back(), mission_num); node2 = CAR(node); - Links[*link_idx].sexp = CAR(node2); + Links.back().sexp = CAR(node2); sexp_mark_persistent(CAR(node2)); free_one_sexp(node2); node3 = CADR(node2); if ( !stricmp( CTEXT(node3), "next-mission") ) { node3 = CDR(node3); - for (j=0; j total_levels) total_levels = z + 2; - Level_counts[z]++; + if (Level_counts.in_bounds(z)) { + Level_counts[z]++; + } z = (Campaign.missions[i].pos + 3) / 2; if (z > total_width) total_width = z; @@ -378,14 +382,12 @@ void campaign_tree_view::initialize() void campaign_tree_view::free_links() { - int i; - - for (i=0; i to_list, from_list; - for (i=0; i= MAX_CAMPAIGN_TREE_LINKS) { - MessageBox("Too many links exist. Can't add any more."); - return; - } - if (Campaign.missions[z].level >= Campaign.missions[i].level) { MessageBox("A branch can only be set to a mission on a lower level"); return; @@ -740,13 +743,13 @@ void campaign_tree_view::OnLButtonUp(UINT nFlags, CPoint point) return; } - for (i=0; i= MAX_CAMPAIGN_TREE_LINKS) - return -1; - Campaign_tree_formp->load_tree(1); - init_link(Links[Total_links], from, to); - Total_links++; + Links.emplace_back(); + init_link(Links.back(), from, to); if (from != to) { if (from >= 0) Elements[from].from_links++; @@ -884,7 +884,7 @@ DROPEFFECT campaign_tree_view::OnDragOver(COleDataObject* pDataObject, DWORD dwK } else { draw_size = CSize(2, 2); - for (i=0; i= MAX_CAMPAIGN_MISSIONS) { // Can't add any more - GlobalUnlock(hGlobal); - MessageBox("Too many missions. Can't add more to Campaign.", "Error"); - return FALSE; - } - level = query_level(point); pos = query_pos(point); Assert((level >= 0) && (pos >= 0)); // this should be impossible @@ -979,14 +973,16 @@ BOOL campaign_tree_view::OnDrop(COleDataObject* pDataObject, DROPEFFECT dropEffe } } - init_element(Elements[Campaign.num_missions]); - cm = &(Campaign.missions[Campaign.num_missions++]); + Elements.emplace_back(); + init_element(Elements.back()); + cm = &Campaign.missions.emplace_back(); cm->name = strdup(pData); cm->formula = Locked_sexp_true; cm->flags |= CMISSION_FLAG_FRED_LOAD_PENDING; cm->notes = NULL; cm->briefing_cutscene[0] = 0; - for (i=0; ilevel = level; cm->pos = pos - 1; - correct_position(Campaign.num_missions - 1); + correct_position(new_mission_idx); sort_links(); SetScrollSizes(MM_TEXT, CSize(total_width * CELL_WIDTH, total_levels * LEVEL_HEIGHT)); Invalidate(); @@ -1042,11 +1038,6 @@ void campaign_tree_view::drop_mission(int m, CPoint point) // grab the filename selected from the listbox listbox->GetText(item, name); - if (Campaign.num_missions >= MAX_CAMPAIGN_MISSIONS) { // Can't add any more - MessageBox("Too many missions. Can't add more to Campaign.", "Error"); - return; - } - if (!level && (get_root_mission() >= 0)) { MessageBox("Only 1 mission may be in the top level"); return; @@ -1077,14 +1068,16 @@ void campaign_tree_view::drop_mission(int m, CPoint point) } } - init_element(Elements[Campaign.num_missions]); - cm = &(Campaign.missions[Campaign.num_missions++]); + Elements.emplace_back(); + init_element(Elements.back()); + cm = &Campaign.missions.emplace_back(); cm->name = strdup(name); cm->formula = Locked_sexp_true; cm->flags |= CMISSION_FLAG_FRED_LOAD_PENDING; cm->notes = NULL; cm->briefing_cutscene[0] = 0; - for (i=0; ilevel = level; cm->pos = pos - 1; - correct_position(Campaign.num_missions - 1); + correct_position(new_mission_idx); sort_links(); SetScrollSizes(MM_TEXT, CSize(total_width * CELL_WIDTH, total_levels * LEVEL_HEIGHT)); Invalidate(); @@ -1112,11 +1105,12 @@ void campaign_tree_view::sort_elements() { int i, j, s1, s2; - for (i=0; i=0; j--) { s2 = Sorted[j]; @@ -1140,7 +1134,7 @@ void campaign_tree_view::correct_position(int num) if (Campaign.missions[num].level + 2 > total_levels) total_levels = Campaign.missions[num].level + 2; - for (i=0; i= Campaign.missions[z].level) ) { @@ -1159,13 +1153,13 @@ void campaign_tree_view::horizontally_align_mission(int num, int dir) int i, z; if ((Campaign.missions[num].pos == -1) || (Campaign.missions[num].pos + 1 == total_width * 2)) { // need to expand total_width - for (i=0; i= 0) && (num < Total_links)); + Assert(Links.in_bounds(num)); int from = Links[num].from; int to = Links[num].to; @@ -1202,12 +1196,8 @@ void campaign_tree_view::delete_link(int num) sexp_unmark_persistent(Links[num].sexp); free_sexp2(Links[num].sexp); - while (num < Total_links - 1) { - Links[num] = Links[num + 1]; - num++; - } + Links.erase(Links.begin() + num); - Total_links--; sort_links(); Invalidate(); Campaign_modified = 1; @@ -1216,9 +1206,7 @@ void campaign_tree_view::delete_link(int num) int campaign_tree_view::get_root_mission() { - int i; - - for (i=0; i= 0); + Assert(Campaign.missions.in_bounds(m)); Campaign_tree_formp->m_filelist.AddString(Campaign.missions[m].name); - z = --Campaign.num_missions; - i = Total_links; + z = sz2i(Campaign.missions.size()) - 1; // index of the slot that will be swapped into m's place + i = sz2i(Links.size()); while (i--) { - if ((Links[i].from == m) || (Links[i].to == m)) + if ((Links[i].from == m) || (Links[i].to == m)) { delete_link(i); + continue; + } if (Links[i].from == z) Links[i].from = m; if (Links[i].to == z) @@ -1294,18 +1284,12 @@ void campaign_tree_view::remove_mission(int m) Elements[m] = Elements[z]; - // free the removed mission's strings before its slot is overwritten, then - // null the vacated slot's pointers, which now alias slot m's strings. (If - // m == z, the assignment is a self-assign of freed pointers, and the - // nulling below leaves the slot clean.) + // free the removed mission's strings before its slot is overwritten; the + // vacated last slot, whose pointers now alias slot m's strings, is then popped mission_campaign_free_mission_strings(Campaign.missions[m]); Campaign.missions[m] = Campaign.missions[z]; - Campaign.missions[z].name = nullptr; - Campaign.missions[z].notes = nullptr; - Campaign.missions[z].mission_branch_desc = nullptr; - Campaign.missions[z].mission_branch_brief_anim = nullptr; - Campaign.missions[z].mission_branch_brief_sound = nullptr; - + Elements.pop_back(); + Campaign.missions.pop_back(); if (m == Cur_campaign_mission) { Cur_campaign_mission = -1; box = (CEdit *) Campaign_tree_formp->GetDlgItem(IDC_HELP_BOX); @@ -1327,7 +1311,7 @@ void campaign_tree_view::OnDeleteRow() return; } - for (i=z=0; i Context_mission) - Campaign.missions[i].level--; + for (auto& mission : Campaign.missions) + if (mission.level > Context_mission) + mission.level--; total_levels--; SetScrollSizes(MM_TEXT, CSize(total_width * CELL_WIDTH, total_levels * LEVEL_HEIGHT)); @@ -1352,13 +1336,11 @@ void campaign_tree_view::OnDeleteRow() Campaign_modified = 1; } -void campaign_tree_view::OnInsertRow() +void campaign_tree_view::OnInsertRow() { - int i; - - for (i=0; i= Context_mission) - Campaign.missions[i].level++; + for (auto& mission : Campaign.missions) + if (mission.level >= Context_mission) + mission.level++; total_levels++; SetScrollSizes(MM_TEXT, CSize(total_width * CELL_WIDTH, total_levels * LEVEL_HEIGHT)); diff --git a/fred2/campaigntreeview.h b/fred2/campaigntreeview.h index 4eb1a53613e..cce8c778f13 100644 --- a/fred2/campaigntreeview.h +++ b/fred2/campaigntreeview.h @@ -12,9 +12,6 @@ #include "mission/missioncampaign.h" -#define MAX_LEVELS 100 -#define MAX_CAMPAIGN_TREE_LINKS 300 - typedef struct campaign_tree_element { int from_links; // total branches from this mission int to_links; // total branches that lead to this mission @@ -37,11 +34,10 @@ typedef struct campaign_tree_link { CPoint p2; } campaign_tree_link; -extern int Total_links; -extern int Level_counts[MAX_LEVELS]; -extern int Sorted[MAX_CAMPAIGN_MISSIONS]; -extern campaign_tree_element Elements[MAX_CAMPAIGN_MISSIONS]; -extern campaign_tree_link Links[MAX_CAMPAIGN_TREE_LINKS]; +extern SCP_vector Level_counts; +extern SCP_vector Sorted; +extern SCP_vector Elements; +extern SCP_vector Links; extern void init_link(campaign_tree_link &link, int from = -1, int to = -1); extern void init_element(campaign_tree_element &element); diff --git a/fred2/campaigntreewnd.cpp b/fred2/campaigntreewnd.cpp index 680fad3928d..29a2e6da557 100644 --- a/fred2/campaigntreewnd.cpp +++ b/fred2/campaigntreewnd.cpp @@ -207,20 +207,18 @@ void campaign_tree_wnd::OnCpgnFileSave() Campaign_tree_viewp->sort_elements(); SCP_vector links; - for (int i = 0; i < Total_links; i++) { - campaign_link link{ - Links[i].from, - Links[i].to, - Links[i].sexp, - Links[i].node, - Links[i].is_mission_loop, - Links[i].is_mission_fork, - Links[i].mission_branch_txt, - Links[i].mission_branch_brief_anim, - Links[i].mission_branch_brief_sound - }; - - links.emplace_back(link); + for (const auto& src : Links) { + links.emplace_back(campaign_link{ + src.from, + src.to, + src.sexp, + src.node, + src.is_mission_loop, + src.is_mission_fork, + src.mission_branch_txt, + src.mission_branch_brief_anim, + src.mission_branch_brief_sound + }); } if (save.save_campaign_file(full_path, links)) @@ -276,18 +274,18 @@ void campaign_tree_wnd::OnCpgnFileSaveAs() Campaign_tree_viewp->sort_elements(); SCP_vector links; - for (int i = 0; i < Total_links; i++) { - campaign_link link{Links[i].from, - Links[i].to, - Links[i].sexp, - Links[i].node, - Links[i].is_mission_loop, - Links[i].is_mission_fork, - Links[i].mission_branch_txt, - Links[i].mission_branch_brief_anim, - Links[i].mission_branch_brief_sound}; - - links.emplace_back(link); + for (const auto& src : Links) { + links.emplace_back(campaign_link{ + src.from, + src.to, + src.sexp, + src.node, + src.is_mission_loop, + src.is_mission_fork, + src.mission_branch_txt, + src.mission_branch_brief_anim, + src.mission_branch_brief_sound + }); } if (save.save_campaign_file((LPCSTR)dlg.GetPathName(), links)) @@ -308,10 +306,11 @@ void campaign_tree_wnd::OnCpgnFileNew() return; Campaign.filename[0] = 0; - Campaign.num_missions = 0; + Campaign.missions.clear(); Campaign.num_players = 0; strcpy_s(Campaign.name, "Unnamed"); Campaign_tree_viewp->free_links(); + Elements.clear(); Campaign_tree_formp->initialize(true, true); Campaign_modified = 0; Campaign.flags = CF_DEFAULT_VALUE; @@ -368,20 +367,16 @@ void campaign_tree_wnd::OnErrorChecker() int campaign_tree_wnd::error_checker() { int i, j, z; - int mcount[MAX_CAMPAIGN_MISSIONS], true_at[MAX_CAMPAIGN_MISSIONS]; - - for (i=0; i mcount(Campaign.missions.size(), 0); + SCP_vector true_at(Campaign.missions.size(), -1); g_err = 0; - for (i=0; i= Campaign.num_missions) ) + if (!Campaign.missions.in_bounds(Links[i].from)) return internal_error("Branch #%d has illegal source mission", i); // #2 check: illegal target mission - if ( (Links[i].to < -1) || (Links[i].to >= Campaign.num_missions) ) + if (!Campaign.missions.in_bounds(Links[i].to) && (Links[i].to != -1)) return internal_error("Branch #%d has illegal target mission", i); // #3 check: formula syntax Sexp_useful_number = Links[i].from; @@ -420,14 +415,14 @@ int campaign_tree_wnd::error_checker() } // #7 check: not always true last branch - for (i=0; i(m_missions.size()); // Free entries that fall outside the new range (e.g. user removed missions). - for (int i = new_count; i < Campaign.num_missions; i++) { + for (int i = new_count; i < sz2i(Campaign.missions.size()); i++) { if (Campaign.missions[i].name) { vm_free(Campaign.missions[i].name); Campaign.missions[i].name = nullptr; } - Campaign.missions[i].events.clear(); - Campaign.missions[i].goals.clear(); - Campaign.missions[i].flags = 0; } - Campaign.num_missions = new_count; + Campaign.missions.resize(new_count); - for (int i = 0; i < new_count && i < MAX_CAMPAIGN_MISSIONS; i++) { + for (int i = 0; i < new_count; i++) { const char* new_name = m_missions[i].filename.c_str(); const bool name_changed = (Campaign.missions[i].name == nullptr) || (strcmp(Campaign.missions[i].name, new_name) != 0); @@ -109,9 +106,8 @@ void CampaignEditorDialogModel::initializeData(const char* filename) m_custom_data = Campaign.custom_data; // Copy mission data from the global Campaign struct - m_missions.reserve(Campaign.num_missions); - for (int i = 0; i < Campaign.num_missions; ++i) { - const auto& source_mission = Campaign.missions[i]; + m_missions.reserve(Campaign.missions.size()); + for (const auto& source_mission : Campaign.missions) { auto& dest_mission = m_missions.emplace_back(); dest_mission.filename = source_mission.name; @@ -173,7 +169,7 @@ void CampaignEditorDialogModel::initializeData(const char* filename) m_current_mission_index = -1; m_current_branch_index = -1; - // Keep Campaign.num_missions in sync so the sexp tree's OPF_MISSION_NAME gate + // Keep Campaign.missions in sync so the sexp tree's OPF_MISSION_NAME gate // (used by is-previous-event-*/is-previous-goal-*) sees the loaded campaign. syncCampaignMissionList(); @@ -213,9 +209,9 @@ void CampaignEditorDialogModel::parseBranchesFromFormula(CampaignMissionData& mi // If this was a loop, find the original cmission to copy the descriptive text. if (is_loop) { const cmission* source_cmission = nullptr; - for (int i = 0; i < Campaign.num_missions; ++i) { - if (mission.filename == Campaign.missions[i].name) { - source_cmission = &Campaign.missions[i]; + for (const auto& candidate : Campaign.missions) { + if (mission.filename == candidate.name) { + source_cmission = &candidate; break; } } @@ -312,7 +308,7 @@ void CampaignEditorDialogModel::commitWorkingCopyToGlobal() Campaign.type = m_campaign_type; Campaign.num_players = m_num_players; Campaign.flags = m_flags; - Campaign.num_missions = static_cast(m_missions.size()); + Campaign.missions.resize(m_missions.size()); Campaign.custom_data = m_custom_data; // Copy ship and weapon permissions @@ -320,7 +316,7 @@ void CampaignEditorDialogModel::commitWorkingCopyToGlobal() Campaign.weapons_allowed = m_weapons_allowed; // Copy mission data - for (int i = 0; i < Campaign.num_missions; ++i) { + for (int i = 0; i < sz2i(Campaign.missions.size()); ++i) { const auto& source_mission = m_missions[i]; auto& dest_mission = Campaign.missions[i]; @@ -485,8 +481,8 @@ void CampaignEditorDialogModel::loadCampaignFromFile(const SCP_string& filename) // Immediately clear the global struct again now that we have our safe working copy. clearCampaignGlobal(); - // clearCampaignGlobal() also zeroed Campaign.num_missions, but the sexp tree's - // OPF_MISSION_NAME gate needs that count to be non-zero for is-previous-event-* / + // clearCampaignGlobal() also emptied Campaign.missions, but the sexp tree's + // OPF_MISSION_NAME gate needs it to be non-empty for is-previous-event-* / // is-previous-goal-* to be usable. Restore it from the WIP list. syncCampaignMissionList(); } @@ -587,7 +583,7 @@ void CampaignEditorDialogModel::saveCampaign(const SCP_string& filename) // Clean up the global struct now that the save is complete. clearCampaignGlobal(); - // clearCampaignGlobal() zeroed Campaign.num_missions, but the dialog is still + // clearCampaignGlobal() emptied Campaign.missions, but the dialog is still // open and the sexp tree relies on that count for is-previous-event-*/ // is-previous-goal-* operator availability. syncCampaignMissionList();