Wrap the pydcs FlyingType in our own AircraftType.

This is an attempt to remove a lot of our supposedly unnecessary error
handling. Every aircraft should have a price, a description, a name,
etc; and none of those should require carrying around the faction's
country as context.

This moves all the data for aircraft into yaml files (only one converted
here as an example). Most of the "extended unit info" isn't actually
being read yet.

To replace the renaming of units based on the county, we instead
generate multiple types of each unit when necessary. The CF-18 is just
as much a first-class type as the F/A-18 is.

This doesn't work in its current state because it does break all the
existing names for aircraft that are used in the faction and squadron
files, and we no longer let those errors go as a warning. It will be an
annoying one time switch, but it allows us to define the names that get
used in these files instead of being sensitive to changes as they happen
in pydcs, and allows faction designers to specifically choose, for
example, the Su-22 instead of the Su-17.

One thing not handled by this is aircraft task capability. This is
because the lists in ai_flight_planner_db.py are a priority list, and to
move it out to a yaml file we'd need to assign a weight to it that would
be used to stack rank each aircraft. That's doable, but it makes it much
more difficult to see the ordering of aircraft at a glance, and much
more annoying to move aircraft around in the priority list. I don't
think this is worth doing, and the priority lists will remain in their
own separate lists.

This includes the converted I used to convert all the old unit info and
factions to the new format. This doesn't need to live long, but we may
want to reuse it in the future so we want it in the version history.
This commit is contained in:
Dan Albert
2021-06-06 14:37:19 -07:00
parent 88abaef7f9
commit 4a3ef42e67
39 changed files with 1314 additions and 890 deletions

View File

@@ -5,12 +5,12 @@ import inspect
import logging
from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, Iterator, Optional, Set, Tuple, Type, Union, cast
from typing import Dict, Iterator, Optional, Set, Tuple, Union, cast
from dcs.unitgroup import FlyingGroup
from dcs.unittype import FlyingType
from dcs.weapons_data import Weapons, weapon_ids
from game.dcs.aircrafttype import AircraftType
PydcsWeapon = Dict[str, Union[int, str]]
PydcsWeaponAssignment = Tuple[int, PydcsWeapon]
@@ -97,12 +97,12 @@ class Pylon:
yield weapon
@classmethod
def for_aircraft(cls, aircraft: Type[FlyingType], number: int) -> Pylon:
def for_aircraft(cls, aircraft: AircraftType, number: int) -> Pylon:
# In pydcs these are all arbitrary inner classes of the aircraft type.
# The only way to identify them is by their name.
pylons = [
v
for v in aircraft.__dict__.values()
for v in aircraft.dcs_unit_type.__dict__.values()
if inspect.isclass(v) and v.__name__.startswith("Pylon")
]
@@ -121,8 +121,8 @@ class Pylon:
return cls(number, allowed)
@classmethod
def iter_pylons(cls, aircraft: Type[FlyingType]) -> Iterator[Pylon]:
for pylon in sorted(list(aircraft.pylons)):
def iter_pylons(cls, aircraft: AircraftType) -> Iterator[Pylon]:
for pylon in sorted(list(aircraft.dcs_unit_type.pylons)):
yield cls.for_aircraft(aircraft, pylon)

View File

