Ejemplo n.º 1
0
        public MissionTemplate GetTemplate(uint templateId)
        {
            MissionTemplate template = null;

            m_templates.TryGetValue(templateId, out template);
            return(template);
        }
Ejemplo n.º 2
0
        public MainForm()
        {
            InitializeComponent();

            Generator = new MissionGenerator();
            Template  = new MissionTemplate();
        }
Ejemplo n.º 3
0
 //Completes the mission
 void MissionCompleted(MissionTemplate mission, int missionID)
 {
     //Flag the mission as completed
     activeMissionComplete[missionID] = true;
     //Show the GUI notification
     StartCoroutine(GUIManager.Instance.ShowMissionComplete(mission.description));
 }
        /// <summary>
        /// Directly copies some simple values (theater database entry ID, etc.) from the template.
        /// </summary>
        /// <param name="mission">The mission</param>
        /// <param name="template">Mission template to use</param>
        private void CopyTemplateValues(DCSMission mission, MissionTemplate template)
        {
            mission.Coalitions[(int)Coalition.Blue] = template.GetCoalition(Coalition.Blue);
            mission.Coalitions[(int)Coalition.Red]  = template.GetCoalition(Coalition.Red);
            mission.CivilianTraffic      = template.OptionsCivilianTraffic;
            mission.CoalitionPlayer      = template.ContextCoalitionPlayer;
            mission.Weather.CloudsPreset = template.EnvironmentCloudPreset.Get();
            mission.RadioAssists         = !template.Realism.Contains(RealismOption.DisableDCSRadioAssists);
            mission.Theater      = template.ContextTheater;
            mission.CountryBlues = new List <Country> {
                Country.CJTFBlue
            };
            mission.CountryReds = new List <Country> {
                Country.CJTFRed
            };
            var countries = template.PlayerFlightGroups.Select(x => x.Country).Distinct().ToList();

            if (template.ContextCoalitionPlayer == Coalition.Blue)
            {
                mission.CountryBlues.AddRange(countries);
            }
            else
            {
                mission.CountryReds.AddRange(countries);
            }
            mission.CountryBlues   = mission.CountryBlues.Distinct().ToList();
            mission.CountryReds    = mission.CountryReds.Distinct().ToList();
            mission.EndMode        = template.OptionsEndMode;
            mission.RealismOptions = template.Realism;
        }
        public void CheckTemplate(MissionTemplate template)
        {
#if !DEBUG
            if (template.GetPlayerCount() < 1)
            {
                throw new HQ4DCSException($"No player flight groups. A mission must have at least one player flight group.");
            }
#endif

            CheckMissingDefinitions(template);
            CheckCoalitions(template);
            CheckTheaterNodes(template);

            //mission.Countries[(int)Coalition.Red].Except(mission.Countries[(int)Coalition.Blue])

            //// Copy blue and red coalitions' countries list
            //mission.Countries[(int)Coalition.Blue] = coalitions[(int)Coalition.Blue].Countries.ToArray();
            //if (mission.Countries[(int)Coalition.Blue].Length == 0)
            //    throw new Exception("Blue coalition has no countries.");

            //mission.Countries[(int)Coalition.Red] = coalitions[(int)Coalition.Red].Countries.ToArray();
            //if (mission.Countries[(int)Coalition.Red].Length == 0)
            //    throw new Exception("Red coalition has no countries.");

            //// Remove blue countries from red coalition to make sure no country belongs to both.
            //mission.Countries[(int)Coalition.Red] = mission.Countries[(int)Coalition.Red].Except(mission.Countries[(int)Coalition.Blue]).ToArray();
            //if (mission.Countries[(int)Coalition.Red].Length == 0)
            //    throw new Exception("Blue and red coalitions share the same countries.");

            //// TODO: check template nodes
            //foreach (HQTemplateNode n in template.Nodes.Values)
            //{
            //}
        }
Ejemplo n.º 6
0
    void SetUpjective()
    {
        MissionTemplate missionTemplate;

        missionIndex = 0;


        // First mission
        missionTemplate           = new MissionTemplate();
        missionTemplate.type      = MissionTemplate.Type.KO;
        missionTemplate.numTarget = 15;
        missionList.Add(missionTemplate);

        // Second mission
        missionTemplate           = new MissionTemplate();
        missionTemplate.type      = MissionTemplate.Type.Capture;
        missionTemplate.numTarget = 1;
        missionList.Add(missionTemplate);

        // Third mission
        missionTemplate               = new MissionTemplate();
        missionTemplate.type          = MissionTemplate.Type.Defeat;
        missionTemplate.numTarget     = 1;
        missionTemplate.defeatTarget  = bossEnemy;
        missionTemplate.targetName    = "Ryu";
        missionTemplate.spawnLocation = new Vector2((enemyHQIndex.x * BASE_DISTANCE) - 0.27f, enemyHQIndex.y - 2.0f);
        missionTemplate.layer         = (int)(enemyHQIndex.y / 10.0f);
        missionList.Add(missionTemplate);

        CreateNewMission();
    }
