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..b2dcae68147 100644 --- a/code/menuui/readyroom.cpp +++ b/code/menuui/readyroom.cpp @@ -202,7 +202,7 @@ 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 SCP_vector Campaign_mission_names; static int Campaign_mission_flags[MAX_MISSIONS]; static int Simroom_show_all = 0; static int Standalone_mission_names_inited = 0; @@ -544,7 +544,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,6 +553,11 @@ 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.assign(Campaign.missions.size(), nullptr); + } + // 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; @@ -596,7 +601,7 @@ int build_campaign_mission_list_do_frame(bool API_Access) 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; @@ -684,10 +689,10 @@ void sim_room_reset_campaign_listing() return; - for (int i=0; iname = 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 +570,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 +578,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 +599,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 +667,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 +678,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 +699,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 +823,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 +1215,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 +1272,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 +1321,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 +1423,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; } @@ -1724,7 +1701,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 +1775,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 +1816,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 +1830,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 +1876,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..87619f21390 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; diff --git a/code/mission/missionload.cpp b/code/mission/missionload.cpp index 79e13169ad3..a06b91dcd70 100644 --- a/code/mission/missionload.cpp +++ b/code/mission/missionload.cpp @@ -160,7 +160,7 @@ 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_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 SCP_vector Campaign_missions; static char Campaign_name_list[MAX_CAMPAIGNS+2][NAME_LENGTH]; -static int Num_campaign_missions; // 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() { @@ -249,8 +248,8 @@ void mission_load_menu_init() 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 +288,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], 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 +354,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/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..e8724725dd8 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? @@ -142,17 +146,28 @@ void pilotfile::csg_read_info() Campaign.prev_mission = cfread_int(cfp); Campaign.next_mission = cfread_int(cfp); - // 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) { - Campaign.next_mission = 0; // Prevent trying to load from invalid mission data downstream - m_data_invalid = true; // Causes a warning popup to be displayed - } - // loop state Campaign.loop_reentry = cfread_int(cfp); Campaign.loop_enabled = cfread_int(cfp); + // check that the mission indexes are within the campaign's missions (-1 for next or reentry means the campaign ends there) + // though ensure we only flag if campaign exists and has been loaded + if (!Campaign.missions.in_bounds(Campaign.prev_mission)) { + Campaign.prev_mission = -1; + } + if (!Campaign.missions.empty()) { + if (!Campaign.missions.in_bounds(Campaign.next_mission) && (Campaign.next_mission != -1)) { + Campaign.next_mission = 0; // Prevent trying to load from invalid mission data downstream + if (!Csg_campaign_mismatch) + m_data_invalid = true; // Causes a warning popup to be displayed + } + if (!Campaign.missions.in_bounds(Campaign.loop_reentry) && (Campaign.loop_reentry != -1)) { + Campaign.loop_reentry = 0; + if (!Csg_campaign_mismatch) + m_data_invalid = true; + } + } + // missions completed Campaign.num_missions_completed = cfread_int(cfp); @@ -266,14 +281,26 @@ void pilotfile::csg_read_missions() { int i, j, idx, list_size; cmission *missionp; + cmission discarded_mission; if ( !m_have_info ) { throw "Missions before Info!"; } - for (i = 0; i < Campaign.num_missions_completed; i++) { + const int num_records = Campaign.num_missions_completed; + + for (i = 0; i < num_records; 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; + // the count is written as the number of saved records, so it must not include this one + Campaign.num_missions_completed--; + } missionp->completed = 1; @@ -362,7 +389,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 +1627,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 +1663,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 +1751,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 +1916,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 +1996,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/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/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..0e7a0e02d2c 100644 --- a/code/scripting/api/objs/player.cpp +++ b/code/scripting/api/objs/player.cpp @@ -245,24 +245,24 @@ 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()); } // use getMainHallName if at all possible. -ADE_FUNC(getMainHallIndex, l_Player, NULL, "Gets player's current main hall number", "number", "Main hall index, or index of first mainhall in campaign if something goes wrong") +ADE_FUNC(getMainHallIndex, l_Player, nullptr, "Gets player's current main hall number", "number", "Main hall index, or index of first mainhall in campaign if something goes wrong. This is a 0-based index, where -1 means not found, as opposed to a Lua 1-based index, where 0 means not found") { 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); @@ -292,7 +292,7 @@ ADE_FUNC(getMultiSquadronName, l_Player, NULL, "Gets current player multi squad return ade_set_args(L, "s", plr->get()->m_squad_name); } -ADE_FUNC(loadCampaignSavefile, l_Player, "string campaign = \"\"", "Loads the specified campaign save file.", +ADE_FUNC(loadCampaignSavefile, l_Player, "string campaign = \"\"", "Loads the specified campaign save file. If the save file is for a campaign other than the one currently loaded, its mission data is discarded, and saving is blocked until a save file for the loaded campaign is loaded or the save data is cleared.", "boolean", "true on success, false otherwise") { player_h* plh; 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= 0) + swap = 1; - if (z > 0) - swap = 1; - - else if (!z) { - z = Campaign.missions[Links[from_list[j]].to].level - - Campaign.missions[Links[from_list[k]].to].level; + } else { + z = Campaign.missions[Links[from_list[j]].to].pos - + Campaign.missions[Links[from_list[k]].to].pos; - if (Campaign.missions[i].pos < Campaign.missions[Links[from_list[j]].to].pos) { - if (z < 0) - swap = 1; + if (z > 0) + swap = 1; - } else { - if (z > 0) - swap = 1; + else if (!z) { + z = Campaign.missions[Links[from_list[j]].to].level - + Campaign.missions[Links[from_list[k]].to].level; + + if (Campaign.missions[i].pos < Campaign.missions[Links[from_list[j]].to].pos) { + if (z < 0) + swap = 1; + + } else { + if (z > 0) + swap = 1; + } } } @@ -583,7 +598,7 @@ void campaign_tree_view::OnLButtonDown(UINT nFlags, CPoint point) } } Mission_dragging = Cur_campaign_mission = Cur_campaign_link = -1; - 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 +750,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 +891,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 +980,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 +1045,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 +1075,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 +1112,12 @@ void campaign_tree_view::sort_elements() { int i, j, s1, s2; - for (i=0; i=0; j--) { s2 = Sorted[j]; @@ -1140,10 +1141,10 @@ 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) ) { + if ( (z >= 0) && (num != z) && (Campaign.missions[num].level >= Campaign.missions[z].level) ) { Campaign.missions[z].level = Campaign.missions[num].level + 1; correct_position(z); } @@ -1159,13 +1160,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 +1203,13 @@ 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); + + if (Cur_campaign_link == num) + Cur_campaign_link = -1; + else if (Cur_campaign_link > num) + Cur_campaign_link--; - Total_links--; sort_links(); Invalidate(); Campaign_modified = 1; @@ -1216,9 +1218,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 +1296,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); @@ -1313,6 +1309,8 @@ void campaign_tree_view::remove_mission(int m) box->SetWindowText(""); Campaign_tree_formp->load_tree(0); + } else if (Cur_campaign_mission == z) { + Cur_campaign_mission = m; } Campaign_modified = 1; @@ -1327,7 +1325,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 +1350,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();