@@ -133,7 +133,7 @@ from dcs.ships import (
from dcs.terrain.terrain import Airport
from dcs.unit import Ship, Unit, Vehicle
from dcs.unitgroup import ShipGroup, StaticGroup
from dcs.unittype import FlyingType, UnitType, VehicleType
from dcs.unittype import UnitType, VehicleType
from dcs.vehicles import (
AirDefence,
Armor,
@@ -803,44 +803,6 @@ REWARDS = {
"derrick": 8,
}
CARRIER_CAPABLE = [
FA_18C_hornet,
F_14A_135_GR,
F_14B,
AV8BNA,
Su_33,
A_4E_C,
S_3B,
S_3B_Tanker,
E_2C,
UH_1H,
Mi_8MT,
Ka_50,
AH_1W,
OH_58D,
UH_60A,
SH_60B,
SA342L,
SA342M,
SA342Minigun,
SA342Mistral,
]
LHA_CAPABLE = [
AV8BNA,
UH_1H,
Mi_8MT,
Ka_50,
AH_1W,
OH_58D,
UH_60A,
SH_60B,
SA342L,
SA342M,
SA342Minigun,
SA342Mistral,
]
"""
---------- END OF CONFIGURATION SECTION
"""
@@ -938,7 +900,9 @@ def unit_type_name_2(unit_type) -> str:
return unit_type.name and unit_type.name or unit_type.id
def unit_get_expanded_info(country_name: str, unit_type, request_type: str) -> str:
def unit_get_expanded_info(
country_name: str, unit_type: Type[UnitType], request_type: str
) -> str:
original_name = unit_type.name and unit_type.name or unit_type.id
default_value = None
faction_value = None
@@ -980,13 +944,6 @@ def unit_type_from_name(name: str) -> Optional[Type[UnitType]]:
return None
def flying_type_from_name(name: str) -> Optional[Type[FlyingType]]:
unit_type = plane_map.get(name)
if unit_type is not None:
return unit_type
return helicopter_map.get(name)
def unit_type_of(unit: Unit) -> UnitType:
if isinstance(unit, Vehicle):
return vehicle_map[unit.type]
@@ -1013,39 +970,3 @@ F_16C_50.Liveries = DefaultLiveries
P_51D_30_NA.Liveries = DefaultLiveries
Ju_88A4.Liveries = DefaultLiveries
B_17G.Liveries = DefaultLiveries
# List of airframes that rely on their gun as a primary weapon. We confiscate bullets
# from most AI air-to-ground missions since they aren't smart enough to RTB when they're
# out of everything other than bullets (DCS does not have an all-but-gun winchester
# option) and we don't want to be attacking fully functional Tors with a Vulcan.
#
# These airframes are the exceptions. They probably should be using their gun regardless
# of the mission type.
GUN_RELIANT_AIRFRAMES: List[Type[FlyingType]] = [
AH_1W,
AH_64A,
AH_64D,
A_10A,
A_10C,
A_10C_2,
A_20G,
Bf_109K_4,
FW_190A8,
FW_190D9,
F_86F_Sabre,
Ju_88A4,
Ka_50,
MiG_15bis,
MiG_19P,
Mi_24V,
Mi_28N,
P_47D_30,
P_47D_30bl1,
P_47D_40,
P_51D,
P_51D_30_NA,
SpitfireLFMkIX,
SpitfireLFMkIXCW,
Su_25,
Su_25T,
]

177
game/dcs/aircrafttype.py Normal file
View File

@@ -0,0 +1,177 @@
from __future__ import annotations
import logging
from collections import defaultdict
from dataclasses import dataclass
from functools import cached_property
from pathlib import Path
from typing import ClassVar, Type, Iterator, TYPE_CHECKING, Optional, Any
import yaml
from dcs.helicopters import helicopter_map
from dcs.planes import plane_map
from dcs.unittype import FlyingType
from game.radio.channels import (
ChannelNamer,
RadioChannelAllocator,
CommonRadioChannelAllocator,
)
from game.utils import Speed, kph
if TYPE_CHECKING:
from gen.aircraft import FlightData
from gen import AirSupport, RadioFrequency, RadioRegistry
from gen.radios import Radio
@dataclass(frozen=True)
class RadioConfig:
inter_flight: Optional[Radio]
intra_flight: Optional[Radio]
channel_allocator: Optional[RadioChannelAllocator]
channel_namer: Type[ChannelNamer]
@classmethod
def from_data(cls, data: dict[str, Any]) -> RadioConfig:
return RadioConfig(
cls.make_radio(data.get("inter_flight", None)),
cls.make_radio(data.get("intra_flight", None)),
cls.make_allocator(data.get("channels", {})),
cls.make_namer(data.get("channels", {})),
)
@classmethod
def make_radio(cls, name: Optional[str]) -> Optional[Radio]:
from gen.radios import get_radio
if name is None:
return None
return get_radio(name)
@classmethod
def make_allocator(cls, data: dict[str, Any]) -> Optional[RadioChannelAllocator]:
try:
alloc_type = data["type"]
except KeyError:
return None
return {"common": CommonRadioChannelAllocator}[alloc_type].from_cfg(data)
@classmethod
def make_namer(cls, config: dict[str, Any]) -> Type[ChannelNamer]:
return {"default": ChannelNamer}[config.get("namer", "default")]
@dataclass(frozen=True)
class AircraftType:
dcs_unit_type: Type[FlyingType]
name: str
description: str
price: int
carrier_capable: bool
lha_capable: bool
always_keeps_gun: bool
intra_flight_radio: Optional[Radio]
channel_allocator: Optional[RadioChannelAllocator]
channel_namer: Type[ChannelNamer]
_by_name: ClassVar[dict[str, AircraftType]] = {}
_by_unit_type: ClassVar[dict[Type[FlyingType], list[AircraftType]]] = defaultdict(
list
)
_loaded: ClassVar[bool] = False
def __str__(self) -> str:
return self.name
@property
def dcs_id(self) -> str:
return self.dcs_unit_type.id
@property
def flyable(self) -> bool:
return self.dcs_unit_type.flyable
@cached_property
def max_speed(self) -> Speed:
return kph(self.dcs_unit_type.max_speed)
def alloc_flight_radio(self, radio_registry: RadioRegistry) -> RadioFrequency:
from gen.radios import ChannelInUseError, MHz
if self.intra_flight_radio is not None:
return radio_registry.alloc_for_radio(self.intra_flight_radio)
freq = MHz(self.dcs_unit_type.radio_frequency)
try:
radio_registry.reserve(freq)
except ChannelInUseError:
pass
return freq
def assign_channels_for_flight(
self, flight: FlightData, air_support: AirSupport
) -> None:
if self.channel_allocator is not None:
self.channel_allocator.assign_channels_for_flight(flight, air_support)
def channel_name(self, radio_id: int, channel_id: int) -> str:
return self.channel_namer.channel_name(radio_id, channel_id)
@classmethod
def register(cls, aircraft_type: AircraftType) -> None:
cls._by_name[aircraft_type.name] = aircraft_type
cls._by_unit_type[aircraft_type.dcs_unit_type].append(aircraft_type)
@classmethod
def named(cls, name: str) -> AircraftType:
if not cls._loaded:
cls._load_all()
return cls._by_name[name]
@classmethod
def for_dcs_type(cls, dcs_unit_type: Type[FlyingType]) -> Iterator[AircraftType]:
yield from cls._by_unit_type[dcs_unit_type]
@staticmethod
def _each_unit_type() -> Iterator[Type[FlyingType]]:
yield from helicopter_map.values()
yield from plane_map.values()
@classmethod
def _load_all(cls) -> None:
for unit_type in cls._each_unit_type():
for data in cls._each_variant_of(unit_type):
cls.register(data)
cls._loaded = True
@classmethod
def _each_variant_of(cls, aircraft: Type[FlyingType]) -> Iterator[AircraftType]:
data_path = Path("resources/units/aircraft") / f"{aircraft.id}.yaml"
if not data_path.exists():
logging.warning(f"No data for {aircraft.id}; it will not be available")
return
with data_path.open() as data_file:
data = yaml.safe_load(data_file)
try:
price = data["price"]
except KeyError as ex:
raise KeyError(f"Missing required price field: {data_path}") from ex
radio_config = RadioConfig.from_data(data.get("radios", {}))
for variant in data.get("variants", [aircraft.id]):
yield AircraftType(
dcs_unit_type=aircraft,
name=variant,
description=data.get("description", "No data."),
price=price,
carrier_capable=data.get("carrier_capable", False),
lha_capable=data.get("lha_capable", False),
always_keeps_gun=data.get("always_keeps_gun", False),
intra_flight_radio=radio_config.intra_flight,
channel_allocator=radio_config.channel_allocator,
channel_namer=radio_config.channel_namer,
)

View File

@@ -18,9 +18,10 @@ from typing import (
TYPE_CHECKING,
)
from dcs.unittype import FlyingType, UnitType
from dcs.unittype import UnitType
from game import db
from game.dcs.aircrafttype import AircraftType
from game.theater import Airfield, ControlPoint
from game.transfers import CargoShip
from game.unitmap import (
@@ -49,8 +50,8 @@ class AirLosses:
def losses(self) -> Iterator[FlyingUnit]:
return itertools.chain(self.player, self.enemy)
def by_type(self, player: bool) -> Dict[Type[FlyingType], int]:
losses_by_type: Dict[Type[FlyingType], int] = defaultdict(int)
def by_type(self, player: bool) -> Dict[AircraftType, int]:
losses_by_type: Dict[AircraftType, int] = defaultdict(int)
losses = self.player if player else self.enemy
for loss in losses:
losses_by_type[loss.flight.unit_type] += 1

View File

@@ -1,5 +1,4 @@
from __future__ import annotations
from game.data.groundunitclass import GroundUnitClass
import logging
from dataclasses import dataclass, field
@@ -23,7 +22,9 @@ from game.data.doctrine import (
COLDWAR_DOCTRINE,
WWII_DOCTRINE,
)
from pydcs_extensions.mod_units import MODDED_VEHICLES, MODDED_AIRPLANES
from game.data.groundunitclass import GroundUnitClass
from game.dcs.aircrafttype import AircraftType
from pydcs_extensions.mod_units import MODDED_VEHICLES
@dataclass
@@ -45,13 +46,13 @@ class Faction:
description: str = field(default="")
# Available aircraft
aircrafts: List[Type[FlyingType]] = field(default_factory=list)
aircrafts: List[AircraftType] = field(default_factory=list)
# Available awacs aircraft
awacs: List[Type[FlyingType]] = field(default_factory=list)
awacs: List[AircraftType] = field(default_factory=list)
# Available tanker aircraft
tankers: List[Type[FlyingType]] = field(default_factory=list)
tankers: List[AircraftType] = field(default_factory=list)
# Available frontline units
frontline_units: List[Type[VehicleType]] = field(default_factory=list)
@@ -114,7 +115,7 @@ class Faction:
has_jtac: bool = field(default=False)
# Unit to use as JTAC for this faction
jtac_unit: Optional[Type[FlyingType]] = field(default=None)
jtac_unit: Optional[AircraftType] = field(default=None)
# doctrine
doctrine: Doctrine = field(default=MODERN_DOCTRINE)
@@ -123,7 +124,7 @@ class Faction:
building_set: List[str] = field(default_factory=list)
# List of default livery overrides
liveries_overrides: Dict[Type[UnitType], List[str]] = field(default_factory=dict)
liveries_overrides: Dict[AircraftType, List[str]] = field(default_factory=dict)
#: Set to True if the faction should force the "Unrestricted satnav" option
#: for the mission. This option enables GPS for capable aircraft regardless
@@ -163,9 +164,9 @@ class Faction:
faction.authors = json.get("authors", "")
faction.description = json.get("description", "")
faction.aircrafts = load_all_aircraft(json.get("aircrafts", []))
faction.awacs = load_all_aircraft(json.get("awacs", []))
faction.tankers = load_all_aircraft(json.get("tankers", []))
faction.aircrafts = [AircraftType.named(n) for n in json.get("aircrafts", [])]
faction.awacs = [AircraftType.named(n) for n in json.get("awacs", [])]
faction.tankers = [AircraftType.named(n) for n in json.get("tankers", [])]
faction.aircrafts = list(
set(faction.aircrafts + faction.awacs + faction.tankers)
@@ -198,7 +199,7 @@ class Faction:
faction.has_jtac = json.get("has_jtac", False)
jtac_name = json.get("jtac_unit", None)
if jtac_name is not None:
faction.jtac_unit = load_aircraft(jtac_name)
faction.jtac_unit = AircraftType.named(jtac_name)
else:
faction.jtac_unit = None
faction.navy_group_count = int(json.get("navy_group_count", 1))
@@ -232,27 +233,14 @@ class Faction:
# Load liveries override
faction.liveries_overrides = {}
liveries_overrides = json.get("liveries_overrides", {})
for k, v in liveries_overrides.items():
k = load_aircraft(k)
if k is not None:
faction.liveries_overrides[k] = [s.lower() for s in v]
for name, livery in liveries_overrides.items():
aircraft = AircraftType.named(name)
faction.liveries_overrides[aircraft] = [s.lower() for s in livery]
faction.unrestricted_satnav = json.get("unrestricted_satnav", False)
return faction
@property
def all_units(self) -> List[Type[UnitType]]:
return (
self.infantry_units
+ self.aircrafts
+ self.awacs
+ self.artillery_units
+ self.frontline_units
+ self.tankers
+ self.logistics_units
)
@property
def ground_units(self) -> Iterator[Type[VehicleType]]:
yield from self.artillery_units
@@ -283,22 +271,6 @@ def unit_loader(unit: str, class_repository: List[Any]) -> Optional[Type[UnitTyp
return None
def load_aircraft(name: str) -> Optional[Type[FlyingType]]:
return cast(
Optional[FlyingType],
unit_loader(name, [dcs.planes, dcs.helicopters, MODDED_AIRPLANES]),
)
def load_all_aircraft(data) -> List[Type[FlyingType]]:
items = []
for name in data:
item = load_aircraft(name)
if item is not None:
items.append(item)
return items
def load_vehicle(name: str) -> Optional[Type[VehicleType]]:
return cast(
Optional[FlyingType],

View File

@@ -6,6 +6,7 @@ from typing import Dict, Iterable, Iterator, Set, Tuple, TYPE_CHECKING, Type
from dcs.unittype import FlyingType
from game.dcs.aircrafttype import AircraftType
from gen.flights.flight import Flight
if TYPE_CHECKING:
@@ -17,9 +18,9 @@ class ControlPointAircraftInventory:
def __init__(self, control_point: ControlPoint) -> None:
self.control_point = control_point
self.inventory: Dict[Type[FlyingType], int] = defaultdict(int)
self.inventory: Dict[AircraftType, int] = defaultdict(int)
def add_aircraft(self, aircraft: Type[FlyingType], count: int) -> None:
def add_aircraft(self, aircraft: AircraftType, count: int) -> None:
"""Adds aircraft to the inventory.
Args:
@@ -28,7 +29,7 @@ class ControlPointAircraftInventory:
"""
self.inventory[aircraft] += count
def remove_aircraft(self, aircraft: Type[FlyingType], count: int) -> None:
def remove_aircraft(self, aircraft: AircraftType, count: int) -> None:
"""Removes aircraft from the inventory.
Args:
@@ -42,12 +43,12 @@ class ControlPointAircraftInventory:
available = self.inventory[aircraft]
if available < count:
raise ValueError(
f"Cannot remove {count} {aircraft.id} from "
f"Cannot remove {count} {aircraft} from "
f"{self.control_point.name}. Only have {available}."
)
self.inventory[aircraft] -= count
def available(self, aircraft: Type[FlyingType]) -> int:
def available(self, aircraft: AircraftType) -> int:
"""Returns the number of available aircraft of the given type.
Args:
@@ -59,14 +60,14 @@ class ControlPointAircraftInventory:
return 0
@property
def types_available(self) -> Iterator[Type[FlyingType]]:
def types_available(self) -> Iterator[AircraftType]:
"""Iterates over all available aircraft types."""
for aircraft, count in self.inventory.items():
if count > 0:
yield aircraft
@property
def all_aircraft(self) -> Iterator[Tuple[Type[FlyingType], int]]:
def all_aircraft(self) -> Iterator[Tuple[AircraftType, int]]:
"""Iterates over all available aircraft types, including amounts."""
for aircraft, count in self.inventory.items():
if count > 0:
@@ -107,9 +108,9 @@ class GlobalAircraftInventory:
return self.inventories[control_point]
@property
def available_types_for_player(self) -> Iterator[Type[FlyingType]]:
def available_types_for_player(self) -> Iterator[AircraftType]:
"""Iterates over all aircraft types available to the player."""
seen: Set[Type[FlyingType]] = set()
seen: Set[AircraftType] = set()
for control_point, inventory in self.inventories.items():
if control_point.captured:
for aircraft in inventory.types_available:

View File

@@ -17,7 +17,7 @@ from dcs.triggers import TriggerStart
from game.plugins import LuaPluginManager
from game.theater.theatergroundobject import TheaterGroundObject
from gen import Conflict, FlightType, VisualGenerator
from gen.aircraft import AIRCRAFT_DATA, AircraftConflictGenerator, FlightData
from gen.aircraft import AircraftConflictGenerator, FlightData
from gen.airfields import AIRFIELD_DATA
from gen.airsupportgen import AirSupport, AirSupportConflictGenerator
from gen.armor import GroundConflictGenerator, JtacInfo
@@ -215,23 +215,7 @@ class Operation:
for flight in flights:
if not flight.client_units:
continue
cls.assign_channels_to_flight(flight, air_support)
@staticmethod
def assign_channels_to_flight(flight: FlightData, air_support: AirSupport) -> None:
"""Assigns preset radio channels for a client flight."""
airframe = flight.aircraft_type
try:
aircraft_data = AIRCRAFT_DATA[airframe.id]
except KeyError:
logging.warning(f"No aircraft data for {airframe.id}")
return
if aircraft_data.channel_allocator is not None:
aircraft_data.channel_allocator.assign_channels_for_flight(
flight, air_support
)
flight.aircraft_type.assign_channels_for_flight(flight, air_support)
@classmethod
def _create_tacan_registry(

View File

@@ -9,6 +9,7 @@ from dcs.unittype import FlyingType, VehicleType
from game import db
from game.data.groundunitclass import GroundUnitClass
from game.dcs.aircrafttype import AircraftType
from game.factions.faction import Faction
from game.theater import ControlPoint, MissionTarget
from game.utils import Distance
@@ -113,7 +114,7 @@ class ProcurementAi:
if available % 2 == 0:
continue
inventory.remove_aircraft(aircraft, 1)
total += db.PRICES[aircraft]
total += aircraft.price
return total
def repair_runways(self, budget: float) -> float:
@@ -198,12 +199,12 @@ class ProcurementAi:
airbase: ControlPoint,
number: int,
max_price: float,
) -> Optional[Type[FlyingType]]:
best_choice: Optional[Type[FlyingType]] = None
) -> Optional[AircraftType]:
best_choice: Optional[AircraftType] = None
for unit in aircraft_for_task(task):
if unit not in self.faction.aircrafts:
continue
if db.PRICES[unit] * number > max_price:
if unit.price * number > max_price:
continue
if not airbase.can_operate(unit):
continue
@@ -224,7 +225,7 @@ class ProcurementAi:
def affordable_aircraft_for(
self, request: AircraftProcurementRequest, airbase: ControlPoint, budget: float
) -> Optional[Type[FlyingType]]:
) -> Optional[AircraftType]:
return self._affordable_aircraft_for_task(
request.task_capability, airbase, request.number, budget
)
@@ -242,7 +243,7 @@ class ProcurementAi:
# able to operate expensive aircraft.
continue
budget -= db.PRICES[unit] * request.number
budget -= unit.price * request.number
airbase.pending_unit_deliveries.order({unit: request.number})
return budget, True
return budget, False

298
game/radio/channels.py Normal file
View File

@@ -0,0 +1,298 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Any, TYPE_CHECKING
if TYPE_CHECKING:
from gen import FlightData, AirSupport
class RadioChannelAllocator:
"""Base class for radio channel allocators."""
def assign_channels_for_flight(
self, flight: FlightData, air_support: AirSupport
) -> None:
"""Assigns mission frequencies to preset channels for the flight."""
raise NotImplementedError
@classmethod
def from_cfg(cls, cfg: dict[str, Any]) -> RadioChannelAllocator:
return cls()
@classmethod
def name(cls) -> str:
raise NotImplementedError
@dataclass(frozen=True)
class CommonRadioChannelAllocator(RadioChannelAllocator):
"""Radio channel allocator suitable for most aircraft.
Most of the aircraft with preset channels available have one or more radios
with 20 or more channels available (typically per-radio, but this is not the
case for the JF-17).
"""
#: Index of the radio used for intra-flight communications. Matches the
#: index of the panel_radio field of the pydcs.dcs.planes object.
inter_flight_radio_index: Optional[int]
#: Index of the radio used for intra-flight communications. Matches the
#: index of the panel_radio field of the pydcs.dcs.planes object.
intra_flight_radio_index: Optional[int]
def assign_channels_for_flight(
self, flight: FlightData, air_support: AirSupport
) -> None:
if self.intra_flight_radio_index is not None:
flight.assign_channel(
self.intra_flight_radio_index, 1, flight.intra_flight_channel
)
if self.inter_flight_radio_index is None:
return
# For cases where the inter-flight and intra-flight radios share presets
# (the JF-17 only has one set of channels, even though it can use two
# channels simultaneously), start assigning inter-flight channels at 2.
radio_id = self.inter_flight_radio_index
if self.intra_flight_radio_index == radio_id:
first_channel = 2
else:
first_channel = 1
last_channel = flight.num_radio_channels(radio_id)
channel_alloc = iter(range(first_channel, last_channel + 1))
if flight.departure.atc is not None:
flight.assign_channel(radio_id, next(channel_alloc), flight.departure.atc)
# TODO: If there ever are multiple AWACS, limit to mission relevant.
for awacs in air_support.awacs:
flight.assign_channel(radio_id, next(channel_alloc), awacs.freq)
if flight.arrival != flight.departure and flight.arrival.atc is not None:
flight.assign_channel(radio_id, next(channel_alloc), flight.arrival.atc)
try:
# TODO: Skip incompatible tankers.
for tanker in air_support.tankers:
flight.assign_channel(radio_id, next(channel_alloc), tanker.freq)
if flight.divert is not None and flight.divert.atc is not None:
flight.assign_channel(radio_id, next(channel_alloc), flight.divert.atc)
except StopIteration:
# Any remaining channels are nice-to-haves, but not necessary for
# the few aircraft with a small number of channels available.
pass
@classmethod
def from_cfg(cls, cfg: dict[str, Any]) -> CommonRadioChannelAllocator:
return CommonRadioChannelAllocator(
inter_flight_radio_index=cfg["inter_flight_radio_index"],
intra_flight_radio_index=cfg["intra_flight_radio_index"],
)
@classmethod
def name(cls) -> str:
return "common"
@dataclass(frozen=True)
class NoOpChannelAllocator(RadioChannelAllocator):
"""Channel allocator for aircraft that don't support preset channels."""
def assign_channels_for_flight(
self, flight: FlightData, air_support: AirSupport
) -> None:
pass
@classmethod
def name(cls) -> str:
return "noop"
@dataclass(frozen=True)
class FarmerRadioChannelAllocator(RadioChannelAllocator):
"""Preset channel allocator for the MiG-19P."""
def assign_channels_for_flight(
self, flight: FlightData, air_support: AirSupport
) -> None:
# The Farmer only has 6 preset channels. It also only has a VHF radio,
# and currently our ATC data and AWACS are only in the UHF band.
radio_id = 1
flight.assign_channel(radio_id, 1, flight.intra_flight_channel)
# TODO: Assign 4-6 to VHF frequencies of departure, arrival, and divert.
# TODO: Assign 2 and 3 to AWACS if it is VHF.
@classmethod
def name(cls) -> str:
return "farmer"
@dataclass(frozen=True)
class ViggenRadioChannelAllocator(RadioChannelAllocator):
"""Preset channel allocator for the AJS37."""
def assign_channels_for_flight(
self, flight: FlightData, air_support: AirSupport
) -> None:
# The Viggen's preset channels are handled differently from other
# aircraft. The aircraft automatically configures channels for every
# allied flight in the game (including AWACS) and for every airfield. As
# such, we don't need to allocate any of those. There are seven presets
# we can modify, however: three channels for the main radio intended for
# communication with wingmen, and four emergency channels for the backup
# radio. We'll set the first channel of the main radio to the
# intra-flight channel, and the first three emergency channels to each
# of the flight plan's airfields. The fourth emergency channel is always
# the guard channel.
radio_id = 1
flight.assign_channel(radio_id, 1, flight.intra_flight_channel)
if flight.departure.atc is not None:
flight.assign_channel(radio_id, 4, flight.departure.atc)
if flight.arrival.atc is not None:
flight.assign_channel(radio_id, 5, flight.arrival.atc)
# TODO: Assign divert to 6 when we support divert airfields.
@classmethod
def name(cls) -> str:
return "viggen"
@dataclass(frozen=True)
class SCR522RadioChannelAllocator(RadioChannelAllocator):
"""Preset channel allocator for the SCR522 WW2 radios. (4 channels)"""
def assign_channels_for_flight(
self, flight: FlightData, air_support: AirSupport
) -> None:
radio_id = 1
flight.assign_channel(radio_id, 1, flight.intra_flight_channel)
if flight.departure.atc is not None:
flight.assign_channel(radio_id, 2, flight.departure.atc)
if flight.arrival.atc is not None:
flight.assign_channel(radio_id, 3, flight.arrival.atc)
# TODO : Some GCI on Channel 4 ?
@classmethod
def name(cls) -> str:
return "SCR-522"
class ChannelNamer:
"""Base class allowing channel name customization per-aircraft.
Most aircraft will want to customize this behavior, but the default is
reasonable for any aircraft with numbered radios.
"""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
"""Returns the name of the channel for the given radio and channel."""
return f"COMM{radio_id} Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "default"
class SingleRadioChannelNamer(ChannelNamer):
"""Channel namer for the aircraft with only a single radio.
Aircraft like the MiG-19P and the MiG-21bis only have a single radio, so
it's not necessary for us to name the radio when naming the channel.
"""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
return f"Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "single"
class HueyChannelNamer(ChannelNamer):
"""Channel namer for the UH-1H."""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
return f"COM3 Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "huey"
class MirageChannelNamer(ChannelNamer):
"""Channel namer for the M-2000."""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
radio_name = ["V/UHF", "UHF"][radio_id - 1]
return f"{radio_name} Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "mirage"
class TomcatChannelNamer(ChannelNamer):
"""Channel namer for the F-14."""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
radio_name = ["UHF", "VHF/UHF"][radio_id - 1]
return f"{radio_name} Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "tomcat"
class ViggenChannelNamer(ChannelNamer):
"""Channel namer for the AJS37."""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
if channel_id >= 4:
channel_letter = "EFGH"[channel_id - 4]
return f"FR 24 {channel_letter}"
return f"FR 22 Special {channel_id}"
@classmethod
def name(cls) -> str:
return "viggen"
class ViperChannelNamer(ChannelNamer):
"""Channel namer for the F-16."""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
return f"COM{radio_id} Ch {channel_id}"
@classmethod
def name(cls) -> str:
return "viper"
class SCR522ChannelNamer(ChannelNamer):
"""
Channel namer for P-51 & P-47D
"""
@staticmethod
def channel_name(radio_id: int, channel_id: int) -> str:
if channel_id > 3:
return "?"
else:
return f"Button " + "ABCD"[channel_id - 1]
@classmethod
def name(cls) -> str:
return "SCR-522"

View File

@@ -8,7 +8,6 @@ from dataclasses import dataclass, field
from enum import unique, Enum
from pathlib import Path
from typing import (
Type,
Tuple,
TYPE_CHECKING,
Optional,
@@ -17,10 +16,9 @@ from typing import (
)
import yaml
from dcs.unittype import FlyingType
from faker import Faker
from game.db import flying_type_from_name
from game.dcs.aircrafttype import AircraftType
from game.settings import AutoAtoBehavior
if TYPE_CHECKING:
@@ -79,7 +77,7 @@ class Squadron:
nickname: str
country: str
role: str
aircraft: Type[FlyingType]
aircraft: AircraftType
livery: Optional[str]
mission_types: tuple[FlightType, ...]
pilots: list[Pilot]
@@ -196,9 +194,11 @@ class Squadron:
with path.open() as squadron_file:
data = yaml.safe_load(squadron_file)
unit_type = flying_type_from_name(data["aircraft"])
if unit_type is None:
raise KeyError(f"Could not find any aircraft with the ID {unit_type}")
name = data["aircraft"]
try:
unit_type = AircraftType.named(name)
except KeyError as ex:
raise KeyError(f"Could not find any aircraft named {name}") from ex
pilots = [Pilot(n, player=False) for n in data.get("pilots", [])]
pilots.extend([Pilot(n, player=True) for n in data.get("players", [])])
@@ -245,8 +245,8 @@ class SquadronLoader:
yield Path(persistency.base_path()) / "Liberation/Squadrons"
yield Path("resources/squadrons")
def load(self) -> dict[Type[FlyingType], list[Squadron]]:
squadrons: dict[Type[FlyingType], list[Squadron]] = defaultdict(list)
def load(self) -> dict[AircraftType, list[Squadron]]:
squadrons: dict[AircraftType, list[Squadron]] = defaultdict(list)
country = self.game.country_for(self.player)
faction = self.game.faction_for(self.player)
any_country = country.startswith("Combined Joint Task Forces ")
@@ -317,7 +317,7 @@ class AirWing:
)
]
def squadrons_for(self, aircraft: Type[FlyingType]) -> Sequence[Squadron]:
def squadrons_for(self, aircraft: AircraftType) -> Sequence[Squadron]:
return self.squadrons[aircraft]
def squadrons_for_task(self, task: FlightType) -> Iterator[Squadron]:
@@ -325,7 +325,7 @@ class AirWing:
if task in squadron.mission_types:
yield squadron
def squadron_for(self, aircraft: Type[FlyingType]) -> Squadron:
def squadron_for(self, aircraft: AircraftType) -> Squadron:
return self.squadrons_for(aircraft)[0]
def iter_squadrons(self) -> Iterator[Squadron]:

View File

@@ -3,9 +3,10 @@ import logging
import typing
from typing import Dict, Type
from dcs.unittype import FlyingType, VehicleType, UnitType
from dcs.unittype import VehicleType
from game.db import PRICES
from game.dcs.aircrafttype import AircraftType
BASE_MAX_STRENGTH = 1
BASE_MIN_STRENGTH = 0
@@ -13,7 +14,7 @@ BASE_MIN_STRENGTH = 0
class Base:
def __init__(self):
self.aircraft: Dict[Type[FlyingType], int] = {}
self.aircraft: Dict[AircraftType, int] = {}
self.armor: Dict[Type[VehicleType], int] = {}
self.strength = 1
@@ -35,7 +36,7 @@ class Base:
logging.exception(f"No price found for {unit_type.id}")
return total
def total_units_of_type(self, unit_type) -> int:
def total_units_of_type(self, unit_type: typing.Any) -> int:
return sum(
[
c
@@ -44,15 +45,16 @@ class Base:
]
)
def commission_units(self, units: typing.Dict[typing.Type[UnitType], int]):
def commission_units(self, units: typing.Dict[typing.Any, int]):
for unit_type, unit_count in units.items():
if unit_count <= 0:
continue
if issubclass(unit_type, VehicleType):
target_dict = self.armor
elif issubclass(unit_type, FlyingType):
target_dict: dict[typing.Any, int]
if isinstance(unit_type, AircraftType):
target_dict = self.aircraft
elif issubclass(unit_type, VehicleType):
target_dict = self.armor
else:
logging.error(
f"Unexpected unit type of {unit_type}: "
@@ -66,21 +68,22 @@ class Base:
for unit_type, count in units_lost.items():
target_dict: dict[typing.Any, int]
if unit_type in self.aircraft:
target_array = self.aircraft
target_dict = self.aircraft
elif unit_type in self.armor:
target_array = self.armor
target_dict = self.armor
else:
print("Base didn't find event type {}".format(unit_type))
continue
if unit_type not in target_array:
if unit_type not in target_dict:
print("Base didn't find event type {}".format(unit_type))
continue
target_array[unit_type] = max(target_array[unit_type] - count, 0)
if target_array[unit_type] == 0:
del target_array[unit_type]
target_dict[unit_type] = max(target_dict[unit_type] - count, 0)
if target_dict[unit_type] == 0:
del target_dict[unit_type]
def affect_strength(self, amount):
self.strength += amount

View File

@@ -32,7 +32,7 @@ from dcs.ships import (
)
from dcs.terrain.terrain import Airport, ParkingSlot
from dcs.unit import Unit
from dcs.unittype import FlyingType, VehicleType
from dcs.unittype import VehicleType
from game import db
from game.point_with_heading import PointWithHeading
@@ -47,6 +47,7 @@ from .theatergroundobject import (
TheaterGroundObject,
)
from ..db import PRICES
from ..dcs.aircrafttype import AircraftType
from ..utils import nautical_miles
from ..weather import Conditions
@@ -125,19 +126,19 @@ class PresetLocations:
@dataclass(frozen=True)
class AircraftAllocations:
present: dict[Type[FlyingType], int]
ordered: dict[Type[FlyingType], int]
transferring: dict[Type[FlyingType], int]
present: dict[AircraftType, int]
ordered: dict[AircraftType, int]
transferring: dict[AircraftType, int]
@property
def total_value(self) -> int:
total: int = 0
for unit_type, count in self.present.items():
total += PRICES[unit_type] * count
total += unit_type.price * count
for unit_type, count in self.ordered.items():
total += PRICES[unit_type] * count
total += unit_type.price * count
for unit_type, count in self.transferring.items():
total += PRICES[unit_type] * count
total += unit_type.price * count
return total
@@ -544,24 +545,16 @@ class ControlPoint(MissionTarget, ABC):
destination.control_point.base.commission_units({unit_type: 1})
destination = heapq.heappushpop(destinations, destination)
def capture_aircraft(
self, game: Game, airframe: Type[FlyingType], count: int
) -> None:
try:
value = PRICES[airframe] * count
except KeyError:
logging.exception(f"Unknown price for {airframe.id}")
return
def capture_aircraft(self, game: Game, airframe: AircraftType, count: int) -> None:
value = airframe.price * count
game.adjust_budget(value, player=not self.captured)
game.message(
f"No valid retreat destination in range of {self.name} for "
f"{airframe.id}. {count} aircraft have been captured and sold for "
f"${value}M."
f"No valid retreat destination in range of {self.name} for {airframe}"
f"{count} aircraft have been captured and sold for ${value}M."
)
def aircraft_retreat_destination(
self, game: Game, airframe: Type[FlyingType]
self, game: Game, airframe: AircraftType
) -> Optional[ControlPoint]:
closest = ObjectiveDistanceCache.get_closest_airfields(self)
# TODO: Should be airframe dependent.
@@ -579,10 +572,10 @@ class ControlPoint(MissionTarget, ABC):
return None
def _retreat_air_units(
self, game: Game, airframe: Type[FlyingType], count: int
self, game: Game, airframe: AircraftType, count: int
) -> None:
while count:
logging.debug(f"Retreating {count} {airframe.id} from {self.name}")
logging.debug(f"Retreating {count} {airframe} from {self.name}")
destination = self.aircraft_retreat_destination(game, airframe)
if destination is None:
self.capture_aircraft(game, airframe, count)
@@ -618,16 +611,16 @@ class ControlPoint(MissionTarget, ABC):
self.base.set_strength_to_minimum()
@abstractmethod
def can_operate(self, aircraft: Type[FlyingType]) -> bool:
def can_operate(self, aircraft: AircraftType) -> bool:
...
def aircraft_transferring(self, game: Game) -> dict[Type[FlyingType], int]:
def aircraft_transferring(self, game: Game) -> dict[AircraftType, int]:
if self.captured:
ato = game.blue_ato
else:
ato = game.red_ato
transferring: defaultdict[Type[FlyingType], int] = defaultdict(int)
transferring: defaultdict[AircraftType, int] = defaultdict(int)
for package in ato.packages:
for flight in package.flights:
if flight.departure == flight.arrival:
@@ -692,7 +685,7 @@ class ControlPoint(MissionTarget, ABC):
def allocated_aircraft(self, game: Game) -> AircraftAllocations:
on_order = {}
for unit_bought, count in self.pending_unit_deliveries.units.items():
if issubclass(unit_bought, FlyingType):
if isinstance(unit_bought, AircraftType):
on_order[unit_bought] = count
return AircraftAllocations(
@@ -704,7 +697,7 @@ class ControlPoint(MissionTarget, ABC):
) -> GroundUnitAllocations:
on_order = {}
for unit_bought, count in self.pending_unit_deliveries.units.items():
if issubclass(unit_bought, VehicleType):
if type(unit_bought) == type and issubclass(unit_bought, VehicleType):
on_order[unit_bought] = count
transferring: dict[Type[VehicleType], int] = defaultdict(int)
@@ -788,7 +781,7 @@ class Airfield(ControlPoint):
self.airport = airport
self._runway_status = RunwayStatus()
def can_operate(self, aircraft: FlyingType) -> bool:
def can_operate(self, aircraft: AircraftType) -> bool:
# TODO: Allow helicopters.
# Need to implement ground spawns so the helos don't use the runway.
# TODO: Allow harrier.
@@ -972,8 +965,8 @@ class Carrier(NavalControlPoint):
def is_carrier(self):
return True
def can_operate(self, aircraft: FlyingType) -> bool:
return aircraft in db.CARRIER_CAPABLE
def can_operate(self, aircraft: AircraftType) -> bool:
return aircraft.carrier_capable
@property
def total_aircraft_parking(self) -> int:
@@ -1006,8 +999,8 @@ class Lha(NavalControlPoint):
def is_lha(self) -> bool:
return True
def can_operate(self, aircraft: FlyingType) -> bool:
return aircraft in db.LHA_CAPABLE
def can_operate(self, aircraft: AircraftType) -> bool:
return aircraft.lha_capable
@property
def total_aircraft_parking(self) -> int:
@@ -1046,7 +1039,7 @@ class OffMapSpawn(ControlPoint):
def total_aircraft_parking(self) -> int:
return 1000
def can_operate(self, aircraft: FlyingType) -> bool:
def can_operate(self, aircraft: AircraftType) -> bool:
return True
@property
@@ -1117,7 +1110,7 @@ class Fob(ControlPoint):
def total_aircraft_parking(self) -> int:
return 0
def can_operate(self, aircraft: FlyingType) -> bool:
def can_operate(self, aircraft: AircraftType) -> bool:
return False
@property

View File

@@ -18,8 +18,9 @@ from typing import (
)
from dcs.mapping import Point
from dcs.unittype import FlyingType, VehicleType
from dcs.unittype import VehicleType
from game.dcs.aircrafttype import AircraftType
from game.procurement import AircraftProcurementRequest
from game.squadrons import Squadron
from game.theater import ControlPoint, MissionTarget
@@ -29,7 +30,7 @@ from game.theater.transitnetwork import (
)
from game.utils import meters, nautical_miles
from gen.ato import Package
from gen.flights.ai_flight_planner_db import TRANSPORT_CAPABLE
from gen.flights.ai_flight_planner_db import TRANSPORT_CAPABLE, aircraft_for_task
from gen.flights.closestairfields import ObjectiveDistanceCache
from gen.flights.flight import Flight, FlightType
from gen.flights.flightplan import FlightPlanBuilder
@@ -191,9 +192,9 @@ class AirliftPlanner:
self.package = Package(target=next_stop, auto_asap=True)
def compatible_with_mission(
self, unit_type: Type[FlyingType], airfield: ControlPoint
self, unit_type: AircraftType, airfield: ControlPoint
) -> bool:
if not unit_type in TRANSPORT_CAPABLE:
if unit_type not in aircraft_for_task(FlightType.TRANSPORT):
return False
if not self.transfer.origin.can_operate(unit_type):
return False
@@ -201,7 +202,7 @@ class AirliftPlanner:
return False
# Cargo planes have no maximum range.
if not unit_type.helicopter:
if not unit_type.dcs_unit_type.helicopter:
return True
# A helicopter that is transport capable and able to operate at both bases. Need
@@ -254,9 +255,11 @@ class AirliftPlanner:
self, squadron: Squadron, inventory: ControlPointAircraftInventory
) -> int:
available = inventory.available(squadron.aircraft)
capacity_each = 1 if squadron.aircraft.helicopter else 2
capacity_each = 1 if squadron.aircraft.dcs_unit_type.helicopter else 2
required = math.ceil(self.transfer.size / capacity_each)
flight_size = min(required, available, squadron.aircraft.group_size_max)
flight_size = min(
required, available, squadron.aircraft.dcs_unit_type.group_size_max
)
capacity = flight_size * capacity_each
if capacity < self.transfer.size:

View File

@@ -3,12 +3,13 @@ from __future__ import annotations
import logging
from collections import defaultdict
from dataclasses import dataclass
from typing import Dict, Optional, TYPE_CHECKING, Type
from typing import Dict, Optional, TYPE_CHECKING, Type, Any
from dcs.unittype import UnitType, VehicleType
from game.theater import ControlPoint
from .db import PRICES
from .dcs.aircrafttype import AircraftType
from .theater.transitnetwork import (
NoPathError,
TransitNetwork,
@@ -24,21 +25,24 @@ class GroundUnitSource:
control_point: ControlPoint
AircraftOrVehicleType = Any
class PendingUnitDeliveries:
def __init__(self, destination: ControlPoint) -> None:
self.destination = destination
# Maps unit type to order quantity.
self.units: Dict[Type[UnitType], int] = defaultdict(int)
self.units: Dict[AircraftOrVehicleType, int] = defaultdict(int)
def __str__(self) -> str:
return f"Pending delivery to {self.destination}"
def order(self, units: Dict[Type[UnitType], int]) -> None:
def order(self, units: Dict[AircraftOrVehicleType, int]) -> None:
for k, v in units.items():
self.units[k] += v
def sell(self, units: Dict[Type[UnitType], int]) -> None:
def sell(self, units: Dict[AircraftOrVehicleType, int]) -> None:
for k, v in units.items():
self.units[k] -= v
@@ -57,13 +61,13 @@ class PendingUnitDeliveries:
logging.info(f"Refunding {count} {unit_type.id} at {self.destination.name}")
game.adjust_budget(price * count, player=self.destination.captured)
def pending_orders(self, unit_type: Type[UnitType]) -> int:
def pending_orders(self, unit_type: AircraftOrVehicleType) -> int:
pending_units = self.units.get(unit_type)
if pending_units is None:
pending_units = 0
return pending_units
def available_next_turn(self, unit_type: Type[UnitType]) -> int:
def available_next_turn(self, unit_type: AircraftOrVehicleType) -> int:
current_units = self.destination.base.total_units_of_type(unit_type)
return self.pending_orders(unit_type) + current_units
@@ -77,15 +81,20 @@ class PendingUnitDeliveries:
self.refund_all(game)
return
bought_units: Dict[Type[UnitType], int] = {}
bought_units: Dict[AircraftOrVehicleType, int] = {}
units_needing_transfer: Dict[Type[VehicleType], int] = {}
sold_units: Dict[Type[UnitType], int] = {}
sold_units: Dict[AircraftOrVehicleType, int] = {}
for unit_type, count in self.units.items():
coalition = "Ally" if self.destination.captured else "Enemy"
name = unit_type.id
if isinstance(unit_type, AircraftType):
name = unit_type.name
else:
name = unit_type.id
if (
issubclass(unit_type, VehicleType)
type(unit_type) == type
and issubclass(unit_type, VehicleType)
and self.destination != ground_unit_source
):
source = ground_unit_source