Ejemplo n.º 7
0
        public void Generate(CampaignTemplate campaignTemplate, string campaignFilePath)
        {
            string campaignName      = Path.GetFileNameWithoutExtension(campaignFilePath);
            string campaignDirectory = Path.GetDirectoryName(campaignFilePath);

            DCSMissionDateTime date = GenerateCampaignDate(campaignTemplate);

            using (MissionGenerator generator = new MissionGenerator())
            {
                for (int i = 0; i < campaignTemplate.MissionsCount; i++)
                {
                    // Increment the date by a few days for each mission after the first
                    if (i > 0)
                    {
                        IncrementDate(ref date);
                    }

                    MissionTemplate template = CreateMissionTemplate(campaignTemplate, i);

                    DCSMission mission = generator.Generate(template);
                    mission.MissionName  = $"{campaignName}, phase {i + 1}";
                    mission.DateTime.Day = date.Day; mission.DateTime.Month = date.Month; mission.DateTime.Year = date.Year;

                    MizFile miz = mission.ExportToMiz();
                    miz.SaveToFile(Path.Combine(campaignDirectory, $"{campaignName}{i + 1:00}.miz"));
                }
            }

            CreateImageFiles(campaignTemplate, campaignFilePath);
            CreateCMPFile(campaignTemplate, campaignFilePath);
        }
