Exemplo n.º 1
0
 public BaseUnit(string name, string description, UnitCategory category, double baseUnitValue)
 {
     Name = name;
     Description = description;
     BaseUnitValue = baseUnitValue;
     Category = category;
 }
Exemplo n.º 2
0
 private void AddUnitGroupToTable(Country country, UnitCategory category, string unitGroupLua)
 {
     if (!UnitLuaTables.ContainsKey(country))
     {
         UnitLuaTables.Add(country, new Dictionary <UnitCategory, List <string> >());
     }
     if (!UnitLuaTables[country].ContainsKey(category))
     {
         UnitLuaTables[country].Add(category, new List <string>());
     }
     UnitLuaTables[country][category].Add(unitGroupLua);
 }
Exemplo n.º 3
0
        /// <summary>
        /// Returns the ID of a random <see cref="DBEntryUnit"/> belonging to one (or more) of the <see cref="UnitFamily"/> passed as parameters.
        /// </summary>
        /// <param name="family">Family of units to choose from</param>
        /// <param name="decade">Decade during which the units must be operated</param>
        /// <param name="count">Number of units to generate</param>
        /// <param name="unitMods">Unit mods units can belong to</param>
        /// <param name="useDefaultList">If true, and no unit of the proper family is found in the coalition countries, a unit will be selected from the default list. If false, and not unit is found, no unit will be returned.</param>
        /// <returns>Array of IDs of <see cref="DBEntryUnit"/></returns>
        public string[] GetRandomUnits(UnitFamily family, Decade decade, int count, string[] unitMods, bool useDefaultList = true)
        {
            // Count is zero, return an empty array.
            if (count < 1)
            {
                return(new string[0]);
            }

            UnitCategory category = Toolbox.GetUnitCategoryFromUnitFamily(family);
            bool         allowDifferentUnitTypes = false;

            switch (category)
            {
            // Units are planes or helicopters, make sure unit count does not exceed the maximum flight group size
            case UnitCategory.Helicopter:
            case UnitCategory.Plane:
                count = Toolbox.Clamp(count, 1, Toolbox.MAXIMUM_FLIGHT_GROUP_SIZE);
                break;

            // Units are ships or static buildings, only one unit per group (that's the law in DCS World, buddy)
            case UnitCategory.Ship:
            case UnitCategory.Static:
                count = 1;
                break;

            // Units are ground vehicles, allow multiple unit types in the group
            case UnitCategory.Vehicle:
                allowDifferentUnitTypes = true;
                break;
            }

            string[] validUnits = SelectValidUnits(family, decade, unitMods, useDefaultList);

            // Different unit types allowed in the group, pick a random type for each unit.
            if (allowDifferentUnitTypes)
            {
                List <string> selectedUnits = new List <string>();
                for (int i = 0; i < count; i++)
                {
                    selectedUnits.Add(Toolbox.RandomFrom(validUnits));
                }

                return(selectedUnits.ToArray());
            }
            // Different unit types NOT allowed in the group, pick a random type and fill the whole array with it.
            else
            {
                string unit = Toolbox.RandomFrom(validUnits);
                return(Enumerable.Repeat(unit, count).ToArray());
            }
        }
Exemplo n.º 4
0
        internal static string ToLuaName(this UnitCategory unitCategory)
        {
            switch (unitCategory)
            {
            case UnitCategory.Helicopter: return("HELICOPTER");

            case UnitCategory.Plane: return("AIRPLANE");

            case UnitCategory.Ship: return("SHIP");

            case UnitCategory.Cargo:
            case UnitCategory.Static: return("STRUCTURE");

            default: return("GROUND_UNIT");    // case UnitCategory.Vehicle
            }
        }