Ejemplo n.º 8
0
        public MainForm()
        {
            InitializeComponent();

            Generator = new MissionGenerator();
            Template  = new MissionTemplate(BRPaths.ROOT + "Default.brt");
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Generates the <see cref="DCSMissionObjective"/>.
        /// </summary>
        /// <param name="mission">The mission for which to generate objectives</param>
        /// <param name="template">Mission template to use</param>
        /// <param name="objectiveDB">Objective database entry</param>
        public void CreateObjectives(DCSMission mission, MissionTemplate template, DBEntryObjective objectiveDB, DBEntryTheater theaterDB)
        {
            // Set the array for the proper number of objective
            mission.Objectives = new DCSMissionObjective[template.ObjectiveCount];

            GenerateObjectivesData(mission, template, objectiveDB, theaterDB);
            GenerateObjectivesScript(mission);
        }
Ejemplo n.º 10
0
        private MissionTemplate CreateMissionTemplate(CampaignTemplate campaignTemplate, int index, string campaignName, ref DCSMissionDateTime currentDate)
        {
            // Increment the date by a few days for each mission after the first
            if (index > 0)
            {
                currentDate = IncrementDate(currentDate);
            }

            MissionTemplate template = new MissionTemplate();

            template.BriefingDate.Enabled = true;
            template.BriefingDate.Day     = currentDate.Day;
            template.BriefingDate.Month   = currentDate.Month;
            template.BriefingDate.Year    = currentDate.Year;
            template.BriefingDescription  = "";
            template.BriefingName         = $"{campaignName}, phase {index + 1}";

            template.ContextCoalitionBlue   = campaignTemplate.ContextCoalitionsBlue;
            template.ContextCoalitionPlayer = campaignTemplate.PlayerCoalition;
            template.ContextCoalitionRed    = campaignTemplate.ContextCoalitionsRed;

            template.EnvironmentTimeOfDay = GetTimeOfDayForMission(campaignTemplate.EnvironmentNightMissionChance);
            template.EnvironmentWeather   = GetWeatherForMission(campaignTemplate.EnvironmentBadWeatherChance);
            template.EnvironmentWind      = Wind.Auto;

            template.ObjectiveCount      = GetObjectiveCountForMission(campaignTemplate.MissionsObjectiveCount);
            template.ObjectiveDistanceNM = Database.Instance.Common.DistanceFromTakeOffLocation[(int)campaignTemplate.MissionsObjectiveDistance];
            template.ObjectiveType       = Toolbox.RandomFrom(campaignTemplate.MissionsTypes);

            template.OppositionAirDefense       = GetPowerLevel(campaignTemplate.SituationEnemyAirDefense, campaignTemplate.SituationVariation, index, campaignTemplate.MissionsCount);
            template.OppositionAirForce         = GetPowerLevel(campaignTemplate.SituationEnemyAirForce, campaignTemplate.SituationVariation, index, campaignTemplate.MissionsCount);
            template.OppositionSkillLevelAir    = GetSkillLevel(campaignTemplate.SituationEnemyAirForce, campaignTemplate.SituationVariation, index, campaignTemplate.MissionsCount);
            template.OppositionSkillLevelGround = GetSkillLevel(campaignTemplate.SituationEnemyAirDefense, campaignTemplate.SituationVariation, index, campaignTemplate.MissionsCount);
            template.OppositionUnitsLocation    = SpawnPointPreferredCoalition.Any;

            template.OptionsCivilianTraffic  = campaignTemplate.OptionsCivilianTraffic;
            template.OptionsEndMode          = MissionEndMode.NoEnd;
            template.OptionsPreferences      = campaignTemplate.OptionsPreferences.ToArray();
            template.OptionsRealism          = campaignTemplate.OptionsRealism.ToArray();
            template.OptionsScriptExtensions = new string[0];
            template.OptionsUnitMods         = campaignTemplate.OptionsUnitMods;

            template.PlayerAISkillLevel   = GetSkillLevel(campaignTemplate.SituationFriendlyAirForce, CampaignDifficultyVariation.Steady, 0, 0);
            template.PlayerEscortCAP      = Toolbox.RandomFrom(2, 2, 2, 2, 3, 4, 4);
            template.PlayerEscortSEAD     = Toolbox.RandomFrom(2, 2, 2, 2, 3, 4, 4);
            template.PlayerMPFlightGroups = new MissionTemplateMPFlightGroup[0];
            template.PlayerSPAircraft     = campaignTemplate.PlayerAircraft;
            template.PlayerSPWingmen      = Toolbox.RandomFrom(1, 1, 1, 1, 2, 3, 3);
            template.PlayerStartLocation  = campaignTemplate.PlayerStartLocation;
            template.PlayerSPCarrier      = campaignTemplate.PlayerStartingCarrier;

            template.TheaterID = campaignTemplate.ContextTheaterID;
            template.TheaterRegionsCoalitions = campaignTemplate.ContextTheaterRegionsCoalitions;
            template.TheaterStartingAirbase   = campaignTemplate.PlayerStartingAirbase;

            return(template);
        }
        /// <summary>
        /// Generates the list of tasks for the mission.
        /// </summary>
        /// <param name="mission"></param>
        /// <param name="template"></param>
        /// <param name="missionTask"></param>
        //public void GenerateMissionTasks(HQMission mission, MissionTemplate template, DefinitionMissionObjective missionTask)
        //{
        //    HQDebugLog.Instance.Log("Generating mission briefing objectives...");

        //    mission.BriefingTasks.Clear();

        //    mission.BriefingTasks.Add(Language.GetStringRandom("BriefingCommon", $"Task.TakeOff").Replace("$AIRBASE$", mission.Airbases[0].Name));

        //    foreach (HQMissionObjectiveLocation o in mission.Objectives)
        //        mission.BriefingTasks.Add(Language.GetStringRandom("BriefingMission", $"Task.{missionTask.BriefingTask}").Replace("$NAME$", o.Name));

        //    mission.BriefingTasks.Add(Language.GetStringRandom("BriefingCommon", $"Task.Land").Replace("$AIRBASE$", mission.Airbases[1].Name));

        //    HQDebugLog.Instance.Log("");
        //}

        //public void GenerateMissionRemarks(HQMission mission, MissionTemplate template, DefinitionMissionObjective missionTask)
        //{
        //    HQDebugLog.Instance.Log("Generating mission briefing remarks...");

        //    mission.BriefingRemarks.Clear();

        //    foreach (string s in missionTask.BriefingRemarks)
        //        mission.BriefingRemarks.Add(Language.GetStringRandom("BriefingMission", $"Remark.{s}"));

        //    HQDebugLog.Instance.Log("");
        //}

        public void GenerateRawTextBriefing(DCSMission mission, MissionTemplate template)
        {
            DebugLog.Instance.Log("Generating raw text MIZ briefing...");

            string text = "";

            if (template.GetPlayerCount() == 1)
            {
                text += $"{Language.GetString("Briefing", "Subtitle.SinglePlayer")}\n\n";
            }
            else
            {
                text += $"{Language.GetString("Briefing", "Subtitle.PvE").Replace("$PLAYERS$", HQTools.ValToString(template.GetPlayerCount()))}\n\n";
            }

            text += mission.BriefingDescription + "\n\n";

            // Tasks
            text += $"{Language.GetString("Briefing", "Section.Tasks").ToUpperInvariant()}{Language.Semicolon}\n";
            foreach (string t in mission.BriefingTasks)
            {
                text += $"- {t}\n";
            }
            if (mission.BriefingTasks.Count == 0)
            {
                text += $"- {Language.GetString("Briefing", "Misc.None")}\n";
            }
            text += "\n";

            // Remarks
            text += $"{Language.GetString("Briefing", "Section.Remarks").ToUpperInvariant()}{Language.Semicolon}\n";
            if (mission.BriefingImperialUnits)
            {
                text += $"- {Language.GetString("Briefing", "Remark.TotalFlightPlanNM", "Distance", (mission.TotalFlightPlanDistance * HQTools.METERS_TO_NM).ToString("F0"))}\n";
            }
            else
            {
                text += $"- {Language.GetString("Briefing", "Remark.TotalFlightPlanKM", "Distance", (mission.TotalFlightPlanDistance / 1000.0).ToString("F0"))}\n";
            }
            foreach (string t in mission.BriefingRemarks)
            {
                text += $"- {t}\n";
            }
            text += "\n";

            // Flight package
            //text += $"{GetString("Section.Package").ToUpperInvariant()}{Language.Semicolon}\n";
            //foreach (HQMissionBriefingFlightGroup fg in (from HQMissionBriefingFlightGroup f in mission.BriefingFlightPackage where !f.IsSupport select f).OrderBy(x => x.Task))
            //    text += $"- {fg.Callsign} ({fg.UnitCount}x {GetUnitName(fg.UnitType)}), {HQTools.ValToString(fg.Frequency, "F1")} Mhz\n";

            // Make sure endlines are in the proper format (escaped LF) or it can cause bugs.
            text = text.Replace("\r\n", "\n").Trim(' ', '\n', '\t').Replace("\n", "\\\n");
            mission.BriefingRawText = text;

            DebugLog.Instance.Log("");
        }
 /// <summary>
 /// Main unit generation method.
 /// </summary>
 /// <param name="mission">Mission to which generated units should be added</param>
 /// <param name="enemyCoalitionDB">Ally coalition database entry</param>
 /// <param name="unitMods">Unit mods selected units can belong to</param>
 public void CreateUnitGroups(DCSMission mission, MissionTemplate template, DBEntryCoalition enemyCoalitionDB, string[] unitMods)
 {
     if (!template.SituationEnemySupportAircraft.RollChance())
     {
         return;
     }
     AddSupportUnit(mission, template, enemyCoalitionDB, UnitFamily.PlaneTankerBasket, unitMods, new Tacan(39, "ETR", AA: true));
     AddSupportUnit(mission, template, enemyCoalitionDB, UnitFamily.PlaneTankerBoom, unitMods, new Tacan(82, "EKR", AA: true));
     AddSupportUnit(mission, template, enemyCoalitionDB, UnitFamily.PlaneAWACS, unitMods); // AWACS must be added last, so it its inserted first into the spawning queue
 }
Ejemplo n.º 13
0
    //Check shop based mission status
    void CheckShopBased(MissionTemplate mission, int i)
    {
        mission.ModifyStoredValue(true, 1);
        GUIManager.Instance.UpdateMissionStatus(i, mission.StoredValue(), mission.valueA);

        if (mission.valueA == mission.StoredValue())
        {
            MissionCompleted(mission, i);
            Save();
        }
    }
Ejemplo n.º 14
0
        /// <summary>
        /// Generate a random mission name if none is provided in the template, or returns the provided name if there is one.
        /// </summary>
        /// <param name="mission">A mission</param>
        /// <param name="template">Mission template to use</param>
        public void GenerateMissionName(DCSMission mission, MissionTemplate template)
        {
            DebugLog.Instance.WriteLine("Generating mission name...", 1);

            mission.MissionName = Database.Instance.Common.MissionNameTemplate;
            for (int i = 0; i < DatabaseCommon.MISSION_NAMES_PART_COUNT; i++)
            {
                mission.MissionName = mission.MissionName.Replace($"$P{i + 1}$", Toolbox.RandomFrom(Database.Instance.Common.MissionNameParts[i]));
            }

            DebugLog.Instance.WriteLine($"Mission name set to \"{mission.MissionName}\"", 2);
        }
Ejemplo n.º 15
0
    //Checks DistanceNoCoin based mission status
    void CheckDistanceNoCoin(MissionTemplate mission, int number, int i)
    {
        if (mission.goalType == MissionTemplate.GoalType.InOneRun)
        {
            GUIManager.Instance.UpdateMissionStatus(i, number, mission.valueA);

            if (mission.valueA <= number && LevelManager.Instance.Coins() == 0)
            {
                MissionCompleted(mission, i);
            }
        }
    }
Ejemplo n.º 16
0
    //Checks DistanceNoPowerUp based mission status
    void CheckDistanceNoPowerUp(MissionTemplate mission, int number, int i)
    {
        if (mission.goalType == MissionTemplate.GoalType.InOneRun)
        {
            GUIManager.Instance.UpdateMissionStatus(i, number, mission.valueA);

            if (mission.valueA <= number && !PlayerManager.Instance.PowerUpUsed())
            {
                MissionCompleted(mission, i);
            }
        }
    }
Ejemplo n.º 17
0
    //Checks SinkBetween based mission status
    void CheckSindBetween(MissionTemplate mission, int number, int i)
    {
        if (mission.goalType == MissionTemplate.GoalType.InOneRun)
        {
            GUIManager.Instance.UpdateMissionStatus(i, number, mission.valueA);

            if (mission.valueA <= number && number <= mission.valueB)
            {
                MissionCompleted(mission, i);
            }
        }
    }
        /// <summary>
        /// Picks a date (day, month and year) for the mission.
        /// </summary>
        /// <param name="mission">The mission</param>
        /// <param name="template">Mission template to use</param>
        /// <param name="coalitions">Coalitions database entries</param>
        public void GenerateMissionDate(DCSMission mission, MissionTemplate template, DBEntryCoalition[] coalitions)
        {
            int   day, year;
            Month month;

            // A fixed date has been provided, use it
            if (template.BriefingDate.Enabled)
            {
                DebugLog.Instance.WriteLine("Using fixed date provided in the mission template", 1);

                day   = template.BriefingDate.Day;
                month = template.BriefingDate.Month;
                year  = template.BriefingDate.Year;
            }
            else // Not fixed date provided, generate a random one
            {
                // Select a random year from the most recent coalition's decade
                year = Toolbox.GetRandomYearFromDecade(template.ContextDecade);

                DebugLog.Instance.WriteLine($"No fixed date provided in the mission template, generating date in decade {template.ContextDecade}", 1);

                if (template.EnvironmentSeason == Season.Random) // Random season, pick any day of the year
                {
                    month = (Month)Toolbox.RandomInt(12);
                    day   = Toolbox.RandomMinMax(1, Toolbox.GetDaysPerMonth(month, year));
                }
                else // Pick a date according to the desired season
                {
                    Month[] seasonMonths = GetMonthsForSeason(template.EnvironmentSeason);

                    int monthIndex = Toolbox.RandomInt(4);
                    month = seasonMonths[monthIndex];
                    switch (monthIndex)
                    {
                    case 0:     // First month of the season, season begins on the 21st
                        day = Toolbox.RandomMinMax(21, Toolbox.GetDaysPerMonth(month, year)); break;

                    case 3:     // Last month of the season, season ends on the 20th
                        day = Toolbox.RandomMinMax(1, 20); break;

                    default:
                        day = Toolbox.RandomMinMax(1, Toolbox.GetDaysPerMonth(month, year)); break;
                    }
                }
            }

            mission.DateTime.Day   = day;
            mission.DateTime.Month = month;
            mission.DateTime.Year  = year;

            DebugLog.Instance.WriteLine($"Misson date set to {mission.DateTime.ToDateString(false)}", 1);
        }
Ejemplo n.º 19
0
        public async Task <FileContentResult> Post(MissionTemplate template)
        {
            var briefingRoom = new BriefingRoom();
            var mission      = await briefingRoom.GenerateMissionAsync(template);

            var mizBytes = mission.SaveToMizBytes();

            if (mizBytes == null)
            {
                return(null);                  // Something went wrong during the .miz export
            }
            return(File(mizBytes, "application/octet-stream", $"{mission.Briefing.Name}.miz"));
        }
Ejemplo n.º 20
0
    //Checks Obstalce based mission status
    void CheckObstacleBased(MissionTemplate mission, int i)
    {
        if (mission.goalType == MissionTemplate.GoalType.InOneRun || mission.goalType == MissionTemplate.GoalType.InMultipleRun)
        {
            mission.ModifyStoredValue(true, 1);
            GUIManager.Instance.UpdateMissionStatus(i, mission.StoredValue(), mission.valueA);

            if (mission.valueA == mission.StoredValue())
            {
                MissionCompleted(mission, i);
            }
        }
    }
Ejemplo n.º 21
0
        internal bool IsExtremeDistance(MissionTemplate template, out double distance)
        {
            var objCenter = new Coordinates(
                double.Parse(GetValue("MissionCenterX"), CultureInfo.InvariantCulture),
                double.Parse(GetValue("MissionCenterY"), CultureInfo.InvariantCulture));
            var playerAirbase = new Coordinates(
                double.Parse(GetValue("MissionAirbaseX"), CultureInfo.InvariantCulture),
                double.Parse(GetValue("MissionAirbaseY"), CultureInfo.InvariantCulture));

            distance = objCenter.GetDistanceFrom(playerAirbase) * Toolbox.METERS_TO_NM;
            var extremeLimit = template.FlightPlanObjectiveDistance * 1.7;

            return(distance > extremeLimit);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Generates the mission briefing.
        /// </summary>
        /// <param name="mission">Mission</param>
        /// <param name="template">Template from which the mission should be built</param>
        /// <param name="airbaseDB">Airbase player will take off from and land back on</param>
        /// <param name="coalitionsDB">Database entries for the mission coalitions</param>
        public void GenerateMissionBriefing(DCSMission mission, MissionTemplate template, DBEntryObjective objectiveDB, DBEntryTheaterAirbase airbaseDB, List <UnitFlightGroupBriefingDescription> flightGroups, DBEntryCoalition[] coalitionsDB)
        {
            DebugLog.Instance.WriteLine("Generating mission briefing...", 1);

            // Get mission features
            DBEntryMissionFeature[] features = Database.Instance.GetEntries <DBEntryMissionFeature>(objectiveDB.MissionFeatures);

            string description = objectiveDB.BriefingDescriptionByUnitFamily[(int)mission.Objectives[0].TargetFamily];

            if (string.IsNullOrEmpty(description)) // No custom briefing for this target family, use the default
            {
                description = objectiveDB.BriefingDescription;
            }

            description =
                GeneratorTools.MakeBriefingStringReplacements(GeneratorTools.ParseRandomString(description), mission, coalitionsDB);
            description = GeneratorTools.SanitizeString(description);

            // Generate tasks
            string        baseName = airbaseDB.Name; // TODO: this doesn't work for lots of carriers so simplifying for now
            List <string> tasks    = new List <string> {
                $"Take off from {baseName}"
            };
            string objectiveTask = GeneratorTools.ParseRandomString(objectiveDB.BriefingTask);

            for (int i = 0; i < mission.Objectives.Length; i++)
            {
                string taskString = GeneratorTools.MakeBriefingStringReplacements(objectiveTask, mission, coalitionsDB, i);
                tasks.Add(taskString);
                mission.CoreLuaScript += $"briefingRoom.mission.objectives[{i + 1}].task = \"{taskString}\"\r\n";
            }
            tasks.Add($"Return to {baseName}");
            DebugLog.Instance.WriteLine($"{tasks.Count} task(s)", 2);

            // Generate mission remarks...
            List <string> remarks = new List <string>();

            remarks.AddRange( // ...from objective
                from string remark in objectiveDB.BriefingRemarks
                select GeneratorTools.MakeBriefingStringReplacements(GeneratorTools.ParseRandomString(remark), mission, coalitionsDB));
            foreach (DBEntryMissionFeature feature in features)
            {
                remarks.AddRange( // ...from features
                    from string remark in feature.BriefingRemarks
                    select GeneratorTools.MakeBriefingStringReplacements(GeneratorTools.ParseRandomString(remark), mission, coalitionsDB));
            }

            mission.BriefingHTML = CreateHTMLBriefing(mission, template, description, tasks, remarks, flightGroups, airbaseDB, coalitionsDB, objectiveDB);
            mission.BriefingTXT  = CreateTXTBriefing(mission, description, tasks, remarks, flightGroups, airbaseDB);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Decide what should be spawned.
        /// </summary>
        /// <param name="mission">Mission to which generated units should be added</param>
        /// <param name="template">Mission template to use</param>
        /// <param name="objectiveDB">Mission objective database entry</param>
        /// <param name="coalitionsDB">Coalitions database entries</param>
        public void CreateUnitGroups(DCSMission mission, MissionTemplate template, DBEntryObjective objectiveDB, DBEntryCoalition[] coalitionsDB)
        {
            Coalition coalition =
                objectiveDB.UnitGroup.Flags.HasFlag(DBUnitGroupFlags.Friendly) ?
                mission.CoalitionPlayer : mission.CoalitionEnemy;
            Side side = objectiveDB.UnitGroup.Flags.HasFlag(DBUnitGroupFlags.Friendly) ? Side.Ally : Side.Enemy;

            SpawnUnitGroups(mission, template, objectiveDB.UnitGroup, coalitionsDB, side, coalition);
            if (objectiveDB.AllyUnitGroup.Category != null)
            {
                DebugLog.Instance.WriteLine($"Generating Friendly units for objective");
                SpawnUnitGroups(mission, template, objectiveDB.AllyUnitGroup, coalitionsDB, Side.Ally, mission.CoalitionPlayer);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Picks a starting airbase for the player(s)
        /// </summary>
        /// <param name="mission">Mission for which the starting airbase must be set</param>
        /// <param name="template">Mission template to use</param>
        /// <param name="theaterDB">Theater database entry</param>
        /// <param name="objectiveDB">Objective database entry</param>
        /// <returns>Information about the starting airbase</returns>
        public DBEntryTheaterAirbase SelectStartingAirbase(DCSMission mission, MissionTemplate template, DBEntryTheater theaterDB, DBEntryObjective objectiveDB)
        {
            List <DBEntryTheaterAirbase[]> airbasesList = new List <DBEntryTheaterAirbase[]>();

            // Select all airbases with enough parking spots
            int requiredParkingSpots = template.GetMissionPackageRequiredParkingSpots();

            airbasesList.Add((from DBEntryTheaterAirbase ab in theaterDB.Airbases where ab.ParkingSpots.Length >= requiredParkingSpots select ab).ToArray());

            // Select all airbases belonging to the proper coalition (unless all airbase belong to the same coalition)
            if ((template.TheaterRegionsCoalitions == CountryCoalition.Default) || (template.TheaterRegionsCoalitions == CountryCoalition.Inverted))
            {
                Coalition requiredCoalition = template.TheaterRegionsCoalitions == CountryCoalition.Inverted ? mission.CoalitionEnemy : mission.CoalitionPlayer;
                airbasesList.Add((from DBEntryTheaterAirbase ab in airbasesList.Last() where ab.Coalition == requiredCoalition select ab).ToArray());
            }

            // If mission must start near water, or some player start on a carrier, select all airbases near water
            if (objectiveDB.Flags.HasFlag(DBEntryObjectiveFlags.MustStartNearWater) || !string.IsNullOrEmpty(template.PlayerCarrier))
            {
                airbasesList.Add((from DBEntryTheaterAirbase ab in airbasesList.Last() where ab.Flags.HasFlag(DBEntryTheaterAirbaseFlag.NearWater) select ab).ToArray());
            }

            // If a particular airbase name has been specified and an airbase with this name exists, pick it
            if (!string.IsNullOrEmpty(template.TheaterStartingAirbase))
            {
                string airbaseName = template.TheaterStartingAirbase.Trim();
                if (airbaseName.Contains(","))
                {
                    airbaseName = airbaseName.Substring(airbaseName.IndexOf(',')).Trim(' ', ',');
                }
                airbasesList.Add((from DBEntryTheaterAirbase airbase in theaterDB.Airbases where airbase.Name == airbaseName select airbase).ToArray());

                if (airbasesList.Last().Length == 0)
                {
                    DebugLog.Instance.WriteLine($"Airbase \"{airbaseName}\" not found or airbase doesn't have enough parking spots. Selecting a random airbase instead.", 1, DebugLogMessageErrorLevel.Warning);
                }
            }

            // Check for valid airbases in all list, starting from the last one (with the most criteria filtered, and go back to the previous ones
            // as long as no airbase is found.
            for (int i = airbasesList.Count - 1; i >= 0; i--)
            {
                if (airbasesList[i].Length > 0)
                {
                    return(Toolbox.RandomFrom(airbasesList[i]));
                }
            }

            throw new Exception($"No airbase found with {requiredParkingSpots} parking spots, cannot spawn all player aircraft.");
        }
Ejemplo n.º 25
0
        public MainForm()
        {
            InitializeComponent();

            GUITools.LoadIcons();
            IMAGE_ERROR   = GUITools.IconsList16.Images["error"];
            IMAGE_INFO    = GUITools.IconsList16.Images["info"];
            IMAGE_WARNING = GUITools.IconsList16.Images["warning"];

            Generator      = new MissionGenerator();
            Template       = new MissionTemplate(BRPaths.ROOT + "Default.brt");
            TreeViewEditor = new TreeViewPropertyEditor <MissionTemplate>(TemplateTreeView, Template);
            TreeViewEditor.OnPropertyValueChanged += OnTreeViewEditorPropertyValueChanged;
        }
Ejemplo n.º 26
0
    public void SetUpMissionParameters(Template misisonTemplate)
    {
        template               = new Template();
        template.type          = misisonTemplate.type;
        template.numTarget     = misisonTemplate.numTarget;
        template.defeatTarget  = misisonTemplate.defeatTarget;
        template.targetName    = misisonTemplate.targetName;
        template.spawnLocation = misisonTemplate.spawnLocation;
        template.layer         = misisonTemplate.layer;

        if (Template.Type.Capture == template.type)
        {
            SetUpCaptureMission();
        }
    }
Ejemplo n.º 27
0
        /// <summary>
        /// Directly copies some simple values (theater database entry ID, etc.) from the template.
        /// </summary>
        /// <param name="mission">The mission</param>
        /// <param name="template">Mission template to use</param>
        private void CopyTemplateValues(DCSMission mission, MissionTemplate template)
        {
            mission.Coalitions[(int)Coalition.Blue] = template.GetCoalition(Coalition.Blue);
            mission.Coalitions[(int)Coalition.Red]  = template.GetCoalition(Coalition.Red);
            mission.CoalitionPlayer     = template.ContextCoalitionPlayer;
            mission.Theater             = template.TheaterID;
            mission.PlayerStartLocation = template.PlayerStartLocation;
            mission.EndMode             = template.OptionsEndMode;

            // "Runway" start locations is not available in MP missions, change to "Parking hot".
            if ((template.GetMissionType() != MissionType.SinglePlayer) &&
                (template.PlayerStartLocation == PlayerStartLocation.Runway))
            {
                mission.PlayerStartLocation = PlayerStartLocation.ParkingHot;
            }
        }
Ejemplo n.º 28
0
        internal static async Task <DCSMission> GenerateRetryableAsync(MissionTemplate template, bool useObjectivePresets)
        {
            var templateRecord = new MissionTemplateRecord(template);
            var mission        = await Policy
                                 .HandleResult <DCSMission>(x => x.IsExtremeDistance(template, out double distance))
                                 .Or <BriefingRoomException>()
                                 .RetryAsync(3)
                                 .ExecuteAsync(() => GenerateAsync(templateRecord, useObjectivePresets));

            if (mission.IsExtremeDistance(template, out double distance))
            {
                BriefingRoom.PrintToLog($"Distance to objectives exceeds 1.7x of requested distance. ({Math.Round(distance, 2)}NM)", LogMessageErrorLevel.Warning);
            }

            return(mission);
        }
Ejemplo n.º 29
0
        public void Mission(int missionID, MissionTemplate template)
        {
            bool          isEdit                   = false;
            Mission       mission                  = null;
            StringBuilder prizeTypes               = new StringBuilder();
            string        prizeUserGroups          = null;
            string        prizeMedals              = null;
            string        prizeMedalIDs            = null;
            string        applyConditionUserGroups = null;

            if (missionID != 0)
            {
                isEdit  = true;
                mission = MissionBO.Instance.GetMission(missionID, true);
                foreach (PrivacyType type in mission.Prize.PrizeTypes)
                {
                    prizeTypes.Append((int)type + ",");
                }
                if (mission.Prize.PrizeTypes.Contains(MissionPrizeType.UserGroup))
                {
                    prizeUserGroups = StringUtil.Join(mission.Prize.UserGroups.Keys);
                }
                applyConditionUserGroups = StringUtil.Join(mission.ApplyCondition.UserGroupIDs);
                if (mission.Prize.PrizeTypes.Contains(MissionPrizeType.Medal))
                {
                    StringBuilder sb  = new StringBuilder();
                    StringBuilder sb2 = new StringBuilder();
                    foreach (PrizeMedal medal in mission.Prize.Medals)
                    {
                        sb.Append(medal.MedalID + "_" + medal.MedalLevelID).Append(",");
                        sb2.Append(medal.MedalID).Append(",");
                    }

                    if (sb.Length > 0)
                    {
                        prizeMedals   = sb.ToString(0, sb.Length - 1);
                        prizeMedalIDs = sb2.ToString(0, sb2.Length - 1);
                    }
                    else
                    {
                        prizeMedals   = string.Empty;
                        prizeMedalIDs = string.Empty;
                    }
                }
            }
            template(isEdit, prizeTypes.ToString(), prizeUserGroups, prizeMedals, prizeMedalIDs, applyConditionUserGroups, mission);
        }
Ejemplo n.º 30
0
        private MissionTemplate CreateMissionTemplate(CampaignTemplate campaignTemplate, int index)
        {
            MissionTemplate template = new MissionTemplate
            {
                ContextCoalitionBlue   = campaignTemplate.ContextCoalitionsBlue,
                ContextCoalitionPlayer = campaignTemplate.ContextCoalitionPlayer,
                ContextCoalitionRed    = campaignTemplate.ContextCoalitionsRed,

                EnvironmentTimeOfDay = GetTimeOfDayForMission(campaignTemplate.EnvironmentNightMissionChance),
                EnvironmentWeather   = GetWeatherForMission(campaignTemplate.EnvironmentBadWeatherChance),
                EnvironmentWind      = Wind.Auto,

                ObjectiveCount    = GetObjectiveCountForMission(campaignTemplate.MissionsObjectiveCount),
                ObjectiveDistance = MissionTemplate.OBJECTIVE_DISTANCE_INCREMENT * 2 * ((int)campaignTemplate.MissionsObjectiveDistance + 1),
                ObjectiveType     = Toolbox.RandomFrom(campaignTemplate.Objectives),

                SituationEnemyAirDefense       = GetPowerLevel(campaignTemplate.SituationEnemyAirDefense, campaignTemplate.MissionsDifficultyVariation, index, campaignTemplate.MissionsCount),
                SituationEnemyAirForce         = GetPowerLevel(campaignTemplate.SituationEnemyAirForce, campaignTemplate.MissionsDifficultyVariation, index, campaignTemplate.MissionsCount),
                SituationEnemySkillLevelAir    = GetSkillLevel(campaignTemplate.SituationEnemyAirForce, campaignTemplate.MissionsDifficultyVariation, index, campaignTemplate.MissionsCount),
                SituationEnemySkillLevelGround = GetSkillLevel(campaignTemplate.SituationEnemyAirDefense, campaignTemplate.MissionsDifficultyVariation, index, campaignTemplate.MissionsCount),
                OptionsEnemyUnitsLocation      = SpawnPointPreferredCoalition.Any,

                OptionsCivilianTraffic = campaignTemplate.OptionsCivilianTraffic,
                OptionsEndMode         = MissionEndMode.Never,
                //template.OptionsPreferences = campaignTemplate.OptionsPreferences.ToArray();
                Realism          = campaignTemplate.Realism.ToArray(),
                ScriptExtensions = new string[0],
                UnitMods         = campaignTemplate.UnitMods,

                SituationFriendlyAISkillLevel = GetSkillLevel(campaignTemplate.SituationFriendlyAirForce, CampaignDifficultyVariation.Steady, 0, 0),
                SituationFriendlyEscortCAP    = Toolbox.RandomFrom(2, 2, 2, 2, 3, 4, 4),
                SituationFriendlyEscortSEAD   = Toolbox.RandomFrom(2, 2, 2, 2, 3, 4, 4),
                PlayerFlightGroups            = new MissionTemplateFlightGroup[0],
            };

            template.PlayerFlightGroups = new MissionTemplateFlightGroup[]
            { new MissionTemplateFlightGroup(
                  campaignTemplate.PlayerAircraft, Toolbox.RandomFrom(2, 2, 2, 2, 3, 4, 4),
                  MissionTemplateFlightGroupTask.Objectives, campaignTemplate.PlayerCarrier, Country.CJTFBlue, PlayerStartLocation.Runway) };   //TODO Make country selectable

            template.ContextTheater = campaignTemplate.ContextTheaterID;
            template.OptionsTheaterCountriesCoalitions = campaignTemplate.OptionsTheaterCountriesCoalitions;
            template.FlightPlanTheaterStartingAirbase  = campaignTemplate.PlayerStartingAirbase;

            return(template);
        }
Ejemplo n.º 31
0
	//Checks DistanceNoCoin based mission status
	void CheckDistanceNoCoin(MissionTemplate mission, int number, int i)
	{
		if (mission.goalType == MissionTemplate.GoalType.InOneRun)
		{
            GUIManager.Instance.UpdateMissionStatus(i, number, mission.valueA);

            if (mission.valueA <= number && LevelManager.Instance.Coins() == 0)
				MissionCompleted(mission, i);
		}
	}
Ejemplo n.º 32
0
	//Check shop based mission status
	void CheckShopBased(MissionTemplate mission, int i)
	{
		mission.ModifyStoredValue(true, 1);
        GUIManager.Instance.UpdateMissionStatus(i, mission.StoredValue(), mission.valueA);
		
		if (mission.valueA == mission.StoredValue())
		{
			MissionCompleted(mission, i);
			Save();
		}
	}
Ejemplo n.º 33
0
        public void Mission(int missionID, MissionTemplate template)
        {
            bool isEdit = false;
            Mission mission = null;
            StringBuilder prizeTypes = new StringBuilder();
            string prizeUserGroups = null;
            string prizeMedals = null;
            string prizeMedalIDs = null;
            string applyConditionUserGroups = null;
            if (missionID != 0)
            {
                isEdit = true;
                mission = MissionBO.Instance.GetMission(missionID, true);
                foreach (PrivacyType type in mission.Prize.PrizeTypes)
                {
                    prizeTypes.Append((int)type + ",");
                }
                if (mission.Prize.PrizeTypes.Contains(MissionPrizeType.UserGroup))
                {
                    prizeUserGroups = StringUtil.Join(mission.Prize.UserGroups.Keys);
                }
                applyConditionUserGroups = StringUtil.Join(mission.ApplyCondition.UserGroupIDs);
                if (mission.Prize.PrizeTypes.Contains(MissionPrizeType.Medal))
                {
                    StringBuilder sb = new StringBuilder();
                    StringBuilder sb2 = new StringBuilder();
                    foreach (PrizeMedal medal in mission.Prize.Medals)
                    {
                        sb.Append(medal.MedalID + "_" + medal.MedalLevelID).Append(",");
                        sb2.Append(medal.MedalID).Append(",");
                    }

                    if (sb.Length > 0)
                    {
                        prizeMedals = sb.ToString(0, sb.Length - 1);
                        prizeMedalIDs = sb2.ToString(0, sb2.Length - 1);
                    }
                    else
                    {
                        prizeMedals = string.Empty;
                        prizeMedalIDs = string.Empty;
                    }
                }
            }
            template(isEdit, prizeTypes.ToString(), prizeUserGroups, prizeMedals, prizeMedalIDs, applyConditionUserGroups, mission);
        }
Ejemplo n.º 34
0
	//Completes the mission
	void MissionCompleted(MissionTemplate mission, int missionID)
	{
		//Flag the mission as completed
		activeMissionComplete[missionID] = true;
		//Show the GUI notification
        StartCoroutine(GUIManager.Instance.ShowMissionComplete(mission.description));
	}
Ejemplo n.º 35
0
	//Checks DistanceNoPowerUp based mission status
	void CheckDistanceNoPowerUp(MissionTemplate mission, int number, int i)
	{
		if (mission.goalType == MissionTemplate.GoalType.InOneRun)
		{
            GUIManager.Instance.UpdateMissionStatus(i, number, mission.valueA);
			
			if (mission.valueA <= number && !PlayerManager.Instance.PowerUpUsed())
				MissionCompleted(mission, i);
		}
	}
Ejemplo n.º 36
0
	//Checks SinkBetween based mission status
	void CheckSindBetween(MissionTemplate mission, int number, int i)
	{
		if (mission.goalType == MissionTemplate.GoalType.InOneRun)
		{
            GUIManager.Instance.UpdateMissionStatus(i, number, mission.valueA);
			
			if (mission.valueA <= number && number <= mission.valueB)
				MissionCompleted(mission, i);
		}
	}
Ejemplo n.º 37
0
	//Checks Obstalce based mission status
	void CheckObstacleBased(MissionTemplate mission, int i)
	{
		if (mission.goalType == MissionTemplate.GoalType.InOneRun || mission.goalType == MissionTemplate.GoalType.InMultipleRun)
		{
			mission.ModifyStoredValue(true, 1);
            GUIManager.Instance.UpdateMissionStatus(i, mission.StoredValue(), mission.valueA);
			
			if (mission.valueA == mission.StoredValue())
				MissionCompleted(mission, i);
		}
	}
Ejemplo n.º 38
0
	//Checks Coin based mission status
	void CheckCoinIn(MissionTemplate mission, int number, int i)
	{
		if (mission.goalType == MissionTemplate.GoalType.InOneRun)
		{
            GUIManager.Instance.UpdateMissionStatus(i, number, mission.valueA);
			
			if (mission.valueA <= number)
				MissionCompleted(mission, i);
		}
		else if (mission.goalType == MissionTemplate.GoalType.InMultipleRun)
		{
			mission.ModifyStoredValue(false, number);
            GUIManager.Instance.UpdateMissionStatus(i, mission.StoredValue(), mission.valueA);
			
			if (mission.valueA <= mission.StoredValue())
				MissionCompleted(mission, i);
		}
	}