Exemplo n.º 5
0
        public string[] GetUnits(UnitCategory category)
        {
            string[] units = null;
            switch (category)
            {
            case UnitCategory.Volume:
                units = Enum.GetNames(typeof(VolumeUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Length:
                units = Enum.GetNames(typeof(LengthUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Mass:
                units = Enum.GetNames(typeof(MassUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Temperature:
                units = Enum.GetNames(typeof(TemperatureUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Energy:
                units = Enum.GetNames(typeof(EnergyUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Area:
                units = Enum.GetNames(typeof(AreaUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Speed:
                units = Enum.GetNames(typeof(SpeedUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Power:
                units = Enum.GetNames(typeof(PowerUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Pressure:
                units = Enum.GetNames(typeof(PressureUnit)).Skip(1).ToArray();
                break;

            case UnitCategory.Angle:
                units = Enum.GetNames(typeof(AngleUnit)).Skip(1).ToArray();
                break;
            }
            return(units);
        }
Exemplo n.º 6
0
        public Address(string address, string city, string state, string postalCode, UnitCategory type, int?unitNumber = null)
        {
            Street        = address;
            City          = city;
            State         = state;
            PostalCode    = postalCode;
            Type          = Enum.GetName(typeof(UnitCategory), type);
            UnitNumber    = (unitNumber == null) ? null : unitNumber.ToString();
            UnitCharacter = (unitNumber == null) ? null : "#";

            var firstWhitespaceIndex = address.TakeWhile(x => !char.IsWhiteSpace(x)).Count();

            if (firstWhitespaceIndex < address.Count())
            {
                StreetNumber = address.Substring(0, firstWhitespaceIndex);
                StreetName   = address.Substring(firstWhitespaceIndex, address.Count() - firstWhitespaceIndex);
            }
        }
Exemplo n.º 7
0
        private string MakeUnitsCategoryLua(DCSMission missHQ, Coalition coalition, UnitCategory categ)
        {
            string categoryUnitsLua = "";

            DCSMissionUnitGroup[] groups =
                (from g in missHQ.UnitGroups
                 where g.Coalition == coalition && g.Category == categ
                 select g).ToArray();

            int categIndex = 1;

            foreach (DCSMissionUnitGroup g in groups)
            {
                string groupLua = HQTools.ReadIncludeLuaFile($"Mission\\{g.LuaGroup}.lua");

                HQTools.ReplaceKey(ref groupLua, "Units", MakeUnitsUnitsLua(g, missHQ.SinglePlayer)); // Must be first, so full-group replacements come after unit-specific ones

                //if (g.Waypoints.Count > 0)
                //    HQTools.ReplaceKey(ref groupLua, "Waypoints", CreatePlayerWaypointsLua(g.Waypoints)); // Must be first after units

                HQTools.ReplaceKey(ref groupLua, "Name", g.Name);
                HQTools.ReplaceKey(ref groupLua, "GroupID", g.GroupID);
                HQTools.ReplaceKey(ref groupLua, "Frequency", g.RadioFrequency, "F2");
                HQTools.ReplaceKey(ref groupLua, "X", g.Coordinates.X);
                HQTools.ReplaceKey(ref groupLua, "Y", g.Coordinates.Y);
                HQTools.ReplaceKey(ref groupLua, "ObjectiveCenterX", missHQ.ObjectivesCenterPoint.X + HQTools.RandomDouble(-UNIT_RANDOM_WAYPOINT_VARIATION, UNIT_RANDOM_WAYPOINT_VARIATION));
                HQTools.ReplaceKey(ref groupLua, "ObjectiveCenterY", missHQ.ObjectivesCenterPoint.Y + HQTools.RandomDouble(-UNIT_RANDOM_WAYPOINT_VARIATION, UNIT_RANDOM_WAYPOINT_VARIATION));
                HQTools.ReplaceKey(ref groupLua, "Hidden", g.Hidden);
                foreach (DCSMissionUnitGroupCustomValueKey k in g.CustomValues.Keys)
                {
                    if (k.UnitIndex != -1)
                    {
                        continue;                    // Replacement applies only to a single unit, don't apply it to the whole group
                    }
                    HQTools.ReplaceKey(ref groupLua, k.Key, g.CustomValues[k]);
                }
                HQTools.ReplaceKey(ref groupLua, "Index", categIndex); // Must be last, used by other values

                categoryUnitsLua += groupLua + "\r\n";
                categIndex++;
            }

            return(categoryUnitsLua);
        }
Exemplo n.º 8
0
        public static IUnit RegisterUnit(string name, string description, UnitCategory category, double baseUnitValue)
        {
            // check for null strings
            if (String.IsNullOrWhiteSpace(name))
                throw new ArgumentException($"Name connot be null or empty");

            // check if the unit exists for the category
            var unit = UnitFromName(name, category);
            if (unit != null)
                throw new ArgumentException($"Unit '{name}' for category '{category}' already registered");


            var newUnit = new BaseUnit(name, description, category, baseUnitValue);
            _units.Add(newUnit);


            
            return newUnit;
        }
Exemplo n.º 9
0
        /// <summary>
        /// Update UnitCategory Update UnitCategory
        /// </summary>
        /// <param name="id">id of UnitCategory</param>
        /// <param name="body">UnitCategory that should be updated</param>
        /// <returns>InlineResponse2002</returns>
        public InlineResponse2002 UnitCategoriesIdPut(int?id, UnitCategory body)
        {
            // verify the required parameter 'id' is set
            if (id == null)
            {
                throw new ApiException(400, "Missing required parameter 'id' when calling UnitCategoriesIdPut");
            }


            var path = "/unitCategories/{id}";

            path = path.Replace("{format}", "json");
            path = path.Replace("{" + "id" + "}", ApiClient.ParameterToString(id));


            var    queryParams  = new Dictionary <String, String>();
            var    headerParams = new Dictionary <String, String>();
            var    formParams   = new Dictionary <String, String>();
            var    fileParams   = new Dictionary <String, FileParameter>();
            String postBody     = null;



            postBody = ApiClient.Serialize(body); // http body (model) parameter


            // authentication setting, if any
            String[] authSettings = new String[] {  };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling UnitCategoriesIdPut: " + response.Content, response.Content);
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling UnitCategoriesIdPut: " + response.ErrorMessage, response.ErrorMessage);
            }

            return((InlineResponse2002)ApiClient.Deserialize(response.Content, typeof(InlineResponse2002), response.Headers));
        }
Exemplo n.º 10
0
        private void Start()
        {
            _menuButton = GameObject.Find("OpenMenuButton").GetComponentInChildren <Text>();

            _categoryButtonsPanel = GameObject.Find("UnitButtons").GetComponent <CanvasGroup>();
            _unitCardsPanel       = GameObject.Find("UnitCards").GetComponent <CanvasGroup>();

            CloseMenu();

            for (UnitCategory cat = 0; cat < UnitCategory._SIZE; cat++)
            {
                UnitCategory categoryForDelegate = cat;  // C# is bad
                GameObject   btn = Instantiate(
                    MenuButtonPrefab, _categoryButtonsPanel.transform);
                btn.GetComponentInChildren <Text>().text = cat.ToString();
                btn.GetComponentInChildren <Button>().onClick.AddListener(
                    delegate { CategorySelected(categoryForDelegate); });
            }
        }
    void ChangeUnitCategory(UnitCategory newCategory)
    {
        SelectedUnityCategory = newCategory;
        DestroyDummyShip();
        selectedDesign        = null;
        selectedStationDesign = null;

        if (SelectedUnityCategory == UnitCategory.Fighters)
        {
            fighterList.CheckFirstEntry(ChangeFighter);
        }
        else if (SelectedUnityCategory == UnitCategory.Stations)
        {
            stationHullList.CheckFirstHull(ChangeStationHull);
        }
        else
        {
            shipHullList.CheckFirstHull(ChangeHull);
        }
    }
        public SimpleConvertViewModel(UnitCategory category, ConversionItemViewModel sourceUnit, ConversionItemViewModel destinationUnit)
        {
            _currentCategory = category;

            // get default source if it doesn't exist
            if ((sourceUnit == null) || (destinationUnit == null))
            {
                SetDefaultUnits(category);
            }
            else
            {
                if ((sourceUnit.ConversionUnit == null || destinationUnit.ConversionUnit == null))
                    SetDefaultUnits(category);
                else
                {

                    this.SourceUnit = sourceUnit;
                    this.DestinationUnit = destinationUnit;
                    UserInputValue = sourceUnit.Value.ToString();
                }
               // TextInputValue = "0";
            }

            PopulateConversionList(_currentCategory);

            DigitPressedCommand = new Command<string>(ProcessDigit);
            ClearCommand = new Command(ProcessClear);
            EditAvailableItemsCommand = new Command(EditAvailableItems);
            CollapseKeyboardCommand = new Command(CollapseKeyboard);
            BackspaceCommand = new Command(ProcessBackspace);
            InformationCommand = new Command(ShowInformation);
            NegateCommand = new Command(NegateEntry);
            SwapValuesCommand = new Command(SwapValues);
            ChangeSourceUnitCommand = new Command(ChangeSourceUnit);
            ChangeDestinationUnitCommand = new Command(ChangeDestinationUnit);
            //            IncrementDecimalPlacesCommand = new Command(IncrementDecimalPlaces);
            //            DecrementDecimalPlacesCommand = new Command(DecrementDecimalPlaces);
            IsKeyaboardVisible = true;
        }
Exemplo n.º 13
0
        public static DCSMissionUnitGroup FromCoalitionArmyAndUnitFamily(
            string luaGroup, string luaUnit,
            DefinitionCoalition army, TimePeriod timePeriod, UnitFamily family, int unitCount,
            int groupID, Coalition coalition, Coordinates coordinates)
        {
            List <string> unitList = new List <string>();

            UnitCategory category = HQTools.GetUnitCategoryFromUnitFamily(family);

            // FIXME: extendSearchToUnitsOfOtherFamilies and returnDefaultIfNoneFound should be parameters
            string[] availableUnits = army.GetUnits(timePeriod, family, false, false);

            if (availableUnits.Length == 0)
            {
                DebugLog.Instance.Log($"    WARNING: Cannot spawn unit group, no units of type {family.ToString().ToUpperInvariant()} for coalition {army.DisplayName.ToUpperInvariant()} in {timePeriod.ToString().ToUpperInvariant()}.");
                return(null);
            }

            do
            {
                unitList.AddRange((from u in HQTools.RandomFrom(availableUnits).Split('|') select u.Trim()));
            } while (unitList.Count < unitCount);

            // Some unit categories (helicopters and planes) require all units to be the same type
            if ((category == UnitCategory.Helicopter) || (category == UnitCategory.Plane))
            {
                for (int i = 1; i < unitList.Count; i++)
                {
                    unitList[i] = unitList[0];
                }
            }

            DCSMissionUnitGroup uGroup = new DCSMissionUnitGroup(
                luaGroup, luaUnit,
                category, groupID, coalition, coordinates,
                unitList.ToArray());

            return(uGroup);
        }
Exemplo n.º 14
0
        private void CategorySelected(UnitCategory cat)
        {
            var allUnitCards = _unitCardsPanel.GetComponentsInChildren <Button>();

            foreach (var c in allUnitCards)
            {
                Destroy(c.gameObject);
            }

            // TODO Get units from Deck not just all units.
            var allUnitsOfCat = _unitService.All().Where(u => u.Category.Name == cat.Name).ToList();

            foreach (var unit in allUnitsOfCat)
            {
                var card = Instantiate(UnitCardDeploymentPrefab, _unitCardsPanel.transform);
                card.GetComponentInChildren <Text>().text = unit.Name;

                // this is very hacky and WIP just to keep the current spawning system working
                var session = GameObject.Find("GameSession");

                // See above, we need to either make this fully dynamic or put the cat names in the type system:
                switch (cat.Name)
                {
                case "TNK":
                    card.GetComponentInChildren <Button>().onClick.AddListener(session.GetComponent <InputManager>().TankButtonCallback);
                    break;

                case "SUP":
                    card.GetComponentInChildren <Button>().onClick.AddListener(session.GetComponent <InputManager>().ArtyButtonCallback);
                    break;

                default:
                    break;
                }

                // TODO Set picture too
                // TODO Transports?
            }
        }
Exemplo n.º 15
0
 /// <summary>
 /// Do units belonging to this category are aircraft?
 /// </summary>
 /// <param name="category">An unit category</param>
 /// <returns>True if unit is an aircraft (helicopter or plane), false otherwise.</returns>
 public static bool IsAircraft(UnitCategory category)
 {
     return((category == UnitCategory.Helicopter) || (category == UnitCategory.Plane));
 }
Exemplo n.º 16
0
        public  static IUnit UnitFromName(string name, UnitCategory unitCategory)
        {
            var unit = _units.FirstOrDefault(u => u.Name == name && u.Category == unitCategory);

            return unit;
        }
Exemplo n.º 17
0
 public static UnitCategory ConvertUnitCategory(int i)
 {
     return(UnitCategory.GetUnitCategory(i));
 }
Exemplo n.º 18
0
 public static IEnumerable<IUnit> GetUnitsOfCategory(UnitCategory category)
 {
     var units = _units.Where(o => o.Category == category);
     return units;
 } 
Exemplo n.º 19
0
 public UnitType(string unitKey, UnitCategory category)
 {
     UnitKey  = unitKey;
     Category = category;
 }
Exemplo n.º 20
0
 public ICollection <Unit> ByCategory(UnitCategory category)
 {
     return(_units.Where(u => u.Category == category).ToList());
 }
Exemplo n.º 21
0
 public double Convert(int value, UnitCategory category, string sourceUnit, string targetUnit)
 {
     return(UnitConverter.ConvertByName(value, category.ToString(), sourceUnit, targetUnit));
 }
 public SelectConversionItemsViewModel(UnitCategory category)
 {
     CurrentCategory = category;
 }
 public SelectUnitViewModel(UnitCategory category)
 {
     //            CurrentCategory = category;
     _currentCategory = category;
     PopulateConversionList(category);
 }
        private void CreateUnitGroups(ref string lua, DCSMission mission, Coalition coalition, UnitCategory unitCategory)
        {
            int    i, j;
            int    groupIndex   = 1;
            string allGroupsLua = "";

            foreach (DCSMissionUnitGroup group in mission.UnitGroups)
            {
                if ((group.Coalition != coalition) ||   // Group does not belong to this coalition
                    (group.Category != unitCategory) || // Group does not belong to this unit category
                    (group.Units.Length == 0))          // Group doesn't contain any units
                {
                    continue;                           // Ignore it
                }
                string groupLua = LuaTools.ReadIncludeLuaFile($"Units\\{group.LuaGroup}");
                LuaTools.ReplaceKey(ref groupLua, "Index", groupIndex);
                LuaTools.ReplaceKey(ref groupLua, "X", group.Coordinates.X);
                LuaTools.ReplaceKey(ref groupLua, "Y", group.Coordinates.Y);
                LuaTools.ReplaceKey(ref groupLua, "X2", group.Coordinates2.X);
                LuaTools.ReplaceKey(ref groupLua, "Y2", group.Coordinates2.Y);
                LuaTools.ReplaceKey(ref groupLua, "Hidden", group.Flags.HasFlag(DCSMissionUnitGroupFlags.Hidden));
                LuaTools.ReplaceKey(ref groupLua, "ID", group.GroupID);
                LuaTools.ReplaceKey(ref groupLua, "FirstUnitID", group.Units[0].ID);
                LuaTools.ReplaceKey(ref groupLua, "Name", group.Name);
                LuaTools.ReplaceKey(ref groupLua, "ObjectiveAirbaseID", group.AirbaseID);

                if (group.CarrierId > 0)
                {
                    LuaTools.ReplaceKey(ref groupLua, "LinkUnit", group.CarrierId);
                }

                if (group.TACAN != null)
                {
                    LuaTools.ReplaceKey(ref groupLua, "TacanFrequency", group.TACAN.freqency);
                    LuaTools.ReplaceKey(ref groupLua, "TacanCallSign", group.TACAN.callsign);
                    LuaTools.ReplaceKey(ref groupLua, "TacanChannel", group.TACAN.channel);
                    LuaTools.ReplaceKey(ref groupLua, "UnitID", group.Units[0].ID);
                }
                if (group.ILS > 0)
                {
                    LuaTools.ReplaceKey(ref groupLua, "ILS", group.ILS);
                }


                DBEntryUnit unitBP = Database.Instance.GetEntry <DBEntryUnit>(group.UnitID);
                if (unitBP == null)
                {
                    continue;                 // TODO: error message?
                }
                // Group is a client group, requires player waypoints
                if (group.IsAPlayerGroup())
                {
                    CreatePlayerWaypoints(ref groupLua, mission, unitBP);
                }

                string allUnitsLua = "";
                for (i = 0; i < group.Units.Length; i++)
                {
                    string      unitLua         = LuaTools.ReadIncludeLuaFile($"Units\\{group.LuaUnit}");
                    Coordinates unitCoordinates = new Coordinates(group.Coordinates);
                    double      unitHeading     = 0;

                    if ((group.Category == UnitCategory.Static) || (group.Category == UnitCategory.Vehicle))
                    {
                        double randomSpreadAngle = Toolbox.RandomDouble(Math.PI * 2);
                        unitCoordinates += new Coordinates(Math.Cos(randomSpreadAngle) * 35, Math.Sin(randomSpreadAngle) * 35);
                        unitHeading      = Toolbox.RandomDouble(Math.PI * 2);
                    }
                    else
                    {
                        unitCoordinates += new Coordinates(50 * i, 50 * i);
                    }

                    if ((group.Category == UnitCategory.Helicopter) || (group.Category == UnitCategory.Plane)) // Unit is an aircraft
                    {
                        if (unitBP == null)
                        {
                            LuaTools.ReplaceKey(ref groupLua, "Altitude", ((group.Category == UnitCategory.Helicopter) ? 1500 : 4572) * Toolbox.RandomDouble(.8, 1.2));
                            LuaTools.ReplaceKey(ref unitLua, "Altitude", ((group.Category == UnitCategory.Helicopter) ? 1500 : 4572) * Toolbox.RandomDouble(.8, 1.2));
                            LuaTools.ReplaceKey(ref groupLua, "EPLRS", false);
                            LuaTools.ReplaceKey(ref unitLua, "PayloadCommon", "");
                            LuaTools.ReplaceKey(ref unitLua, "PayloadPylons", "");
                            LuaTools.ReplaceKey(ref unitLua, "RadioPresetsLua", "");
                            LuaTools.ReplaceKey(ref unitLua, "PropsLua", "");
                            LuaTools.ReplaceKey(ref groupLua, "RadioBand", 0);
                            LuaTools.ReplaceKey(ref groupLua, "RadioFrequency", 124.0f);
                            LuaTools.ReplaceKey(ref groupLua, "Speed", ((group.Category == UnitCategory.Helicopter) ? 51 : 125) * Toolbox.RandomDouble(.9, 1.1));
                        }
                        else
                        {
                            LuaTools.ReplaceKey(ref groupLua, "Altitude", unitBP.AircraftData.CruiseAltitude);
                            LuaTools.ReplaceKey(ref unitLua, "Altitude", unitBP.AircraftData.CruiseAltitude);
                            LuaTools.ReplaceKey(ref groupLua, "EPLRS", unitBP.Flags.HasFlag(DBEntryUnitFlags.EPLRS));
                            LuaTools.ReplaceKey(ref unitLua, "PayloadCommon", unitBP.AircraftData.PayloadCommon);
                            if (group.IsAPlayerGroup())
                            {
                                LuaTools.ReplaceKey(ref unitLua, "RadioPresetsLua", string.Join("", unitBP.AircraftData.RadioPresets.Select((x, index) => $"[{index + 1}] = {x.ToLuaString()}")));
                                LuaTools.ReplaceKey(ref unitLua, "PropsLua", unitBP.AircraftData.PropsLua);
                            }
                            else
                            {
                                LuaTools.ReplaceKey(ref unitLua, "RadioPresetsLua", "");
                                LuaTools.ReplaceKey(ref unitLua, "PropsLua", "");
                            }
                            LuaTools.ReplaceKey(ref groupLua, "RadioBand", (int)unitBP.AircraftData.RadioModulation);
                            LuaTools.ReplaceKey(ref groupLua, "RadioFrequency", unitBP.AircraftData.RadioFrequency);
                            LuaTools.ReplaceKey(ref groupLua, "Speed", unitBP.AircraftData.CruiseSpeed);

                            string   pylonLua = "";
                            string[] payload  = unitBP.AircraftData.GetPayload(group.Payload, mission.DateTime.Decade);
                            for (j = 0; j < DBEntryUnitAircraftData.MAX_PYLONS; j++)
                            {
                                string pylonCode = payload[j];
                                if (!string.IsNullOrEmpty(pylonCode))
                                {
                                    pylonLua += $"[{j + 1}] = {{[\"CLSID\"] = \"{pylonCode}\" }},\r\n";
                                }
                            }

                            LuaTools.ReplaceKey(ref unitLua, "PayloadPylons", pylonLua);
                        }
                    }
                    else if ((group.Category == UnitCategory.Ship))
                    {
                        if (group.RadioFrequency > 0)
                        {
                            LuaTools.ReplaceKey(ref unitLua, "RadioBand", (int)group.RadioModulation);
                            LuaTools.ReplaceKey(ref unitLua, "RadioFrequency", group.RadioFrequency * 1000000);
                        }
                        else
                        {
                            LuaTools.ReplaceKey(ref unitLua, "RadioBand", 0);
                            LuaTools.ReplaceKey(ref unitLua, "RadioFrequency", 127.0f * 1000000);
                        }
                        LuaTools.ReplaceKey(ref groupLua, "Speed", group.Speed);
                    }

                    if (unitBP == null)
                    {
                        LuaTools.ReplaceKey(ref unitLua, "ExtraLua", "");
                    }
                    else
                    {
                        LuaTools.ReplaceKey(ref unitLua, "ExtraLua", unitBP.ExtraLua);
                    }

                    LuaTools.ReplaceKey(ref unitLua, "Callsign", group.CallsignLua); // Must be before "index" replacement, as is it is integrated in the callsign
                    LuaTools.ReplaceKey(ref unitLua, "Index", i + 1);
                    LuaTools.ReplaceKey(ref unitLua, "ID", group.Units[i].ID);
                    LuaTools.ReplaceKey(ref unitLua, "Type", group.Units[i].Type);
                    LuaTools.ReplaceKey(ref unitLua, "Name", $"{group.Name} {i + 1}");
                    if (group.Flags.HasFlag(DCSMissionUnitGroupFlags.FirstUnitIsPlayer))
                    {
                        LuaTools.ReplaceKey(ref unitLua, "Skill", (i == 0) ? DCSSkillLevel.Player : group.Skill, false);
                    }
                    else
                    {
                        LuaTools.ReplaceKey(ref unitLua, "Skill", group.Skill, false);
                    }
                    LuaTools.ReplaceKey(ref unitLua, "X", group.Units[i].Coordinates.X);
                    LuaTools.ReplaceKey(ref unitLua, "Y", group.Units[i].Coordinates.Y);
                    LuaTools.ReplaceKey(ref unitLua, "Heading", group.Units[i].Heading);
                    LuaTools.ReplaceKey(ref unitLua, "OnboardNumber", Toolbox.RandomInt(1, 1000).ToString("000"));
                    LuaTools.ReplaceKey(ref unitLua, "ParkingID", group.Units[i].ParkingSpot);

                    allUnitsLua += unitLua + "\n";
                }
                LuaTools.ReplaceKey(ref groupLua, "units", allUnitsLua);

                allGroupsLua += groupLua + "\n";

                groupIndex++;
            }

            LuaTools.ReplaceKey(ref lua, $"Groups{unitCategory}{coalition}", allGroupsLua);
        }
Exemplo n.º 25
0
        internal Tuple <Country, List <string> > GetRandomUnits(List <UnitFamily> families, Decade decade, int count, List <string> unitMods, Country?requiredCountry = null)
        {
            // Count is zero, return an empty array.
            if (count < 1)
            {
                throw new BriefingRoomException("Asking for a zero unit list");
            }
            if (families.Select(x => x.GetUnitCategory()).Any(x => x != families.First().GetUnitCategory()))
            {
                throw new BriefingRoomException($"Cannot mix Categories in types {string.Join(", ", families)}");
            }

            UnitCategory category = families.First().GetUnitCategory();
            bool         allowDifferentUnitTypes = false;

            switch (category)
            {
            // Units are planes or helicopters, make sure unit count does not exceed the maximum flight group size
            case UnitCategory.Helicopter:
            case UnitCategory.Plane:
                count = Toolbox.Clamp(count, 1, Toolbox.MAXIMUM_FLIGHT_GROUP_SIZE);
                break;

            // Units are ships or static buildings, only one unit per group (that's the law in DCS World, buddy)
            case UnitCategory.Ship:
            case UnitCategory.Static:
                count = 1;
                break;

            // Units are ground vehicles, allow multiple unit types in the group
            case UnitCategory.Vehicle:
                allowDifferentUnitTypes = true;
                break;
            }

            var validUnits = SelectValidUnits(families, decade, unitMods);

            var selectableUnits = new List <string>();
            var country         = Toolbox.RandomFrom(validUnits.Keys.ToList());

            if (requiredCountry.HasValue)
            {
                if (validUnits.ContainsKey(requiredCountry.Value))
                {
                    country = requiredCountry.Value;
                }
                else
                {
                    BriefingRoom.PrintToLog($"Could not find suitable units for {requiredCountry.Value} using units from other coalition members.", LogMessageErrorLevel.Info);
                }
            }

            selectableUnits = validUnits[country];



            // Different unit types allowed in the group, pick a random type for each unit.
            if (allowDifferentUnitTypes)
            {
                List <string> selectedUnits = new List <string>();
                for (int i = 0; i < count; i++)
                {
                    selectedUnits.Add(Toolbox.RandomFrom(selectableUnits));
                }

                return(new (country, selectedUnits.ToList()));
            }

            // Different unit types NOT allowed in the group, pick a random type and fill the whole array with it.
            string unit = Toolbox.RandomFrom(selectableUnits);

            return(new (country, Enumerable.Repeat(unit, count).ToList()));
        }
 public SelectConversionItems(UnitCategory category)
 {
     InitializeComponent();
     this.BindingContext = new SelectConversionItemsViewModel(category);
 }
Exemplo n.º 27
0
        internal UnitMakerGroupInfo?AddUnitGroup(
            string[] units, Side side, UnitFamily unitFamily,
            string groupTypeLua, string unitTypeLua,
            Coordinates coordinates,
            UnitMakerGroupFlags unitMakerGroupFlags = 0,
            params KeyValuePair <string, object>[] extraSettings)
        {
            if (units.Length == 0)
            {
                return(null);
            }

            Coalition coalition = (side == Side.Ally) ? PlayerCoalition : PlayerCoalition.GetEnemy();
            Country   country   = (coalition == Coalition.Blue) ? Country.CJTFBlue : Country.CJTFRed;

            if (extraSettings.Any(x => x.Key == "Country"))
            {
                country = (Country)extraSettings.First(x => x.Key == "Country").Value;
            }

            var skill = GeneratorTools.GetDefaultSkillLevel(Template, side);

            if (extraSettings.Any(x => x.Key == "Skill"))
            {
                skill = (DCSSkillLevel)extraSettings.First(x => x.Key == "Skill").Value;
            }


            var          isUsingSkynet = Template.MissionFeatures.Contains("SkynetIADS");
            string       groupName;
            UnitCallsign?callsign = null;

            if (unitFamily.GetUnitCategory().IsAircraft())
            {
                callsign  = CallsignGenerator.GetCallsign(unitFamily, coalition, side, isUsingSkynet);
                groupName = callsign.Value.GroupName;
                if (extraSettings.Any(x => x.Key == "PlayerStartingType") && extraSettings.First(x => x.Key == "PlayerStartingType").Value.ToString() == "TakeOffParking")
                {
                    groupName += "(C)";
                }
            }
            else
            {
                groupName = GeneratorTools.GetGroupName(GroupID, unitFamily, side, isUsingSkynet);
            }

            if (unitFamily.GetUnitCategory() == UnitCategory.Static || unitFamily.GetUnitCategory() == UnitCategory.Cargo && unitFamily != UnitFamily.FOB)
            {
                return(AddStaticGroup(
                           country,
                           coalition,
                           skill,
                           unitFamily,
                           side,
                           units,
                           groupName,
                           callsign,
                           groupTypeLua,
                           coordinates,
                           unitMakerGroupFlags,
                           extraSettings
                           ));
            }

            var groupLua = CreateGroup(
                groupTypeLua,
                coordinates,
                groupName,
                extraSettings
                );


            int firstUnitID = UnitID;

            var(unitsLuaTable, unitsIDList) = AddUnits(
                units,
                groupName,
                callsign,
                unitTypeLua,
                coordinates,
                unitMakerGroupFlags,
                extraSettings
                );


            if (unitsIDList.Count == 0)
            {
                return(null);                        // No valid units added to this group
            }
            GeneratorTools.ReplaceKey(ref groupLua, "Units", unitsLuaTable);

            DBEntryUnit firstUnitDB        = units.Select(x => Database.Instance.GetEntry <DBEntryUnit>(x)).First(x => x != null);
            var         aircraftCategories = new UnitCategory[] { UnitCategory.Helicopter, UnitCategory.Plane };
            var         isAircraft         = firstUnitDB != null && aircraftCategories.Contains(firstUnitDB.Category);

            if (isAircraft)
            {
                groupLua = ApplyAircraftFields(groupLua, firstUnitDB, extraSettings);
                if (unitMakerGroupFlags.HasFlag(UnitMakerGroupFlags.ImmediateAircraftSpawn))
                {
                    Mission.AppendValue("AircraftActivatorCurrentQueue", $"{GroupID},");
                }
                else if (unitMakerGroupFlags.HasFlag(UnitMakerGroupFlags.RadioAircraftSpawn))
                {
                    Mission.AppendValue("AircraftRadioActivator", $"{{{GroupID}, \"{groupName}\"}},");
                }
                else if (groupTypeLua != "GroupAircraftParkedUncontrolled")
                {
                    Mission.AppendValue("AircraftActivatorReserveQueue", $"{GroupID},");
                }
            }

            GeneratorTools.ReplaceKey(ref groupLua, "UnitID", firstUnitID);                                                                         // Must be after units are added
            GeneratorTools.ReplaceKey(ref groupLua, "Skill", skill);                                                                                // Must be after units are added, because skill is set as a unit level
            GeneratorTools.ReplaceKey(ref groupLua, "Hidden", GeneratorTools.GetHiddenStatus(Template.OptionsFogOfWar, side, unitMakerGroupFlags)); // If "hidden" was not set through custom values

            AddUnitGroupToTable(country, unitFamily.GetUnitCategory(), groupLua);

            BriefingRoom.PrintToLog($"Added group of {units.Length} {coalition} {unitFamily} at {coordinates}");

            GroupID++;

            if (firstUnitDB == null)
            {
                return(new UnitMakerGroupInfo(GroupID - 1, coordinates, unitsIDList, groupName));
            }
            return(new UnitMakerGroupInfo(GroupID - 1, coordinates, unitsIDList, groupName, firstUnitDB.AircraftData.RadioFrequency, firstUnitDB));
        }
Exemplo n.º 28
0
        protected async void DownloadXml()
        {
            var myXmlDocument = new XmlDocument();

            myXmlDocument.Load("https://raw.githubusercontent.com/BSData/wh40k/master/Tyranids.cat");
            var catalogue = myXmlDocument.GetElementsByTagName("catalogue")[0];
            var army      = await ArmyRepository.GetByBattleScribeId(catalogue.Attributes["id"].Value);

            if (army == null)
            {
                army = new Data.Models.Army
                {
                    BattleScribeId       = catalogue.Attributes["id"].Value,
                    BattleScribeRevision = catalogue.Attributes["revision"].Value,
                    Name = catalogue.Attributes["name"].Value
                };
                await ArmyRepository.Create(army);
            }

            var categoryNodeList = myXmlDocument.GetElementsByTagName("categoryEntry");

            foreach (XmlNode categoryNode in categoryNodeList)
            {
                var category = await CategoryRepository.GetByBattleScribeId(categoryNode.Attributes["id"].Value);

                var create = false;
                if (category == null)
                {
                    create   = true;
                    category = new Category();
                }

                category.Name           = HttpUtility.HtmlDecode(categoryNode.Attributes["name"].Value);
                category.BattleScribeId = categoryNode.Attributes["id"].Value;
                if (create)
                {
                    await CategoryRepository.Create(category);
                }
                else
                {
                    await CategoryRepository.Update(category);
                }
            }

            var unitList = myXmlDocument.GetElementsByTagName("selectionEntry");

            foreach (XmlNode unitNode in unitList)
            {
                if (!unitNode.Attributes["type"].Any() || unitNode.Attributes["type"].Value != "unit")
                {
                    continue;
                }
                var create = false;
                var unit   = await UnitRepository.GetByBattleScribeId(unitNode.Attributes["id"].Value);

                if (unit == null)
                {
                    create = true;
                    unit   = new Data.Models.Unit();
                }

                unit.Name           = unitNode.Attributes["name"].Value;
                unit.BattleScribeId = unitNode.Attributes["id"].Value;
                unit.Army           = army;
                if (create)
                {
                    await UnitRepository.Create(unit);
                }
                else
                {
                    await UnitRepository.Update(unit);
                }

                var categoryLinkNodes = unitNode.ChildNodes.Cast <XmlNode>()
                                        .First(nc => nc.LocalName == "categoryLinks").Cast <XmlNode>()
                                        .Where(ncc => ncc.LocalName == "categoryLink");
                foreach (var categoryLinkNode in categoryLinkNodes)
                {
                    var unitCateg = await UnitCategoryRepository.GetbyBattleScribeIds(
                        categoryLinkNode.Attributes["targetId"].Value, unitNode.Attributes["id"].Value);

                    if (unitCateg != null)
                    {
                        continue;
                    }
                    Console.WriteLine("CREATE CATEG");
                    var category =
                        await CategoryRepository.GetByBattleScribeId(categoryLinkNode.Attributes["targetId"].Value);

                    if (category == null)
                    {
                        continue;
                    }
                    unitCateg = new UnitCategory
                    {
                        Unit     = unit,
                        Category = category
                    };
                    await UnitCategoryRepository.Create(unitCateg);
                }

                var keywordNodes = unitNode.ChildNodes.Cast <XmlNode>()
                                   .FirstOrDefault(nc => nc.LocalName == "profiles")?.Cast <XmlNode>()
                                   .FirstOrDefault(ncc =>
                                                   ncc.LocalName == "profile" && ncc.Attributes["typeName"] != null &&
                                                   ncc.Attributes["typeName"].Value == "Keywords")?.Cast <XmlNode>()
                                   .FirstOrDefault(atr => atr.LocalName == "characteristics")?.Cast <XmlNode>()
                                   .Where(atr => atr.LocalName == "characteristic");
                if (keywordNodes == null)
                {
                    continue;
                }
                foreach (var keywordNode in keywordNodes)
                {
                    var keyword = await KeywordRepository.GetByName(HttpUtility.HtmlDecode(keywordNode.InnerText));

                    if (keyword == null)
                    {
                        keyword = new Keyword
                        {
                            Name = HttpUtility.HtmlDecode(keywordNode.InnerText)
                        };
                        await KeywordRepository.Create(keyword);
                    }

                    var unitKeyword = await UnitKeywordRepository.GetbyIds(keyword.Id, unit.Id);

                    if (unitKeyword != null)
                    {
                        continue;
                    }
                    unitKeyword = new UnitKeyword
                    {
                        Unit    = unit,
                        Keyword = keyword
                    };
                    await UnitKeywordRepository.Create(unitKeyword);
                }
            }
        }
Exemplo n.º 29
0
 public Boolean Has(UnitCategory category) => this.Has(u => u.Category == category);
Exemplo n.º 30
0
 internal static bool IsAircraft(this UnitCategory unitCategory)
 {
     return((unitCategory == UnitCategory.Helicopter) || (unitCategory == UnitCategory.Plane));
 }