Compare commits

..

1185 Commits

Author SHA1 Message Date
Dan Albert
5037a5c9d7 Bump version to 5.2.1. 2022-10-31 13:21:29 -07:00
Dan Albert
fb734d4f09 Note hold point fix in the changelog.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/2494.

(cherry picked from commit 73b7be0606)
2022-10-31 13:21:29 -07:00
Raffson
173b99f610 Fix for orbit's broken stop condition
(cherry picked from commit 7e7c920816d384001ac1dbf1bcbcf8ccaad4a093)
(cherry picked from commit 73ee2ba4c0)
2022-10-31 13:21:29 -07:00
RndName
a87fa119aa Set unrestricted_satnav for NATO factions
cherry-pick from f7f565477c
2022-03-26 17:11:43 +01:00
MetalStormGhost
eb8859ebea Don't reject exact fits when transferring squadrons.
cherry-pick from a024be6b1d
2022-03-26 15:39:40 +01:00
RndName
7e54c8dea7 Update changelog for 5.2.0 2022-03-26 13:19:12 +01:00
RndName
e86bd4fa14 Capaign update: Task Force Thunder
Submission by sith1144

cherry-pick from 6a6df8936e
2022-03-26 13:15:27 +01:00
RndName
178ae3774e Support campaign version 10.0 for Liberation 5.2.0
- add a new const to the version.py to allow future campaign version to be backwards compatible
- Version 10.0 was only about orientation of ground objects which does not break the compatibility so we can give support for this specific version
2022-03-26 12:47:02 +01:00
RndName
1988836c61 Campaign updates & submission by Fuzzle
- new campaign: Tripoint Hostility
- updated other campaings and set 10.0 compat

Submission by sgtfuzzle17

cherry-pick from
7b0676025b
9050e705ff
d30701c1bb
2022-03-26 12:23:58 +01:00
RndName
e0ba2609b1 Update pyinstaller dependency to match develop 2022-03-25 10:14:52 +01:00
Benjamin Fischer
72050df5ff Make Apache LHA capable.
cherry-pick from 8eb97136b0
2022-03-25 09:19:29 +01:00
Benjamin Fischer
28c775af60 Fix can_operate for airfields without runways.
cherry-pick from e9c5cac20c
2022-03-25 09:19:18 +01:00
RndName
3d5f94db1f Support for the AH-64D radios
- Support for the AH-64D radios
- Mention missing Radio preset support for AH-64D

cherry-pick from 437fdd6d12
2022-03-23 17:18:21 +01:00
RndName
c93695ac36 Update pydcs to fix issues with syria map updates 2022-03-22 13:18:20 +01:00
RndName
0b33b0f9fb Update pydcs to fix save-compat issues
fixes #2103
2022-03-22 11:53:08 +01:00
Starfire13
e043e6073e Peace Spring, Vectron's Claw, Vegas Nerve updates.
cherry-pick from 46e220cecc
2022-03-21 21:37:32 +01:00
Dan Albert
c7d764da85 Scenic Route II update.
cherry-pick from 123a44fefc
2022-03-21 10:07:25 +01:00
Dan Albert
367a7f9829 Add Apache squadrons.
cherry-pick from b683246647
2022-03-21 10:06:07 +01:00
Dan Albert
4a99b59a38 Fix helicopters at airfields breaking generation.
Helipads at airfields don't work well right now because they are not
counted as additional parking, but we should still allow them to take
off from the airfield parking.

Follow up work would be to fix the parking problem and allow adding
helipads to airfields, or maybe to just "ground" start helicopters at
airfields so they take off from parking rather than the runway.

cherry-pick from 2499276b2a
2022-03-21 00:06:34 +01:00
RndName
9b125a644e Update Changelog 2022-03-20 21:10:57 +01:00
bbirchnz
5a037d8b75 Add windsocks to FARPs
cherry-pick from 39152eab3c
2022-03-20 20:52:52 +01:00
MetalStormGhost
30ac898aa9 Updated the Community A-4E-C mod support to version 2.0.0
cherry-pick from 11328ea241
2022-03-20 20:48:09 +01:00
MetalStormGhost
74fb390dcd Commit JAS-39-C support update for v1.8.0-beta again 2022-03-20 20:48:09 +01:00
RndName
6f0119731b Fix heli spawn & farp helipad creation
cherry-pick from
ad0d3412fb
6f8c30ec81
c88fa6d2af
a53812c0fb
2022-03-20 20:48:04 +01:00
Ben Birch
a6e1dc14c3 Add all helipads to single group per FARP allowing take off from parking behavour
cherry-pick from a70a951192 with adoptions
2022-03-20 20:23:55 +01:00
RndName
d23b1fbb2c Temporary Workaround for weapon save compat
Adds a temporary workaround for save game loading when weapon data got removed and can not be updated anymore.

This can lead to some unexpected behaviour especially when generating the next turn miz as pydcs will most likely crash. This could be solved by just changing the loadout (not tested yet)
2022-03-20 19:49:58 +01:00
RndName
26f3bf5827 Fix for removed units
Latest dcs data exports have some units removed which were used in two generators.
2022-03-20 13:54:54 +01:00
RndName
48945c1ce9 Update pydcs to develop-5.2 fork 2022-03-20 13:46:15 +01:00
RndName
a75a3af13d Add support for the flyable Apache. 2022-03-20 13:40:50 +01:00
Dan Albert
a88cd60f31 Update pydcs. 2022-03-20 13:40:37 +01:00
RndName
86b204883a Revert "Add support for AH-64D_BLK_II as PyDCS Extension"
This reverts commit 7d65e55665.
2022-03-20 13:28:29 +01:00
walterroach
4d2289ece9 Add Starfire's loadouts for AH-64D_BLK_II 2022-03-18 13:02:12 -05:00
RndName
7d65e55665 Add support for AH-64D_BLK_II as PyDCS Extension
The new human flyable Apache will be handled like a mod in 5.X to be save compat and to prevent switching to the newest version of pydcs. There will no checkbox on the newgame wizard like with other mods as it can be used by everyone.

- exported the AH-64D_BLK_II and the weapon data from the latest open beta
- added the needed ressources
- maked the AH-64D_BLK_II as flyable
2022-03-18 10:25:09 +01:00
RndName
edb10f60fb Update Changelog 2022-03-18 10:19:09 +01:00
DillieKoe
a7a28205a9 Fix unit role of Type 04A (ZBD-04A).
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/2072.
2022-03-18 10:16:19 +01:00
Dan Albert
a22452baca Add Sith1144's new campaigns.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1833.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1834.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1835.
2022-03-18 10:16:14 +01:00
Benjamin Fischer
8422823921 another high dpi fix which fixes some resizing issues. 2022-03-18 10:15:27 +01:00
Benjamin Fischer
30fe1ca6af Round balance and income in the finance window.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1983
2022-03-18 10:14:01 +01:00
Benjamin Fischer
faf70debce fixes #1987 by adding highdpi qt attributes. 2022-03-18 10:13:56 +01:00
Benjamin Fischer
42929b08d8 Fixes #1774 by adding a logmessage for non ascii install path. 2022-03-18 10:13:50 +01:00
Benjamin Fischer
91bb5acd04 Log information about the generated campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1735
2022-03-18 10:13:30 +01:00
Benjamin Fischer
d69841f261 Make the flight dialog modal to prevent inventory loss.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1971.
2022-03-18 10:13:18 +01:00
RndName
dba8c26887 Bump Version to 5.2.0 2022-03-18 09:45:57 +01:00
MetalStormGhost
bef27ffb20 UH-60L mod support
Resolves #1964 but adding CTLD will require the use of Liberation plugins and thus are not included in this pull request.

- Implemented support for the UH-60L mod by =X51= Kinkkujuustovoileipa, Cubeboy, Jonas, JinxxDCS, Dorian, =X51= Parzival & =X51= Lawson.
- Because the standard DCS tankers will not fly below 160ish knots, the UH-60L mod team have included a modified version of the KC-130 tanker designed for refueling at speeds of 120-130kts.
2022-03-17 21:47:05 +01:00
C. Perreau
d9eac37766 Update README.md 2022-03-17 20:31:52 +01:00
Khopa
39a5d4e7c4 Properly credit CC artwork author. 2022-03-17 20:31:48 +01:00
Khopa
ce4d388e27 🇺🇦 Support for Ukraine 2022-03-17 20:31:43 +01:00
RndName
3a318fbbdf Add OCA/Runway loadouts for F-15E and F-16C.
Unguided bombs for the AI.

cherry-pick from ac5d20ff82
2022-03-17 20:28:12 +01:00
RndName
526d082020 Loaadouts for the Tornado GR4
cherry-pick from 9f7f391609
2022-03-17 20:23:34 +01:00
Hornet2041
3d68eabcaa Remove Fw A-8 and D-9 from Germany 1940/1942 faction
cherry-pick from 8a66bf2e09
2022-03-17 20:20:51 +01:00
RndName
409a099339 changelog 2022-02-02 21:31:38 +01:00
RndName
0ba86af4fd Add NASAM Radar and Launcher to radar_db
This will allow correct calculation of the threat range and prevent creating a threat zone when the SR is dead.

cherry-pick from 3afc6ba
2022-02-02 21:31:38 +01:00
MetalStormGhost
99d4cb7ad5 Tolerate empty TGOs in max_threat_range.
cherry-pick from 3231d00
2022-02-02 21:31:21 +01:00
SnappyComebacks
815849ae64 Typhoon GR4 and Typhoon IDS images (#1970)
* Add icons for Tornado GR4 and Tornado IDS.

cherry-pick from b3a3eb4
2022-02-02 21:31:07 +01:00
Starfire13
31efac53f4 Update bluefor_modern.json
cherry-pick from 0300b77
2022-02-02 21:30:51 +01:00
RndName
3ede2b5755 Add otion to ignore the empty install dir warning message
Adds a do not show again checkbox to the empty install dir warning popup on lib start. This only appears when the install dir is empty to prevent mission scripting replacement.

Also adds a warning message to the log when the dir is empty. Will help to identify this in bug reports.

cherry-pick from 93a0db3
2022-02-02 21:30:35 +01:00
leemarov
de43c0d621 Fix unculled zones not updating when needed.
cherry-pick from 5d29184
2022-02-02 21:30:18 +01:00
MetalStormGhost
7a6ec30368 Add missing HTTPS to pydcs URL.
cherry-pick from ecd2f2b
2022-02-02 21:29:51 +01:00
RndName
08c3da9502 Update Iran factions / Revert previous changes
readded ZSU-57 and SA-17 as they can be used from the country even if dcs mission editor leaves the type empty / does not have them for the country.

cherry-pick from 194b4df
2022-02-02 21:28:36 +01:00
RndName
6d389f7612 Fix the P-47D and P-51D radio definition
set the correct ChannelAllocator
from common to SCR-522)

cherry-pick from d9b4342
2022-02-02 21:28:15 +01:00
Starfire13
bc3b6c2a26 Update Vegas Nerve campaign
cherry-pick from eb6c1871
2022-01-07 18:02:11 +01:00
RndName
041cd0057a Fix threat range calculation
threat range calculation had a hidden bug which could possibly lead to wrong threat range calculation

cherry-pick from 808db05d
2022-01-07 15:47:26 +01:00
RndName
57ee611d06 Update Distance comparison operators
remove order=True and implement the comparison operators manually to fix typing error

cherry-pick from 795df1a9
2022-01-07 15:47:11 +01:00
RndName
f63fae2d4f Fix incorrect threat range of SA-5
The SA-5 was not part of the radar_db.py and therefore the threat_range calculation was wrong / ever LN counted as threat even when the TR was dead. Also fixed a wrong unit for the SA-11 TELAR.

cherry-pick from 54745e78
2022-01-07 14:49:02 +01:00
RndName
cd120047cb Update Version to 5.1.1 2022-01-07 14:44:50 +01:00
RndName
7bb41d07b3 Revert "Remove front line minimum distance."
This reverts commit dbe9691d
2022-01-07 09:59:14 +01:00
RndName
8aca036bf0 Update pydcs
Latest version with the new terrain from 2.7.9.18080

cherry-pick from 82dfeb8a
2022-01-06 21:30:50 +01:00
RndName
878695b2c7 Update for the nevada map update
Conflicttheater and Airfields needed an update as nearly all Nevada Airports were renamed with the last map update

cherry-pick from 8df9f698
2022-01-06 21:30:35 +01:00
Starfire13
f57bd2f253 Update campaign Exercise Vegas Nerve by Starfire
cherry-pick from 19713e61
2022-01-06 18:07:54 +01:00
RndName
cf7330e938 Update SA-5 Generator for factions without the TinShield
- added an EarlySA5Generator with the P-19 FlatFace SR which is supported by all factions
- allows factions without access to the TinShield to have a working SA-5

cherry-pick from f526681f
2022-01-05 01:09:49 +01:00
RndName
e56abbe768 Add Igla manpad INS ground unit
cherry-pick from 77edeac9
2022-01-04 23:56:37 +01:00
RndName
b7a92a2ebf Campaign submission from Fuzzle
- new campaign Scenic Route 2 - Dust To Dust including NATO_OIF faction and 3 squadrons
- update for pacific repartee

cherry-pick from 2c0d7c8e
2022-01-04 23:56:37 +01:00
RndName
a17b8dac7f Update faction Iran 1988 & 2015
support for the latest pydcs export as some units were not usable by the country

cherry-pick from 5c0227b8
2022-01-04 21:31:31 +01:00
MetalStormGhost
dbe9691d9e Remove front line minimum distance.
This isn't what it says. It doesn't enforce a minimum distance between
points, but a minimum path length, which isn't useful and isn't a
documented requirement.

cherry-pick from c844c364
2022-01-02 23:59:45 +01:00
MetalStormGhost
d2eb98bcc5 Added option for only night missions.
- Moved the night mission setting back from the Mission restrictions section to the Mission difficulty section.
- Changed the Night/day mission option into a dropdown menu.

Resolves #1786
2022-01-02 13:23:36 +01:00
RndName
475cb4851a Cleanup the killed map objects recognition
removed the extra array to track killed_map_objects and reuse the existing killed_ground_units routine to remove duplicate code and possible confusion

cherry-pick from 41392585
2022-01-02 12:55:42 +01:00
MetalStormGhost
24e904134e Update multi-part Caucasus campaigns. 2022-01-02 01:52:38 +01:00
RndName
365eaa98f7 Update pydcs 2022-01-02 01:23:49 +01:00
RndName
e070d5bf0d Rework killed map_objects recognition
- removed the map_object_id from the TGO
- add a new TriggerRule with the MapObjectIsDead Condition which adds the map object to the killed_map_objects array in the state.json
- Use the trigger_zone_name as the unique identifier used for the unit_map to recognize the kill
2022-01-02 01:23:48 +01:00
MetalStormGhost
ffd8152b36 Improved the F-104G CAP loadout.
Replace hydra pods with more AIM-9s.
2022-01-02 01:23:06 +01:00
Starfire13
11812f07fc Added missing squadron nickname 2022-01-02 01:23:05 +01:00
RndName
ba4de3dc27 Fix Viggen FR22 group channel id and mention in changelog
cherry-pick from deb7227c
2021-12-30 18:49:00 +01:00
RndName
208382f3c4 Update Viggen radio presets for 2.7.9
the radio presets of the Viggen were changed with the recent dcs update, they will no longer be automatically generated so we have to add them manually
cherry-pick from 0063d8db
2021-12-30 18:19:57 +01:00
RndName
aadb2dd54d Updated changelog
- marked as compat as currently there seems to be no change that the update is not save compat
- mentioned the recent dcs update
2021-12-30 11:13:37 +01:00
RndName
1b2eb1236f Update Fuzzle Campaigns
cherry-pick from 81cbf807
2021-12-30 11:11:42 +01:00
Dan Albert
00bdbf65ce Update pydcs.
cherry-pick from d81c6a0
2021-12-28 17:52:12 +01:00
MetalStormGhost
290646c8ae Updates for WW2 loadouts.
Major changes:
 - FW190A8 ground attack loadout WGr21 rockets (primarily an air-to-air weapon) replaced with SC500J or AB500 bombs.
 - FW190D9 WGr21 rockets replaced with R4M rocket packs and SC500 bombs for CAS.
 - Added droptanks for I-16.
 - Ju-88A4 CAS loadout changed for AB500 cluster bombs.
 - Mosquito now has rockets which were introduced in DCS World 2.7.9.17830 open beta
 - Added more/heavier bombs to P-47
 - P-51 now has a separate OCA/Runway loadout with bombs. Other ground attack loadouts switched to rockets.

Also includes an SA342Minigun loadout which we didn't previously have.

cherry-pick from 5684570
2021-12-28 17:50:56 +01:00
Dan Albert
8f58832527 Add ECM pod to Viper A2G loadouts.
Didn't add to the A2A loadouts since the ECM interferes with radar
operation and is otherwise weight and drag. It does have a radar
priority mode though, so maybe it should be added there too?

cherry-pick from c0dfa77
2021-12-28 17:50:02 +01:00
Dan Albert
f426a16e9d Add weapon data for the AN/ALQ-184.
cherry-pick from 0c7d549
2021-12-28 17:49:38 +01:00
Dan Albert
6f4e436305 Fix misclassification of the HTS as a TGP.
cherry-pick from fc4022a
2021-12-28 17:49:16 +01:00
RndName
08288c9da9 Mention squadron config and f-104 mod in changelog 2021-12-23 13:46:18 +01:00
RndName
9bfac347db Finish implementation of add/remove squadrons from AirWingConfigurationDialog
Users can now add and remove squadrons with specific buttons. this also allows new aircraft types to be added as well.

- rebased existing PR to develop
- reverted observable and changed to signals
- changed the general concept so that changes only affect the ui data model and not the game directly. Game will only be updated on apply
- removed unused code
- adopt to review comments
- allow user to choose a predefined squadron preset (also alow none value to use the random generator)
- Reuse the squadron defs from the default assigner in the AirWing class
- allow user to re-roll the squadron nickname (also added new ui icons for the button)

cherry-pick from d2f7785f
2021-12-23 13:45:13 +01:00
Richard Pump
22a35b0d2e Added squadron configuration gui
- added add/remove buttons to Air Wing Menu, implemented remove

cherry-pick from e4ba9a8b
2021-12-23 13:45:13 +01:00
Starfire13
e56d8de800 Fixed typo in squadrondefgenerator.py
cherry-pick from 4803ae5f
2021-12-23 13:43:49 +01:00
Starfire13
c806980ab8 Fixed typo in naming.py
cherry-pick from d739d830
2021-12-23 13:43:24 +01:00
MetalStormGhost
4750fff114 Re-add From Caen to Evreux campaign.
cherry-pick from 3626fa79
2021-12-23 13:43:04 +01:00
MetalStormGhost
b405b8e7ee F-104 mod support.
cherry-pick from 88bc4fd8
2021-12-23 13:42:49 +01:00
RndName
074ae328ee Revert "Temporary Fix for broken upload action"
This reverts commit 64d273b433.
2021-12-21 09:35:18 +01:00
RndName
5fd6ccb81d Enable / Disable game specific functions if no game is loaded
- Disable Save, Settings, Stats and Notes if game is none

cherry-pick from f9ed61d1
2021-12-20 13:56:20 +01:00
RndName
64d273b433 Temporary Fix for broken upload action
The upload-artifact version 2.3 has problems with 0byte files and prevent the build action from beeing completed.
This temporary fix should be reverted when they fixed the bug.
2021-12-13 20:49:50 +01:00
RndName
d7f833ecfb Fix empty convoy when transfer is not completable
fixes #1553
2021-12-13 20:49:49 +01:00
RndName
5d89b9ac25 Add Easy Communication Setting
allow to enforce the mission setting for easy communication
cherry-pick from 2c21644
2021-12-12 01:24:01 +01:00
RndName
056851765f Update Branch to V5.1.0 2021-12-10 00:14:32 +01:00
MetalStormGhost
54bf9357bf Add option to limit convoy travel distances.
CPU load seems to scale with route length, so add an option to limit
the length of the convoy route. The tradeoff is that the performance
sensitive route won't necessarily be a correct route.
2021-12-10 00:14:32 +01:00
Dan Albert
dfcc458479 Note HTS support in the changelog. 2021-12-10 00:14:31 +01:00
Dan Albert
f3f0e23eff Add weapon data and loadouts for the HTS.
Used in the default Viper DEAD and SEAD loadouts.
2021-12-10 00:14:30 +01:00
Dan Albert
5ce6de6645 Update pydcs.
HTS support.
2021-12-10 00:14:30 +01:00
Dan Albert
50b4d420fe Clarify the role of the faction aircraft list. 2021-12-10 00:14:29 +01:00
MetalStormGhost
224c78ac11 Add a new base banner for FARPs. 2021-12-10 00:14:28 +01:00
Dan Albert
227b054279 Fix incorrect radio range for AN/ARC-222.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1740
2021-12-10 00:14:27 +01:00
Khopa
0093fa0fe1 Fix #1718 : Remove Merkava IV from faction "Israel 1982" 2021-12-10 00:14:02 +01:00
Khopa
3cdfd9d7d2 Fix #1717 : Removed SA5Generator from Iran 1988 faction 2021-12-10 00:14:02 +01:00
Khopa
5e2e07da80 pydcs : Updated to latest pydcs master commit 2021-12-10 00:14:01 +01:00
Khopa
5f3f6f8c9f SA5Generator : Added an ural truck to reload SA-5 sites 2021-12-10 00:13:56 +01:00
RndName
0077b04698 Update UI when buy or sell raises exception
fixes #1562 cherry-pick from 34100d1c
2021-11-26 21:00:44 +01:00
RndName
bb1e314260 Generate unit_id for helipads
fixes mission scripting error (1748)

cherry-picked from 676a256
2021-11-22 15:10:03 +01:00
Dan Albert
d710c2631a Update branch to 5.0.1. 2021-11-13 11:48:25 -08:00
Dan Albert
7278878266 Remove incompatible campaigns.
(cherry picked from commit 2ea2ecec94)
2021-11-13 11:20:42 -08:00
Dan Albert
ec8391bbfb Add A-4E squadrons.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1716

(cherry picked from commit a3038e75cf)
2021-11-13 11:16:27 -08:00
Dan Albert
74504173c7 Add IRIAF F-4E squadron.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1721

(cherry picked from commit 5dcd4580c3)
2021-11-13 11:12:36 -08:00
MetalStormGhost
792c7c5091 Update Marianas campaigns.
More FARPs to both Orote Point and Andersen Northwest Field.

(cherry picked from commit 68b48ad610)
2021-11-13 11:10:26 -08:00
Dan Albert
b7e9a4a243 Drop a few unsupported campaigns.
Probably more coming but these are the ones that are confirmed not
happening before release.

(cherry picked from commit 94f65d8f70)
2021-11-12 14:03:21 -08:00
Dan Albert
bdbb338e83 Update Syria full campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1728

(cherry picked from commit 46e5299c60)
2021-11-12 13:42:55 -08:00
Dan Albert
98fa70c73d Update Pacific Repartee.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1707

(cherry picked from commit d645b4fe73)
2021-11-06 19:13:40 -07:00
Dan Albert
7991e0157d Update Caucasus multi-part Georgia.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1706

(cherry picked from commit 68c794f608)
2021-11-06 19:13:39 -07:00
Dan Albert
21643c500f 5.0 changelog fixes.
(cherry picked from commit 475d18b701)
2021-11-06 19:07:18 -07:00
Dan Albert
b4ddfb9dfd Prevent assigning fixed wing squadrons to FARPs.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1671

(cherry picked from commit e9634b7066)
2021-11-06 18:45:05 -07:00
Dan Albert
d1e50a5bbe Fix fixed wing squadrons retreating to FARPs.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1615

(cherry picked from commit 35900c2350)
2021-11-06 16:54:59 -07:00
Dan Albert
a188f7b7e5 Add missing NavalControlPoint case for BAI.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1702

(cherry picked from commit 7a18d160c8)
2021-11-06 16:36:44 -07:00
Dan Albert
4f76b73de2 Split runway attack list from strike list.
Not all strike aircraft are capable of runway attack, so copy the strike
list into the runway attack list and remove the incompatible aircraft.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1703

(cherry picked from commit a33104d7c4)
2021-11-06 16:26:36 -07:00
Dan Albert
a4b09bc973 Update Skynet to 2.4.0.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1713

(cherry picked from commit 7f57180da4)
2021-11-06 16:22:11 -07:00
Dan Albert
a792c73cae Restore missing income multiplier labels.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1712

(cherry picked from commit a23e7fe83d)
2021-11-06 16:20:05 -07:00
Dan Albert
113380661c Updates for Syria full.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1675

(cherry picked from commit c854508381)
2021-11-06 16:16:19 -07:00
Dan Albert
3ab9b25b08 Updates for Northern Russia.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1676

(cherry picked from commit d1cf8915e3)
2021-11-06 16:16:19 -07:00
Dan Albert
29d4ca38f9 Check in Pacific Repartee campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1701

(cherry picked from commit d9b5b87f2b)
2021-11-06 16:16:18 -07:00
Dan Albert
6a3ff8d6ac Tell Qt that we actually want text to fit.
Why isn't this the default?

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1670

(cherry picked from commit 5923ba21de)
2021-11-03 19:36:12 -07:00
Dan Albert
c1f194b3d5 Add E-2D variant of the E-2C.
In game this is an E-2D, but the ID of the aircraft in the game data is
E-2C. Presumably it was repainted at some point in a DCS update.

This adds a variant but doesn't delete the old one to avoid breaking
campaigns and factions. I moved blufor modern to the E-2D but the rest
of the factions are too old so we'll let them pretend.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1696

(cherry picked from commit 33f00fb811)
2021-10-30 15:29:41 -07:00
Dan Albert
a6809e0103 Document Su-33 carrier takeoff fix.
https://github.com/dcs-liberation/dcs_liberation/issues/1352
(cherry picked from commit ae99558f40)
2021-10-30 15:17:18 -07:00
Dan Albert
a559aa8646 Fix (presumable) accidental edit of A-4 pylons.
I'm not sure if this was a mistaken edit that the author made on check-
in or if we have a broken script that's generating these. For now I've
manually fixed it.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1574

(cherry picked from commit 70dbe7c9ca)
2021-10-30 15:06:26 -07:00
ghost
c766322960 Update Marianas campaigns to use the Tu-142.
(cherry picked from commit 2d0b5023c9)
2021-10-30 15:06:18 -07:00
ghost
c7581568c2 Enable anti-ship missions for the Tu-142.
This is the only mission type that the Tu-142 is capable of.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1683

(cherry picked from commit 92fdd0b80d)
2021-10-30 15:06:08 -07:00
Starfire13
f0827a429e Campaigns updated to 9.1
Peace Spring, Vectron's Claw, and Vegas Nerve have been updated to 9.1. Squadrons have also been completely overhauled to work much better, so there should no longer be a whole bunch of squadrons on OPFOR that are never used.

(cherry picked from commit 2d93ac58fc)
2021-10-30 15:06:00 -07:00
Starfire13
c2ee44d8bb H-6J Loadout Update
Added loadouts for DEAD and OCA/Aircraft as those are default mission types for the H-6J.

(cherry picked from commit 79924a59bc)
2021-10-30 15:05:57 -07:00
MetalStormGhost
af362be3a2 Forcibly allow GPS for more non-US factions.
Enable unrestricted_satnav with non-US factions operating either the
F-16CM or the F/A-18C to allow the use of GPS in missions.

(cherry picked from commit 545f974552)
2021-10-30 15:05:50 -07:00
Dan Albert
80c8563d67 Use stored alignment for the F-14A.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1689

(cherry picked from commit 2699a38f7b)
2021-10-30 15:05:28 -07:00
MetalStormGhost
f44654f66e Use Chinese navy group generators for China.
Replaced Chinese factions' Type54GroupGenerator naval group generators with
ChineseNavyGroupGenerator to make Type 52B and Type 52C destroyers also
spawn besides frigates.

(cherry picked from commit 13d52803d6)
2021-10-30 15:04:05 -07:00
MetalStormGhost
ca7f61c938 Added H-6J support for China 2010 and Iraq 1991.
Includes H-6J loadouts by @Starfire13

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1661

(cherry picked from commit 49033f67f3)
2021-10-30 15:03:22 -07:00
MetalStormGhost
10ccada17a Marianas campaigns 2.7.7.14727
Updated Marianas Mount Barrigada and Landing at Agat campaigns to DCS World 2.7.7.14727 open beta.

(cherry picked from commit 410077467b)
2021-10-30 15:03:18 -07:00
Dan Albert
46bf952562 Add Forrestal support, use in US 1975.
https://github.com/dcs-liberation/dcs_liberation/issues/1657
2021-10-22 10:11:15 -07:00
Dan Albert
822d737f65 Adapt to pydcs update.
https://github.com/dcs-liberation/dcs_liberation/issues/1657
2021-10-22 00:13:33 -07:00
Dan Albert
d656ec3220 Update pydcs.
https://github.com/dcs-liberation/dcs_liberation/issues/1657
2021-10-22 00:10:20 -07:00
Dan Albert
a2140b915f Flip main/detail text boldness.
Emphasize the main item text and leave the fine print as fine print.
2021-10-21 22:27:35 -07:00
Dan Albert
6dae5b98d5 Fix carrier option not taking effect this turn.
This really shouldn't need to happen but I don't feel like rewriting the
culling code right now. There's no reason for these to be persisted to
the Game at all, we should be generating these once they're needed.
2021-10-21 20:05:07 -07:00
Dan Albert
626740366b Port the mission generator settings to auto.
Done now. Not porting the cheat menu because it contains non-settings
elements as well.
2021-10-21 19:54:58 -07:00
Dan Albert
a618f00662 Port the campaign management page to auto.
Also fixes the oversight in the previous commit where float options were
not saved when changed.
2021-10-21 19:16:47 -07:00
Dan Albert
7bec4c62f7 Generate settings pages automatically.
This adds metadata to settings fields that can be used to automatically
generate the settings window. For now I have replaced the Difficulty
page. Will follow up to replace the others.
2021-10-21 18:30:56 -07:00
Dan Albert
39fae9effc Update MissionScripting.original.lua.
We don't really even need this. Some cleanup of the replacer could just
keep the original contents in memory, but this will do for now.
2021-10-21 15:50:52 -07:00
Dan Albert
3c145cf2ff Updates for Fuzzle's campaigns and squadrons.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1664
2021-10-21 15:23:49 -07:00
Dan Albert
ad6f3ef8cc Update for Northern Russia campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1663
2021-10-21 15:22:18 -07:00
MetalStormGhost
79839f83a0 Change AI Su-33 carrier flights to "Takeoff from runway".
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1352
2021-10-20 19:11:22 +00:00
Johan Aberg
17011820de Fix crash if log window is open when entering mission.
Use signal to append text to LogWindow to avoid crash from crossing thread boundaries.
Change modal flag to enable interacting with LogWindow while the mission is running

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1493
2021-10-19 17:04:16 -07:00
Dan Albert
551ea728fc Update Skynet to 2.3.0.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1658
2021-10-18 17:02:14 -07:00
Dan Albert
d4f77f6588 Fix changelog sorting. 2021-10-18 17:01:32 -07:00
Dan Albert
8fe7551176 Update pydcs with radio preset fix.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1596
2021-10-18 16:57:43 -07:00
Dan Albert
e47276ce2e Fix config file name. 2021-10-17 19:50:15 -07:00
Dan Albert
fd1463eb4c Disable the blank issue template.
Why do we even have that lever?
2021-10-17 19:38:45 -07:00
Dan Albert
d5eaa4d091 Add a preferred_start_date for campaigns.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1079
2021-10-17 17:37:23 -07:00
Dan Albert
b174e668f4 Fix day being off-by-one on turn zero.
Doesn't have any real effect since no mission can be generated for that
turn, but shows up wrong in the top bar.
2021-10-17 17:33:29 -07:00
Dan Albert
fd49d213c2 Load custom campaigns from the user directory.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1311
2021-10-17 16:48:19 -07:00
Dan Albert
bbeb80fc48 Give aircraft purchase the majority of the window.
This makes long squadron names more likely to fit. I also added a
horizontal scroll bar for the cases when this still isn't enough space
and made the vertical scroll bar only appear when necessary. Typically
aircraft purchase menus are neither wide enough for long enough to need
either scroll bar.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1592
2021-10-17 13:28:02 -07:00
Dan Albert
702e29b54b Fix case of unused aircraft not spawning.
This function was exiting too early causing unused aircraft to stop
being spawned at *any* airfield as soon as the first full airfield was
found.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1566
2021-10-17 13:03:15 -07:00
Dan Albert
0fd911feb1 Fix some CAS planning quirks.
CAS would never be planned for turn 0 because there were no enemy ground
units, so a breakthrough attack was planned and CAS was considered
unnecessary. Fix that by rejecting all frontline stance tasks when there
are no *friendly* ground units to command.

Another issue is that CAS missions were being planned even when there
were no enemy front line forces. Skip planning in that case except on
turn 0 since we expect there to be enemy ground units on turn 1.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1629
2021-10-17 12:31:12 -07:00
Dan Albert
39234adff7 Update Allied Sword campaign miz.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1655.
2021-10-17 11:27:07 -07:00
Dan Albert
e45505b406 Note PR #1600 in the changelog. 2021-10-17 11:23:24 -07:00
Dan Albert
b1eb876572 Note PR #1646 in the changelog. 2021-10-17 11:21:45 -07:00
Dan Albert
7e66aa16f7 Fix submerged ammo depot in Black Sea.
Not sure if this was originally an accidental extra ammo depot or if it
was intended to belong to Sochi, but I've moved it to Sochi to increase
the difficulty at the first front.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1644
2021-10-17 11:16:40 -07:00
Dan Albert
35b30a01ed Fix flight resizing when switching aircraft.
No idea why we were only resetting this if the max was >= 2. Instead,
always reset the flight to the default size when switching aircraft. The
default for anything capable of a two-ship is two, but limit based on
the airframe's group size limit and the number of aircraft available.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1593
2021-10-14 21:03:55 -07:00
Dan Albert
76b3ff5f6e Override squadron base preferences when named.
This allows campaign designers to forcibly place specific squadrons at
bases that they would not normally be assigned to, such as assigning
CV-only squadrons to the shore. The airframe itself must be compatible
with the location type, so A-10s still may not be assigned to carriers.

This change only applies to squadrons that are named explicitly. There's
no need for squadrons defined by type because a squadron will always be
generated to fit the need if no pre-defined squadron is found.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1621
2021-10-14 20:49:18 -07:00
Starfire13
5e5f249bd2 Starfire's Campaigns 9.0 Update (#1654) 2021-10-13 22:51:13 -07:00
Dan Albert
ce57acb9d6 Update Fuzzle's campaigns and supporting content.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1651
2021-10-13 17:45:49 -07:00
MetalStormGhost
2a79e4a4e5 Force carrier planes to start at +1s (#1600)
Forces carrier planes with original start_time of zero seconds to have a start time of 1 second. This will prevent them from spawning on the 'sixpack' and functions as a workaround for a DCS problem (deadlock / traffic jam).

Fixes #1309.
2021-10-13 17:10:17 -07:00
ghost
7f948465a4 Added a missing call to commit_cargo_ship_losses when committing mission results, fixing a problem which caused lost ground units on sinked cargo ships to not register. 2021-10-13 17:04:49 -07:00
ghost
a24ab63fc7 Changed "range" to "max_range" on several aircraft .yaml files since that is the key which is actually evaluated in the code. 2021-10-13 17:03:59 -07:00
MetalStormGhost
643718be23 Two Marianas Guam campaigns (#1652)
This PR contains two new campaigns for the Marianas terrain, depicting capture of the island of Guam. The first has BLUFOR start after landing at Agat and requires a carrier/LHA capable BLUFOR faction, because there are no land based airbases captured initially. The second has about half of the island already in control, enabling BLUFOR land based aircraft to operate from Antonio B Won Pat (and can also be used by WWII factions). Both campaigns support inversion.

Credit to Dank Williams, the campaigns were heavily inspired by his Marianas insurgency campaign and contain some ground units placed by him, used with permission of course.

They are by no means historical and contain a relatively large number of FOBs compared to only having two airfields. The routes zig-zag a bit since space is limited on the island and I had to place the FOBs far enough from each other to clear the capture zone radius.

The two other airfields on Guam, Orote and Andersen Northwest Field, have FARPs, enabling helicopter operations as well as rearming and refueling for player fixed wing flights (but no mission starts or AI takeoffs).

Included are also two WWII factions which don't require the WWII asset pack. The "Japanese" faction consists of German/Russian equipment with stock Japanese liveries.
2021-10-13 17:01:54 -07:00
C. Perreau
d4d6ee3d26 Merge pull request #1645 from MetalStormGhost/mi24_hind_campaign_squadrons
Changed the Mi-24 squadrons of 2 campaigns
2021-10-12 22:29:57 +02:00
Khopa
4399e10cef SA-5 support 🚀 2021-10-12 22:26:59 +02:00
ghost
519f0542dd Changed the Mi-24 squadrons of 2 campaigns from:
- Mi-24P Hind-F
        - Mi-24P Hind-E
to:
        - Mi-24P Hind-F
        - Mi-24V Hind-E
fixing a problem which caused Mi-24V no not show up in the campaign.
2021-10-08 20:42:28 +03:00
Khopa
9456fd77d1 Updated Mozdok to Maykop campaign to v9 2021-09-21 22:27:50 +02:00
Khopa
37874d82f2 Pydcs : Switched to the pydcs version from the official repo 2021-09-21 21:24:44 +02:00
Khopa
9f2a9bf458 pydcs version : Use temporary version with mosquito flyable fix 2021-09-19 23:30:57 +02:00
Khopa
43a8897c28 Added MosquitoFBMkVI support (use campaign operation dynamo) 2021-09-19 02:05:08 +02:00
Khopa
6980f96697 JAS-39 mod : removed reference to a weapon class that was removed in last update 2021-09-18 18:51:54 +02:00
Khopa
4ffb294d65 Update pydcs version 2021-09-18 18:01:17 +02:00
C. Perreau
ae46631b2b Merge pull request #1622 from teamMOYA/banners_icons
Banners and icons
2021-09-18 17:49:07 +02:00
teamMOYA
c42bdd256f fix wrong extension 2021-09-18 15:32:42 +02:00
teamMOYA
8990e0c1ff leopard-2A4 banner fix 2021-09-18 15:27:09 +02:00
teamMOYA
f26452c07d vehicle banners 2021-09-18 15:10:44 +02:00
teamMOYA
89789f16d2 f-86 icon fix 2021-09-18 15:09:05 +02:00
teamMOYA
3bb4c9c29a aircrafts banners 2021-09-16 22:26:17 +02:00
teamMOYA
3b8e392395 aircrafts icons 2021-09-16 22:24:47 +02:00
Magnus Wolffelt
3e6d63e8f7 Fix random heading function, randomize wind better (#1619)
* Fix random heading function, randomize wind better

* Use 359 as max default for random heading, for uniform distribution
2021-09-16 12:29:00 +02:00
Khopa
90ca619839 Load red static group to define helipads for farp 2021-09-14 22:22:46 +02:00
Starfire13
8c2aa78b9f Add missing data to Frenchpack technicals. 2021-09-10 15:34:57 -07:00
Starfire13
e544b2d1ba Mirage Squadron Mission Types Fix (#1607)
* Update ADA_EscadronDeChasse_1-30_Alsace.yaml

* Update ADA_EscadronDeChasse_2-5_IleDeFrance.yaml

* Update ADA_EscadronDeChasse_1-12_Cambresis.yaml
2021-09-09 09:52:26 -04:00
C. Perreau
82f5287282 Merge pull request #1183 from dcs-liberation/helipads
[WIP] Add possibility to add helipads to FOB control points
2021-09-08 22:54:05 +02:00
C. Perreau
589a353f02 Merge pull request #1603 from teamMOYA/bugfix/helicopter_carrier-Type_071
fix for Type_071 helicopter carrier
2021-09-08 22:47:37 +02:00
Khopa
e84e36fd22 Merge remote-tracking branch 'khopa/develop' into helipads
# Conflicts:
#	changelog.md
2021-09-08 21:56:45 +02:00
dependabot[bot]
a4b03c5cfe Bump pillow from 8.2.0 to 8.3.2
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.2.0 to 8.3.2.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.2.0...8.3.2)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-09-07 20:00:45 -07:00
teamMOYA
6aee4c2ec4 fix for Type_071 helicopter carrier
fixed bad name for Type_071 helicopter carrier
2021-09-07 11:59:36 +02:00
Starfire13
65abef7979 Update squadrondefgenerator.py 2021-09-07 02:37:25 -07:00
Dan Albert
45b52f4dea Remove auto-loss on front line for skipped turns. 2021-09-05 21:19:36 -07:00
Dan Albert
18336f58d3 Minor cleanup of notification system. 2021-09-05 21:15:32 -07:00
Dan Albert
12ad4fbf63 Note the FC3 laser codes in the changelog. 2021-09-05 02:13:13 -07:00
MetalStormGhost
b1fee9fe56 Add an option to use FC3-compatible laser codes.
FC3 aircraft don't have laser codes like all the other aircraft do, they just use 1113.
2021-09-05 02:10:24 -07:00
Dan Albert
2a6f250706 Fix transcription error in Abu Dhabi. 2021-09-04 14:20:29 -07:00
Dan Albert
ab2bb6814e Clean up aircraft allocation and procurement.
This also does improve the over-purchase problems, though I can't spot
the behavior change that's causing that. Presumably the old
implementation had a bug I can't spot and in rewriting it I solved the
problem...

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1582
2021-09-03 17:08:32 -07:00
Dan Albert
94fb0d8c66 Don't create squadrons for removed bases. 2021-09-03 15:25:34 -07:00
Dan Albert
a192e4c872 Allow showing the enemy aircraft inventory. 2021-09-03 13:56:03 -07:00
Dan Albert
99acd52e89 Increase some range estimates.
These are still fairly pessimistic because the AI loves afterburner, but
less so.
2021-09-03 13:33:15 -07:00
Dan Albert
a1ee9d7476 Add more aircraft range estimates. 2021-09-03 13:23:23 -07:00
Dan Albert
757363e372 Fix JSON -> YAML translation error in Black Sea. 2021-09-03 13:14:38 -07:00
Dan Albert
7d0b3a096d Update Abu Dhabi. 2021-09-03 13:14:16 -07:00
Starfire13
24a0211d8c Update naming.py 2021-09-02 04:06:44 -07:00
Dan Albert
2c8f960696 Prevent creating empty ferry packages.
An empty squadron or a fully-assigned squadron won't have anything to
assign to the ferry mission.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1588
2021-09-01 19:22:37 -07:00
Dan Albert
16d397db1c Fix unit info menus for aircraft.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1586
2021-09-01 19:22:37 -07:00
Dan Albert
9c3171f1ce Sort the animal names list.
Make it easier to figure out what's already there.
2021-09-01 18:01:53 -07:00
Dan Albert
8a60fa5c83 Fix errors when changing task or aircraft type.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1587
2021-09-01 17:14:51 -07:00
Magnus Wolffelt
15ce48e712 Arm the ferry viper :) (#1584) 2021-09-01 21:56:11 +02:00
Dan Albert
c252fd6a77 Add a ferry loadout for the viper. 2021-08-31 23:13:02 -07:00
Dan Albert
90a8bb63dc Fix AI landing behavior.
The landing waypoints need the airdrome_id field set to actually
associate with the airfield. Without this ferry flights will take off
and immediately land at their departure airfield.
2021-08-31 23:06:20 -07:00
Dan Albert
1a4be911c0 Implement ferry flights for squadron transfers.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1145
2021-08-31 23:03:27 -07:00
Dan Albert
f9f0b429b6 Set the flight airfields based on the Squadron. 2021-08-31 22:14:00 -07:00
Dan Albert
a404792bd2 Reset the max flight size when changing squadrons. 2021-08-31 22:10:23 -07:00
Dan Albert
e0047b1bbc Move the start type requirement into ControlPoint. 2021-08-31 22:09:39 -07:00
Dan Albert
18eb661e84 Merge branch 'squadron-relocation' into develop 2021-08-29 16:22:02 -07:00
Dan Albert
c2e5cba061 Implement manual squadron transfers.
Lightly tested but seems to work fine.

https://github.com/dcs-liberation/dcs_liberation/issues/1145
2021-08-29 16:21:54 -07:00
Dan Albert
cd15de6d42 Add an uncaught exception handler. 2021-08-29 16:21:54 -07:00
Mustang-25
60a5ee42fe Adds Most Default USN F-14A & B Squadrons 2021-08-29 15:26:44 -07:00
Mustang-25
46e2d8c1f9 Adds All Default USAF F-15E Squadrons 2021-08-29 15:26:44 -07:00
Mustang-25
824745c11d Adds All Default A-10C I & II Squadrons 2021-08-29 15:26:44 -07:00
Mustang-25
33709b0558 Adds All Default USAF F-15C Squadrons 2021-08-29 15:26:44 -07:00
Mustang-25
aac91c15d9 Adds AEW&C Squadrons 2021-08-29 15:26:44 -07:00
Mustang-25
67405e4af5 Adds Tanker Squadrons 2021-08-29 15:26:44 -07:00
Mustang-25
41aa743947 Adds all default USAF Viper Squadrons 2021-08-29 15:26:44 -07:00
Mustang-25
7aca108ef5 Adds Russian VVS Mig-29S Squadrons 2021-08-29 15:26:44 -07:00
Dan Albert
380d6bf47a Fix weird wrong default campaign field bug.
I tried fixing this using setField after registering it, but it does
nothing. I suspect this is because the page hasn't been registered with
the wizard yet so it's setting the field for the wrong wizard.
2021-08-29 02:17:10 -07:00
Dan Albert
8fea8e7b47 Move squadron end-turn behavior into the squadron. 2021-08-28 18:03:33 -07:00
Dan Albert
469b1e5efe Reimplement aircraft retreats for captured bases. 2021-08-28 18:02:11 -07:00
Dan Albert
5fae178081 Reduce squadron location bookkeeping. 2021-08-28 17:59:56 -07:00
Dan Albert
4715773bba Store the owning coalition in ControlPoint.
This is needed fairly often, and we have a lot of Game being passed
around to ControlPoint methods specifically to support this. Just store
the owning Coalition directly in the ControlPoint to clean up. I haven't
cleaned up *every* API here, but did that aircraft allocations as an
example.
2021-08-28 16:40:55 -07:00
Dan Albert
74577752e0 Update pydcs for the Viper CBU-105. 2021-08-26 23:59:29 -07:00
Magnus Wolffelt
056e6b28da Simplify and rename TACAN registry reserve function (#1559)
* Simplify and rename TACAN registry reserve function

* Remove unused tacan error
2021-08-18 14:46:55 +02:00
Nils Heiden
0cb10e4224 Make the Mi-24 LHA capable. 2021-08-17 17:00:16 -07:00
Magnus Wolffelt
34ff5fbc6a Allow operation.py to ignore TACAN rules 2021-08-18 00:06:34 +02:00
Magnus Wolffelt
f63a35b1fa Use TACAN channels more selectively, use pytest (#1554)
* Use TACAN channels more selectively

* Increase tacan range to 126

* Use pytest and add workflow

* Skip faction tests due to outdated test data

* Run mypy on tests directory also

* Use iterators for bands AND usages, add tests
2021-08-17 23:14:54 +02:00
Khopa
57e78d5c55 Added squadrons for Syria & Israel 2021-08-16 19:47:40 +02:00
Khopa
2ee604d2a4 Fixed : Missing icons for E-2C Hawkeye 2021-08-16 19:47:38 +02:00
Khopa
a7c3a0f7fd Added squadrons for Syria & Israel 2021-08-16 19:47:00 +02:00
Khopa
5445c41f81 Fixed : Missing icons for E-2C Hawkeye 2021-08-16 19:45:43 +02:00
Khopa
e1e1e471a1 Added comment on total_aircraft_parking 2021-08-16 19:37:21 +02:00
Khopa
2e3b43b28b Allow both FARP SINGLE_HELIPAD, and Invisible FARP in campaigns files. 2021-08-16 13:27:41 +02:00
Khopa
fe118d81db Fixed error introduced during last merge. (Missing import) 2021-08-16 13:04:58 +02:00
Khopa
d3b2a751e2 Golan heights campaign migrated to v 9.0 2021-08-16 12:58:26 +02:00
Khopa
b856a84adc Ran black to fix lint issue. 2021-08-16 12:23:51 +02:00
C. Perreau
707d13a65c Merge branch 'develop' into helipads 2021-08-16 12:20:43 +02:00
Magnus Wolffelt
7417429fdb Merge pull request #1552 from dcs-liberation/better-tarcap-racetracks-2
Better TARCAP racetracks
2021-08-16 11:52:50 +02:00
Magnus Wolffelt
8f5b6f58d1 Add rmul to distance and speeds, so that reversed operands work 2021-08-16 10:38:26 +02:00
Magnus Wolffelt
08365bcbda Simplify and enhance tarcap flight planning 2021-08-16 10:37:44 +02:00
Dan Albert
4423288a53 Assign aircraft to squadrons rather than bases.
This is needed to support the upcoming squadron transfers, since
squadrons need to bring their aircraft with them.

https://github.com/dcs-liberation/dcs_liberation/issues/1145
2021-08-15 17:42:56 -07:00
Dan Albert
99274133ff Add range estimates for the F-15s. 2021-08-14 21:51:25 -07:00
Dan Albert
55c6728c42 Update Black Sea to campaign version 9.0. 2021-08-14 21:51:01 -07:00
Dan Albert
357487b767 Remove random purchase pessimization.
Aircraft variety is now handled by explicit squadron selection, so no
longer needed.
2021-08-14 21:46:27 -07:00
Dan Albert
9768fb3493 Add base selection UI to startup.
https://github.com/dcs-liberation/dcs_liberation/issues/1145
2021-08-14 21:46:27 -07:00
Dan Albert
90ad1f4a61 Change squadrons to operate out of a single base.
https://github.com/dcs-liberation/dcs_liberation/issues/1145

Currently this is fixed at the start of the campaign. The squadron
locations are defined by the campaign file.

Follow up work:

* Track aircraft ownership per-squadron rather than per-airbase.
* UI for relocating squadrons.
* Ferry missions for squadrons that are relocating.
* Auto-relocation (probably only for retreat handling).

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1138
2021-08-14 21:46:27 -07:00
Dan Albert
51e056a765 Convert Black Sea to yaml. 2021-08-14 20:15:05 -07:00
Dan Albert
8e1b33bc51 Add range info for some Russian aircraft. 2021-08-14 20:12:33 -07:00
Dan Albert
d2e22ef8bf More campaign loader cleanup. 2021-08-14 13:39:27 -07:00
Magnus Wolffelt
103675e5bb Make some paths cross-platform compatible (#1543)
* Make some paths cross-platform compatible

* Fix lint error for Path
2021-08-14 21:45:23 +02:00
RndName
b5b0d82a1a Open all files with utf-8 encoding
- will not be used for binary read/writes (rb,wb)!
- prevents a bug where units with special characters in the unit name can not be tracked anymore as there will be a name mismatch due to wrong encoding
2021-08-14 13:10:43 +02:00
Magnus Wolffelt
c80d0e5378 Raise helo AGL to 60 m for ingress, egress, cap, escort (#1542) 2021-08-14 00:54:48 +02:00
RndName
adeebbc422 Enable sell button according to available aircraft
also added a tooltip which gives the user the hint that maybe the aircraft is assigned to mission and therefore the button is disabled
2021-08-12 22:06:48 +02:00
RndName
ee8e8d4a9a Fix selling of units not visible
allow pending_deliveries to become negative again but still delete the delivery when the amount of a specific unit_type comes to exactly 0 to prevent emtpy group sizes
2021-08-12 19:42:40 +02:00
RndName
bc5ffdec8e EWR heading towards conflict
implements #1530
2021-08-11 20:58:54 +02:00
Dan Albert
88d52003b3 Allow using yaml for campaign definitions.
JSON continues to be supported as well. No additional work needed here,
just needed to allow both.
2021-08-10 18:21:52 -07:00
Dan Albert
6c7b62b8b1 Move MizCampaignLoader out of conflicttheater.py.
Also removes the useless `size` and `importance` fields from
`ControlPoint`.
2021-08-10 18:21:26 -07:00
Magnus Wolffelt
37491ceffb Stop using Su-34 for CAP missions, update changelog 2021-08-10 13:38:35 +02:00
Magnus Wolffelt
b3dedbdf75 Update changelog with sam site heading fix 2021-08-10 13:32:58 +02:00
Magnus Wolffelt
42d09292b7 Update changelog with Marianas fix for 4.1.1 2021-08-10 13:32:12 +02:00
Dan Albert
c80293d9e0 Add a bug template for mod support requests. 2021-08-08 12:58:04 -07:00
RndName
b31c09c4ff Fix AAA Flak generator using wrong index
- Fixes #1519 as the Opel Blitz unit generator was using the index without incrementing it
2021-08-08 13:16:39 +02:00
Dan Albert
91daabc9d2 Fixup auto-assignable tasks when limits change.
The air wing config was fixing the main `mission_types` field, but the
`auto_assignable_mission_types` property had already been set. Update
that field whenever the `mission_types` are changed.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1515
2021-08-07 14:04:32 -07:00
Kangwook Lee
def5454e5f Add battle damage assessment option 2021-08-07 13:11:10 -07:00
Kangwook Lee
74e6226d13 Fix typo 2021-08-07 13:03:13 -07:00
Kangwook Lee
72d83e2fe4 Reorganize setting fields to match UI 2021-08-07 13:00:22 -07:00
Dan Albert
85ccbf34c7 Add fuel esimtations for the Viper. 2021-08-06 19:24:07 -07:00
Khopa
5e715daded Changed helipad generation structure as to not impact "Game" object, as suggested by Dan. 2021-08-07 01:05:57 +02:00
Khopa
5412487178 Handle another error case in generate_at_cp_helipad + align helos heading with their slot 2021-08-07 00:38:12 +02:00
Khopa
c4937e95e9 Refactored the helipad generation code in a dedicated method "_generate_at_cp_helipad" + better error handling + removed useless temp variables 2021-08-07 00:16:07 +02:00
Khopa
4f53e2beea Fixed another minor issue with the PR 2021-08-07 00:12:55 +02:00
Khopa
9ea1edf9db Applied minor requested changes 2021-08-06 23:55:58 +02:00
Khopa
ce1c416b20 Revert version bump for campaign that do not use helipads 2021-08-06 23:28:36 +02:00
Magnus Wolffelt
fdbc3c55c7 Add weather changes to changelog (#1513)
Co-authored-by: Magnus Wolffelt <magnus.wolffelt@avanza.se>
2021-08-06 18:17:46 +02:00
Magnus Wolffelt
71559154a8 Cherry-pick cap/helo changelog from 4.x (#1512)
* Changelog updates for 4.x.

Regarding patrol speeds and helo fix.

* Update changelog for 4.x

BAI missions are actually planned at low altitude. The problem remaining is that they have join/hold/split waypoints, which makes the flight times _incredibly_ long for these slow movers.
2021-08-06 18:01:24 +02:00
Dan Albert
07f8a203ea Remove abandoned campaigns. 2021-08-05 19:32:52 -07:00
RndName
b67fd16081 tweak the airlift procurement
- only buy airlift capable aircraft if there is one friendly cp without a factory which can only be reached via airlift
- prevent that an airlift procurement gets fulfilled at a different cp than the requesting one. this ensures that the cp also has a factory to produce ground units which can then be transported
- fixes an infinite buy loop if the fulfilling cp has no factory and the requesting cp has no space for airlift
- have always 2 reserve transport planes at the biggest CP
2021-08-05 22:09:53 +02:00
Magnus Wolffelt
9792c17c69 Make arid theaters more likely to have clouds, and tweak others sliiightly (#1501) 2021-08-05 13:54:42 +02:00
Magnus Wolffelt
8488a5ec1a Use AGL altitude for helo hold (#1499) 2021-08-05 13:52:33 +02:00
Dan Albert
ff571db494 Update Syria Full and Humble Helper campaigns.
https://github.com/dcs-liberation/dcs_liberation/issues/1494
https://github.com/dcs-liberation/dcs_liberation/issues/1497
2021-08-04 23:33:22 -07:00
Kangwook Lee
aaa932f725 Update freq list for ARC-210 2021-08-04 20:40:47 -07:00
Kangwook Lee
c58ecd96f0 Make Radio dataclass store list of ranges 2021-08-04 20:40:47 -07:00
Kangwook Lee
8608b73009 Wrap lines for NotesPage 2021-08-03 17:53:01 -07:00
Magnus Wolffelt
30801dff9f Use more sensible patrol speeds for CAP, and fix is_helo (#1492)
* Use more sensible patrol speeds for CAP, and fix is_helo
2021-08-03 12:22:55 +02:00
Khopa
912311ad55 changelog update 2021-08-03 01:32:10 +02:00
Khopa
14615f9976 Bump campaign miz file version for helipad support 2021-08-03 01:10:00 +02:00
Khopa
9121cf7ecb Fixed icons not appearing in UI for Mi-24V, Tu-95 and Tu-142 2021-08-03 01:05:27 +02:00
Khopa
a831800a05 Fixed mypy errors 😒 2021-08-03 01:00:56 +02:00
Khopa
399c739fd7 Fixed mypy errors 2021-08-03 00:51:47 +02:00
Khopa
63f687a20e Fixed mypy errors in gen 2021-08-03 00:42:49 +02:00
Khopa
fbd0198771 Fixed mypy errors 2021-08-03 00:37:26 +02:00
Khopa
00e85280fd Golan heights campaign updated with helipads. 2021-08-03 00:29:06 +02:00
Khopa
5b37698d36 Fixed mypy errors 2021-08-03 00:28:22 +02:00
Khopa
483640b0c6 Fixed errors after merge on helipad feature. 2021-08-03 00:15:14 +02:00
Khopa
1e96aad484 Fixed icons not appearing in UI for Mi-24V, Tu-95 and Tu-142 2021-08-02 23:51:56 +02:00
Khopa
b88e0e8a52 Merge branch 'develop' into helipads
# Conflicts:
#	resources/squadrons/A20/no_107_squadron_raf.yaml
#	resources/squadrons/SpitfireLFMkIX/no_145_squadron_raf.yaml
#	resources/squadrons/SpitfireLFMkIX/no_16_squadron_raf.yaml
2021-08-02 22:05:36 +02:00
Khopa
6028009aac Added RAF clipped wing spitfire squadron 2021-08-02 22:00:17 +02:00
Khopa
9aa9b72557 Fixed issue with previously added squadrons 2021-08-02 21:57:50 +02:00
Khopa
8c023c5727 Added Ju-88A4 squadron 2021-08-02 21:57:27 +02:00
Khopa
d9edaede89 Added FW-190D9 squadron 2021-08-02 21:57:10 +02:00
Khopa
0220b37c2d Added FW-190A8 squadron 2021-08-02 21:57:00 +02:00
Khopa
f2d2d1cc8d Added Bf-109K4 squadron 2021-08-02 21:56:47 +02:00
Khopa
437eeef9a0 Fixed icon not showing for Ju 88 A-4 2021-08-02 21:15:22 +02:00
Khopa
8e4f291389 Added Spitfire LF Mk IX's squadrons for RAF 2021-08-02 21:08:07 +02:00
Khopa
8f27222b07 Added A-20G squadron for RAF 2021-08-02 21:08:05 +02:00
Khopa
9e05991908 Fixed issue with livery in custom M2000-C squadron 2021-08-02 21:08:05 +02:00
Khopa
1c76bf93a2 Added Spitfire LF Mk IX's squadrons for RAF 2021-08-02 20:00:14 +02:00
Khopa
d5cedee6c5 Added A-20G squadron for RAF 2021-08-02 19:59:13 +02:00
Khopa
eb1b7176a6 Fixed issue with livery in custom M2000-C squadron 2021-08-02 19:46:07 +02:00
Khopa
71143536bf Merge branch 'develop' into helipads
# Conflicts:
#	game/game.py
#	game/operation/operation.py
#	game/theater/conflicttheater.py
#	game/theater/controlpoint.py
#	gen/groundobjectsgen.py
#	resources/campaigns/golan_heights_lite.miz
2021-08-02 19:34:05 +02:00
Khopa
f2608cecd5 Campaign Update 8.0 : operation_dynamo.miz, updated mission targets ids 2021-08-02 19:24:34 +02:00
Khopa
c95d5464d8 Campaign Update 8.0 : golan_heights_lite.miz, updated mission targets ids 2021-08-02 19:21:09 +02:00
Khopa
0ac7466a81 Campaign Update 8.0 : caen_to_evreux.miz, updated mission targets ids 2021-08-02 19:15:31 +02:00
Kangwook Lee
77e62d5a54 Fix text foreground color for dark kneeboard 2021-08-01 23:37:10 -07:00
Dan Albert
bef015eb57 Changelog updates for 4.x. 2021-08-01 17:27:01 -07:00
Kangwook Lee
d99d95217f Remove console window 2021-08-01 15:42:14 -07:00
Kangwook Lee
5cbf8db272 Add QLogsWindow 2021-08-01 15:42:14 -07:00
Kangwook Lee
6ee0c7600b Add HookableInMemoryHandler logging handler 2021-08-01 15:42:14 -07:00
Magnus Wolffelt
6621421a6f Tweak max-speed-based patrol altitudes 2021-08-01 15:21:32 -07:00
Dan Albert
edf95ea9fb Dedup purchase requests.
Since the theater commander runs once per campaign action, missions that
do not have aircraft available may be checked more than once a turn.
Without deduping requests this can lead to cases where the AI buys
dozens of tankers on turn 0.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1470
2021-08-01 15:17:43 -07:00
Magnus Wolffelt
a3e3e9046f Estimate preferred patrol altitude based on max speed 2021-08-01 12:15:15 -07:00
RndName
04cdb6fbfc fix for wrong patrol speed 2021-08-01 12:05:28 -07:00
bgreman
8c7e56a2bd Update skynet plugin (#1478) 2021-08-01 11:36:37 -04:00
Dan Albert
3e08574fbe Reduce the size of kneeboard non-table text.
The bullseye and weather data were looking a bit more like headers than
content.
2021-07-31 16:54:00 -07:00
Dan Albert
73ba7933da Assign laser codes to players with TGPs.
This doesn't configure the bombs in the mission or anything yet; it only
pre-assigns a laser code for the player to use if they choose to.
2021-07-31 16:49:58 -07:00
bgreman
fc45c3b98c Fixes an unlikely bug with JTAC laser code allocation (#1477)
* Fixes an unlikely bug with JTAC laser code allocation, allows for future allocation of codes to a/c with TGPs

* Fixing typing issues

* Changelog
2021-07-31 18:44:16 -04:00
Mustang-25
0d6f420f97 Rebalanced Aircraft Planning Hierarchies
CAP List:
[+] Mig-21 #1372
[+] Su-34
[moved up] F-15C above the F-14 (probably contentious to some but IMO the AI never capitalizes on the AIM-54 range and the Eagle AI seems to do better in general)
[moved up] JF-17
[moved up] Gripen
[moved down] Su-33
[moved down] Su-27
[moved down] MiG-31
[moved down] MiG-25
[moved down] MiG-29G
[moved down] MiG-29A

* Downgraded MiGs and Sukhois that do not have Fox-3s due to this disadvantage. From personal experience, the 31s and 25s also won't use the longer range of their Fox-1s to warrant for a higher spot on the list.

CAS/BAI List:
[+] Su-33 #1367
[-] Su-24MR (dedicated recce platform, no AG munitions)
[moved up] Su-34
[moved down] Mig-19P
[moved down] UH-1

Strike List:
[-] Su-24MR (dedicated recce platform, no AG munitions)
[moved up] JF-17
[moved up] Harrier

Runway Attack List:
[+] Mirage 2000C
2021-07-31 14:57:49 -07:00
Dan Albert
bef85963a6 Update USN 2005 faction.
https://github.com/dcs-liberation/dcs_liberation/issues/1427
2021-07-31 14:47:13 -07:00
Dan Albert
3be57efa97 Campaign updates from Starfire. 2021-07-31 14:40:38 -07:00
Dan Albert
981d8510c2 Ack new campaign version for unaffected maps. 2021-07-31 14:37:49 -07:00
Dan Albert
5d8f655243 Work around pydcs bug.
https://github.com/pydcs/dcs/issues/175 causes setting the AI comm
frequency to raise an exception for aircraft without preset channel
support.
2021-07-31 14:23:46 -07:00
Dan Albert
0cb41469ab Update pydcs to latest master.
https://github.com/dcs-liberation/dcs_liberation/issues/1448
2021-07-31 13:54:17 -07:00
Dan Albert
971d7e730a Add ALIC codes for the tin shield and NASAMS.
https://github.com/dcs-liberation/dcs_liberation/issues/1448
2021-07-31 13:53:04 -07:00
Dan Albert
06f8b9b817 Update the F-16 DEAD loadout to use JSOWs.
https://github.com/dcs-liberation/dcs_liberation/issues/1448
2021-07-31 13:48:02 -07:00
Dan Albert
db51384b63 Add auto-generation warning to files. 2021-07-31 13:40:04 -07:00
RndName
ac088ea692 improved the validation for planned transfers
- instead of only checking if the transfer destination was captured it now checks if there is a valid route between origin and destination. This also ensures that there will be a check if the current position or next_stop was captured and therefore the transfer should be disbanded.
- disband uncompletable transfer before planning or performing (also when user cheated a base capture)
2021-07-31 13:27:48 -07:00
Dan Albert
2a5793e8ce Fix display of AEW&C channel on the kneeboard. 2021-07-31 13:04:42 -07:00
Dan Albert
6c60ff88a3 Fix intra_flight_channel filter syntax. 2021-07-31 13:00:14 -07:00
Dan Albert
8d68c10905 Set up JTAC channel assignments. 2021-07-31 13:00:14 -07:00
bgreman
119d4b9514 Vendor ruler (#1476)
* Fixes ruler module integrity issues by bringing module into source

* Changing ruler stylesheet to vaguely match DCS theme in Liberation

* Changelog
2021-07-31 15:43:48 -04:00
Kangwook Lee (이강욱)
0370aa8df5 Add AFAC task to JTAC unit.
This causes the JTAC unit that's used for autolase to also work as
a FAC over the radio.
2021-07-31 12:37:18 -07:00
Kangwook Lee (이강욱)
6034c899d3 Add flight intra radio channel to mission briefing (#1475) 2021-07-31 12:34:49 -07:00
bgreman
d2fe11ba6f Updates Gripen support, fixes missing DEAD legacy loadouts. (#1469) 2021-07-31 12:07:57 -04:00
bgreman
58c96e1329 Adds more details to frontline movement logging (#1465)
* adds more detailed logging for frontline movement

* Fixing attribute name

* Fixing if, adding else
2021-07-31 12:05:22 -04:00
Magnus Wolffelt
4c51b4b822 Seasonal weather types per theater.
Adjusts the weather conditions per theater and  per season.
2021-07-31 03:57:23 -07:00
C. Perreau
f5dea4935c Merge pull request #1467 from Mustang-25/develop
Increment Campaigns to v8.0
2021-07-31 00:13:45 +02:00
Mustang-25
0117ab8aa4 Increment to Campaign v8.0 2021-07-28 10:37:14 -07:00
Mustang-25
a5ade0c41a Increment to Campaign v8.0 2021-07-28 10:36:43 -07:00
Mustang-25
4df12ae675 Increment to Campaign v8.0 2021-07-28 10:36:17 -07:00
Mustang-25
274a41f052 Increment to Campaign v8.0 2021-07-28 10:35:12 -07:00
Mustang-25
3670c8f879 Increment to Campaign v8.0 2021-07-28 10:34:28 -07:00
Mustang-25
e88bb442f3 Increment to Campaign v8.0 2021-07-28 10:32:47 -07:00
Mustang-25
a0d1bf4b5c Merge branch 'dcs-liberation:develop' into develop 2021-07-28 10:31:31 -07:00
Khopa
32f05dccd9 Added Tin Shield EWR support 2021-07-28 00:15:00 +02:00
Khopa
4aac2d2b7b Added NASAMS support 2021-07-27 23:43:00 +02:00
Mustang-25
e5a40bfb69 Merge branch 'dcs-liberation:develop' into develop 2021-07-27 14:07:41 -07:00
C. Perreau
741ae36d4c Merge pull request #1459 from RndName/fix-empty-transfer
fix generation of empty transfer during cp capture
2021-07-27 22:54:51 +02:00
RndName
67fa4a8910 fix generation of empty transfer during cp capture
when a cp capture happens and the next cp has pending unit deliveries then they will be redeployed to the newly captured cp. The redeploy was drecreasing the num of pending unit deliveries for the old cp but was not removing them completly from the dict when all were removed
2021-07-25 15:24:16 +02:00
Dan Albert
80bf3c97b2 Remove the SA-10 from Syria 2011.
They didn't get this until a few years later. This was a stand-in for
the SA-5 that DCS doesn't have, but the SA-10 is so much more capable
that it's not a good replacement.
2021-07-24 15:10:22 -07:00
Dan Albert
9f23cb35a9 Update pydcs to latest master. 2021-07-24 15:09:35 -07:00
RndName
458de17b8f adopt sam heading to new heading class 2021-07-23 15:57:03 -07:00
RndName
dd50ee92a9 calculate heading to center of conflict for sams 2021-07-23 15:57:03 -07:00
bgreman
1094085872 Fixes #1449 and updates another area where the Heading class can apply (#1451) 2021-07-22 15:30:46 -04:00
Dan Albert
edbd3de4a4 Bump campaign version to 8.0 for latest DCS.
Building IDs changed again. Ack the change in my two campaigns which
don't use these target types.
2021-07-21 17:10:29 -07:00
bgreman
91d430085e Addresses #478, adding a heading class to represent headings and angles (#1387)
* Addresses #478, adding a heading class to represent headings and angles
Removed some unused code

* Fixing bad merge

* Formatting

* Fixing type issues and other merge resolution misses
2021-07-21 10:29:37 -04:00
Dan Albert
fab550157a Add a per-aircraft weapon linter.
Run with `main.py lint-weapons $AIRCRAFT` to show all the weapons the
aircraft can carry that do not have data.
2021-07-19 20:07:58 -07:00
Dan Albert
5e2ed04d72 Add weapon data for the CBU-87 and CBU-97. 2021-07-19 16:53:49 -07:00
Dan Albert
e87aa83666 Add CLI generator options for date restrictions. 2021-07-19 16:27:20 -07:00
Dan Albert
c9b6b5d4a8 Correct changelog. 2021-07-18 19:38:55 -07:00
Dan Albert
ce01ad2083 Default to aircraft at only appropriate bases. 2021-07-18 17:12:34 -07:00
Dan Albert
0eb8ec70d9 Make opfor airwing configurable. 2021-07-18 16:09:20 -07:00
Dan Albert
270f87f193 Add per-aircraft tabs to air wing configuration. 2021-07-18 15:49:58 -07:00
Dan Albert
c2951e5e41 Increase minimum hold distance.
The previous values were far too optimistic for a non-AB climb to hold
altitude, especially for the AI.
2021-07-18 14:52:12 -07:00
Dan Albert
e22e8669e1 Add fallback locations for join zones.
It's rare with the current 5NM buffer around the origin, but if we use
the hold distance as the buffer like we maybe should it's possible for
the preferred join locations to fall entirely within the home zone. In
that case, fall back to a location within the max-turn-zone that's
outside the home zone and is nearest the IP.
2021-07-18 14:52:12 -07:00
Dan Albert
2580fe6b79 Update the changelog. 2021-07-17 19:53:16 -07:00
Dan Albert
c11c6f40d5 Add minimum fuel per waypoint on the kneeboard. 2021-07-17 19:51:55 -07:00
Dan Albert
3c90a92641 Add fuel consumption data for the Hornet.
Will be used to calculate bingo and min remaining fuel for the
kneeboard.
2021-07-17 18:23:20 -07:00
Dan Albert
4c0a97e62f Log a warning for unknown max ranges. 2021-07-17 17:27:40 -07:00
Dan Albert
0a57bb5029 Increase airfield distance in Battle of Abu Dhabi.
Removes some of the low capacity airfields from the campaign now that
missions can plan longer ranges if needed.

This removes Khasab, Bandar Lengeh, and Qeshm from the blue side, so
blue no longer has any airfields on the peninsula.

The CVN has moved quite a ways west to make it a good platform for
attacking the area around Dubai, and to prevent it from being the
primary mission source (with a 90 aircraft limit, a *lot* of missions
can get planned there before other airbases will be used).

The LHA moves to near where the CVN was, making it a good platform for
early game missions. Once the LHA's 20 aircraft limit is exhausted, Kish
and Bandar Abbas will be the primary airfields early game. Bandar Abbas
is still close enough to source Hornet and Viper missions to most of the
area around Dubai. It's unable to reach Lar with those aircraft, but
Kish and the CVN can (as can captured airfields).
2021-07-17 16:34:13 -07:00
Dan Albert
c65ac5a7cf Move mission range data into the aircraft type.
The doctrine/task limits were capturing a reasonable average for the
era, but it did a bad job for cases like the Harrier vs the Hornet,
which perform similar missions but have drastically different max
ranges. It also forced us into limiting CAS missions (even those flown
by long range aircraft like the A-10) to 50nm since helicopters could
commonly be fragged to them.

This should allow us to design campaigns without needing airfields to be
a max of ~50-100nm apart.
2021-07-17 16:34:13 -07:00
Dan Albert
04a8040292 Prevent carriers from claiming most TGOs.
The naval CP generators will only spawn ships, so if any of the other
TGO types were closest to the CV or LHA they just would not be
generated.
2021-07-17 16:34:13 -07:00
Dan Albert
adab00bc0e Update changelog. 2021-07-17 14:31:14 -07:00
Dan Albert
9bb8e00c3d Allow configuration of the air wing at game start.
After completing the new game wizard but before initializing turn 0,
open a dialog to allow the player to customize their air wing. With this
they can remove squadrons from the game, rename them, add players, or
change allowed mission types. *Adding* squadrons is not currently
supported, nor is changing the squadron's livery (the data in pydcs is
an arbitrary class hierarchy that can't be safely indexed by country).

This only applies to the blue air wing for now.

Future improvements:

* Add squadron button.
* Collapse disable squadrons to declutter?
* Tabs on the side like the settings dialog to group by aircraft type.
* Top tab bar to switch between red and blue air wings.
2021-07-17 14:29:04 -07:00
Dan Albert
f2dc95b86d Fix typo. 2021-07-16 22:43:59 -07:00
Dan Albert
28f98aed88 Migrate pressure to a typed unit. 2021-07-16 22:38:41 -07:00
Dan Albert
d11174da21 Stop cluttering the kneeboard with empty notes. 2021-07-16 22:25:40 -07:00
Dan Albert
8e977f994f Remove LGBs from degraded loadouts without TGPs.
This only takes effect for default loadouts. Custom loadouts set from
the UI will allow LGBs. In the default case there will not be buddy-lase
coordination so we should take iron bombs instead.

Also adds single/double Mk 83 and Mk 82 weapon data to accomodate this.
2021-07-16 18:34:41 -07:00
Dan Albert
11c2d4ab25 Add JDAMs and their fallbacks.
Hornet should be compatible with 1990 campaigns now. Air-to-ground
weapon restrictions are less interesting for AI aircraft so I haven't
covered *all* the variants here (the >2 variants of each carried by the
B1 and such).
2021-07-16 16:23:22 -07:00
Dan Albert
b733e6855b Add SLAM/SLAM-ER weapon data. 2021-07-16 15:48:12 -07:00
Dan Albert
aa3d644f97 Prevent empty cheek stations for the Hornet.
This is a bit of a hack that makes the TGPs fall back to AIM-120s. It
works okay because this only applies to a few cases:

The A-10 gets an empty pylon. That's fine. Maybe later we can add
multiple fallback paths and depth-first-search through them so that that
pylon could carry bombs instead.

The Viper has no replacemnt for that station. The jammer goes on the
other fuselage station, the HTS isn't a replacement, and we don't have
LANTIRN for the Viper. No weapons can be fit to those stations.

What this helps is the Hornet, where any Gulf War scenario ends up with
an empty cheek station because we don't have the NITE HAWK to fall back
to. In this case we can instead fall back through the air-to-air
missiles to fill the station.
2021-07-16 15:27:32 -07:00
Dan Albert
bb46d00f22 Add weapon data for R-77, R-27, and R-24. 2021-07-16 15:22:11 -07:00
Dan Albert
771c74ee75 Fill out weapon data for AIM-9s. 2021-07-16 15:12:49 -07:00
Magnus Wolffelt
04a346678c Add situational temperature and pressure variation.
Now varies by:

* Season
* Theater
* Weather
* Time of day
2021-07-16 14:08:14 -07:00
Dan Albert
e5c0fc92ec Don't reload weapon data if already loaded. 2021-07-16 01:06:31 -07:00
Dan Albert
1b640f40dc Fix map issues when debugging tools are disabled. 2021-07-16 00:27:11 -07:00
Mustang-25
ee77516716 Replace TGP with SPJ for JF-17 CAP/SEAD.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1422.
2021-07-16 00:17:20 -07:00
Dan Albert
82cca0a602 [3/3] Rework hold points. 2021-07-15 23:21:56 -07:00
Dan Albert
d444d716f5 [2/3] Improve join point placement. 2021-07-15 23:18:10 -07:00
Dan Albert
e03d710d53 [1/3] Rework IP placement.
Test cases:

1. Target is not threatened.

   The IP should be placed on a direct heading from the origin to the
   target at the max ingress distance, or very near the origin airfield
   if the airfield is closer to the target than the IP distance.

2. Unthreatened home zone, max IP between origin and target, safe
   locations available for IP.

   The IP should be placed in LAR at the closest point to home.

3. Unthreatened home zone, origin within LAR, safe locations available
   for IP.

   The IP should be placed near the origin airfield to prevent
   backtracking more than needed.

4. Unthreatened home zone, origin entirely nearer the target than LAR,
   safe locations available for IP.

   The IP should be placed in LAR as close as possible to the origin.

5. Threatened home zone, safe locations available for IP.

   The IP should be placed in LAR as close as possible to the origin.

6. No safe IP.

   The IP should be placed in LAR at the point nearest the threat
   boundary.
2021-07-15 23:18:10 -07:00
Mustang-25
b46d44c3a5 Change CAP and SEAD Loadouts
Replaced the TGP with SPJ pod for these roles.
2021-07-15 16:58:14 -07:00
Mustang-25
7a459fd5b8 Merge branch 'dcs-liberation:develop' into develop 2021-07-15 16:55:03 -07:00
Magnus Wolffelt
2b696144e3 Add QNH and temperature to the kneeboard. 2021-07-15 15:34:58 -07:00
RndName
62036a273e allow user to set empty dcs install dir
This will allow expert users to disable the automatic MissionScripting.lua replacement. There are many warnings and errors which have to be ignored to achieve this because DCS Liberation will not work with unmodified MissionScripting.lua
2021-07-15 13:46:59 -07:00
Magnus Wolffelt
d25befabdd Randomize mission temperature and pressure. 2021-07-15 13:34:09 -07:00
Dan Albert
56b17dfbcf Correct behavior for multi-task HTN methods.
Add tasks to the left of the deque, not the right.

Not symptomatic yet since we don't actually have any multi-task methods
currently.
2021-07-14 18:34:33 -07:00
Dan Albert
72c181a399 Fix budget mismatch in the UI.
Much of the UI was using the old budget which wasn't removed from Game
like it should have been when Coaltion was introduced. The UI displayed
(and in some cases pulled from) the starting budget rather than the real
budget.
2021-07-14 17:33:01 -07:00
Dan Albert
b1b60f4286 Add JSOW A and C weapon data and fallbacks.
Both types use JSOW -> Walleye -> Mk 84. The JSOW A should maybe fall
back to some CBU instead, but I think the standoff capability is more
important to preserve than the warhead type.
2021-07-14 01:27:00 -07:00
Dan Albert
7648716199 Make weapon groups explicit and moddable.
The only parts of the old weapon data that worked well (didn't commonly
result in empty pylons) did this implicitly, so make the grouping
explicit.

This also moves the data out of Python and into the resources, which
both makes the data moddable and isolates us from a huge amount of
effort and a save compat break whenever ED changes weapon names.

I didn't auto migrate the old data since the old groups were not
explict and there's no way to infer the grouping. Besides, since most of
the weapons were *not* grouped, the old data did more harm than good in
my experience. I've handled the AIM-120 and AIM-7 for now, but will get
at least all the fox 3 missiles before we ship.
2021-07-14 01:04:03 -07:00
Dan Albert
9177588220 Don't target ammo depots at inactive front lines. 2021-07-13 20:49:31 -07:00
Dan Albert
9bbcee645e Cleanup and document some of Doctrine. 2021-07-13 20:18:30 -07:00
Dan Albert
a7d49b986d Exclude both path endpoints for joins/splits.
Without this the points would often be placed exactly on top of the
origin airfield, when in that case we actually should use the fallback
behavior.
2021-07-13 20:11:09 -07:00
Dan Albert
7c3e08050f Perturb fallback join/split points.
Otherwise they're placed exactly on top of each other, which makes the
map harder to read.
2021-07-13 20:10:29 -07:00
Dan Albert
076df7cf66 Fix placement of fallback split points.
Using the target placed the split in the threatened area.
2021-07-13 20:07:42 -07:00
Dan Albert
415b8c6317 Allow the split point to differ from the join.
This places the split point based on the best path from the IP to home,
rather than the best path from home to the target. The outcome is that
the planner might choose an alternate route out of a threatened area
based on the safest escape from the IP, which is where the aircraft
should be when it releases its weapons, rather than at the target.
That's of course not always perfect since the IP distance is not based
on the carried weapon, but it's a better choice when it matters more
(when carrying standoff weapons attacking a more dangerous target).
2021-07-13 19:59:22 -07:00
Dan Albert
c1d3c93dbb Speed up turn processing.
Run the expensive precondition check (package fulfillment) last.
2021-07-13 18:56:06 -07:00
Dan Albert
8e59c99666 Improve hold point placement for nearby joins. 2021-07-13 18:43:02 -07:00
Dan Albert
dfcd372d2d Remove egress points from most flight plans.
These don't have any function. Remove them and remove the angled attack
heading from the IP.
2021-07-13 18:36:38 -07:00
Dan Albert
f7bbe0fa94 Improve flight plan layout for untheatened IPs.
Try all the nav points between the origin and the target rather than
just the first non-threatened point. This prevents us from using the
fallback behavior for any target that's sufficiently far from the
package airfield.
2021-07-13 18:22:42 -07:00
Dan Albert
a1910f49a8 Color navmesh zones based on threat. 2021-07-13 17:49:10 -07:00
Dan Albert
5f8be5fa91 Fix type checker issue. 2021-07-13 17:08:37 -07:00
Dan Albert
587034ad03 Prioritize ammo depots when appropriate.
The AI will now prioritize targeting ammo depots if the current
deployable enemy forces outnumber the friendly cap by 50% or more.
2021-07-13 17:06:25 -07:00
Dan Albert
9568bc7ea6 Fix inversion of AI management for opfor. 2021-07-13 17:04:49 -07:00
Dan Albert
ccf6b6ef5f Check for available aircraft as task precondition.
This makes it so that the mission planning effects are applied only if
the package can be fulfilled. For example, breakthrough will be used
only if all the BAI missions were fulfilled, not if they will *attempt*
to be fulfilled.
2021-07-13 16:26:15 -07:00
Dan Albert
24f6aff8c8 Reduce mission planning dependence on Game. 2021-07-13 15:20:42 -07:00
Dan Albert
17c19d453b Factor out Coalition from Game. 2021-07-13 14:29:40 -07:00
Dan Albert
4534758c21 Account for planned missions for breakthrough.
Consider BAI missions planned this turn when determining if a control
point is still garrisioned for preventing breakthrough.

This isn't very accurate yet since the HTN isn't checking for aircraft
fulfillment yet, so it might *plan* a mission to kill the garrison, but
there's no way to know if it will be fulfilled.
2021-07-13 13:50:50 -07:00
Dan Albert
c180eb466d Use aggressive stance for similar troop counts.
Bumps the breakthrough requirement to 2x, elimination to 1.5x, and uses
agressive for 0.8-1.5x.
2021-07-12 21:28:00 -07:00
Dan Albert
0a416ab758 Let the TheaterCommander manage front line stance.
This improves the AI behavior by choosing the stances non-randomly:

* Breakthrough will be used if the base is expected to be capturable and
  the coalition outnumbers the enemy by 20%.
* Elimination will be used if the coalition has at least as many units
  as the enemy.
* Defensive will be used if the coalition has at least half as many
  units as the enemy.
* Retreat will be used if the coalition is significantly outnumbers.

This also exposes the option to the player.
2021-07-12 21:12:02 -07:00
Dan Albert
575aca5886 Fix targeting dead BAI targets. 2021-07-12 20:44:19 -07:00
Dan Albert
c0cc5657a7 Attack detecting radars with low priority.
IADS that are in detection range (but not attack range) of missions will
be targeted at very low priority. These will typically only be planned
when no other targets are in range.
2021-07-12 17:33:45 -07:00
Dan Albert
78514b6c2e Only auto-target strike against buildings.
The players can still manually assign strike missions on other target
types since that's sometimes better for player waypoint generation (one
waypoint per unit is nice for SAMs), but it's bad for the AI so by
default we should exclude non-buildings.

This also prevents double targeting of groups, since they might have
been identified by other missions as well.

We already did some of this, but since we were excluding specific TGO
types rather than only allowing building TGOs we were often missing
things (missile sites, coastal defenses, and EWRs, it seems).
2021-07-12 17:04:17 -07:00
Dan Albert
7e4390d743 Improve prioritization of garrison targeting.
Garrison groups should be preferred with the following priority:

1. Groups blocking base capture
2. Groups at bases connected to an active front line
3. Rear guard units

Previously they were being prioritized based on the distance to the
closest friendy control point, which is similar to this but an
aggressively placed carrier could throw it off.
2021-07-12 16:59:49 -07:00
Dan Albert
cd558daf5a Add decorator for tracking save compat.
Used to decorate functions or methods that have save compat code for a
given major version.

```
@has_save_compat_for(5)
def foo() -> None:
    ...
```

This function will raise an error at startup if it is decorated as
having save compat for a version other than the current major version of
the game. A new major version is the definition of a save compat break,
so keeping around the old compat code serves no purpose other than
hiding initialization bugs. The compat code and the decorator should be
removed in the branch raising the error.
2021-07-12 13:44:49 -07:00
Dan Albert
dda5955121 Improve DEAD mission prioritization.
This alters the DEAD task planning to be the *least* preferred task, but
prevents other tasks from being planned unless they are excepted to be
clear of air defenses first. Even so, missions are a guaranteed success
so those other missions will still get SEAD escorts if there's potential
for a SAM in the area.

This means that air defenses that are not protecting a more useful
target (like a convoy, armor column, building, etc) will no longer be
considered by the mission planner. This isn't *quite* right since we
currently only check the target area for air defenses rather than the
entire flight plan, so there's a chance that we ignore IADS that have
threatened ingress points (though that's mostly solved by the flight
plan layout).

This also is still slightly limited because it's not checking for
aircraft availability at this stage yet, so we may aggressively plan
missions that we should be skipping unless we can guarantee that the
DEAD mission was planned. However, that's not new behavior.
2021-07-12 13:02:23 -07:00
Dan Albert
783ac18222 Replace existing campaign planner with an HTN.
An HTN (https://en.wikipedia.org/wiki/Hierarchical_task_network) is
similar to a decision tree, but it is able to reset to an earlier stage
if a subtask fails and tasks are able to account for the changes in
world state caused by earlier tasks.

Currently this just uses exactly the same strategy as before so we can
prove the system, but it should make it simpler to improve on task
planning.
2021-07-12 13:02:23 -07:00
Dan Albert
81c8052449 Note tracking bug for shapely type annotations. 2021-07-11 14:41:40 -07:00
Dan Albert
6ce02282e7 Correct int/float confusion in Point APIs.
The heading and distance calculations always return floats.
2021-07-11 14:33:46 -07:00
Dan Albert
a19a0b6789 Use Pillow types from typeshed. 2021-07-11 13:53:58 -07:00
Dan Albert
9de08dc83f Update to latest pydcs.
This includes the basics that we need to get type checking for pydcs
calls.

Type checking has been disabled in a few monkey-patching cases. Patches
ought to be sent upstream (or in the case of dead unit tracking,
replaced with a better model).
2021-07-11 13:37:17 -07:00
Dan Albert
96c7b87ac7 More adaptation for pydcs updates.
This is as much as we can do until pydcs actually adds the py.typed
file. Once that's added there are a few ugly monkey patching corners
that will just need `# type: ignore` for now, but we can't pre-add those
since we have mypy warning us about superfluous ignore comments.
2021-07-09 16:35:03 -07:00
Brock Greman
469dd49def Fixing broken group generation. 2021-07-09 12:35:32 -07:00
Dan Albert
53f6a0b32b Fix some typing in preparation for pydcs types.
Not complete, but progress.
2021-07-08 23:23:05 -07:00
Dan Albert
fb9a0fe833 Flesh out typing information, enforce. 2021-07-07 17:41:29 -07:00
Dan Albert
69c3d41a8a Disallow partially specified generics. 2021-07-07 16:01:20 -07:00
Dan Albert
fc32b98341 Type check the contents of untyped functions.
By default mypy doesn't type check the code within an untyped function.
This enables that and fixes typing errors to accomodate it.

This did uncover a very old bug:
https://github.com/dcs-liberation/dcs_liberation/issues/1417
2021-07-07 15:47:19 -07:00
Dan Albert
299ed88f09 Fix unreachable code issues, enable checking.
The loadout case actually could (and previously did) hide bugs from the
type checker, since mypy was smart enough to see that we were removing
None from the input it assumed that the member was non-optional, but
later modifications could cause null values, and since those came from
the UI mypy couldn't reason about this. This meant that mypy assumed the
type could not be optional and wouldn't check that case.
2021-07-07 15:17:05 -07:00
Dan Albert
29753a6aa9 Add (mostly disabled) mypy configs.
We're missing a lot of checking right now. Most of it requires
additional cleanup. For now I've enabled what I could and will follow up
to clean up and enable more checking.
2021-07-07 15:17:05 -07:00
Dan Albert
7983cd8d62 Add documentation for turn processing. 2021-07-07 14:44:38 -07:00
RndName
05fab1f79d correct display of turn statistics 2021-07-07 14:12:20 -07:00
RndName
7229b886e0 replan opfor mission on sell or buy of tgos 2021-07-07 14:12:20 -07:00
Dan Albert
8b70d2674f Note fix for empty convoy groups. 2021-07-05 15:54:23 -07:00
RndName
8ba27cdaea remove completely destroyed units from the convoy 2021-07-05 15:51:34 -07:00
Khopa
1c2411a0fc Added a basic campaign on Mariana Islands theater to try it out. 2021-07-04 19:35:36 +02:00
Khopa
ec88d07ef1 Corrected some bugs preventing marianas campaigns from running 2021-07-04 19:34:58 +02:00
bgreman
aa328d3ef7 Adds Marianas Islands support (#1406)
* Implements #1399

* Reverting accidental change in generate_landmap.py

* Changelog update

* Import beacon data for Marianas.

Co-authored-by: Dan Albert <dan@gingerhq.net>
2021-07-03 14:51:26 -04:00
Dan Albert
727facfb90 Fixup None loadouts for aircraft with no loadouts.
Aircraft that have no loadouts at all (such as the IL-78M) will have no
loadouts and thus no values in the dropdown menu. If the player toggles
the custom layout box we reset the flight's loadout to the selected
loadout, and with no loadouts in the combo box that is None, and
`Flight.loadout` isn't supposed to be optional.

Check for that case in the loadout selector and replace with an empty
loadout if that happens.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1402
2021-07-02 17:33:24 -07:00
Dan Albert
4add853473 Fix the legacy tanker.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1379
2021-07-02 17:18:21 -07:00
RndName
b2db27f9aa remove prices from sam generators
The prices are only estimations due to randomization. the real price will be only known when the generator was used and the final units are known
2021-07-02 16:46:16 -07:00
RndName
96be6c0efe correct prices for ewr and sams
prices will now be calculated for the whole group by the generator by
looking up the price using the  GroundUnitType wrapper

fixes #1163
2021-07-02 16:46:16 -07:00
Dan Albert
3f42f1281d Note the silkworm fix in the changelog. 2021-07-02 16:28:06 -07:00
Mustang-25
bab8384803 Corrected Silkworm launcher name 2021-07-02 16:26:47 -07:00
Mustang-25
ceb77c990b Corrected Silkworm launcher name 2021-07-02 11:45:01 -07:00
Florian
3f65928e9d Remove the randomness from SAM group size. 2021-07-02 01:38:27 -07:00
Dan Albert
4e6659e7e8 4.0.1 -> 4.1.0
This includes new features now.
2021-07-02 01:27:51 -07:00
Chris Seagraves
9e22d4b5df Note TGO tooltip improvement in the changelog. 2021-07-02 01:26:55 -07:00
RndName
357361de3d fixed lua data generation 2021-07-02 01:25:03 -07:00
RndName
de443fa3f0 reworked the skynet group name generation
- added information about the role of the aa site
- moved handling of ground name from tgo to the sam generator to make the tgo cleaner
- adjusted the skynet-config lua to the changes
2021-07-02 01:25:03 -07:00
Dan Albert
20839853b7 Minor formatting fix for the changelog. 2021-07-01 20:07:28 -07:00
Chris Seagraves
bc2539b566 Fix for crash when clear weather.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1394
2021-07-01 20:07:01 -07:00
Dan Albert
c89416702d Revert "Revert "Add Cloud Base Altitude to Weather Display (#1371)""
This reverts commit b2dd8c68e1.
2021-07-01 20:07:01 -07:00
Dan Albert
b2dd8c68e1 Revert "Add Cloud Base Altitude to Weather Display (#1371)"
Reverting until
https://github.com/dcs-liberation/dcs_liberation/issues/1394 is
resovled.

This reverts commit f80696b724.
2021-07-01 20:00:08 -07:00
Dan Albert
2ef2eafdd3 Remove debug cruft.
We don't need to print the description of every unit on startup.
2021-07-01 19:37:08 -07:00
Schneefl0cke
568655d503 Add incomes for WW2 villages and camps. 2021-07-01 17:04:03 -07:00
bgreman
9bd6f9ef47 Addresses #478 to clean up the angle summing functionality. (#1386) 2021-06-30 23:58:20 -04:00
bgreman
c8e5cefd36 Increasing time JTAC radio messages stay on the UI. (#1369)
- Target lost or killed: 10s -> 20s
- New target : 10s -> 30s
- Request JTAC Status: 25s -> 60s
2021-06-30 23:55:37 -04:00
bgreman
7ba4077f9f Fixes #240 by making statistics windows axis labels integers (#1370) 2021-06-30 23:50:02 -04:00
Mustang-25
151f8bf329 Update TGP Restriction Dates
TGP dates to more accurately reflect IRL IOC dates.
2021-06-30 19:17:14 -07:00
Chris Seagraves
e94d48c265 Notes to kneeboard (#1375)
Adds global-level kneeboard notes.  Explicit save compatability with 4.0.0
2021-06-30 18:07:53 -04:00
Fryderyk Wysocki
2a5c523afd Update poland_2010.json (#1380)
* Update poland_2010.json

* Adding MiG-29G to PL faction

Poland has bought some MiG-29Gs from unified Germany in the early '90s
2021-06-30 15:30:38 -04:00
Chris Seagraves
f80696b724 Add Cloud Base Altitude to Weather Display (#1371)
Adds tooltip with cloud base altitude to weather panel
2021-06-30 15:22:14 -04:00
Chris Seagraves
5f5b5f69e3 asset reference links 😎 (#1363)
Adds urls to unit info pages that don't have data.
2021-06-30 15:04:06 -04:00
Chris Seagraves
d99f8fef09 Update main.py (#1382) 2021-06-29 18:19:37 -04:00
Khopa
97e59db5e6 Helipads : Support for warm takeoff, use InvisibleFarp rather than Single Helipad. 2021-06-27 19:57:04 +02:00
Khopa
1c813c0e0e Merge remote-tracking branch 'khopa/develop' into helipads 2021-06-27 18:35:24 +02:00
Simon Clark
e39f17b3de Fix begin campaign button on reload. 2021-06-26 22:43:22 +01:00
Dan Albert
0b90b53e09 Add changelog section for 4.0.1. 2021-06-26 14:40:00 -07:00
Dan Albert
847d729ba4 Release 4.0.0. (#1365) 2021-06-26 12:46:26 -07:00
Dan Albert
aa86a6e53b Add the most important feature to the changelog. 2021-06-26 12:33:56 -07:00
Brock Greman
34470336e4 Clarify the impact of non-cold flight starts. 2021-06-26 12:29:17 -07:00
Mustang-25
5a2a89f19e Update Op Mole Cricket 2010 Campaign.
Moved SAM generator at Rosh Pina so it does not spawn units on the runway.
2021-06-26 12:17:27 -07:00
Dan Albert
7eb4df770e Revert accidental change to default pilot limit. 2021-06-26 12:06:18 -07:00
Simon Clark
550bb5fd33 Bump campaign versions. 2021-06-26 19:30:03 +01:00
Chris Seagraves
ffcae66f59 Include control point name in ground object info.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/498
2021-06-26 11:24:12 -07:00
Dan Albert
d2df795ba7 Ack campaign version update.
No scenery targets in this campaign so no work needed.

https://github.com/dcs-liberation/dcs_liberation/issues/1359
2021-06-26 11:19:02 -07:00
Dan Albert
b930e13964 Remove dead campaign.
https://github.com/dcs-liberation/dcs_liberation/issues/1359
2021-06-26 11:18:46 -07:00
Khopa
1b9da9cdd8 Fixed mypy error after merge 2021-06-26 20:00:10 +02:00
Dan Albert
e6bf318cdf Fix save path for new games. 2021-06-26 10:59:58 -07:00
Dan Albert
4cfed08247 Disband unfilled incompletable transfers.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1317
2021-06-26 10:54:09 -07:00
Khopa
4460b526cb Golan heights : re-add helipads for testing in helipad branch after merge of develop feature. 2021-06-26 19:27:33 +02:00
Khopa
01e6a87968 Mod support : Updated frenchpach to version 4.6 (Added new units VBCI and AMX-13 support) + some frenchpack units yaml tweaks 2021-06-26 19:22:13 +02:00
Khopa
7667a4f8c0 Merge branch 'develop' into helipads
# Conflicts:
#	game/game.py
#	resources/campaigns/golan_heights_lite.miz
2021-06-26 18:00:36 +02:00
Khopa
6fbfb83e6c Fixed duplicates in france 2005 faction 2021-06-26 15:26:33 +02:00
Khopa
123d3e182a Fixed yaml issue causing an issue with Leclerc MBT 2021-06-26 15:16:46 +02:00
Khopa
fd8d16035c Updated campaign : Operation Dynamo for The Channel map 2021-06-26 14:44:16 +02:00
Khopa
1ff45b55d6 Updated campaign : Russia Small, renamed it to "From Mozdok to Maykop" 2021-06-26 13:48:31 +02:00
Khopa
0ce02d7766 Updated campaign : Battle for Golan Heights 2021-06-26 13:27:01 +02:00
Dan Albert
959a13a514 Fix save path cleanup. 2021-06-25 23:21:31 -07:00
Chris Seagraves
b601d713d2 Use directory of current save for open/save-as. 2021-06-25 23:01:49 -07:00
Dan Albert
dc96d8699a Add "Nevada Limited Air" campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1358
2021-06-25 21:34:28 -07:00
Dan Albert
f38cdd8432 Add "Scenic Route" campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1334
2021-06-25 21:28:27 -07:00
Dan Albert
91655a3d5a Fix lint. 2021-06-25 19:33:55 -07:00
Dan Albert
7774a9b2ab Move the default save game directory.
The top level DCS directory gets messy fast if we fill it with save
games.
2021-06-25 17:48:09 -07:00
Dan Albert
80cf8f484d Fix targeting of carrier groups with TGOs.
The assumption that the first group is the carrier group is wrong.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1346
2021-06-25 16:46:49 -07:00
Dan Albert
cb7c075a61 State carrier requirement for Blackball.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1355
2021-06-25 16:35:15 -07:00
Dan Albert
4d0fb67c53 Fix crash when buying or selling TGO units.
Updating the game destroys this window so we cannot continue with the
calls. It worked in my initial testing, so presumably it's partly
dependent on when the finalizers run.

Since the windows will be destroyed there's nothing for us to actually
update, so just remove that signal and the explicit close calls.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1344
2021-06-25 16:30:18 -07:00
Dan Albert
380d1d4f18 Ack campaign version bump.
Campaigns don't use scenery targets.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1341
2021-06-24 18:17:25 -07:00
Dan Albert
71832859a5 Update pydcs to use latest master.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/993
2021-06-24 18:14:11 -07:00
docofmur
a31432ad9e Fixes #1337 by making ground location search look in both directions (#1338) 2021-06-24 13:24:13 -04:00
bgreman
26743154d8 Implements #1331 by changing the Pass Turn button text on Turn 0. (#1333) 2021-06-24 10:59:12 -04:00
bgreman
a50a6fa917 Adds a ruler to the map (#1332)
* Adds a ruler to the map

* Updating changelog

* Updating changelog
2021-06-24 02:58:39 -04:00
bgreman
b43e5bac0b Fix #1329 player loses frontline progress when skipping turn 0 (#1330) 2021-06-24 02:04:27 -04:00
Dan Albert
ddaef1fb64 Retry reading state.json on failure.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1313
2021-06-23 20:18:06 -07:00
Dan Albert
6f264ff5de Signal game update when buying/selling TGO units.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1312
2021-06-23 20:08:05 -07:00
Dan Albert
a06fc6d80f Fix another unit type mismatch. 2021-06-23 20:01:38 -07:00
Dan Albert
3ddfc47d3a Add a feature flag for pilot limits.
This doesn't currently interact very well with the auto purchase since
the procurer might by aircraft that don't have pilots available. That
should be fixed, but for the short term we should just default to not
enabling this new feature.
2021-06-23 18:47:34 -07:00
docofmur
905bd05ba8 Campaign version update (#1326)
Caucasus Multi part campaign version update. No map strike objects so just the version change
2021-06-23 20:00:39 -04:00
Dan Albert
aa19787654 Document high level concepts of unit transfers. 2021-06-23 16:50:54 -07:00
bgreman
3274f3ec35 Fix empty convoys (#1327)
* Hopefully getting rid of empty convoys for good

* changing Dict to dict for type checks
2021-06-23 19:48:16 -04:00
bgreman
c3b8c48ca2 Fixes #1310 (#1325)
* Fixes #1310 by only refunding GUs if no faction CP has an attached factory.  Previously it would refund all units at the CP, including aircraft.

Also changes the CP CAPTURE cheat to work at any CP regardless of adjacency to frontline or BLUEFOR/OPFOR state.

* Fixing typing issues, changint all Dict[] types to dict[]

* Updating changelog
2021-06-23 17:09:17 -04:00
Dan Albert
d365094616 Update From Caen to Evreux.
Add support for inversion and ack the version change (Normandy is
unaffected by ID updates).

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1232
2021-06-23 13:57:16 -07:00
Dan Albert
7c76684076 Ack version update for PG campaigns.
PG is unaffected by building ID changes.
2021-06-23 13:49:27 -07:00
Dan Albert
0ef27b038a Update Vectron's Claw and Peace Spring.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1323
2021-06-23 12:58:56 -07:00
Dan Albert
610a27c0e4 Copy initialization fix to AircraftType. 2021-06-23 12:50:07 -07:00
RndName
752c91a721 set window title empty on new game
also fixed small exception when aborting the open file dialog which lead to " as filename

fixes #1305
2021-06-23 12:24:36 -07:00
Dan Albert
d3d655da07 Fixed missed initialization of unit data on load.
We'd only load unit data if a name lookup was done and missed it on a
type lookup. Ideally we wouldn't need to do a type lookup here until the
ground unit templates are reworked we still do.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1299
2021-06-22 23:41:05 -07:00
Dan Albert
db36cf248e Return pilots when canceling flight creation. 2021-06-22 23:36:39 -07:00
Dan Albert
153d8e106e Add the Around the Mountain campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1280
2021-06-22 23:28:54 -07:00
Dan Albert
df8829b477 Add Operation Blackball campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1320
2021-06-22 23:22:42 -07:00
Dan Albert
569bc297a8 Update Syria Full campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1319
2021-06-22 23:20:03 -07:00
Dan Albert
099cbbdb64 Update Northern Russia campaign.
I bumped the submitted 6.1 to 7.0 (which didn't exist when the files
were uploaded) because this campaign uses no scenery targets.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1318
2021-06-22 23:16:12 -07:00
Dan Albert
ca7469b92e Update Allied Sword.
Only change from the uploaded files is that I increased the campaign
version to 7.0 since this doesn't use any scenery targets so has no work
to do for that.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1249
2021-06-22 23:13:16 -07:00
Dan Albert
6db4145927 Correct mistakenly updated campaign. 2021-06-22 23:08:12 -07:00
Dan Albert
ca93f2baff Bump campaign version to account for DCS changes.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1308
2021-06-22 23:04:16 -07:00
Dan Albert
84a0a3caeb Fix unit type mismatch.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1314
2021-06-22 22:54:40 -07:00
Dan Albert
7b327693e2 Update Operation Peace Spring.
https://github.com/dcs-liberation/dcs_liberation/issues/1303
2021-06-22 15:17:39 -07:00
docofmur
dba70dc6d5 Faction Audit.
Transports and mod aircraft added where needed cleaned up various
duplicates in factions.
2021-06-22 15:01:50 -07:00
Mike Jones
bd1618e41d Use pydcs has_tacan attribute to check if tankers support TACAN. 2021-06-22 14:35:28 -07:00
Mike Jones
08b7aff0d8 Add gunfighter flag to aircraft data files. 2021-06-22 14:35:28 -07:00
Mike Jones
a75688f89c Add patrol configuration to unit data files.
This allows altitude/speed of AEW&C and tankers to be configured.
2021-06-22 14:35:28 -07:00
Mike Jones
30763b5401 Fix unit type comparisons.
When comparing UnitType against a pydcs type, use .dcs_unit_type.
2021-06-22 14:35:28 -07:00
Chris Seagraves
814519248c Fix bug with file name in title with invalid save games. 2021-06-22 14:19:53 -07:00
Simon Clark
8c71be5257 Campaign clarity. 2021-06-22 17:21:21 +01:00
Simon Clark
91763b233e Add clarity for mod selection page. 2021-06-21 20:04:58 +01:00
Simon Clark
ab51f5e69a Merge branch 'develop' of https://github.com/dcs-liberation/dcs_liberation into develop 2021-06-21 19:46:10 +01:00
Simon Clark
d278d58f6c Add Operation Atilla campaign.
It's a Cyprus invasion campaign - what's not to like!
2021-06-21 19:46:05 +01:00
Dan Albert
47e038c9fa Fix command line campaign generator. 2021-06-20 23:46:06 -07:00
Dan Albert
e96210f48c Don't order transports for incapable factions.
If these orders can't be fulfilled for the faction it will prevent the
faction from ordering any non-reserve aircraft since transports are
given priority after reserve missions, and they'll never be fulfillable.
As such, no non-reserve aircraft will ever be purchased for factions
without transport aircraft.

Factions without transport aircraft are screwed in other ways, but this
will fix their air planning for campaigns that aren't dependent on
airlift.
2021-06-20 23:44:00 -07:00
Simon Clark
aa3811ad02 Updated factions to reflect mod select changes. 2021-06-21 01:32:43 +01:00
Simon Clark
963ab38b2e Refactor the mod select changes, re-add accidentally deleted factions. 2021-06-21 01:16:48 +01:00
Simon Clark
11069cc219 Make mod selection nicer and deprecate MB-339.
Mod selection is now done via checkbox in the new game wizard.

The MB-339 is being turned into a paid module, and the free mod no longer works, so it's been removed.
2021-06-21 01:16:41 +01:00
Dan Albert
d074500109 Revert "Don't propose missions the air wing can't plan."
This is redundant because plan_mission already checks this.

This reverts commit 3338df9836.
2021-06-20 15:57:54 -07:00
Dan Albert
63af28b016 Develop is now 5.x. 2021-06-20 15:48:54 -07:00
Dan Albert
d2cc3f673e Switch pydcs to a pip requirement. 2021-06-20 15:16:22 -07:00
Dan Albert
dc85644d71 Exclude weapon names and weights from comparisons.
Only the class ID matters, and the names sometimes change with new pydcs
updates.
2021-06-20 15:11:35 -07:00
SnappyComebacks
0b5bdf8151 Move max_group_size from S-3B to S-3B Tanker. 2021-06-20 14:13:23 -07:00
jsjlewis96
b27238a69a Moved Hind-F to separate faction, not operational at time, but only gunship pilotable 2021-06-20 14:13:03 -07:00
Mike
bb2bf78e8a Fix current_airlift_capacity always returning 0.
Squadron.aircraft is of type AircraftType, while TRANSPORT_CAPABLE is
a list of pydcs DcsUnitTypes. As a result, the intersection was always
empty causing the function to always return 0.
2021-06-20 13:56:00 -07:00
Chris Seagraves
7e17533cc6 Air/ground intel prettification. (#1285)
* Sort rows.
* Add totals to group headers.
* Indent content.
* Add space between sections.
2021-06-20 13:43:54 -07:00
Chris Seagraves
7808da118a Include the save name in the window title. 2021-06-20 13:33:27 -07:00
Mustang-25
4259cf8764 Add IAF Eagle Sqn 2021-06-20 13:33:01 -07:00
Mustang-25
994c55945e Add IAF Strike Eagle Sqn 2021-06-20 13:33:01 -07:00
Mustang-25
f20c145ece Add IAF Viper Sqns 2021-06-20 13:33:01 -07:00
SnappyComebacks
5b31026e1c Fix UI to obey max group sizes.
This also adds max group sizes for aircraft that need it but don't
according to DCS. Only the first tanker or AEW&C unit in a group can be
contacted by radio.
2021-06-20 13:32:00 -07:00
Simon Clark
39fe5951f7 Add factories to Russian Intervention Campaign. 2021-06-20 19:23:07 +01:00
Simon Clark
9d767c3dd8 Fix destination opacity bug. 2021-06-20 19:06:24 +01:00
Simon Clark
2a3f9bf81c More Russian Intervention campaign work. 2021-06-20 18:48:46 +01:00
Khopa
82bb2fcf6a Helipad : fixed typing errors after merge 2021-06-20 18:25:19 +02:00
Khopa
e56e765450 Helipad : fixed errors after merge of develop features. 2021-06-20 18:20:40 +02:00
Simon Clark
3fd4359cb1 Adds Russian Intervention 2015 campaign. 2021-06-20 17:08:44 +01:00
Khopa
c70169b4a0 Merge branch 'develop' into helipads
# Conflicts:
#	game/game.py
#	game/operation/operation.py
#	game/theater/controlpoint.py
#	gen/aircraft.py
#	resources/campaigns/golan_heights_lite.miz
2021-06-20 18:07:50 +02:00
Khopa
ca1be580df Squadrons : Added french Sa-342 and Mirage 2000-5 squadrons 2021-06-20 17:43:35 +02:00
Khopa
28820f2e64 Squadrons : Allow unicode characters in squadrons names 2021-06-20 17:43:07 +02:00
Simon Clark
6c3987ec86 Updates the intel box text for turn 0.
It was a bit misleading beforehand, as there were no forces on either side.
2021-06-20 15:56:53 +01:00
Simon Clark
089eb9e86b Changelog. 2021-06-20 15:36:40 +01:00
Simon Clark
0793e9afc5 Addresses #1184.
CV and LHA icons are now the same colour as airfields.

Destination markers now have transparency.
2021-06-20 15:33:01 +01:00
Dan Albert
1e2522375b Increase squadron size and replenishment rate.
Given the current lack of control over the number of squadrons this
needs be be raised to make it have less of an impact.
2021-06-19 23:24:23 -07:00
Dan Albert
e09f53da8f Fix exceptions when no aircraft are selected.
This commonly happens during reset of the UI, but also happens when the
player is out of aircraft.
2021-06-19 20:26:33 -07:00
Dan Albert
29b4b62a44 Revert "Add Around the Mountain campaign."
Doesn't include basic requirements like factories.

This reverts commit 30cab8e3a7.
2021-06-19 15:11:41 -07:00
Dan Albert
b1a63db1fc Correct some ILS/VOR frequencies in Syria.
`MHz(110, 30)` is 110.03 MHz, not 110.30 MHz.
2021-06-19 15:07:45 -07:00
Dan Albert
9940dc8451 Fix type annotations for some UI code. 2021-06-19 15:03:39 -07:00
Dan Albert
703c68eb66 Add Akrotiri to Inherent Resolve. 2021-06-19 12:17:47 -07:00
Dan Albert
3338df9836 Don't propose missions the air wing can't plan.
We were doignt his for escorts, but now that we quit planning as soon as
we find an unplannable mission (to save money for higher priority
missions), if we hit an early unplannable mission like BARCAP no other
missions wil be planned.

Maybe fixes https://github.com/dcs-liberation/dcs_liberation/issues/1228
2021-06-19 11:47:43 -07:00
SnappyComebacks
dc4794b246 Add kneeboard data for new Syria Cyprus airfields. (#1277)
* Add kneeboard data for new Syria Cyprus airfields.
2021-06-19 12:29:21 -06:00
Dan Albert
b130c9882a Remove max distance for AEW&C auto planning.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1259
2021-06-19 11:27:52 -07:00
Dan Albert
5f8b838652 Add new campaign minor version for Cyprus. 2021-06-19 11:18:31 -07:00
Dan Albert
4efd1b5d3e Note EWR waypoint selector fix. 2021-06-19 11:16:20 -07:00
RndName
ad6ed21b6b Add EWR objects to predefined waypoints 2021-06-19 11:01:35 -07:00
Dan Albert
2ffaa71bb5 Note some new features in the changelog. 2021-06-19 10:47:59 -07:00
RndName
1763f59320 Allow deletion of multiple waypoints by selection
#1221
2021-06-19 10:40:40 -07:00
RndName
08d32ffc77 Allow shift/ctrl click to buy/sell multiple units.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1221
2021-06-19 10:36:33 -07:00
RndName
7e3cebb96d Fix purchase groups.
The new class PurchaseGroup coming in with commit 9bb986c was not
initiallized correctly.

This causes the bug that the update function is not working when you
for example open the AircraftRecruitmentMenu press "+" or "-", close
the dialog and then open ArmorRecruitmentMenu. If you then want to buy
or sell the update function will raise an error "Internal C++ Object
Already Deleted".
2021-06-19 10:33:35 -07:00
Jake Lewis
930fb404af Updated Hind-F price for rebalance 2021-06-19 03:43:55 -07:00
jsjlewis96
6cd711a1e2 Added option to disable AI pilot levelling 2021-06-19 03:03:50 -07:00
docofmur
1bcc332885 Syrian Terrain update 2021-06-19 02:28:11 -07:00
Dan Albert
9bb986cff9 Update *all* buy/sell buttons, not just the row.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1207
2021-06-18 20:14:44 -07:00
Dan Albert
1247942bf1 Note fix for convoy naming bug. 2021-06-18 19:41:03 -07:00
Dan Albert
95d3ff4cbe Don't show ground unit menu at carriers.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1220
2021-06-18 19:39:42 -07:00
Marcel
0a874a28ef Fix group name for EWRs.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1246
2021-06-18 19:26:42 -07:00
Dan Albert
2dee702060 Persist name generator state to the save game.
This is a bit of an ugly hack but it's effectively what we would need
anyway. We could clean up the global replacement by making the name
generator _only_ a property of Game and plumbing it through to a large
number of places. Could maybe also use `__getstate__` and `__setstate__`
tricks to save `naming.namegen` to the file even without making it truly
a part of Game.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1247
2021-06-18 19:24:23 -07:00
Dan Albert
4ea66477fe Add options for changing pilot limits and rates. 2021-06-18 18:33:15 -07:00
Dan Albert
d3be732566 Fix tooltips for scuds/silkworms.
Same problem as the ground object menu, same cleanup required at some
point.
2021-06-18 18:14:20 -07:00
Dan Albert
933517055e Fix ground object menus for scuds and silkworms.
These really need to be added to the unit data, but this will do as a
stop gap since the group generators need an overhaul anyway.
2021-06-18 18:06:05 -07:00
Dan Albert
040a3d9b36 Add coastal defenses and missiles to Abu Dhabi. 2021-06-18 18:02:33 -07:00
Florian
2c859bf280 Rebalance aircraft prices.
Main goal here is to make sure that warbirds don't cost more than early
jets, but this includes rebalancing of all aircraft.
2021-06-18 17:53:19 -07:00
jsjlewis96
fe227e02b8 Shows total at top for economic intel 2021-06-18 17:35:18 -07:00
Dan Albert
c68e583c20 Note the Skynet EWR fix. 2021-06-18 17:02:22 -07:00
Khopa
6620d56859 Factions : Added hind-P to Russia 75. 2021-06-19 01:58:11 +02:00
Dan Albert
1ec72d3e94 Fix mission generation when infantry is disabled.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1256
2021-06-18 16:52:03 -07:00
Dan Albert
5c3bb75786 Fix EPLRS for aircraft.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1237
2021-06-18 16:48:59 -07:00
Dan Albert
a90cb0dad9 Fix carrier names in factions.
The rest of the ships were covered but it looks like carriers were
missed.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1258
2021-06-18 16:42:34 -07:00
Khopa
8854a491ab Custom banner for Mi-24P (different from Mi-24V) 2021-06-19 01:32:43 +02:00
UKayeF
74e8073328 add Mi-24V Hind icons as placeholders for Mi-24P icons yet to come 2021-06-19 01:32:43 +02:00
Dan Albert
a6d62a7596 Add some missing changes to the changelog. 2021-06-18 16:23:44 -07:00
Dan Albert
980a224d02 Move fixes to the correct changelog section.
What was to be 3.1.0 is now 4.0.0 to accomodate that DCS update.
2021-06-18 16:11:02 -07:00
Khopa
0c6b83fc35 Added default Mi-24P payloads 2021-06-19 01:05:14 +02:00
UKayeF
6d2310f59d add Mi-24P as CAS capable aircraft - unsure which other tasks it could be useful for? 2021-06-19 00:54:20 +02:00
jsjlewis96
05107fab1c Added Mi-24P to factions post '80 that use Hind-E 2021-06-19 00:51:49 +02:00
jsjlewis96
285bed65c6 Added Mi-24P to Russia 1990 & 2010 factions 2021-06-19 00:51:47 +02:00
Khopa
b523c23e7a Added french Mirage-2000C squadrons 2021-06-18 18:38:05 +02:00
Khopa
4c9a028a4e Fixed pydcs error in test_factions.py 2021-06-18 18:19:48 +02:00
C. Perreau
cea970f065 Merge pull request #1248 from jsjlewis96/dot-neutral
#987 Neutral dot labels in options
2021-06-18 18:13:09 +02:00
Khopa
d8511fab1d Fixed pydcs error with missiles units 2021-06-18 18:08:03 +02:00
Khopa
b2d10e92e9 Fixed requirements.txt changes not required 2021-06-18 18:01:44 +02:00
Khopa
0582d5e2b6 Merge branch 'develop' of https://github.com/khopa/dcs_liberation into develop 2021-06-18 18:00:58 +02:00
C. Perreau
da2b56b5b1 Merge pull request #1252 from docofmur/terrain_update_cyprus
Syria Terrian map update
2021-06-18 18:00:09 +02:00
docofmur
46c15f37c5 exclusion zone update 1 test change on caucases, massive update on syria 2021-06-18 17:58:08 +02:00
Dan Albert
4ddc02d7fe Update pydcs. 2021-06-17 23:01:20 -07:00
Dan Albert
4c3ac0af91 Adapt to DCS update. 2021-06-17 22:58:46 -07:00
Dan Albert
edd0b90576 Update pydcs. 2021-06-17 22:22:47 -07:00
Dan Albert
11dca41945 Remove unused file. 2021-06-17 22:11:00 -07:00
Dan Albert
75c4724200 Delete the obsolete converter. 2021-06-17 22:10:15 -07:00
Dan Albert
09704b6f37 Add a wrapper type for ground unit info. 2021-06-17 22:09:17 -07:00
Dan Albert
8a0824880e Add unit classes and weights to infantry. 2021-06-17 22:09:16 -07:00
Dan Albert
d84abf021e Fix some bad unit data. 2021-06-17 22:09:16 -07:00
Dan Albert
e7223da19f Convert remaining unit data. 2021-06-17 22:09:16 -07:00
Dan Albert
499d143199 Add a converter for groun unit info. 2021-06-17 22:09:06 -07:00
Dan Albert
fefeb3c006 Fix broken factions. 2021-06-17 18:49:55 -07:00
Dan Albert
6aeee933d2 Fix broken ground unit data. 2021-06-17 18:39:45 -07:00
Dan Albert
34c0698c48 Remove unused aircraft from the old unit data. 2021-06-17 18:39:45 -07:00
jsjlewis96
1cc1a00820 Updated changelog 2021-06-17 23:12:57 +01:00
jsjlewis96
62f6b57948 Added neutral dot option 2021-06-17 23:12:30 +01:00
docofmur
5387acf533 exclusion zone update 1 test change on caucases, massive update on syria 2021-06-17 14:51:48 -07:00
C. Perreau
077b3ef04d Merge pull request #1243 from DanAlbert/f-16-strike-gbu-31
Update F-16 strike loadout to use GBU-31.
2021-06-17 22:39:58 +02:00
Dan Albert
9c654254d3 Update F-16 strike loadout to use GBU-31. 2021-06-16 21:43:09 -07:00
Mustang-25
4bb8bbbad8 Add remaining HAF Viper squadrons. 2021-06-16 21:05:50 -07:00
Dan Albert
39adafb1be Fix Greek F-16 livery ID. 2021-06-16 20:52:15 -07:00
Dan Albert
e19bfcdd04 Add a Greek F-16 squadron. 2021-06-16 20:37:07 -07:00
Dan Albert
6fde92f5ac Add the 191. Filo Turkish F-16 squadron. 2021-06-16 20:13:07 -07:00
Dan Albert
7170a7b302 Fix spawning unused aircraft.
These are assigned a squadron even though they're unused as a hack. We
need to tolerate these aircraft having no pilot assigned since that's
the desired case for unused aircraft (though only happens when the
squadron runs out of pilots, which should be fixed).
2021-06-16 20:11:36 -07:00
Dan Albert
24884e4a77 Import latest beacon data from DCS. 2021-06-16 19:46:19 -07:00
Dan Albert
384be8ceae Update Turkish faction.
Add a bunch of missing helicopters, some ground units, and remove the
KC-130 which they don't seem to use.
2021-06-16 19:10:23 -07:00
Dan Albert
ee9a5e8482 Update the Greek faction.
Greece has C-130s and Patriots. They don't have the E-3 but they do have
AEW&C via the ER-99, which isn't in DCS so just use an E-3 to pretend.
Also remove the Hawk radar as an EWR since we have the P-19 which is
better.
2021-06-16 18:54:12 -07:00
Dan Albert
34453fa3be Fix incorrect conditional. 2021-06-16 17:23:57 -07:00
Dan Albert
f727712bfa Make non-interactive map elements unobstructive.
This makes most of the lines and polygons on the map non-interactive so
they don't capture mouse events, and also makes the culling exclusion
zones unfilled so they don't obscure real map objects in dense areas.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1217
2021-06-16 17:22:07 -07:00
Dan Albert
3bb974b9e0 Note procurement fix in the changelog. 2021-06-16 17:10:21 -07:00
Dan Albert
021445216e Escape the JTAC zone name in the plugin data.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1218
2021-06-16 17:06:45 -07:00
Schneefl0cke
c13bf3ccd1 Fix procurement for factions that lack some units.
Fixes procurement for factions with no aircraft, no ground units, or no
tanks.
2021-06-16 09:34:58 -07:00
Mustang-25
8d53f42421 Update KC135MPRS.yaml
Fixed minor spelling error
2021-06-13 22:56:35 -07:00
Dan Albert
ace42019fb Cap squadron size, limit replenishment rate.
This caps squadrons to 12 pilots and limits their replenishment rate to
1 pilot per turn. Should probably make those values configurable, but
they aren't currently.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1136
2021-06-13 14:40:15 -07:00
Dan Albert
54aa161da0 Fix new game wizard faction template.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1227
2021-06-12 21:48:22 -07:00
Dan Albert
25c289deaa Make squadron nicknames optional. 2021-06-12 21:43:26 -07:00
Dan Albert
3c802e7d55 Fix unit info window. 2021-06-12 21:35:01 -07:00
Dan Albert
ba3cf4d2bd Put back all the radio data. 2021-06-12 20:56:24 -07:00
Dan Albert
4aa905716b Remove old file.
This was from testing and shouldn't have been kept.
2021-06-12 20:28:14 -07:00
Dan Albert
0fc1e8ec10 Remove unused file, begin fixing radios.
My radio data converter broke at some point while testing, so adding
this all back manually.
2021-06-12 20:27:18 -07:00
Dan Albert
0875d35129 Fix some squadrons.
I accidentally reverted my changes here while testing something earlier.
2021-06-12 20:24:04 -07:00
Dan Albert
8c62a081fe Remove unused code from AircraftType conversion. 2021-06-12 20:13:45 -07:00
Dan Albert
f811ae6c61 Convert factions and unit data. 2021-06-12 20:13:45 -07:00
Dan Albert
4a3ef42e67 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.
2021-06-12 20:13:45 -07:00
Dan Albert
88abaef7f9 Fix inconsistencies in prices and unit data. 2021-06-12 20:13:45 -07:00
Schneefl0cke
21fe746f2f Use ID for unit info lookups instead of name. 2021-06-12 02:24:21 -07:00
Dan Albert
c3c6915fa0 Include the micro version in the version string. 2021-06-11 16:52:23 -07:00
Dan Albert
b2705c1a13 Update Northern Russia campaign.
https://github.com/dcs-liberation/dcs_liberation/issues/1206
2021-06-11 16:42:12 -07:00
Mustang-25
75e3b4cc84 Add the First Lebanon War Historical Campaign. 2021-06-10 17:38:40 -07:00
Khopa
78f5235eca Removed helipad from golan heights campaign to avoid capture trigger error 2021-06-10 23:27:45 +02:00
Khopa
adad88681e Generate helipads as neutral objects, so they do not interfer with base capture trigger 2021-06-10 23:18:41 +02:00
Florian
78cd17e279 added missing units 2021-06-10 11:18:52 -07:00
Khopa
1b9ac088e4 Refactor & fix code after comments 2021-06-10 13:19:22 +02:00
Khopa
e00951e5b9 Merge remote-tracking branch 'khopa/develop' into helipads 2021-06-10 13:01:24 +02:00
Dan Albert
c51c8aae5c Clarify the docs/name of the task type list. 2021-06-09 21:53:45 -07:00
Dan Albert
40aa7734e1 Fix CAS commit range display.
CAS commits around the target, not its flight plan.
2021-06-09 21:51:26 -07:00
Dan Albert
0594e1148e Update Operation Mole Cricket.
https://github.com/dcs-liberation/dcs_liberation/issues/1203
2021-06-09 21:26:47 -07:00
Dan Albert
9eacd1563f Add Northern Russia campaign.
https://github.com/dcs-liberation/dcs_liberation/issues/1202
2021-06-09 21:25:59 -07:00
SnappyComebacks
a53a648a63 Add plannable tankers.
This Pull Request lets users plan Tanker flights.

Features:

- Introduction of `Refueling` flight type.
- Tankers can be purchased at airbases and carriers.
- Tankers get planned by AI.
- Tankers are planned from airbases and at aircraft carriers.
- Tankers aim to be at high, fast, and 70 miles from the nearest threat.
  (A10s won't be able to tank)
- Tankers racetrack orbit for one hour.
- Optional Tickbox to enable legacy tankers.
- S-3B Tanker added to factions.
- KC-130 MPRS added to factions.
- Kneeboard shows planned tankers, their tacans, and radios.

Limitations:

- AI doesn't know whether to plan probe and drogue or boom refueling
  tankers.
- User can't choose tanker speed.  Heavily loaded aircraft may have
  trouble.
- User can't choose tanker altitude.  A-10s will not make it to high
  altitude.

Problems:

- Tanker callsigns do not increment, see attached image.  (Investigated:
  Need to use `FlyingType.callsign_dict`, instead of just
  `FlyingType.callsign`.  This seems like it might be significant work
  to do.).
- Having a flight of two or more tankers only spawns one tanker.
- Let me know if you have a solution, or feel free to commit one.

https://user-images.githubusercontent.com/74509817/120909602-d7bc3680-c633-11eb-80d7-eccd4e095770.png
2021-06-09 21:14:10 -07:00
Dan Albert
a9dacf4a29 Fix engagement distance display. 2021-06-09 21:01:14 -07:00
Dan Albert
66f82b6ff9 Update mission start guidance. 2021-06-09 19:20:56 -07:00
Dan Albert
0e68884493 Remove incompatible campaigns.
We have quite a few campaigns now, so removing the broken ones.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1178
2021-06-09 19:08:36 -07:00
Dan Albert
f8d885fc9a Fix broken import. 2021-06-09 19:06:02 -07:00
Florian
366190ee99 added missing units to price table 2021-06-09 19:03:25 -07:00
Dan Albert
42d56a324f Make campaign names consistent. 2021-06-09 18:58:35 -07:00
docofmur
7d1f1ea2f7 Campaigns for 3.0
4 campaigns updated for 3.0 1 small PG 3 for Caucasus 1 full and 2 parts based on the full
2021-06-09 18:55:22 -07:00
Dan Albert
30cab8e3a7 Add Around the Mountain campaign.
https://github.com/dcs-liberation/dcs_liberation/issues/1199
2021-06-09 18:51:34 -07:00
Dan Albert
e0e2162c6d Add Operation Allied Sword campaign and factions.
https://github.com/dcs-liberation/dcs_liberation/issues/1196
2021-06-09 18:44:09 -07:00
Dan Albert
f1582fcc10 Add Humble Helper campaign and factions.
https://github.com/dcs-liberation/dcs_liberation/issues/1197
2021-06-09 18:39:26 -07:00
Florian
eb6206ea57 added texts for all units 2021-06-09 12:42:56 -07:00
Brock Greman
3ad51cafa8 Fixing display of "sunny" during clear conditions at night. 2021-06-09 02:16:05 -07:00
Dan Albert
b8c14d69c3 Make enable_and_reset not half lie.
https://github.com/dcs-liberation/dcs_liberation/issues/1185
2021-06-08 21:19:48 -07:00
Dan Albert
725b5083c7 Fix typo in Incirlik runway data.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1188
2021-06-08 21:14:36 -07:00
Dan Albert
87dd6b19bf Fix repeated JTACs after multiple generations.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1191
2021-06-08 20:56:00 -07:00
bgreman
3188994261 Gripen mod support.
(cherry picked from commit 0220fa4ff6)
2021-06-08 20:49:24 -07:00
Schneefl0cke
e4c9d8799e Add Recon combat role. 2021-06-08 19:48:56 -07:00
dependabot[bot]
bc938db7f9 Bump pillow from 8.1.1 to 8.2.0
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.1.1 to 8.2.0.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.1.1...8.2.0)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-08 16:15:25 -07:00
Khopa
b7a0feba5b Added more helipads on Golan Heights 2021-06-08 13:45:21 +02:00
Khopa
51fa0a0891 Added function to get cp number of fuel depots 2021-06-08 13:18:27 +02:00
Khopa
f4c54bb9e6 Autogenerate ammo & fuel for helipads so player controlled helicopter can use ground crew menu to refuel and rearm at FARPs. 2021-06-08 13:17:34 +02:00
Khopa
e00ca5d096 Merge branch 'develop' into helipads 2021-06-08 13:09:11 +02:00
Dan Albert
0a9dc49e7f Remove UNIT_BY_TASK. 2021-06-07 19:13:49 -07:00
Dan Albert
07cdfc16d0 Move support tanker off find_unittype. 2021-06-07 19:12:30 -07:00
Dan Albert
622a171ac4 Move armor TGO purchase off find_unittype. 2021-06-07 19:01:16 -07:00
Dan Albert
fd85efbf55 Remove more dead code in game.db. 2021-06-07 18:59:02 -07:00
Dan Albert
ae2a818d8c Move the base intel menu off find_unittype. 2021-06-07 18:54:51 -07:00
Dan Albert
6966c16dd2 Remove dead code. 2021-06-07 18:54:39 -07:00
Dan Albert
27b5f24a0f Move unit purchase off find_unittype. 2021-06-07 18:54:21 -07:00
Dan Albert
ea15421308 Migrate support AEW&C away from find_unittype. 2021-06-07 18:52:54 -07:00
Dan Albert
ef35ad90b8 Remove one user of UNIT_BY_TASK. 2021-06-07 18:01:31 -07:00
Dan Albert
914691eaa7 Remove more unused code from Base. 2021-06-07 17:51:25 -07:00
Dan Albert
37bb83dfa6 Delete a bunch of unused code from Base. 2021-06-07 17:48:03 -07:00
Dan Albert
d8881e2734 Fix hangar status display. 2021-06-06 17:12:44 -07:00
Dan Albert
45869c428e Label the player checkbox in the roster editor. 2021-06-06 13:43:34 -07:00
Dan Albert
40832bd3a1 Update screenshot on the front page. 2021-06-06 13:37:01 -07:00
Khopa
126a8e8efb Added a small WW2 campaign on Normandy map (Replacing the former Normandy Small campaign). 2021-06-06 18:50:16 +02:00
Khopa
07b93167f0 Improved implementation. 2021-06-06 17:49:56 +02:00
Khopa
29c0a8d054 Fixed ground start for helos in FOB 2021-06-06 17:28:23 +02:00
Khopa
73b1be36a2 Merge branch 'develop' into helipads
# Conflicts:
#	game/theater/conflicttheater.py
#	gen/flights/flightplan.py
2021-06-06 15:46:30 +02:00
Dan Albert
1796c21f48 Update the Syria full campaign.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1182
2021-06-05 21:39:45 -07:00
Dan Albert
363d4af639 Add Jordan 2010 faction. 2021-06-05 19:08:52 -07:00
Dan Albert
f1c881378c Add/updates campaigns from Starfire.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1181
2021-06-05 19:07:13 -07:00
Dan Albert
d316e13fa6 Suppress events fired while rebuilding model. 2021-06-05 15:21:23 -07:00
Dan Albert
1ea98a6ed1 Hide incompatible campaigns by default.
https://github.com/dcs-liberation/dcs_liberation/issues/1178
2021-06-05 15:15:30 -07:00
Dan Albert
3d4415d5d2 Move develop to 4.0. 2021-06-05 14:35:07 -07:00
Dan Albert
3e43414d9c Make the new package dialog modal.
In the *new* package dialog, a package has been created and may have
aircraft assigned to it, but it is not a part of the ATO until the user
saves it.

Other actions (modifying settings, closing some other dialogs like the
base menu) can cause a Game update which will forcibly close this window
without either accepting or rejecting it, so we neither save the package
nor release any allocated units.

While it would be preferable to be able to update this dialog as needed
in the event of game updates, the quick fix is to just not allow
interaction with other UI elements until the new package has either been
finalized or canceled.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1027
2021-06-05 14:21:31 -07:00
Dan Albert
6d682d509f Restore former turn 0 budget split. 2021-06-05 14:09:10 -07:00
Florian
3a592aee8b Split purchase budget based on investment ratio.
The AI purchaser will aim to have a 50/50 ground/air investment mix.
This allows it to overspend on one category if significant losses were
taken the previous turn.

The total purchase amount is still limited, so if the bases are full
when only 10% of the investment is in ground units, the full budget for
the turn will still go to air.
2021-06-05 14:07:18 -07:00
Dan Albert
b74f60fe0e Stagger packages in units of seconds, not minutes.
Missions with very large numbers of packages and short mission windows
would raise an exception here because we couldn't schedule more
frequently than once a minute. Switch to using seconds instead of
minutes to avoid that problem. If there are more packages than there are
seconds in the mission the game is broken for other reasons.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1154
2021-06-05 13:50:28 -07:00
Dan Albert
34f3a50234 Fix UI quirks when reopening custom loadout.
* Disable the selector.
* Select the default loadout rather than the first one so unchecking the
  custom box goes back to the default loadout.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1152
2021-06-05 13:40:11 -07:00
Dan Albert
6094179a40 Show pending ground unit count in the base menu.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1161
2021-06-05 13:24:12 -07:00
Dan Albert
e3bc2688ba Revert accidental change to IR campaign.
Used this for debugging airlifts and accidentally included it.
2021-06-05 12:46:19 -07:00
Dan Albert
96cdea2a94 Load two units per cargo plane.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1029
2021-06-05 12:21:34 -07:00
Dan Albert
cb159e3341 Fix canceling transfers.
singledispatchmethod only overloads on the first argument.
2021-06-05 12:00:43 -07:00
Dan Albert
136e776b03 Add map markers for each building in the group.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1126
2021-06-04 18:07:12 -07:00
Dan Albert
a0833e8943 Allow selection of auto-assigned mission types.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1176
2021-06-04 17:50:21 -07:00
Dan Albert
8bb1b1da7c Fix squadron roster size.
This was excluding a number of pilots from the end of the roster equal
to the number of losses the squadron had suffered.
2021-06-04 17:01:29 -07:00
Dan Albert
558502d8ea Convert flight creator to pilot roster.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1143
2021-06-04 17:01:29 -07:00
Khopa
8edb952800 Updated campaign "Golan Heights" to version 6.0 2021-06-05 01:24:08 +02:00
Mustang-25
f3d79e58db Add the Battle for the UAE Campaign.
The Battle for the UAE is a follow-on campaign to the Battle for Abu Dhabi.
2021-06-03 23:30:02 -07:00
Dan Albert
f26ff085e1 Add a new bug template for campaign update "PRs". 2021-06-03 19:08:00 -07:00
Brock Greman
7ea550738e Sorts flights in the base menu by mission start time. Also makes base menu dialog bigger. 2021-06-03 15:32:49 -07:00
Brock Greman
6b1048590f Fixes issue where only first a/c in a flight would show in air inventory 2021-06-03 14:46:12 -07:00
Schneefl0cke
203f0d3851 Introduce recon unit type, adjust ratios. 2021-06-02 23:00:35 -07:00
Dan Albert
d9c38a716c Move settings and stats to the toolbar.
https://github.com/dcs-liberation/dcs_liberation/issues/1146
2021-06-01 22:59:15 -07:00
Mustang-25
24709d01bd Add the Operation Mole Cricket 2010 Campaign. 2021-06-01 22:13:23 -07:00
Dan Albert
2dc2681f84 Attach bug URL to a TODO. 2021-06-01 20:16:33 -07:00
Dan Albert
d53a39860e Update Black Sea to latest campaign format. 2021-06-01 18:49:33 -07:00
SnappyComebacks
ad2f084112 Added ammunition depot changes to 3.0 changelog. 2021-05-31 22:20:38 -07:00
Dan Albert
d59c42ed3f Fix generation crash for large campaigns.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1162
2021-05-31 21:02:46 -07:00
Dan Albert
e022ffee62 Auto-ASAP player missions. 2021-05-31 20:05:04 -07:00
Dan Albert
77ddd5ed78 Don't include off-map spawns for AEW&C planning. 2021-05-31 20:00:10 -07:00
Dan Albert
8604faffe6 Make EWR sites purchasable.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/968
2021-05-31 16:33:55 -07:00
Dan Albert
45919200c4 Depopulate captured objectives.
Buildings are left to be captured, but the retreating coalition now
destroys their abandoned equipment.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1158
2021-05-31 15:43:20 -07:00
Dan Albert
d498bb9cff Give AEW&C a significant buffer from threats. 2021-05-31 15:33:21 -07:00
Dan Albert
389f60786a Fix moving carriers. 2021-05-31 15:13:56 -07:00
Dan Albert
2d0929cd69 Plan AEW&C in safer locations.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1119
2021-05-31 14:57:25 -07:00
Dan Albert
e94ebd6ed2 Invert AEW&C default behavior.
This is working well. Make it the default, but don't remove it since we
don't have HAVCAP yet.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1118
2021-05-31 14:42:22 -07:00
Dan Albert
77373606fe Fix crash in startup. 2021-05-31 14:36:25 -07:00
Dan Albert
284f2bc323 Show runway status on the new map.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1105
2021-05-31 14:18:27 -07:00
Dan Albert
355e6e1d15 Fix several cases of wrongly using broken runways.
The usual symptom here was the game breaking when a carrier is
destroyed. The carrier would no longer be operational but missions would
be assigned there that could not generate flight plans.
2021-05-31 14:13:33 -07:00
Dan Albert
f6909d2f98 Use airfield icons for off-map spawns.
Nothing else is really appropriate, and these are meant to represent
off-map airfields.
2021-05-31 13:23:47 -07:00
Dan Albert
c42974f7b3 Update FOB icon.
Also removes the possibility of generating FOBs that are not FOBs.
2021-05-31 13:14:45 -07:00
Khopa
230d80a2a5 Updated campaign "Russia Small" campaign to version 6.0 2021-05-31 19:52:06 +02:00
Dan Albert
551038b295 Fix TGO purchase UI.
Enable buying and selling of armor groups. Don't allow armor groups to
be replaced with air defenses or vice versa. These are a different TGO
type and this has always been a thing that will break the flight
planner.
2021-05-30 21:17:55 -07:00
Dan Albert
4055b06e71 Clean up and rename ControlPoint.for_airbase. 2021-05-30 21:17:12 -07:00
Dan Albert
6616359baf Remove "base defenses" UI features.
There's no such thing any more. There are just objectives that are
closer to the CP than the others.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1130
2021-05-30 21:07:48 -07:00
Dan Albert
a5336bbe56 Note dropping random objectives in the changelog. 2021-05-30 20:51:18 -07:00
Dan Albert
871e7f7a50 Remove random objective generation.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1076
2021-05-30 20:47:20 -07:00
Dan Albert
d1c7146a47 Add cheat options back to front lines.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1108.
2021-05-30 20:16:54 -07:00
Dan Albert
30f6220c3e Remove the old map. 2021-05-30 19:57:14 -07:00
Dan Albert
acd3e87996 Remove accidentally preserved debug log in UI. 2021-05-30 19:46:38 -07:00
Dan Albert
8c8814d07e Add culling display option to the new map.
https://github.com/dcs-liberation/dcs_liberation/issues/1097
2021-05-30 19:32:08 -07:00
Dan Albert
417fc3af5b Allow objects near missile launchers to be culled.
We want the scud to not be culled, but we should still cull things
nearby. Rather than making the scud the center of a 2.5km unculled zone,
just exclude missile objectives from culling.
2021-05-30 19:29:59 -07:00
Dan Albert
2218733da4 Add exclusion zone display to the new map.
https://github.com/dcs-liberation/dcs_liberation/issues/1097
2021-05-30 18:50:53 -07:00
Brock Greman
9d1060975e Fixes the ugly border on the Air Inventory View 2021-05-30 16:47:18 -07:00
Dan Albert
82281e2477 Fix inventory handling when adjusting flight size.
We need to resize the flight before attempting to claim the aircraft, or
we'll reclaim the original number of aircraft rather than the new size.
2021-05-30 15:46:54 -07:00
Dan Albert
d0976c45e9 Add pilot assignements to the inventory table. 2021-05-30 14:28:58 -07:00
bgreman
a888397bef Add a global air inventory view to air wing dialog.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/428.
2021-05-30 13:40:51 -07:00
Brock Greman
7b2bb4a128 Show ground unit supply info in the base menu.
Update the base UI to have a hint about ground unit deployment limits
and a matching tooltip for how it is calculated.
2021-05-30 13:15:06 -07:00
SnappyComebacks
d440dc00f1 Purchase reserves at front lines.
This changes the ground unit purchase behavior such that the supply
limit is exceeded by 30%, with the extra units kept in reserve.

The old hard cap of 50 units is no longer needed, since the ammo supply
now does the same task, so that's been removed.
2021-05-30 13:04:18 -07:00
Florian
d61382f4e2 Maintain composition when buying ground units.
Unit composition is defined by the doctrine. The most understaffed CP
will now get the most underrepresented unit type. Previously a random
understaffed CP would get a random unit type.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1057.
2021-05-30 12:52:35 -07:00
Khopa
d4fe893539 Updated "Russia Small" campaign to 5.0 (ammo depots) 2021-05-30 17:58:56 +02:00
Khopa
1af95955b6 Base menu UI : Added ammo depots & factory information (WIP UX) 2021-05-30 17:49:15 +02:00
Khopa
4eb78810c6 Merge branch 'develop' into helipads
# Conflicts:
#	resources/campaigns/golan_heights_lite.miz
2021-05-30 17:29:55 +02:00
Khopa
a43e926dd2 Updated campaign "Golan Height" for v5.0 (Ammo depots) 2021-05-30 16:59:02 +02:00
Khopa
ff49046bfa Updated locales for a few factions 2021-05-30 16:57:51 +02:00
SnappyComebacks
95b0b851a5 Limit front line size with ammo depots.
This limit is determined by the number of buildings that belong to Ammo
Depots at the front line's connected Control Point. The limit increases
for every surviving building at ammo depot objectives.

There is a lower limit to the number of units that will spawn, so that
if there are no surviving ammo depot buildings at a control point, there
will still be some ground conflict.
2021-05-29 13:25:23 -07:00
Dan Albert
077ca19912 Add ammo depots to Abu Dhabi and Inherent Resolve.
IR gets one per base to maintain the old behavior. Abu Dhabi has a bit
more variety, with major bases like Al Dhafra and Bandar Abbas getting
two and FOBs getting none.
2021-05-29 12:36:05 -07:00
Brock Greman
089cc23648 Fixing duplicate connected CPs between Beslan and Modok and Beslan and Nalchik. 2021-05-29 03:05:22 -07:00
Dan Albert
e6b9a73d03 Improve AI air defense target prioritization.
Target the air defenses whose *threat ranges* come closest to friendly
bases rather than the closest sites themselves. In other words, the
SA-10 that is 5 miles behind the SA-6 will now be the priority.

This also treats EWRs a bit differently. If they are not protected by a
SAM their detection range will be used for determining their "threat"
range. Otherwise a heuristic is used to determine whether or not they
can be safely attacked without encroaching on the covering SAM.
2021-05-28 19:27:02 -07:00
Dan Albert
cea264e871 Remove special case behavior for FOB missions.
The only difference from the main CP types was that it didn't support
AEW&C (which shouldn't have been on the main ControlPoint class anyway)
and add strike.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1132
2021-05-28 18:02:57 -07:00
Dan Albert
d0bde7b016 Check for interesection when localizing.
Apparently it is possible to place an objective exactly on the boundary
of a navpoly.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1140
2021-05-28 17:26:46 -07:00
Dan Albert
5b271df66f Propagate planning error for package waypoints.
We did this for the flight plan itself, but did not if the package
waypoints failed to generate.

https://github.com/dcs-liberation/dcs_liberation/issues/1140
2021-05-28 17:26:31 -07:00
Dan Albert
bc7faee880 Add navmesh map mode to the new map.
https://github.com/dcs-liberation/dcs_liberation/issues/1097
2021-05-28 17:00:33 -07:00
Dan Albert
a2abdcf5d3 Ensure that a transit path exists for recruitment.
Networks can be disconnected even by airlift because FOBs are not
airports.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1147
2021-05-28 16:28:50 -07:00
Dan Albert
d4e843983d Add more tracing for turn processing.
Most of the time (1-2 seconds) is going to flight plan layout. There
don't seem to be any easy opportunities for improvement.
2021-05-28 15:31:33 -07:00
Dan Albert
6e41c36a44 Fix replacing unassigned pilot slots. 2021-05-27 22:51:11 -07:00
Dan Albert
1fe3451120 Set locales for some factions.
Far from complete.
2021-05-27 21:37:04 -07:00
Dan Albert
bc4a95d0a5 Un-WIP squadrons in the changelog.
This is feature complete.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 21:05:01 -07:00
Dan Albert
14dc6d1604 Add squadron selector to flight creator.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1142
2021-05-27 21:00:32 -07:00
Dan Albert
1795ed7617 Limit squadron tasks to those of the aircraft.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 20:27:45 -07:00
Dan Albert
e8edb31be3 Revert "Don't assign pilots to unused aircraft."
The unitmap needs to account for this.

This reverts commit dae3835eb0.
2021-05-27 20:02:39 -07:00
Dan Albert
58fd30e6ad Add the 15th Airlift Squadron. 2021-05-27 19:58:45 -07:00
Dan Albert
9a34ada258 Clear last turn's procurement requests each turn.
Without this, *this turn's* urgent requests are lower priority than last
turn's stretch goals. The requests are remade every turn so we lose
nothing by removing this.

Bug was introduced by f69450e2ae, so this
doesn't affect 2.5.
2021-05-27 19:58:45 -07:00
Dan Albert
748a752e29 Fix pydcs loadout cache for command line launcher. 2021-05-27 19:58:45 -07:00
Dan Albert
37748ef3bd Obey squadron mission types when planning airlift.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 19:58:45 -07:00
Dan Albert
d41007de8e Add VFA-192. 2021-05-27 19:58:45 -07:00
Dan Albert
45befd440c Consider squadron for task capability checking.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 19:58:45 -07:00
Dan Albert
a2c10f1c7a Check for compatible squadrons when buying planes.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 19:58:45 -07:00
Dan Albert
d7768f86d3 Obey squadron mission types in auto-planning.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 19:58:45 -07:00
Dan Albert
dae3835eb0 Don't assign pilots to unused aircraft.
These "flights" are only created so that we can spawn the aircraft on
the ramp for OCA strikes. They shouldn't have pilots assigned.
2021-05-27 19:58:45 -07:00
Dan Albert
e9b5784d30 Update player slot advice for update UI.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 17:35:54 -07:00
Dan Albert
1521f0a9b1 Add on-leave toggle for pilots.
Pilots on leave will not be assignable to any flights (but will not be
unassigned from any already scheduled this turn).

https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 17:09:09 -07:00
Dan Albert
9a9c351f47 Copy the list of random names as was intended.
Every name generated depopulated the global list which made reset do
nothing. Large numbers of TGOs (or generation of many campaigns) would
drain the list fully and new squadrons would no longer have a name list
to pull from.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1144
2021-05-27 16:32:21 -07:00
Dan Albert
4ec11ddea5 Auto-ASAP player packages based on preferences.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 16:04:51 -07:00
Dan Albert
f619b6b9fc Choose player pilots based on player preference.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 16:00:27 -07:00
Dan Albert
bcccb3206d Connect auto-ATO disable option.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/315
2021-05-27 15:43:47 -07:00
Dan Albert
11a8ff7f70 Add settings UI for auto-ato behavior.
https://github.com/dcs-liberation/dcs_liberation/issues/276
https://github.com/dcs-liberation/dcs_liberation/issues/315
2021-05-27 15:41:08 -07:00
Dan Albert
f6ab1aad77 Clean up signal handling in pilot roster editor. 2021-05-27 15:06:36 -07:00
Dan Albert
5a732acf64 Fix creating new fights to create player pilots.
This is just a hack that automatically converts the assigned pilots to
players if needed. This really needs to be replaced with a roster editor
like the flight edit screen has, but that also requires squadron
selection, which isn't a thing we're ready for yet.

https://github.com/dcs-liberation/dcs_liberation/issues/1139
2021-05-27 14:15:27 -07:00
Dan Albert
e4e06e0a6e Add player toggle to flight settings.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 02:18:57 -07:00
Dan Albert
28f20d47d3 Add player pilot invulnerability option.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 01:40:23 -07:00
Dan Albert
82ce688a0d Allow players to be defined in the squadron file.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 01:15:52 -07:00
Dan Albert
f36757b650 Add livery selection for predefined squadrons.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 00:56:05 -07:00
Dan Albert
ac4a7441e9 Add predefined squadron support.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-27 00:23:40 -07:00
Dan Albert
9091afe682 Remove very dead campaign.
This was never updated to the miz format. Patches welcome if someone
wants to bring it up to date.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1129
2021-05-26 23:05:57 -07:00
Dan Albert
e2034b19e7 Update missing clients advice.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 20:41:22 -07:00
Dan Albert
1b7a225f9d Replace client count with player pilots.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 20:33:23 -07:00
Dan Albert
a52043ef29 Allow toggling player/AI pilot state.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 20:33:15 -07:00
Dan Albert
b38d271f10 Show player/AI status for pilots.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 19:47:53 -07:00
Dan Albert
e480519855 Increase skill level for experienced pilots.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 19:34:24 -07:00
Dan Albert
8b8d1e87e7 Track missions flown for each pilot.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 19:04:06 -07:00
Dan Albert
cd6de191d1 Track pilot deaths.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 18:54:07 -07:00
Dan Albert
8b8e018521 Fix cases where pilots were not returned.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 18:49:19 -07:00
Dan Albert
5277beede3 Show active and available pilots in air wing view.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 18:18:22 -07:00
Dan Albert
57a2457050 Show aircraft type in the squadron list.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 17:49:53 -07:00
Dan Albert
2f8656d54f Generate random squadron nicknames.
A little weird that the animal names aren't plural, but good enough.

https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 17:49:53 -07:00
Dan Albert
49102e510d Disallow creating missions with missing pilots.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 17:49:53 -07:00
Dan Albert
e7b8548698 Clean up more delegates.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 17:49:53 -07:00
Dan Albert
9c2bad85d5 Show number of missing pilots in the UI.
https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 17:49:53 -07:00
Dan Albert
4147d2f684 Initial squadrons implementation.
Doesn't actually do anything yet, but squadrons are created for each
aircraft type and pilots will be created as needed to fill flights.

https://github.com/dcs-liberation/dcs_liberation/issues/276
2021-05-26 17:49:53 -07:00
Dan Albert
6b30f47588 Fix airlifts always using player country. 2021-05-26 16:48:36 -07:00
Dan Albert
e49da6afd6 Inject the saved games path from preferences.
pydcs can't guess the saved games path accurately for all users, so
inject the path that they've told us is correct to work around that.

It seems pydcs has two problems:

1. Only `DCS` is checked, not `DCS.openbeta`.
2. Only `%USERPROFILE%/Saved Games` is used, so if the user has moved
   their Saved Games directory (but not their whole user profile) pydcs
   cannot find the location.

https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid would
be the starting place for fixing problem 2 properly. 1 is just a matter
of trying both.
2021-05-26 16:02:54 -07:00
Dan Albert
6fa0a29249 Update to Python 3.9.
This is what I've been using locally for ages and it seems to work fine.
2021-05-26 13:15:27 -07:00
bgreman
c163e2c981 Inject mod plane weapons into pydcs.
Adds a simple injector that iterates over attrs of an input class and
injects things that look like custom weapons into pydcs's weapons
classes.

Also updated all current mod aircraft configs to perform the injection.
2021-05-26 12:49:49 -07:00
Brock Greman
372bf9d97f Fixing F-22 loadouts 2021-05-26 01:46:29 -07:00
Dan Albert
619d5dd1b9 Teach sweep to care about multi-role too.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1124
2021-05-25 22:58:09 -07:00
Dan Albert
4939faf5fa Schedule SEAD with a one minute lead time. 2021-05-25 22:53:57 -07:00
bgreman
205e4aa707 Add ability to toggle between own/enemy intel. 2021-05-25 22:23:33 -07:00
Dan Albert
81ce7fbb62 Fix handling of empty polys in the new UI.
This was copied from the Qt map and tweaked, but the use cases are
slightly different so this needs to return an empty list for an empty
polygon instead of None.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1121
2021-05-25 19:19:45 -07:00
Dan Albert
de9651533f Load map.js explicitly from canvas.html.
Without this it's hard to get to map.js in the debug tools since Chrome
doesn't know about the anonymous js. Probably improves logging too.
2021-05-25 18:46:41 -07:00
Dan Albert
e6e31fd234 Actually ASAP the ASAP packages.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1117
2021-05-25 14:23:00 -07:00
Brock Greman
d242079a74 Making Sweep flight types have appropriate aircraft 2021-05-25 13:20:47 -07:00
Dan Albert
48f26cb181 Fix Bandar Abbas airfield data.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1114
2021-05-25 00:14:20 -07:00
bgreman
c37a5b2405 Prevent empty transfers.
Disables the 'create transfer order' button in the unit transfer dialog if no units are actually selected for transfer (including when the dialog is first loaded).
2021-05-24 20:43:33 -07:00
Dan Albert
d15bfaac76 Fix group targeting for multi-group TGOs.
AI flights were only getting a single Attack Group task against multi-
group TGOs (currently only a small group of SAMs like the SA-10, I
believe), so the AI would never attack the point defense SA-15 or AAA
groups.
2021-05-24 19:26:03 -07:00
Dan Albert
e94657875f Reselect same row after deleting waypoint. 2021-05-24 18:20:19 -07:00
Dan Albert
f2bd7300aa Improve precision of kneeboard lat/lon.
DMS with decimal seconds is what the hornet uses for PP targest. In the
future we'll want to make this aircraft specific (and potentially user
preference for jets like the A-10 that can handle both L/L and MGRS).
2021-05-24 18:06:47 -07:00
Dan Albert
c255aee3b9 Make default AEW&C missions ASAP. 2021-05-24 17:21:33 -07:00
Dan Albert
305d1f0523 Reset non-custom loadout when changing task. 2021-05-24 16:57:36 -07:00
Dan Albert
970f2c25dd Fix loadout reset when disabling custom loadouts. 2021-05-24 16:49:31 -07:00
Dan Albert
b7b3b35816 Make some waypoint types undraggable.
None of these (takeoff, landing, divert, bullseye, precise target
locations) can be usefully moved, so prevent it.
2021-05-24 16:45:21 -07:00
Dan Albert
e8f326ebce Update Skynet to 2.1.0. 2021-05-24 14:35:22 -07:00
Dan Albert
62b743025a Fix supply route clobbering, make immutable.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1083
2021-05-23 17:30:50 -07:00
Dan Albert
7934463a53 Add base capture cheat to the new UI.
We don't have a context menu yet, so just add it to the base menu.

https://github.com/dcs-liberation/dcs_liberation/issues/1108
2021-05-23 17:18:01 -07:00
Dan Albert
d15ef63182 Remove unused method of ControlPoint. 2021-05-23 17:17:59 -07:00
Dan Albert
c7edba5120 Add TGO-specific layers.
This also splits the main and debug controls because the main list was
getting too long.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1069
2021-05-23 15:36:22 -07:00
Dan Albert
188f871bc8 Remove errant whitespace. 2021-05-23 15:01:10 -07:00
Dan Albert
31eba975fd Note flight planner changes.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1106
2021-05-23 15:00:27 -07:00
Dan Albert
2ea0bccd25 Hide dead opfor objectives.
These are just clutter.
2021-05-23 14:44:24 -07:00
Dan Albert
fa321c7ddc Don't plan SEAD when only a search radar remains. 2021-05-23 13:15:42 -07:00
Dan Albert
1d7b0c9b17 Tweak F/A-18 BARCAP and CAS loadouts.
Add bags to each. CAS only gets one but that should be plenty for only
four Mavericks. CAP gets two.
2021-05-23 13:07:16 -07:00
Dan Albert
a4fbcd2d02 Update pydcs for loadout loading fix. 2021-05-23 13:07:16 -07:00
Dan Albert
d788b286aa Remove unused UI classes. 2021-05-23 13:03:18 -07:00
Dan Albert
eedb5c26a9 Ignore non-escorted regions when planning escorts.
We shouldn't consider the non-escorted parts of the flight path when
checking for threats to determine if escorts should be used or not,
since escorts can't help in those areas anyway. This was causing escorts
to be overly requested since the bullseye is now a part of the
"flight plan", but could have also triggered for divert waypoints, or
for aircraft taking off in a retreat from a threatened location.
2021-05-23 13:01:44 -07:00
Dan Albert
ddd6e7d18f Improve detection of functional radar SAMs.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1109
2021-05-23 13:01:44 -07:00
Dan Albert
eae0d6be94 Add threat zone drawing for the new map.
https://github.com/dcs-liberation/dcs_liberation/issues/1097
2021-05-23 12:25:15 -07:00
Dan Albert
5e68dbe1ca Correct the list of units with radars.
Probably.

https://github.com/dcs-liberation/dcs_liberation/issues/1109
2021-05-23 01:30:23 -07:00
Dan Albert
98e0be6be9 Revert "Correct radar detection."
We need this after all, but we do need to audit the list. Will follow
up with that fix.

https://github.com/dcs-liberation/dcs_liberation/issues/1109

This reverts commit f68935735d.
2021-05-23 01:10:29 -07:00
Dan Albert
7450a6b7eb Configure more loadout fallbacks. 2021-05-22 20:12:56 -07:00
Dan Albert
c3802e5a37 Make UI created packages ASAP by default. 2021-05-22 19:35:56 -07:00
Dan Albert
43cd9bce67 Fix cargo ship locations in Abu Dhabi.
Apparently these ships have a > 32ft draft and these ports are shallow.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1104
2021-05-22 19:17:53 -07:00
Dan Albert
2f6ab6d2b0 Update Hornet loadouts, add DEAD loadout. 2021-05-22 17:11:10 -07:00
Dan Albert
2df17c32cd Clean up aircraft selector. 2021-05-22 17:11:10 -07:00
Dan Albert
16fff8d87a Fall back to SEAD loadout for SEAD escort.
These usually do not need to differ.
2021-05-22 17:11:10 -07:00
Dan Albert
1087069277 Fix F-14 SEAD/DEAD loadouts.
The AI doesn't use mixed loadouts effectively (only the TALDs get used
and the flight returns home with a full bomb load):
https://forums.eagle.ru/topic/271941-ai-rtbs-after-firing-decoys-despite-full-load-of-bombs/

This makes the SEAD loadout TALDs only and the DEAD loadout bombs only.
2021-05-22 16:53:48 -07:00
Dan Albert
1b624e7e6f Remove center tank for F-16 loadouts. 2021-05-22 16:53:48 -07:00
Dan Albert
7223ae327a Add DEAD loadout for the F-16. 2021-05-22 16:45:06 -07:00
Dan Albert
bcdefda0db Make the F-15E CAS loadout less empty. 2021-05-22 16:45:06 -07:00
Dan Albert
fc56642631 Fix default mission length in the UI too. 2021-05-22 16:15:29 -07:00
Dan Albert
69299d395c Empty gun for AI missions that do not need a gun.
There is no "all but gun" RTB winchester option, so air to ground
missions with mixed weapon types will insist on using all of their
bullets after running out of missiles and bombs. Take away their bullets
so they don't strafe a Tor.

Exceptions are made for player flights and for airframes where the gun
is essential like the A-10 or warbirds.
2021-05-22 16:14:20 -07:00
Dan Albert
a789f58068 Allow SEAD escorts against broken SAMs and EWRs. 2021-05-22 15:37:31 -07:00
Dan Albert
f68935735d Correct radar detection.
This list includede units without radars and also missed units with
radars. Stop curating the list and just query the unit type.
2021-05-22 15:36:56 -07:00
Dan Albert
ba2157cc43 Tweak winchester behavior for SEAD escort.
They can't suppress air defenses after running out of TALDs or ARMs.
2021-05-22 15:09:10 -07:00
Dan Albert
57fe5c04ec Improve DEAD mission planning.
We don't need to include a SEAD flight in missions against EWRs or SAMs
that no longer have a radar.

Also plan DEAD missions against air defenses that have no radars.
Previously we would never finish killing launcher only sites (which
cannot defend any more, but are cheaper to return to working order than
a fully destroyed site) nor would we plan DEAD against IR SAMs or AAA.
2021-05-22 14:56:18 -07:00
Dan Albert
3a08944c99 Use the CAS DCS type for SEAD so F-14s can do it.
The CAS task type appears to be a superset of the SEAD task in every
way. Larger task variety as well as larger aircraft pool.
2021-05-22 14:27:30 -07:00
Dan Albert
b6154b273c Differentiate SEAD and SEAD escorts.
SEAD suppresses the package's target. SEAD escort protects the package
from any SAM threat along its flight path.
2021-05-22 14:24:13 -07:00
Dan Albert
e332bff362 Decrease error margin on TOT planning.
Everyone seems to do pretty okay generally, with the exception of
estimating ground ops time, which I've also increased (and is a
non-issue for runway/air start defaults).
2021-05-22 01:11:28 -07:00
Dan Albert
59e03434e4 Increase flight speeds to mach 0.85 or 85% of max.
Everyone seems a bit slow, generally. 0.85 is probably a better cruise
speed for supersonic jets and 85% of max is probably fine for subsonic.
2021-05-22 01:10:23 -07:00
Dan Albert
2ca0edf5fd Increase estimate for airfield ground ops.
5 minutes is pretty optimistic at most airfields.
2021-05-22 01:09:43 -07:00
Dan Albert
90dca9072e Change default mission duration to 60 minutes.
This seems like it works better for the number of missions we usually
frag, plus the fact that players will almost always choose an ASAP
package.
2021-05-22 01:04:10 -07:00
Dan Albert
c0ead4a484 Add icons for CPs. 2021-05-21 23:26:15 -07:00
Dan Albert
f8cb9e2bd3 Update Inherent Resolve to use non-random TGOs.
Also adds Ramat David to blue.
2021-05-21 19:13:32 -07:00
Dan Albert
df4dabf68f Add an LHA to Abu Dhabi. 2021-05-21 17:59:19 -07:00
Dan Albert
40720f9949 Fix convoy spawn point from Tabqa to Jirah.
The current spawn point is a disonnected road network according to the
map, so the convoy will never start moving because they have no route to
the destination.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1101
2021-05-21 17:54:01 -07:00
Dan Albert
7e7a1dce7b Fix icons for dead SAMs showing as damaged.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1099
2021-05-21 11:11:44 -07:00
Khopa
f31861441b Merge branch 'develop' into helipads
# Conflicts:
#	game/data/weapons.py
#	game/db.py
#	game/theater/conflicttheater.py
#	resources/factions/france_1995.json
#	resources/factions/insurgents.json
#	resources/factions/iraq_1991.json
#	resources/factions/syria_1967_with_ww2_weapons.json
#	resources/factions/syria_2011.json
2021-05-21 13:58:22 +02:00
Dan Albert
39b9a7f0ed Note DCS bugs that are common issues. 2021-05-21 00:24:12 -07:00
Dan Albert
43010779d4 Enable multirole fighter targeting for escorts.
pydcs didn't support this until now :(
2021-05-20 23:58:05 -07:00
Dan Albert
a1a4fc8c7c Update pydcs. 2021-05-20 23:57:52 -07:00
Dan Albert
621e4a513c Fix DEAD flights to use more than just missiles.
It doesn't seem like AI pilots are capable of using more than one weapon
effectively (see link below), but this at least makes DEAD flights work
when the DEAD flight is carrying only one type of weapon and some other
flight is performing SEAD.

https://forums.eagle.ru/topic/271941-ai-rtbs-after-firing-decoys-despite-full-load-of-bombs/
2021-05-20 23:51:39 -07:00
Dan Albert
6c821039b5 Add a spectator slot.
So I stop accidentally giving orders while testing AI behavior after
waiting 20 minutes for them to get to their objective.
2021-05-20 21:46:20 -07:00
Dan Albert
f80b948fb1 Fix loadout downgrading bugs.
If the pylon had no weapon this would raise, and if no replacement was
found we wouldn't clear the pylon.
2021-05-20 21:10:02 -07:00
Dan Albert
d4c27da892 Move the strike eagle down the CAP list.
Most of the pylons are not actually capable of carrying air to air
missiles.
2021-05-20 20:12:49 -07:00
Dan Albert
11bf0ca868 Replace JSOW fallbacks with walleyes.
The GBU-12 that was chosen doesn't fit on the hornet in the first place,
and we ought to replace glide bombs with glide bombs.
2021-05-20 19:58:26 -07:00
Dan Albert
664092c023 Remove non-CP FOBs. 2021-05-20 19:01:43 -07:00
Dan Albert
0cd2c4a90c Stop awarding income for FOB structures.
The CP already grants income.

Fixes: https://github.com/dcs-liberation/dcs_liberation/issues/685
2021-05-20 18:59:03 -07:00
Dan Albert
2f6c04a86d Add bullseye to the kneeboard.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/136
2021-05-20 18:35:32 -07:00
Dan Albert
a382e74a89 Set up bullseye early, create waypoints.
Setting this up as part of the game makes it possible for us to show in
the UI.

https://github.com/dcs-liberation/dcs_liberation/issues/136
2021-05-20 18:29:35 -07:00
Khopa
3c8c76f50d Unit support : La Combattante II class ship 2021-05-21 02:45:15 +02:00
Khopa
cbce379132 Unit support : T-155 Firtina 2021-05-21 02:29:31 +02:00
Dan Albert
e795e96bfb Don't show red support units on blue kneeboards.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1080
2021-05-20 17:24:39 -07:00
Khopa
e12e2c4b0b Unit support : Chieftain Mk3 2021-05-21 02:24:14 +02:00
Khopa
9a1b21a2fa Unit support : PT-76 2021-05-21 02:19:52 +02:00
Khopa
79708f9ba6 Unit support : VAB Mephisto 2021-05-21 02:06:35 +02:00
Dan Albert
102544877d Fix common cases of kneeboard overflow. 2021-05-20 16:57:35 -07:00
Dan Albert
1c32ae1227 Create default strike target implementation. 2021-05-20 16:50:01 -07:00
Dan Albert
55d7e444c7 Split support info into its own kneeboard page.
The first page is getting very crowded.
2021-05-20 16:25:06 -07:00
Khopa
cc93c686d9 pydcs update for DCS 2.7.1 2021-05-21 01:17:56 +02:00
Khopa
9243fd499b pydcs update for DCS 2.7.1 2021-05-21 01:15:54 +02:00
Khopa
d5990e60c9 Helicopter flights can be planned from FOBs 2021-05-21 00:34:51 +02:00
Khopa
844dc48d65 Merge branch 'develop' of https://github.com/khopa/dcs_liberation into develop 2021-05-20 13:23:06 +02:00
Dan Albert
52d96b8518 Include steerpoint number in strike page.
https://github.com/dcs-liberation/dcs_liberation/issues/1001
2021-05-20 00:20:48 -07:00
Dan Albert
8274e68846 Add SEAD/DEAD target info kneeboard page.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/965
2021-05-20 00:13:49 -07:00
Dan Albert
f1adcd1836 Be permissive about presumably incorrect loadouts.
These might be broken loadouts, or might be broken pydcs data. In case
it's the latter, attempt to load the pylon. DCS will remove the weapon
if it's not compatible automatically.
2021-05-19 23:33:24 -07:00
Dan Albert
2a77f57aa4 Improve AI strike targeting.
We were setting up all the correct *target* waypoints but the AI doesn't
use the target waypoints; they use the targets property of the ingress
waypoint. This meant that the flight plan looked correct in the UI and
was correct for players but the tasks were set up incorrectly for the AI
because building TGOs are aggravatingly multiple TGOs with the same name
in the implementation.

Mission targets now enumerate their own strike targets so that this
mistake is harder to make in the future.

This won't be perfect, the AI is still not able to parallelize tasks and
since buildings aren't groups they can only attack one structure at a
time, but they'll now at least switch to the next target after hitting
the first one.

As a bonus, stop bombing the dead buildings.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/235
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/244
2021-05-19 23:33:15 -07:00
Dan Albert
04ebe4c68a Add the rest of the TGO icons. 2021-05-19 21:40:36 -07:00
Dan Albert
1c7e065c52 Add more icons. 2021-05-19 21:24:54 -07:00
Dan Albert
80f3857f44 Stop forcing open CP tooltips.
These obscure the TGOs around them. Easy enough to mouse over, and the
names aren't the important part.
2021-05-19 20:49:51 -07:00
Dan Albert
3b62831401 Replace icons for some TGOs.
Only covered about half of the types so far.

This also removes the clustering, since that doesn't really seem to be
needed with the newer icons.
2021-05-19 20:47:52 -07:00
Khopa
a047e1d063 Updated Operation Dynamo campaign 2021-05-19 14:03:24 +02:00
Khopa
45985e1684 Updated payloads for Ju-88A4 2021-05-19 13:24:11 +02:00
Dan Albert
7dac886375 Remove fixed todo from the map. 2021-05-18 23:55:00 -07:00
Dan Albert
af3b8a9902 Set up icons for TGOs.
These are just the old icons, but it's better than nothing.
2021-05-18 23:35:25 -07:00
Dan Albert
4e37666037 Clean up the category property of TGOs.
This really needs to be a proper type, but this is a start: create new
categories for the types of TGOs that are missing. This removes some
icon special cases.
2021-05-18 23:35:25 -07:00
Dan Albert
2769d32c81 Mark enemy transfers in the transfer menu.
https://github.com/dcs-liberation/dcs_liberation/issues/1069
2021-05-18 21:20:38 -07:00
Dan Albert
4b004320a4 Make the transfer button more obvious.
https://github.com/dcs-liberation/dcs_liberation/issues/1069
2021-05-18 21:17:38 -07:00
Dan Albert
edfc879b41 Reorder some CAS aircraft priorities.
Move the harrier up, and the F-14s and B-1 down.
2021-05-18 21:04:11 -07:00
Dan Albert
0879d1da0d Use the best aircraft rather than first found.
The priority list was guiding the purchase decision which largely meant
that this was working correctly, but there were suboptimal cases where
the list was being taken in FIFO order by purchased type. This fixes the
search to be locally optimal, although this does still mean that a worse
but closer aircraft will be chosen over a better but slightly farther
away aircraft. We'd need to have a quality vs distance rating to do
better.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/755
2021-05-18 21:01:26 -07:00
Dan Albert
c5159f8a87 Fix swapped list order for purchase priorities.
We were accidentally iterating over the faction list and checking it
against the priority list rather than the other way around, so the
faction's aircraft list was being used for purchase priority rather than
the actual priority list in the game.
2021-05-18 19:54:39 -07:00
Dan Albert
a0d9bf0f26 Add Ju-88 to the CAS, strike, and DEAD lists.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1008
2021-05-18 19:51:27 -07:00
Dan Albert
a3cce8ff72 Invert the random location warning.
Campaigns should no longer be using these. Remove the warning when a
location cannot be found, and emit a warning when they are used.
2021-05-18 19:36:20 -07:00
Dan Albert
242f00390d Fix purchasing past 0 budget for ground units too.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1032
2021-05-18 19:23:29 -07:00
Dan Albert
f4b64370bb Remove fallback for old non-convoy behavior. 2021-05-18 19:21:43 -07:00
MaHuJa
ae57e4da83 Black sea campaign, inverted: "Russia" now blue. 2021-05-18 19:17:32 -07:00
Dan Albert
cd391a360c Add support for AAA objectives.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/999
2021-05-18 17:29:42 -07:00
Schneefl0cke
dcbe12f1af Changed latest planned flight to desired game settings. 2021-05-18 11:54:56 -07:00
Dan Albert
5b61cfe922 Remove random objectives from Abu Dhabi. 2021-05-18 00:48:12 -07:00
Dan Albert
739406614d Add support for required variants of all TGOs.
Adds required variants of:

* SHORADS
* Armor groups
* Buildings
* Oil rigs
* Coastal defenses
* Missile sites
* Ships

This is prep work for removing random generation.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1076
2021-05-18 00:48:12 -07:00
Dan Albert
8076206a90 Add major/minor versioning of the campaign schema.
Many of the schema version increases are just to add new features that
don't render old campaigns obsolete. Convert the version number to a
major/minor format so we can detect the difference between changes that
render old campaigns obsolete (major versions) and new features that
will not work on older builds of Liberation (minor versions).
2021-05-18 00:12:55 -07:00
Dan Albert
f63d218aae Fix loadouts to work with clean pylons. 2021-05-17 21:28:12 -07:00
Dan Albert
f2e3ccd18c Add loadout names for every Liberation task type.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/867
2021-05-17 01:51:21 -07:00
Dan Albert
d41e69d770 Add DCS loadout selector.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/273.
2021-05-17 01:24:55 -07:00
Dan Albert
0e3bc1ce43 Loadout implementation cleanup.
Loadout selection no longer has two (disagreeing) implementations. What
the UI shows is now what the miz will have.

We now store the chosen layout in the Flight *always*, not just for
custom loadouts. This means that we do loadout lookups at the start of
each turn, but the data is cached in pydcs.

Era-specific loadout degradation is still done at generation (and
presentation) time. This is so that players can toggle that option and
have it affect the *current* turn, rather than the next one.
2021-05-17 01:23:00 -07:00
Dan Albert
6ca175345f Fix DEAD for many bombers, audit DEAD/SEAD lists.
Many of the aircraft that we use for DEAD are not actually capable of
the SEAD task in DCS, so they were being loaded as some other task type,
usually one that doesn't support Attack Group, which made them lose
their waypoint actions and do nothing.

This switches them to using CAS which supports a superset of the SEAD
capable aircraft.

I've also audited the SEAD/DEAD lists. The F-117 was removed because it
is not capable of Attack Group *at all*, and all the non-SEAD aircraft
that are capable of ground attack moved from SEAD to DEAD.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1086
2021-05-16 22:23:01 -07:00
Dan Albert
c063a638cd Disable double click zoom action.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1087
2021-05-16 21:59:48 -07:00
Dan Albert
2dfe1420bc Add "Show all" option for flight plans.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1085
2021-05-16 13:15:51 -07:00
Dan Albert
7dd379c5c3 Show active supply routes in the new UI. 2021-05-16 12:58:03 -07:00
Dan Albert
752eb6235d Remove errant factory from Abu Dhabi.
This wasn't supposed to be here, and it wasn't showing up until I fixed
the bug preventing FOBs from spawning factories.
2021-05-16 12:55:20 -07:00
Dan Albert
3f077727ae Group allied and enemy SAM controls. 2021-05-15 22:08:00 -07:00
Dan Albert
51d557524d Fix unit list for non-building TGOs.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1082
2021-05-15 22:05:14 -07:00
Dan Albert
5d9563304f Update commit boundaries after moving waypoints.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1084
2021-05-15 21:57:37 -07:00
Dan Albert
53cb68f82c Make waypoints draggable. 2021-05-15 16:21:03 -07:00
Dan Albert
95b107ffad Pop up CV move errors. 2021-05-15 14:22:19 -07:00
Dan Albert
06dedf51aa Improve CV waypointing UX. 2021-05-15 14:12:43 -07:00
Dan Albert
ed7c8c11d9 Make CV waypoint less janky.
The CP is now draggable when there is no destination. Otherwise the
destination is draggable.
2021-05-15 13:23:56 -07:00
Dan Albert
643e5954f3 Cluster TGOs less aggressively. 2021-05-15 12:41:04 -07:00
Dan Albert
c7cc9d2a65 Disable SAM threat fill, thicken outline.
As predicted, this only runs well on my machine.
2021-05-15 12:36:56 -07:00
Dan Albert
5050914d25 Make the new UI the default. 2021-05-15 03:38:29 -07:00
Dan Albert
31fa2d866f Allow setting CV routes in the new UI.
This is a pretty janky system until we get add context menu support. For
now the destination is set by dragging the CV marker and cleared by
right clicking the destination marker. Once we have a context menu a
context action will begin setting the destination the way it did in the
old UI, and the destination marker will be draggable.
2021-05-15 03:35:35 -07:00
Dan Albert
4a096cb728 Use load instead of setHtml so paths resolve.
Without this we can't resolve local paths to files.
2021-05-15 01:21:25 -07:00
Dan Albert
16b52f929c Bring CP markers to the front. 2021-05-15 00:21:22 -07:00
Dan Albert
8ec133830f Don't tell the UI about CP TGOs.
These are an implementation quirk, and passing them to the UI just means
that we put TGO pins on top of the CP, which makes the base menu
unopenable.

In the old UI we avoided this by not drawing anything that was
`for_airbase`, but now that we can zoom in further we're drawing base
defenses.
2021-05-15 00:10:05 -07:00
Dan Albert
c144799a11 Shade SAM threat ranges.
This runs a little bit worse but looks a lot better. Will flip back off
if this runs poorly on less powerful computers.
2021-05-14 23:58:37 -07:00
Dan Albert
e56511a05a Ack campaign version 4 for Abu Dhabi.
V4 is scenery objects, so not required.
2021-05-14 23:48:58 -07:00
Dan Albert
bdb959d986 Draw patrol commit ranges in the new map. 2021-05-14 23:41:55 -07:00
Dan Albert
dae9c368b7 Replace var with const/let in map.js. 2021-05-14 23:18:34 -07:00
Dan Albert
2a401a302d Add a topographic map layer. 2021-05-14 23:10:04 -07:00
Dan Albert
ff3b8e5270 Note scenery objective support in the changelog. 2021-05-14 17:19:49 -07:00
SnappyComebacks
bb1a066ff7 Let map objects be Strike targets.
This PR allows campaign creators to incorporate map objects (referred to as Scenery in the code) into their Liberation campaign.

Map objects are defined using white trigger zones created by right clicking on scenery and clicking `assign as...`.   Objective groups are defined by creating a blue TriggerZone surrounding the centers of the white trigger zones.  The type of objective is determined by the campaign creator, assigning the value of the first property of the blue TriggerZone with the objective type.

Map objects maintain their visually dead state by assigning a `Mission Start` `Scenery Object Dead` trigger to the trigger zone.  It is important for the Liberation generated TriggerZone to be as small as possible so that no other scenery is marked dead by DCS.

TriggerZones are hidden during gameplay (DCS behavior.  I don't know if it's possible to turn that off.)  TriggerZones are visible in the mission editor and mission planner however.  If a player is using an older plane, it is important for them to remember where the target is.

In the mission planner, the trigger zones' will be blue or red depending on which faction the map objects belong to.

Inherent Resolve campaign has been modified to integrate scenery objects.

### **Limitations:**
- Objective definitions (Any Blue TriggerZones) in campaign definition cannot overlap.
- Map object deaths in `state.json` is tracking integers.  You won't know what died until debriefing.
- No images for the various buildings.  In theory it can be done, but an unreasonable amount of work.
- Every blue trigger zone must have a unique name.  (If you let DCS auto increment the names this is not a concern.
- No output to screen when scenery object is dead.  You can see the building drawn as dead in the F10 map though.


### **Pictures:**

An objective:
![CampaignCreation](https://user-images.githubusercontent.com/74509817/117526797-c294af00-af84-11eb-9fb7-3940db64c5d8.png)

How the objective looks once in the mission planner/editor.  This objective belongs to the enemy faction:
![MissionPlanner](https://user-images.githubusercontent.com/74509817/117526819-ece66c80-af84-11eb-9db0-64000dedcf89.png)
2021-05-14 17:18:03 -07:00
Dan Albert
9a9872812f Generate factories at FOBs.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1021
2021-05-14 11:38:14 -07:00
Khopa
969e4a2d65 Merge remote-tracking branch 'khopa/develop' into develop 2021-05-14 16:16:11 +02:00
Khopa
77f0b87c54 Campaigns : Migrated campaign Golan Height to version 3 2021-05-14 15:31:46 +02:00
Dan Albert
eec56256e8 Add AEW&C aircraft to the faction aircraft list.
To avoid confusion, use only the aircraft list for the purchasable
aircraft. This fix also caught a faction's Tu-142 that was not actually
purchasable. Invalid aircraft in the faction aircraft list will now
raise an error.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1074
2021-05-13 21:44:07 -07:00
Dan Albert
99dc91dcb4 Fix game break when capturing factory.
We need to recompute the transit networks after a capture *before*
processing transfers. Otherwise units deployed that turn will not be
able to find their destination.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/1070
2021-05-13 21:00:13 -07:00
Dan Albert
5adcfbd7bd Work around PySide2 bug in Property.
https://bugreports.qt.io/browse/PYSIDE-1426

For whatever reason this only shows up in packaged builds for us, and
also the recommended workaround of using a member property rather than a
decorated method does not work for us.

Until PySide2 5.15.3 (or later) is released, we need to use a named
signal for every property we expose.
2021-05-13 20:24:22 -07:00
Dan Albert
3c5f1f7c4b Log python version at startup. 2021-05-13 19:16:54 -07:00
Dan Albert
4415429661 Stop requiring user input for mkrelease.py. 2021-05-13 19:16:40 -07:00
Dan Albert
92c404fbb6 Persist DCS configuration across installs. 2021-05-13 18:55:48 -07:00
Khopa
956b9aaf95 Updated campaign "Russia Small" to campaign version 3 2021-05-13 19:30:10 +02:00
Khopa
c8348f1b44 Added campaign Operation Dynamo for The Channel map. 2021-05-13 18:59:53 +02:00
Dan Albert
d73ceb374c Add front lines to new map UI.
Only shows an approximate front line. Still need support for "actual".
2021-05-13 01:49:35 -07:00
Dan Albert
3e01953a3a Supply route styling, line weight rebalancing. 2021-05-13 01:23:15 -07:00
Dan Albert
1a65b1affb Connect CP/TGO package fragging dialogs. 2021-05-13 01:05:15 -07:00
Dan Albert
dd75078019 Connect TGO dialogs. 2021-05-13 00:56:35 -07:00
Dan Albert
1ab205cb46 Add tooltips for TGOs. 2021-05-13 00:44:47 -07:00
Dan Albert
eb26d54ac1 Show tooltips automatically based on zoom level. 2021-05-13 00:16:59 -07:00
Dan Albert
d884645f37 Cluster TGO markers. 2021-05-12 23:43:47 -07:00
Dan Albert
45f0c3c85f Add map scale widget. 2021-05-12 23:30:54 -07:00
Dan Albert
4e498e6932 Add waypoint info tooltip to the new map. 2021-05-12 23:03:53 -07:00
Dan Albert
d9d68cd37c Add a new Leaflet based map UI.
This is extremely WIP. It is not usable for play yet. Enable with
`--new-map`.
2021-05-12 21:52:23 -07:00
Schneefl0cke
56abd0bb7f Add option for setting desired mission length. 2021-05-11 03:13:15 -07:00
Dan Albert
747683e9e8 Allow other TGO types to be factories.
The `FactoryGroundObject` is just a special case of
`BuildingGroundObject` that we maybe don't actually need. For now it
provides some special case logic for the layout, but this allows any TGO
with the "factory" category to behave as a ground unit source.

Note that the "factory" random strike targets are *not* generated
anymore, so this doesn't affect campaign design currently.
2021-05-10 20:21:19 -07:00
Hornet2041
5b191d72a6 Add F-4E Phantom to the list of CAS/STRIKE capable planes. 2021-05-10 18:14:56 -07:00
Dan Albert
b7619630cf Add logged_duration context manager for profiling. 2021-05-08 18:06:55 -07:00
Dan Albert
de07f10e57 Remove fixed TODO. 2021-05-08 16:50:35 -07:00
Dan Albert
87e6080215 Fix "show actual front line location". 2021-05-08 16:49:05 -07:00
Dan Albert
e721a234e1 Clean up front line code.
The routes do not need be be recreated each time we create a
`FrontLine`. The front lines follow the convoy routes, which are static.
Add the convoy route data to the `ControlPoint` the way we do for
shipping lanes and have `FrontLine` load the data from there.
2021-05-08 16:46:02 -07:00
Dan Albert
67289bbba2 Fix now obvious reversal of convoy friendliness.
Convoy attack and shipping attacks were being planned against *only*
friendly targets. The renaming made the bug obvious.
2021-05-07 21:10:22 -07:00
Dan Albert
b0c24f6e51 Refactor front line code to make sides explicit.
A was intended to be the blue point and B was intended to be the red
point. Make this a part of the name so that's clear, and clean up
related code to keep that reliable.
2021-05-07 21:10:22 -07:00
Dan Albert
12f474ecbe Fix name of Al Minhad for latest DCS version. 2021-05-07 19:59:34 -07:00
Dan Albert
e2f20a7a65 Fix initialization order of turn 0.
Fixes https://github.com/dcs-liberation/dcs_liberation/issues/674
2021-05-07 19:58:39 -07:00
Dan Albert
58ffabe2d6 Fix aggressive objectives in Abu Dhabi.
Some of the objective locations for the starting front line are too
aggressive and put opfor at a disadvantage since blue ships might start
so close to their bases.
2021-05-07 19:37:25 -07:00
SnappyComebacks
426f06045e Updated pydcs version. 2021-05-07 19:13:45 -07:00
Dan Albert
2ca875192a Save budget for filling whole packages.
No sense filling airbases with cheap escorts if we'll never afford the
rest of the package. Filling the airbases with cheap escorts also makes
it impossible to buy the rest of the package when the faction eventually
does have the money since there's nowhere to park the needed aircraft.

https://github.com/dcs-liberation/dcs_liberation/issues/1058
2021-05-07 18:22:52 -07:00
Dan Albert
36b2f24de9 Skip planning for faction incompatible missions.
Required for improving purchasing as well, since we need to not halt
purchasing when a faction has no AEW&C aircraft.

Fixes https://github.com/dcs-liberation/dcs_liberation/issues/683
2021-05-07 18:22:52 -07:00
Dan Albert
2cf3b3be2b Fix bug causing overpurchase of aircraft.
After fulfilling a request we were not exiting the loop, so we'd fulfill
the request for the aircraft at _all_ the bases capable of operating it
until either the bases were full or the budget ran out. In factions like
Iraq 1991 this could cause the budget to be spent on tons of cheap
MiG-19s while never buying the more expensive Su-17s or Su-24s that they
need to actually complete a package.

https://github.com/dcs-liberation/dcs_liberation/issues/1058
2021-05-07 17:25:14 -07:00
Dan Albert
8320c6940b Fix map centering for CLI generated games. 2021-05-07 17:13:53 -07:00
Dan Albert
3c9d21e38d Fix CLI campaign generator.
Factions can be loaded from the user directory now so we need to know
where that is.
2021-05-07 17:13:03 -07:00
Dan Albert
0d7f00aef6 Fix lint error. 2021-05-07 16:58:42 -07:00
Dan Albert
1640763a7f Show parking status for enemy airfields. 2021-05-07 15:30:09 -07:00
Dan Albert
0ec5346574 Auto center the map on load.
Stops all PG campaigns from starting with their view pointed way up
north at the empty mountains.
2021-05-07 14:55:33 -07:00
Khopa
977845e2f4 Fixed links to github in the repo to account for the transfer to the new github organization. 2021-05-07 13:08:39 +02:00
Khopa
4bb2ab73c1 Changelog update 2021-05-07 13:03:15 +02:00
Khopa
af5584d244 Added a settings to control the amount smoke effects on frontlines. Default smoke spacing changed from 800 to 1600 (half the current amount) 2021-05-07 12:49:56 +02:00
Khopa
b289e41a0d Merge remote-tracking branch 'khopa/develop' into develop 2021-05-07 01:01:00 +02:00
Khopa
c0b4eef948 Updated readme for new organization repo link 2021-05-07 01:00:41 +02:00
Marcos Sigueros Fernández
b8e6c2fe78 Check for empty package before estimating TOT.
Fixes https://github.com/Khopa/dcs_liberation/issues/1014.
2021-05-03 11:01:41 -07:00
Dan Albert
b10e86e484 Add support for user faction directory.
This allows users to install custom factions to their home directory
rather than the Liberation install directory. Makes it easier to keep
mods across Liberation downloads, and easier for us devs to keep custom
factions without git always wanting us to add them.
2021-05-02 14:35:21 -07:00
Dan Albert
1c31cffe4b More Python 3.9 compat. 2021-05-02 14:33:24 -07:00
Dan Albert
b9822cd5d1 Python 3.9 compatibility.
This argument was removed and wasn't needed anyway since the file itself
is already opened UTF-8.
2021-05-02 14:31:08 -07:00
Dan Albert
ef1c70123c Remove duplicate SH-60s from factions. 2021-05-02 14:19:47 -07:00
Dan Albert
c245531d65 Update changelog for 2.5.1.
(cherry picked from commit 4555a4968d)
2021-05-02 13:18:21 -07:00
Dan Albert
522495fd11 Update pyinstaller.
Need a version smart enough to handle pyproj.

Fixes https://github.com/Khopa/dcs_liberation/issues/1049.
2021-05-01 11:06:01 -07:00
Marcos Sigueros Fernández
b2a551dc63 FIX: Purchase from airfield or anywhere allows negative budget. 2021-04-29 00:57:48 -07:00
SnappyComebacks
840107c69e Move base EWRs into their own category.
Without this we're sometimes spawning base EWRs at points far outside the base perimeter.
2021-04-28 21:08:54 -07:00
Dan Albert
2a06a1ffdf Add proof-of-concept target info kneeboard page.
This is extremely rough and just serves as an example of how to use the
map projection API.
2021-04-27 21:20:11 -07:00
Dan Albert
8a01209ded Add data for lat/lon conversions. 2021-04-27 21:20:11 -07:00
Dan Albert
2b8dfc9dbc Stop counting neutral base captures in status.
These had no effect but were being counted on the waiting for mission
results page. Cleaned up the implementation a bunch while I was here.

Fixes https://github.com/Khopa/dcs_liberation/issues/1037
2021-04-26 17:54:32 -07:00
Dan Albert
e9f25eb562 Remove unused file.
mypy is flagging problems with this in the github action but not locally
for whatever reason, but it's not used so just delete it.
2021-04-25 20:30:55 -07:00
Dan Albert
475c7fd6db Update black and mypy requirements. 2021-04-25 18:46:37 -07:00
HerrTom
fa5d64022d Condense budget and intel sections of the top panel.
Budget and Intel panels now house a single button instead of separate Details buttons. Makes the top bar more compact and can fit in a 1080p monitor now.
2021-04-25 18:38:45 -07:00
Dan Albert
5c0f6cf65e Flip default for factory feature flag.
This is feature complete, we have a handful of campaigns that work with
the new mode now and it will be the only option at some point.
2021-04-25 18:20:20 -07:00
Dan Albert
0f8d366e31 Reformat with the latest black. 2021-04-25 18:09:33 -07:00
Dan Albert
9e2e593825 Improve transport descriptions. 2021-04-25 17:38:05 -07:00
Dan Albert
028bfc11eb Fix convoys skipping intermediate stops. 2021-04-25 17:38:05 -07:00
Dan Albert
b6cf7a4534 Fix cancelling convoys and cargo ships.
Not sure when I broke this but all transports were being cancelled as if
they were airlifts.
2021-04-25 17:10:24 -07:00
Dan Albert
0779679b99 Connect networks to enable multi-mode transfers.
Removing the per-transit type supply routes allows us to find the best
route from A to B even if the unit needs to switch transit modes along
the way.

The "best" route is the one that will generate better gameplay. That is,
convoys are preferred to ships (use cases for GMT are rare in DCS), and
ships are preferred to airlift (reasons to attack cargo ships are also
rare). Avoiding airlift is also a good strategic choice generally since
it consumes aircraft that could be performing other missions.

The extreme weight against airlift in the pathfinding algorithm could
probably be scaled way down so that airlift would be given preference
over a very long trip, possibly only for urgent transfers.

Later when we add rail that will probably be given the most preference,
but possibly between road and shipping.

https://github.com/Khopa/dcs_liberation/issues/823
2021-04-25 17:02:18 -07:00
Dan Albert
a48ef69e41 Disband cargo ships after processing.
Shipping lanes that received a ship would never lose their ships when
transfers completed, so the line on the map was staying solid (and
probably targetable).
2021-04-25 14:43:25 -07:00
Dan Albert
64d7953e50 Fix crash when opening FOB menus. 2021-04-25 14:39:32 -07:00
Dan Albert
21c35b31d4 AI planning for anti shipping missions.
Same as for anti convoy, these are rarely planned due to ordering issue
between mission planning and procurement.

Fixes https://github.com/Khopa/dcs_liberation/issues/826
2021-04-25 14:37:49 -07:00
Dan Albert
2d64acf299 Add mission targeting for cargo ships.
https://github.com/Khopa/dcs_liberation/issues/826
2021-04-25 14:31:13 -07:00
Dan Albert
e80819fc06 Add campaign inversion support to Abu Dhabi. 2021-04-25 14:17:24 -07:00
Dan Albert
7e40d58d04 Add cargo ships to the sim, track kills.
Not targetable yet.

https://github.com/Khopa/dcs_liberation/issues/826
2021-04-25 14:12:59 -07:00
Dan Albert
ba8fafcc95 First pass at cargo ships.
The simple form of this works, but without the multi-mode routing it'll
only get used when the final destination is a port with a link to a port
with a factory.

These also aren't targetable or simulated yet.

https://github.com/Khopa/dcs_liberation/issues/826
2021-04-25 12:10:06 -07:00
Dan Albert
42694d2004 Update 3.0 compatible campaigns to latest version.
Adds shipping lanes to Battle of Abu Dhabi. The others are acking the
new requirement but don't have an viable shipping lanes so no changes
are needed.
2021-04-24 21:55:40 -07:00
Dan Albert
5e67ce0ab2 Add shipping lane support to campaign files.
These don't actually do anything yet, this is just the campaign support
and UI.

https://github.com/Khopa/dcs_liberation/issues/826
2021-04-24 21:33:21 -07:00
Dan Albert
97b73e1a01 Add a north-to-south PG campaign.
Going to use this as the test bed for shipping transfers.
2021-04-24 19:43:40 -07:00
Dan Albert
4239257000 Add UAE 2015 faction.
Same as 2005 but with the Patriot  and some additional utilit aircraft.
2021-04-24 18:09:53 -07:00
Dan Albert
6bd94761d0 Update pydcs. 2021-04-24 15:33:51 -07:00
Starfire13
bc54e57fd4 Update campaigns and the splash damage plugin. 2021-04-24 15:30:31 -07:00
Dan Albert
17751e52fd Clear transports when disbanding convoys.
Also changes when we clear the convoys. Because we plan when transfers
are added (to plan UI orders immediately) we were planning convoys when
delivering units, then clearing the convoys, then planning them again.

Aside from the wasted effort, when we cleared the convoys we forgot to
tell the transfer that they no longer had transport, so when replanning
they did not get a new convoy.
2021-04-24 15:18:45 -07:00
Dan Albert
6016ebd3b4 Get transports from the closest airfield.
https://github.com/Khopa/dcs_liberation/issues/825
2021-04-23 23:24:25 -07:00
Dan Albert
8a44fc19ee Limit range for transport helicopters.
https://github.com/Khopa/dcs_liberation/issues/825
2021-04-23 23:24:25 -07:00
Dan Albert
f69450e2ae Add auto-procurment for airlift assets.
https://github.com/Khopa/dcs_liberation/issues/825
2021-04-23 23:24:25 -07:00
Mustang-25
3161ccced3 Re-adds GAR-8 (now AIM-9B in DCS) Fallback dates (#1025) 2021-04-23 22:25:11 -07:00
Dan Albert
909aad22a6 Make landing stops for cargo missions.
Until pydcs supports the timeReFuAr property this will have a wait time
of zero minutes, but it does seem to work.

Updating to https://github.com/pydcs/dcs/pull/132 will make the wait
time work automatically.

https://github.com/Khopa/dcs_liberation/issues/825
2021-04-23 22:19:54 -07:00
Dan Albert
c8b4fd1690 Use any (and only) transport aircraft for airlift.
https://github.com/Khopa/dcs_liberation/issues/825
2021-04-23 22:06:38 -07:00
Dan Albert
dac2271084 Add transport aircraft to US factions. 2021-04-23 22:06:38 -07:00
Dan Albert
5320d20f71 Add C-130 to the CAS capable list, clean up. 2021-04-23 21:21:05 -07:00
Dan Albert
20d8cc2b47 Plan transports at the beginning of the turn.
https://github.com/Khopa/dcs_liberation/issues/823
2021-04-23 20:31:52 -07:00
Dan Albert
d3fdbdbca5 Fix convoys not spawning where they should. 2021-04-23 20:23:23 -07:00
Dan Albert
d80f7ebf3b Refactor transfers to support unfulfilled orders.
This gives a clean break between the transfer request and the type of
transport allocated to make way for transports that need to switch
types (to support driving to a port, then getting on a ship, to a train,
then back on the road, etc).

https://github.com/Khopa/dcs_liberation/issues/823
2021-04-23 20:10:29 -07:00
C. Perreau
d6c84e362f Merge pull request #1012 from SpaceEnthusiast/develop
Added and modified factions
2021-04-24 00:13:45 +02:00
Khopa
6aba07c33b Fixed ai_flight_planner for maps lacking frontlines (such as battle of britain on The Channel map) 2021-04-24 00:10:57 +02:00
Dan Albert
45913b0add Bump to 3.0.
DCS version numbers and Liberation version numbers are getting
confusing. Push us ahead before we're both on 2.7.
2021-04-23 01:11:46 -07:00
Dan Albert
c258409a8d Add AI planning for airlifts.
Downside to the current implementation is that whether or not transports
that were purchased last turn will be available for airlift this turn is
arbitrary. This is because transfers are created at the same time as
units are delivered, and units are delivered in an arbitrary order per
CP. If the helicopters are delivered before the ground units they'll
have access to the transports, otherwise they'll be refunded. This will
be fixed later when I rework the transfer requests to not require
immediate fulfillment.

https://github.com/Khopa/dcs_liberation/issues/825
2021-04-23 01:10:03 -07:00
Dan Albert
26cd2d3fef Add todo for transfer refactor. 2021-04-22 22:24:57 -07:00
Dan Albert
4069074f41 Move unit delivery out of an unrelated file.
Historically this inherited from Event but there was no reason for that.
That's gone now. Finish the separation and move the unit order tracking
class out of the combat results reaction class's file.
2021-04-22 22:15:45 -07:00
Dan Albert
182422249f Remove support for mizdata/random locations.
The introduction of factories broke every existing campaign so we don't
need to keep support for the ancient formats any more.
2021-04-22 22:12:52 -07:00
Dan Albert
29b70b3247 Track airlift cargo kills.
https://github.com/Khopa/dcs_liberation/issues/825
2021-04-22 19:22:41 -07:00
Dan Albert
e474748f4d Stop projecting threat zones from front lines.
This is an interim improvement since we should probably be pushing the
BARCAPs into TARCAP roles when the front line is so close. This does
regress flight pathing for anything that should route around the front
(to avoid getting shot at by SHORADS and TARCAPs), but for now it's one
or the other and this is the one everyone's complaining about.
2021-04-22 18:20:26 -07:00
Dan Albert
132ba905c7 Generalize commit range display for all patrols.
Fixes https://github.com/Khopa/dcs_liberation/issues/890
2021-04-22 17:55:14 -07:00
Dan Albert
208d1b82b5 Show BARCAP commit ranges by default.
BARCAP placement confuses a lot of people but this should make it more
clear.
2021-04-22 17:45:19 -07:00
Simon Clark
1fd7c95f1b Fix Russian carrier name; Kuznetov -> Kuznetsov. 2021-04-22 23:08:56 +01:00
Dan Albert
481f195725 Airlift support.
UI isn't finished. Bulk transfers where the player doesn't care what
aircraft get used work (though they're chosen with no thought at all),
but being able to plan your own airlift flight isn't here yet.

Cargo planes are not implemented yet.

No way to view the cargo of a flight (will come with the cargo flight
planning UI).

The airlift flight/package creation should probably be moved out of the
UI and into the game code.

AI doesn't use these yet.

https://github.com/Khopa/dcs_liberation/issues/825
2021-04-22 00:30:18 -07:00
SpaceEnthusiast
d6c1550a1d Added Australia with C130 Faction 2021-04-21 23:58:18 -04:00
SpaceEnthusiast
60b9ae0a70 Added Canada with C130 Faction 2021-04-21 23:43:31 -04:00
SpaceEnthusiast
bf71351e6d Canadian, Australian, and Spanish Hornets now use proper liveries 2021-04-21 22:45:44 -04:00
Dan Albert
8e361a8776 Fix missing index valid check in transfer menu.
Fixes https://github.com/Khopa/dcs_liberation/issues/1006
2021-04-21 17:14:45 -07:00
Khopa
e39fd53727 Fixed Lint issue 2021-04-21 22:55:08 +02:00
Khopa
76efcca64b Fixed error with Ramat David frequency (typo) 2021-04-21 22:41:04 +02:00
Khopa
35f49d9bc0 Fixed airfields frequency on Persian Gulf 2021-04-21 22:31:52 +02:00
Khopa
a0a55797a9 Fixed airfields frequency on Syria 2021-04-21 22:31:49 +02:00
Khopa
696a429e9e Pydcs update to latest version 2021-04-21 13:20:06 +02:00
Dan Albert
29cd55e795 Add WIP airlift UI.
Doesn't do anything yet.

https://github.com/Khopa/dcs_liberation/issues/825
2021-04-21 01:02:02 -07:00
Dan Albert
c2ebf61fd3 Disable cancel actions on enemy transfers.
Decided to leave these in the menu as intel for the player, but the
player can no longer cancel them.

Fixes https://github.com/Khopa/dcs_liberation/issues/995
2021-04-20 23:20:08 -07:00
Dan Albert
489b4d6acf Add AI convoy attack planning.
Like the comment says this rarely has any effect due to the ordering of
flight planning and convoy creation. Could be separated, but opfor will
still not be able to target any convoys that the player creates in the
UI on that turn because they planning is done before the player can use
the UI.

Multi-turn transfers will be targetable, however.
2021-04-20 22:56:53 -07:00
Dan Albert
6cffc47f3c Clean up convoy code. 2021-04-20 22:21:42 -07:00
Dan Albert
50d8e08a34 Redo convoy attack flight plans.
The previous flight plan only makes sense if the convoy will make it a
significant distance from its starting point. At road speeds over the
typical mission duration this is not true, so we can actually plan this
as if it was a strike mission near the origin point and that's close
enough.

There's some cleanup work to do here that I've added todos for.

Fixes https://github.com/Khopa/dcs_liberation/issues/996
2021-04-20 22:04:57 -07:00
Dan Albert
3f16c0378a Add BAI planning against supply routes.
This currently is only supported for player flights. I have no idea how
to create an AI flight plan that won't just get them killed. AI-only BAI
missions against supply routes will warn the player on mission creation.
2021-04-19 23:09:39 -07:00
Dan Albert
2b06d8a096 Convert front line segments to proper class.
Needed so we can add context menus to the lines.
2021-04-19 21:41:56 -07:00
Dan Albert
2a5b37b9ad Show convoys on the map. 2021-04-19 20:37:15 -07:00
Dan Albert
cabbd234af Fix incorrect docs. 2021-04-19 20:24:20 -07:00
Dan Albert
480039ca50 Add --cheats to the CLI mission generator.
Doesn't enable the red ATO display because that's a lot of clutter, but
enables the commonly needed for debugging things.
2021-04-19 17:22:31 -07:00
Dan Albert
81d5cddac9 Remove weird single-CP supply route edge case.
A CP with a factory would be able to supply itself, but was not in a
supply route if it was the only connected friendly CP. When the player
starts with only one base against an enemy base this meant that it was
in no supply route, causing it to not be a recruitment location or a
place to buy more than a reserve of vehicles automatically.
2021-04-19 17:15:41 -07:00
Dan Albert
bb3e83548c Remove support for old-style campaigns.
These won't work any more since they won't be able to define factories
or supply routes. They were made obsolete ages ago, so just remove them.
2021-04-19 01:54:16 -07:00
Dan Albert
a3ff58c42d Turn feature flags on for development mode. 2021-04-19 00:04:46 -07:00
Dan Albert
30bf4542f0 Special case turn 0 for recruitment.
We want there to be units on the front line on turn 1 regardless of
factory locations, so bypass the recruitment restrictions on turn 0.

https://github.com/Khopa/dcs_liberation/issues/986
2021-04-19 00:03:47 -07:00
Dan Albert
d11c9a4615 Use convoy spawn points defined by the campaign.
The start/end points of the waypoints that define the course of the
front line also define the spawn points for convoys. Use them.

https://github.com/Khopa/dcs_liberation/issues/824
2021-04-18 23:57:13 -07:00
Dan Albert
d4679e0029 Note the semi-completion of the factory feature.
https://github.com/Khopa/dcs_liberation/issues/986
2021-04-18 23:35:18 -07:00
Dan Albert
3c4d6eb8e4 Automate transfers for purchases in the UI.
Buying a unit places the order, but the unit will appear at the nearest
connected source and a transfer will be automatically created next turn.

https://github.com/Khopa/dcs_liberation/issues/986
2021-04-18 23:31:45 -07:00
Dan Albert
df98e1f8ac Fix campaign format version.
Updatd the comment but forgot to update the number...
2021-04-18 23:25:44 -07:00
Dan Albert
56fc2986e9 Automate transfers from factories.
The purchase system will seek out a source for its units when the
purchase is completed. If no source is available the order will be
refunded. Orders with no source available are prevented, so this only
happens when the source was cut off from the destination during the
turn.

There's still some funkiness going on with the first turn (but possibly
only when the first turn includes a cheat to capture) where the AI buys
a ton of units somewhere other than the front line. First turn behavior
should probably be different anyway, with the first turn allowing
purchases anywhere to avoid empty front lines while troops reinforce if
the front line isn't a factory.

https://github.com/Khopa/dcs_liberation/issues/986
2021-04-18 23:22:30 -07:00
Dan Albert
627f18c42b Require factories for purchasing ground units.
https://github.com/Khopa/dcs_liberation/issues/986
2021-04-18 23:22:30 -07:00
Dan Albert
67b341cbd6 Add feature flag for new ground unit recruitment.
This is going to render most campaigns unusable because they won't have
any places to spawn ground units, so flagging off for now.

https://github.com/Khopa/dcs_liberation/issues/986
2021-04-18 23:22:30 -07:00
Dan Albert
eff5b94db7 Add factory placement to the campaign files.
This also removes the "factory" type from the normal strike target
(money generating) generators to avoid confusion. Later only control
points with factories will be able to spawn ground units, at which point
these will no longer generate income.

https://github.com/Khopa/dcs_liberation/issues/986
2021-04-18 23:22:30 -07:00
Dan Albert
707323ca12 Update Inherent Resolve to latest camapign format.
* Moves front line endpoints to roads for convoys (not used yet).
* Adds EWR sites.
2021-04-18 23:22:30 -07:00
Dan Albert
cb2ba2f53a Update pydcs, move back to upstream. 2021-04-18 23:22:11 -07:00
Dan Albert
777cd310ef Clarify which game we're talking about. 2021-04-18 17:45:27 -07:00
Dan Albert
9a4ec5a899 Fix campaign description template. 2021-04-18 17:41:27 -07:00
Dan Albert
c92e4e06cc Move campaign format version to a stable location. 2021-04-18 17:37:55 -07:00
Dan Albert
39135f8c80 Add version field to campaign descriptor file.
This is used to provide a UI hint to guide players towards campaigns
that have been updated to work with the current version of the game.
All the campaigns we currently have were made for an unknown version of
the game, so they're all flagged as incompatible.

The version field is not the DCS Liberation version number because the
campaign format may change multiple times during development. Instead
the version number is a monotonically increasing integer that we
increment whenever a game change requires campaign updates.
2021-04-18 17:30:49 -07:00
Dan Albert
5e054cfc77 Disallow selling ground units.
Ground units should be transferred to a new location, not sold and
repurchased.

https://github.com/Khopa/dcs_liberation/issues/823
2021-04-18 16:32:02 -07:00
Dan Albert
3b72c13f9d Add ground unit transfers to the changelog.
Also documented the behavior on the wiki (link in the changelog).

This is currently fully functional for players, but since units can be
bought and sold at any base there's no real reason to use these yet.
Will follow up with making ground units only purchasable at bases with
factories (the UI will still allow the purchase directly at the base,
but it will automatically create the transfer order) so convoys end up
being used, and to make factories a more interesting strategic target.

https://github.com/Khopa/dcs_liberation/issues/824
2021-04-18 16:22:51 -07:00
Dan Albert
65ed110ab7 Track convoy kills.
https://github.com/Khopa/dcs_liberation/issues/824
2021-04-18 16:22:51 -07:00
Dan Albert
5dd7ea3060 Spawn convoys for transfers.
Destroying these units currently has no effect.

https://github.com/Khopa/dcs_liberation/issues/824
2021-04-18 16:22:51 -07:00
Dan Albert
bd9cbf5e3b Move transfers one CP per turn.
https://github.com/Khopa/dcs_liberation/issues/824
2021-04-18 16:22:51 -07:00
Dan Albert
65f6a4eddd Restrict transfers to connected bases.
https://github.com/Khopa/dcs_liberation/issues/824
2021-04-18 15:59:15 -07:00
Dan Albert
e9ff554f39 Basic implementation of road based transfers.
This adds the models and UIs for creating ground unit transfer orders.
Most of the feature is still missing:

* The AI doesn't do them.
* Transfers can move across the whole map in one turn.
* Transfers between disconnected bases are allowed.
* Transfers are not modeled in the simulation, so they can't be
  interdicted.

https://github.com/Khopa/dcs_liberation/issues/824
2021-04-18 15:59:15 -07:00
Dan Albert
b65d178cf1 Move develop to 2.6. 2021-04-18 15:57:18 -07:00
1490 changed files with 51114 additions and 22459 deletions

View File

@@ -9,6 +9,8 @@ assignees: ''
Before filing, please search the issue tracker to see if the issue has already been reported.
If reporting a DCS AI bug, check https://github.com/dcs-liberation/dcs_liberation#dcs-bugs.
**Describe the bug**
A clear and concise description of what the bug is.

View File

@@ -0,0 +1,28 @@
---
name: Campaign update submission
about: Submit an update to a campaign you maintain.
title: 'Update for <campaign name>'
labels: campaign-update-submission
assignees: ''
---
This form should only be used for submitted updated miz/json files for campaigns
distributed with Liberation. If you are _requesting_ an update to a campaign, see
https://github.com/dcs-liberation/dcs_liberation/wiki/Campaign-maintenance. If the
campaign has an owner, it will be updated before release. If it does not, you can
volunteer to own it.
If you are not the owner of the campaign listed on
https://github.com/dcs-liberation/dcs_liberation/wiki/Campaign-maintenance, please start
there.
Otherwise, delete everything above the line below and fill out the following form. Note:
GitHub does not accept .miz files. You can either rename the file to .miz.txt or add the
file to a .zip file.
---
* Campaign name:
* Files:
* Update summary (optional):

1
.github/ISSUE_TEMPLATE/config.yml vendored Normal file
View File

@@ -0,0 +1 @@
blank_issues_enabled: false

View File

@@ -9,6 +9,8 @@ assignees: ''
Before filing, please search the issue tracker to see if this feature has already been requested.
If requesting a DCS AI feature, check If reporting a DCS AI bug, check https://github.com/dcs-liberation/dcs_liberation#dcs-bugs.
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

12
.github/ISSUE_TEMPLATE/mod_support.md vendored Normal file
View File

@@ -0,0 +1,12 @@
---
name: Mod support request
about: Request Liberation support for new mods, or updates to existing mods
title: Add/update <mod name>
labels: mod support
assignees: ''
---
* Mod name:
* Mod URL:
* Update or new mod?

View File

@@ -11,10 +11,10 @@ jobs:
with:
submodules: true
- name: Set up Python 3.8
- name: Set up Python 3.9
uses: actions/setup-python@v2
with:
python-version: 3.8
python-version: 3.9
- name: Install environment
run: |
@@ -36,6 +36,11 @@ jobs:
run: |
./venv/scripts/activate
mypy gen
- name: mypy tests
run: |
./venv/scripts/activate
mypy tests
- name: update build number
run: |

View File

@@ -13,10 +13,10 @@ jobs:
with:
submodules: true
- name: Set up Python 3.8
- name: Set up Python 3.9
uses: actions/setup-python@v2
with:
python-version: 3.8
python-version: 3.9
- name: Install environment
run: |

33
.github/workflows/test.yml vendored Normal file
View File

@@ -0,0 +1,33 @@
name: Test
on: [push, pull_request]
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
submodules: true
- name: Set up Python 3.9
uses: actions/setup-python@v2
with:
python-version: 3.9
- name: Install environment
run: |
python -m venv ./venv
- name: Install dependencies
run: |
./venv/scripts/activate
python -m pip install -r requirements.txt
# For some reason the shiboken2.abi3.dll is not found properly, so I copy it instead
Copy-Item .\venv\Lib\site-packages\shiboken2\shiboken2.abi3.dll .\venv\Lib\site-packages\PySide2\ -Force
- name: run tests
run: |
./venv/scripts/activate
pytest tests

3
.gitignore vendored
View File

@@ -12,12 +12,13 @@ resources/tools/a.miz
# User-specific stuff
.idea/
.env
env/
/kneeboards
/liberation_preferences.json
/state.json
logs/
/logs/
qt_ui/logs/liberation.log

4
.gitmodules vendored
View File

@@ -1,4 +0,0 @@
[submodule "pydcs"]
path = pydcs
url = https://github.com/pydcs/dcs
branch = master

View File

@@ -11,7 +11,7 @@ Note that you may need to remove the filter for open bugs if it's something we'v
## Making content for Liberation
You can create new campaigns : See [campaign creation wiki](https://github.com/Khopa/dcs_liberation/wiki/Custom-Campaigns).
You can create new campaigns : See [campaign creation wiki](https://github.com/dcs-liberation/dcs_liberation/wiki/Custom-Campaigns).
You can also improve existing campaigns.
You can then submit new campaigns on the "campaigns" channel on Discord, or by making a pull request if you are comfortable with git.

View File

@@ -1,39 +1,48 @@
![Logo](https://i.imgur.com/c2k18E1.png)
[![Logo](https://i.imgur.com/HJBT4BL.png)](https://shdwp.github.io/ukraine/)
(Github Readme Banner and Splash screen Artwork by Andriy Dankovych, CC BY-SA 4.0)
[![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg?logo=paypal)](https://www.paypal.com/paypalme/KhopaDCSL)
[![Patreon](https://img.shields.io/badge/patreon-become%20a%20patron-orange?logo=patreon)](https://patreon.com/khopa)
[![Download](https://img.shields.io/github/downloads/khopa/dcs_liberation/total?label=Download)](https://github.com/Khopa/dcs_liberation/releases)
[![Download](https://img.shields.io/github/downloads/dcs-liberation/dcs_liberation/total?label=Download)](https://github.com/dcs-liberation/dcs_liberation/releases)
[![Discord](https://img.shields.io/discord/595702951800995872?label=Discord&logo=discord)](https://discord.gg/bKrtrkJ)
[![GitHub pull requests](https://img.shields.io/github/issues-pr/khopa/dcs_liberation)](https://github.com/Khopa/dcs_liberation)
[![GitHub issues](https://img.shields.io/github/issues/khopa/dcs_liberation)](https://github.com/Khopa/dcs_liberation/issues)
![GitHub stars](https://img.shields.io/github/stars/khopa/dcs_liberation?style=social)
[![GitHub pull requests](https://img.shields.io/github/issues-pr/dcs-liberation/dcs_liberation)](https://github.com/dcs-liberation/dcs_liberation)
[![GitHub issues](https://img.shields.io/github/issues/dcs-liberation/dcs_liberation)](https://github.com/dcs-liberation/dcs_liberation/issues)
![GitHub stars](https://img.shields.io/github/stars/dcs-liberation/dcs_liberation?style=social)
## About DCS Liberation
DCS Liberation is a [DCS World](https://www.digitalcombatsimulator.com/en/products/world/) turn based single-player or co-op dynamic campaign.
It is an external program that generates full and complex DCS missions and manage a persistent combat environment.
![Logo](https://i.imgur.com/4hq0rLq.png)
![Screenshot](https://user-images.githubusercontent.com/315852/120939254-0b4a9f80-c6cc-11eb-82f5-ce3f8d714bfe.png)
## Downloads
Latest release is available here : https://github.com/Khopa/dcs_liberation/releases
Latest release is available here : https://github.com/dcs-liberation/dcs_liberation/releases
To download preview builds of the next version of DCS Liberation, see https://github.com/Khopa/dcs_liberation/wiki/Preview-builds.
To download preview builds of the next version of DCS Liberation, see https://github.com/dcs-liberation/dcs_liberation/wiki/Preview-builds.
## DCS bugs
These DCS bugs prevent us from improving AI behavior. Please upvote them! (But please
_don't_ spam them with comments):
* [A2A and SEAD escorts don't escort](https://forums.eagle.ru/topic/251798-options-for-alternate-ai-escort-behavior/?tab=comments#comment-4668033)
* [DEAD can't use mixed loadouts effectively](https://forums.eagle.ru/topic/271941-ai-rtbs-after-firing-decoys-despite-full-load-of-bombs/)
## Bugs and feature requests
If you need to report a bug or want to suggest a new feature, you can do this on our [bug tracker](https://github.com/Khopa/dcs_liberation/issues). In either case, please use the search bar at the top of the page to see if it has already been reported. Note that you may need to remove the filter for open bugs if it's something we've recently fixed.
If you need to report a bug or want to suggest a new feature, you can do this on our [bug tracker](https://github.com/dcs-liberation/dcs_liberation/issues). In either case, please use the search bar at the top of the page to see if it has already been reported. Note that you may need to remove the filter for open bugs if it's something we've recently fixed.
## Roadmap
Our plans for future releases can be found on our [Projects page](https://github.com/Khopa/dcs_liberation/projects). Each planned release has a Project, and the page for that project has columns for to do, in progress, and done. Items in the Done column are in the [preview build](https://github.com/Khopa/dcs_liberation/wiki/Preview-builds) for that release. Items in the To do column are planned to be added to that release.
Our plans for future releases can be found on our [Projects page](https://github.com/dcs-liberation/dcs_liberation/projects). Each planned release has a Project, and the page for that project has columns for to do, in progress, and done. Items in the Done column are in the [preview build](https://github.com/dcs-liberation/dcs_liberation/wiki/Preview-builds) for that release. Items in the To do column are planned to be added to that release.
## Resources
Tutorials, contributors and developer's guides are available in the project's [Wiki](https://github.com/Khopa/dcs_liberation/wiki/)
Tutorials, contributors and developer's guides are available in the project's [Wiki](https://github.com/dcs-liberation/dcs_liberation/wiki/)
## Special Thanks

View File

@@ -1,3 +1,266 @@
# 5.2.1
## Fixes
* **[Mission Generation]** Work around DCS 2.8 bug preventing the AI from leaving their hold point.
# 5.2.0
Saves from 5.1.0 are compatible with 5.2.0
## Features/Improvements
* **[Engine]** Support for DCS DCS 2.7.11.21408, including the new Apache AH-64D and the Syria map extension
* **[Mission Generation]** Improved FARP Helipad handling and creation (now includes windsocks)
* **[Modding]** Add UH-60L mod support
* **[Modding]** Updated Community A-4E-C mod version support to 2.0.0 release. Version 1.4.2 is no longer compatible, unless the mod default loadouts are deleted/modified.
* **[Modding]** Updated JAS-39-C mod support for v1.8.0-beta
* **[Campaign]** Peace Spring, Vectron's Claw, Vegas Nerve, Scenic Route 2 campaign update
* **[Campaign]** Added Tripoint Hostility campaign by Fuzzle
* **[Campaign]** Add 3 new campaigns from Sith1144
## Fixes
* **[Mission Generation]** Fixed incorrect SA-5 and NASAMS threat range when TR destroyed. It will not count as threat anymore when the TR is dead.
* **[Mission Generation]** Fixed "Max Threat Range" error
* **[Mission Generation]** Fix unculled zones not updating when needed
* **[Mission Planner]** Now allows squadron transfers to control points where the number of free slots matches exactly the expected size of the transferring squadron next turn.
* **[Data]** Removed Fw 190 A-8 and D-9 from Germany 1940 and 1942 faction list for historical accuracy.
* **[Data]** Updated Loadouts for Tornado GR4, F-15E and F-16C
* **[Data]** Corrected some unit data
* **[UI]** Fixed various UI issues (for example Scaling and HighDPI)
* **[UI]** Typhoon GR4 and IDS images
# 5.1.0
Saves from 5.0.0 are compatible with 5.1.0
## Features/Improvements
* **[Engine]** Support for DCS 2.7.9.17830 and newer, including the HTS and ECM pod.
* **[Campaign]** Add option to manually add and remove squadrons and different aircraft type in the new game wizard / air wing configuration dialog.
* **[Mission Generation]** Add Option to enforce the Easy Communication setting for the mission
* **[Mission Generation]** Add Option to select between only night missions, day missions or any time (default).
* **[Modding]** Add F-104 mod support
## Fixes
* **[Campaign]** Fixed some minor issues in campaigns which generated error messages in the log.
* **[Campaign]** Changed the way how map object / scenery kills where tracked. This fixes issues with kill recognition after map updates from ED which change the object ids and therefore prevent correct kill recognition.
* **[Mission Generation]** Fixed incorrect radio specification for the AN/ARC-222.
* **[Mission Generation]** Fixed mission scripting error when using a dedicated server.
* **[Mission Generation]** Fixed an issue where empty convoys lead to an index error when a point capture made a pending transfer of units not completable anymore.
* **[Mission Generation]** Corrected Viggen FR22 & FR24 preset channels for the DCS 2.7.9 update
* **[Mission Generation]** Fixed the SA-5 Generator to use the P-19 FlatFace SR as a Fallback radar if the faction does not have access to the TinShield SR.
* **[UI]** Enable / Disable the settings, save and stats actions if no game is loaded to prevent an error as these functions can only be used on a valid game.
* **[UI]** Added missing icons for Tornado GR4, and Tornado IDS.
# 5.0.0
Saves from 4.x are not compatible with 5.0.
## Features/Improvements
* **[Campaign]** Weather! Theaters now experience weather that is more realistic for the region and its current season. For example, Persian Gulf will have very hot, sunny summers and Marianas will experience lots of rain during fall. These changes affect pressure, temperature, clouds and precipitation. Additionally, temperature will drop during the night, by an amount that is somewhat realistic for the region.
* **[Campaign]** Weapon data such as fallbacks and introduction years is now moddable. Due to the new architecture to support this, the old data was not automatically migrated.
* **[Campaign]** Era-restricted loadouts will now skip LGBs when no TGP is available in the loadout. This only applies to default loadouts; buddy-lasing can be coordinated with custom loadouts.
* **[Campaign]** FOBs control point can have FARP/helipad slot and host helicopters. To enable this feature on a FOB, add "Invisible FARP" statics objects near the FOB location in the campaign definition file.
* **[Campaign]** Squadrons now have a home base and will not operate out of other bases. See https://github.com/dcs-liberation/dcs_liberation/issues/1145 for status.
* **[Campaign]** Aircraft now belong to squadrons rather than bases to support squadron location transfers.
* **[Campaign]** Skipped turns are no longer counted as defeats on front lines.
* **[Campaign AI]** Overhauled campaign AI target prioritization.
* **[Campaign AI]** Player front line stances can now be automated. Improved stance selection for AI.
* **[Campaign AI]** Reworked layout of hold, join, split, and ingress points. Should result in much shorter flight plans in general while still maintaining safe join/split/hold points.
* **[Campaign AI]** Auto-planning mission range limits are now specified per-aircraft. On average this means that longer range missions will now be plannable. The limit only accounts for the direct distance to the target, not the path taken.
* **[Campaign AI]** Transport aircraft will now be bought only if necessary at control points which can produce ground units and are capable to operate transport aircraft.
* **[Campaign AI]** Aircraft will now only be automatically purchased or assigned at appropriate bases. Naval aircraft will default to only operating from carriers, Harriers will default to LHAs and shore bases, helicopters will operate from anywhere. This can be customized per-squadron.
* **[Engine]** Support for DCS 2.7.7.14727 and newer, including support for F-16 CBU-105s, SA-5s, and the Forrestal.
* **[Kneeboard]** Minimum required fuel estimates have been added to the kneeboard for aircraft with supporting data (currently only the Hornet and Viper).
* **[Kneeboard]** QNH (pressure MSL) and temperature have been added to the kneeboard.
* **[Mission Generation]** EWRs are now also headed towards the center of the conflict
* **[Mission Generation]** FACs can now use FC3 compatible laser codes. Note that this setting is global, not per FAC.
* **[Modding]** Can now install custom campaigns to <DCS saved games>/Liberation/Campaigns instead of the Liberation install directory.
* **[Modding]** Campaigns can now define a default start date.
* **[Modding]** Campaigns now specify the squadrons that are present in the campaign, their roles, and their starting bases. Players can customize this at game start but the campaign will choose the defaults.
* **[New Game Wizard]** Can now customize the player's air wing before campaign start to disable, relocate, or rename squadrons.
* **[Plugins]** Updated SkynetIADS to 2.4.0 (adds SA-5 support).
* **[UI]** Sell Button for aircraft will be disabled if there are no units available to be sold or all are already assigned to a mission
* **[UI]** Enemy aircraft inventory now viewable in the air wing menu.
## Fixes
* **[Campaign]** Naval control points will no longer claim ground objectives during campaign generation and prevent them from spawning.
* **[Campaign]** Units aboard sunk cargo ships will now have their losses tracked properly.
* **[Mission Generation]** Mission results and other files will now be opened with enforced utf-8 encoding to prevent an issue where destroyed ground units were untracked because of special characters in their names.
* **[Mission Generation]** Fixed generation of landing waypoints so that the AI obeys them.
* **[Mission Generation]** AI carrier aircraft with a start time of T+0 will now start at T+1s to avoid traffic jams.
* **[Mission Generation]** Fixed cases of unused aircraft not being spawned at airfields as soon as any airport filled up.
* **[Mission Generation]** Fixed cases with multiple client flights of the same airframe all received the same preset channels.
* **[Mission Generation]** F-14A is now generated with stored alignment.
* **[Mission Generation]** Su-33s set to cold or warm start on the Kuznetsov will always be generated as runway starts to avoid the AI getting stuck.
* **[Mission Generation]** Fixed AI not receiving anti-ship tasks against carriers and LHAs.
* **[Mods]** Fixed broken A-4 support causing no weapons to be available.
* **[UI]** Selling of Units is now visible again in the UI dialog and shows the correct amount of sold units
* **[UI]** Fixed bug where an incompatible campaign could be generated if no action is taken on the campaign selection screen.
# 4.1.1
Saves from 4.1.0 are compatible with 4.1.1.
## Fixes
* **[Campaign]** Fixed broken support for Mariana Islands map.
* **[Mission Generation]** Fix SAM sites pointing towards the center of the conflict.
* **[Flight Planning]** No longer using Su-34 for CAP missions.
# 4.1.0
Saves from 4.0.0 are compatible with 4.1.0.
## Features/Improvements
* **[Campaign]** Air defense sites now generate a fixed number of launchers per type.
* **[Campaign]** Added support for Mariana Islands map.
* **[Campaign AI]** Adjustments to aircraft selection priorities for most mission types.
* **[Engine]** Support for DCS 2.7.4.9632 and newer, including the Marianas map, F-16 JSOWs, NASAMS, and Tin Shield EWR.
* **[Flight Planning]** CAP patrol altitudes are now set per-aircraft. By default the altitude will be set based on the aircraft's maximum speed.
* **[Flight Planning]** CAP patrol speeds are now set per-aircraft to be more suitable/sensible. By default the speed will be set based on the aircraft's maximum speed.
* **[Mission Generation]** Improvements for better support of the Skynet Plugin and long range SAMs are now acting as EWR
* **[Mission Generation]** SAM sites are now headed towards the center of the conflict
* **[Mods]** Support for latest version of Gripen mod. In-progress campaigns may need to re-plan Gripen flights to pick up updated loadouts.
* **[Plugins]** Increased time JTAC Autolase messages stay visible on the UI.
* **[Plugins]** Updated SkynetIADS to 2.2.0 (adds NASAMS support).
* **[UI]** Added ability to take notes and have those notes appear as a kneeboard page.
* **[UI]** Hovering over the weather information now dispalys the cloud base (meters and feet).
* **[UI]** Google search link added to unit information when there is no information provided.
* **[UI]** Control point name displayed with ground object group name on map.
* **[UI]** Buy or Replace will now show the correct price for generated ground objects like sams.
* **[UI]** Improved logging for frontline movement to be more descriptive about what happened and why.
* **[UI]** Brought ruler map module into source, which should fix file integrity issues with the module.
## Fixes
* **[Campaign]** Fixed the Silkworm generator to include launchers and not all radars.
* **[Data]** Fixed Introduction dates for targeting pods (ATFLIR and LITENING were both a few years too early).
* **[Data]** Removed SA-10 from Syria 2011 faction.
* **[Economy]** EWRs can now be bought and sold for the correct price and can no longer be used to generate money
* **[Flight Planning]** Helicopters are now correctly identified, and will fly ingress/CAS/BAI/egress and similar at low altitude.
* **[Flight Planning]** Fixed potential issue with angles > 360° or < 0° being generated when summing two angles.
* **[Mission Generation]** The lua data for other plugins is now generated correctly
* **[Mission Generation]** Fixed problem with opfor planning missions against sold ground objects like SAMs
* **[Mission Generation]** The legacy always-available tanker option no longer prevents mission creation.
* **[Mission Generation]** Prevent the creation of a transfer order with 0 units for a rare situtation when a point was captured.
* **[Mission Generation]** Planned transfers which will be impossible after a base capture will no longer prevent the mission result submit.
* **[Mission Generation]** Fix occasional KeyError preventing mission generation when all units of the same type in a convoy were killed.
* **[Mission Generation]** Fix for AAA Flak generator using Opel Blitz preventing the mission from being generated because duplicate unit names were used.
* **[Mission Generation]** Fixed a potential bug with laser code generation where it would generate invalid codes.
* **[UI]** Statistics window tick marks are now always integers.
* **[UI]** Statistics window now shows the correct info for the turn
* **[UI]** Toggling custom loadout for an aircraft with no preset loadouts no longer breaks the flight.
# 4.0.0
Saves from 3.x are not compatible with 4.0.
## Features/Improvements
* **[Engine]** Support for DCS 2.7.2.7910.1 and newer, including Cyprus, F-16 JDAMs, and the Hind.
* **[Campaign]** Squadrons now (optionally, off by default) have a maximum size and killed pilots replenish at a limited rate.
* **[Campaign]** Added an option to disable levelling up of AI pilots.
* **[Campaign]** Added Russian Intervention 2015 campaign on Syria, for a small and somewhat realistic Russian COIN scenario.
* **[Campaign]** Added Operation Atilla campaign on Syria, for a reasonably large invasion of Cyprus scenario.
* **[Campaign AI]** AI will plan Tanker flights.
* **[Campaign AI]** Removed max distance for AEW&C auto planning.
* **[Economy]** Adjusted prices for aircraft to balance out some price inconsistencies.
* **[Factions]** Added more tankers to factions.
* **[Flight Planner]** Added ability to plan Tankers.
* **[Modding]** Campaign format version is now 7.0 to account for DCS map changes that made scenery strike targets incompatible with existing campaigns.
* **[Mods]** Added support for the Gripen mod.
* **[Mods]** Removes MB-339PAN support, as the mod is now deprecated and no longer works with DCS 2.7+.
* **[Mission Generation]** Added support for "Neutral Dot" label options.
* **[New Game Wizard]** Mods are now selected via checkboxes in the new game wizard, not as separate factions.
* **[UI]** Ctrl click and shift click now buy or sell 5 or 10 units respectively.
* **[UI]** Multiple waypoints can now be deleted simultaneously if multiple waypoints are selected.
* **[UI]** Carriers and LHAs now match the colour of airfields, and their destination icons are translucent.
* **[UI]** Updated intel box text for first turn.
* **[UI]** Base Capture Cheat is now usable at all bases and can also be used to transfer player-owned bases to OPFOR.
* **[UI]** Pass Turn button is relabled as "Begin Campaign" on Turn 0.
* **[UI]** Added a ruler to the map.
* **[UI]** Liberation now saves games to `<DCS user directory>/Liberation/Saves` by default to declutter the main directory.
## Fixes
* **[Campaign AI]** Fix procurement for factions that lack some unit types.
* **[Campaign AI]** Fix auto purchase of aircraft for factions that have no transport aircraft.
* **[Campaign AI]** Fix refunding of pending aircraft purchases when a side has no factory available.
* **[Mission Generation]** Fixed problem with mission load when control point name contained an apostrophe.
* **[Mission Generation]** Fixed EWR group names so they contribute to Skynet again.
* **[Mission Generation]** Fixed duplicate name error when generating convoys and cargo ships when creating manual transfers after loading a game.
* **[Mission Generation]** Fixed empty convoys not being disbanded when all units are killed/removed.
* **[Mission Generation]** Fixed player losing frontline progress when skipping from turn 0 to turn 1.
* **[Mission Generation]** Fixed issue where frontline would only search to the right for valid locations.
* **[UI]** Made non-interactive map elements less obstructive.
* **[UI]** Added support for Neutral Dot difficulty label
* **[UI]** Clear skies at night no longer described as "Sunny" by the weather widget.
* **[UI]** Removed ability to buy (useless) ground units at carriers and LHAs.
* **[UI]** Fixed enable/disable of buy/sell buttons.
* **[UI]** EWRs now appear in the custom waypoint list.
# 3.0.0
Saves from 2.5 are not compatible with 3.0.
## Features/Improvements
* **[Campaign]** Ground units can now be transferred by road, airlift, and cargo ship. See https://github.com/dcs-liberation/dcs_liberation/wiki/Unit-Transfers for more information.
* **[Campaign]** Ground units can no longer be sold. To move units to a new location, transfer them.
* **[Campaign]** Ground units must now be recruited at a base with a factory and transferred to their destination. When buying units in the UI, the purchase will automatically be fulfilled at the closest factory, and a transfer will be created on the next turn.
* **[Campaign]** Non-control point FOBs will no longer spawn.
* **[Campaign]** Added squadrons and pilots. See https://github.com/dcs-liberation/dcs_liberation/wiki/Squadrons-and-pilots for more information.
* **[Campaign]** Capturing a base now depopulates all of its attached objectives with units: air defenses, EWRs, ships, armor groups, etc. Buildings are captured.
* **[Campaign]** Ammunition Depots determine how many ground units can be deployed on the frontline by a control point.
* **[Campaign AI]** AI now considers Ju-88s for CAS, strike, and DEAD missions.
* **[Campaign AI]** AI planned AEW&C missions will now be scheduled ASAP.
* **[Campaign AI]** AI now considers the range to the SAM's threat zone rather than the range to the SAM itself when determining target priorities.
* **[Campaign AI]** Auto purchase of ground units will now maintain unit composition instead of buying randomly. The unit composition is predefined.
* **[Campaign AI]** Auto purchase will aim to purchase enough ground units to support the frontline, plus 30% reserve units.
* **[Campaign AI]** Auto purchase will now adjust its air/ground balance to favor whichever is under-funded.
* **[Flight Planner]** Desired mission length is now configurable (defaults to 60 minutes). A BARCAP will be planned every 30 minutes. Other packages will simply have their takeoffs spread out or compressed such that the last flight will take off around the mission end time.
* **[Flight Planner]** Flight plans now include bullseye waypoints.
* **[Flight Planner]** Differentiated SEAD and SEAD escort. SEAD is tasked with suppressing the package target, SEAD escort is tasked with protecting the package from all SAMs along its route.
* **[Flight Planner]** Planned airspeed increased to 0.85 mach for supersonic airframes and 85% of max speed for subsonic.
* **[Flight Planner]** Taxi time estimation for airfields increased from 5 minutes to 8 minutes.
* **[Flight Planner]** Reduce expected error margin for flight plans from 10% to 5%.
* **[Flight Planner]** SEAD flights are scheduled one minute ahead of the package's TOT so that they can suppress the site ahead of the strike.
* **[Flight Planner]** Automatic ATO generation for the player's coalition can now be disabled in the settings.
* **[Payloads]** AI flights for most air to ground mission types (CAS excluded) will have their guns emptied to prevent strafing fully armed and operational battle stations. Gun-reliant airframes like A-10s and warbirds will keep their bullets.
* **[Kneeboard]** ATC table overflow alleviated by wrapping long airfield names and splitting ATC frequency and channel into separate rows.
* **[UI]** Overhauled the map implementation. Now uses satellite imagery instead of low res map images. Display options have moved from the toolbar to panels in the map.
* **[UI]** Campaigns generated for an older or newer version of the game will now be marked as incompatible. They can still be played, but bugs may be present.
* **[UI]** DCS loadouts are now selectable in the loadout setup menu.
* **[UI]** Added global aircraft inventory view under Air Wing dialog.
* **[UI]** Base menu now shows information about ground unit deployment limits.
* **[Modding]** Campaigns now choose locations for factories to spawn.
* **[Modding]** Campaigns now choose locations for ammunition depots to spawn.
* **[Modding]** Campaigns now use map structures as strike targets.
* **[Modding]** Campaigns may now set *any* objective type to be a required spawn rather than random chance. Support for random objective generation was removed.
* **[Modding]** Campaigns may now place AAA objectives.
* **[Modding]** Can now install custom factions to <DCS saved games>/Liberation/Factions instead of the Liberation install directory.
* **[Performance Settings]** Added a settings to lower the number of smoke effects generated on frontlines. Lowered default settings for frontline smoke generators, so less smoke should be generated by default.
* **[Configuration]** Liberation preferences (DCS install and save game location) are now saved to `%LOCALAPPDATA%/DCSLiberation` to prevent needing to reconfigure each new install.
* **[Skynet]** Updated to 2.1.0.
## Fixes
* **[Campaign AI]** Fix purchase of aircraft by priority (the faction's list was being used as the priority list rather than the game's).
* **[Campaign AI]** Fixed bug causing AI to over-purchase cheap aircraft.
* **[Campaign AI]** Auto planner will no longer attempt to plan missions for which the faction has no compatible aircraft.
* **[Campaign AI]** Stop purchasing aircraft after the first unaffordable package to attempt to complete more packages rather than filling airfields with cheap escorts that will never be used.
* **[Campaign]** Fixed bug where offshore strike locations were being used to spawn ship objectives.
* **[Campaign]** EWR sites are now purchasable.
* **[Flight Planner]** AI strike flight plans now include the correct target actions for building groups.
* **[Flight Planner]** AI BAI/DEAD/SEAD flights now have tasks to attack all groups at the target location, not just the primary group (for multi-group SAM sites).
* **[Flight Planner]** Fixed some contexts where damaged runways would be used. Destroying a carrier will no longer break the game.
# 2.5.1
## Features/Improvements

View File

@@ -0,0 +1,80 @@
# Measuring estimated fuel consumption
To estimate fuel consumption numbers for an aircraft, create a mission with a
typical heavy load for the aircraft. For example, to measure for the F/A-18C, a
loadout with two bags, two GBU-31s, two sidewinders, an AMRAAM, and an ATFLIR.
Do **not** drop bags or weapons during the test flight.
Start the aircraft on the ground at a large airport (for example, Akrotiri) at a
parking space at the opposite end of the takeoff runway so you can estimate long
taxi fuel consumption.
When you enter the jet, note the amount of fuel below, then taxi to the far end
of the runway. Hold short and note the remaining fuel below.
Follow a typical takeoff pattern for the aircraft. For the F/A-18C, this might
be AB takeoff, reduce to MIL at 350KIAS, and maintian 350KIAS/0.85 mach until
cruise altitude (angles 25).
Once you reach angels 25, pause the game. Note your remaining fuel below and
measure the distance traveled from takeoff. Mark your location on the map.
Level out and increase to cruise speed if needed. Liberation assumes 0.85 mach
for supersonic aircraft, for subsonic aircraft it depends so pick something
reasonable and note your descision in a comment in the file when done. Maintain
speed, heading, and altitude for a long distance (the longer the distance, the
more accurate the result, but be careful to leave enough fuel for the final
section). Once complete, note the distance traveled and the remaining fuel.
Finally, increase speed as you would for an attack. At least MIL power,
potentially use AB sparingly, etc. The goal is to measure fuel consumption per
mile traveled during an attack run.
```
start:
taxi end:
to 25k distance:
at 25k fuel:
cruise (.85 mach) distance:
cruise (.85 mach) end fuel:
combat distance:
combat end fuel:
```
Finally, fill out the data in the aircraft data. Below is an example for the
F/A-18C:
```
start: 15290
taxi end: 15120
climb distance: 40NM
at 25k fuel: 13350
cruise (.85 mach) distance: 100NM
cruise (.85 mach) end fuel: 11140
combat distance: 100NM
combat end fuel: 8390
taxi = start - taxi end = 15290 - 15120 = 170
climb fuel = taxi end - at 25k fuel = 15120 - 13350 = 1770
climb ppm = climb fuel / climb distance = 1770 / 40 = 44.25
cruise fuel = at 25k fuel - cruise end fuel = 13350 - 11140 = 2210
cruise ppm = cruise fuel / cruise distance = 2210 / 100 = 22.1
combat fuel = cruise end fuel - combat end fuel = 11140 - 8390 = 2750
combat ppm = combat fuel / combat distance = 2750 / 100 = 27.5
```
```yaml
fuel:
# Parking A1 to RWY 32 at Akrotiri.
taxi: 170
# AB takeoff to 350/0.85, reduce to MIL and maintain 350 to 25k ft.
climb_ppm: 44.25
# 0.85 mach for 100NM.
cruise_ppm: 22.1
# ~0.9 mach for 100NM. Occasional AB use.
combat_ppm: 27.5
min_safe: 2000
```
The last entry (`min_safe`) is the minimum amount of fuel that the aircraft
should land with.

View File

@@ -0,0 +1,2 @@
from .campaign import Campaign
from .campaignairwingconfig import CampaignAirWingConfig, SquadronConfig

View File

@@ -0,0 +1,183 @@
from __future__ import annotations
import datetime
import json
import logging
from collections import Iterator
from dataclasses import dataclass
from pathlib import Path
from typing import Optional, Tuple, Dict, Any
from packaging.version import Version
import yaml
from game.profiling import logged_duration
from game.theater import (
ConflictTheater,
CaucasusTheater,
NevadaTheater,
PersianGulfTheater,
NormandyTheater,
TheChannelTheater,
SyriaTheater,
MarianaIslandsTheater,
)
from game.version import CAMPAIGN_FORMAT_VERSION, SUPPORTED_CAMPAIGN_VERSION
from .campaignairwingconfig import CampaignAirWingConfig
from .mizcampaignloader import MizCampaignLoader
from .. import persistency
PERF_FRIENDLY = 0
PERF_MEDIUM = 1
PERF_HARD = 2
PERF_NASA = 3
@dataclass(frozen=True)
class Campaign:
name: str
icon_name: str
authors: str
description: str
#: The revision of the campaign format the campaign was built for. We do not attempt
#: to migrate old campaigns, but this is used to show a warning in the UI when
#: selecting a campaign that is not up to date.
version: Tuple[int, int]
recommended_player_faction: str
recommended_enemy_faction: str
recommended_start_date: Optional[datetime.date]
performance: int
data: Dict[str, Any]
path: Path
@classmethod
def from_file(cls, path: Path) -> Campaign:
with path.open() as campaign_file:
if path.suffix == ".yaml":
data = yaml.safe_load(campaign_file)
else:
data = json.load(campaign_file)
sanitized_theater = data["theater"].replace(" ", "")
version_field = data.get("version", "0")
try:
version = Version(version_field)
except TypeError:
logging.warning(
f"Non-string campaign version in {path}. Parse may be incorrect."
)
version = Version(str(version_field))
start_date_raw = data.get("recommended_start_date")
# YAML automatically parses dates, but while we still support JSON campaigns we
# need to be able to handle parsing dates from strings ourselves as well.
start_date: Optional[datetime.date]
if isinstance(start_date_raw, str):
start_date = datetime.date.fromisoformat(start_date_raw)
elif isinstance(start_date_raw, datetime.date):
start_date = start_date_raw
elif start_date_raw is None:
start_date = None
else:
raise RuntimeError(
f"Invalid value for recommended_start_date in {path}: {start_date_raw}"
)
return cls(
data["name"],
f"Terrain_{sanitized_theater}",
data.get("authors", "???"),
data.get("description", ""),
(version.major, version.minor),
data.get("recommended_player_faction", "USA 2005"),
data.get("recommended_enemy_faction", "Russia 1990"),
start_date,
data.get("performance", 0),
data,
path,
)
def load_theater(self) -> ConflictTheater:
theaters = {
"Caucasus": CaucasusTheater,
"Nevada": NevadaTheater,
"Persian Gulf": PersianGulfTheater,
"Normandy": NormandyTheater,
"The Channel": TheChannelTheater,
"Syria": SyriaTheater,
"MarianaIslands": MarianaIslandsTheater,
}
theater = theaters[self.data["theater"]]
t = theater()
try:
miz = self.data["miz"]
except KeyError as ex:
raise RuntimeError(
"Old format (non-miz) campaigns are no longer supported."
) from ex
with logged_duration("Importing miz data"):
MizCampaignLoader(self.path.parent / miz, t).populate_theater()
return t
def load_air_wing_config(self, theater: ConflictTheater) -> CampaignAirWingConfig:
try:
squadron_data = self.data["squadrons"]
except KeyError:
logging.warning(f"Campaign {self.name} does not define any squadrons")
return CampaignAirWingConfig({})
return CampaignAirWingConfig.from_campaign_data(squadron_data, theater)
@property
def is_out_of_date(self) -> bool:
"""Returns True if this campaign is not up to date with the latest format.
This is more permissive than is_from_future, which is sensitive to minor version
bumps (the old game definitely doesn't support the minor features added in the
new version, and the campaign may require them. However, the minor version only
indicates *optional* new features, so we do not need to mark out of date
campaigns as incompatible if they are within the same major version.
"""
return self.version[0] < CAMPAIGN_FORMAT_VERSION[0]
@property
def is_from_future(self) -> bool:
"""Returns True if this campaign is newer than the supported format."""
return self.version > SUPPORTED_CAMPAIGN_VERSION
@property
def is_compatible(self) -> bool:
"""Returns True is this campaign was built for this version of the game."""
if self.version == (0, 0):
return False
if self.is_out_of_date:
return False
if self.is_from_future:
return False
return True
@staticmethod
def iter_campaigns_in_dir(path: Path) -> Iterator[Path]:
yield from path.glob("*.yaml")
yield from path.glob("*.json")
@classmethod
def iter_campaign_defs(cls) -> Iterator[Path]:
yield from cls.iter_campaigns_in_dir(
Path(persistency.base_path()) / "Liberation/Campaigns"
)
yield from cls.iter_campaigns_in_dir(Path("resources/campaigns"))
@classmethod
def load_each(cls) -> Iterator[Campaign]:
for path in cls.iter_campaign_defs():
try:
logging.debug(f"Loading campaign from {path}...")
campaign = Campaign.from_file(path)
yield campaign
except RuntimeError:
logging.exception(f"Unable to load campaign from {path}")

View File

@@ -0,0 +1,68 @@
from __future__ import annotations
import logging
from collections import defaultdict
from dataclasses import dataclass
from typing import Any, TYPE_CHECKING, Union
from gen.flights.flight import FlightType
from game.theater.controlpoint import ControlPoint
if TYPE_CHECKING:
from game.theater import ConflictTheater
@dataclass(frozen=True)
class SquadronConfig:
primary: FlightType
secondary: list[FlightType]
aircraft: list[str]
@property
def auto_assignable(self) -> set[FlightType]:
return set(self.secondary) | {self.primary}
@classmethod
def from_data(cls, data: dict[str, Any]) -> SquadronConfig:
secondary_raw = data.get("secondary")
if secondary_raw is None:
secondary = []
elif isinstance(secondary_raw, str):
secondary = cls.expand_secondary_alias(secondary_raw)
else:
secondary = [FlightType(s) for s in secondary_raw]
return SquadronConfig(
FlightType(data["primary"]), secondary, data.get("aircraft", [])
)
@staticmethod
def expand_secondary_alias(alias: str) -> list[FlightType]:
if alias == "any":
return list(FlightType)
elif alias == "air-to-air":
return [t for t in FlightType if t.is_air_to_air]
elif alias == "air-to-ground":
return [t for t in FlightType if t.is_air_to_ground]
raise KeyError(f"Unknown secondary mission type: {alias}")
@dataclass(frozen=True)
class CampaignAirWingConfig:
by_location: dict[ControlPoint, list[SquadronConfig]]
@classmethod
def from_campaign_data(
cls, data: dict[Union[str, int], Any], theater: ConflictTheater
) -> CampaignAirWingConfig:
by_location: dict[ControlPoint, list[SquadronConfig]] = defaultdict(list)
for base_id, squadron_configs in data.items():
if isinstance(base_id, int):
base = theater.find_control_point_by_id(base_id)
else:
base = theater.control_point_named(base_id)
for squadron_data in squadron_configs:
by_location[base].append(SquadronConfig.from_data(squadron_data))
return CampaignAirWingConfig(by_location)

View File

@@ -0,0 +1,144 @@
from __future__ import annotations
import logging
from typing import Optional, TYPE_CHECKING
from game.squadrons import Squadron
from game.squadrons.squadrondef import SquadronDef
from gen.flights.flight import FlightType
from .campaignairwingconfig import CampaignAirWingConfig, SquadronConfig
from ..dcs.aircrafttype import AircraftType
from ..theater import ControlPoint
if TYPE_CHECKING:
from game import Game
from game.coalition import Coalition
class DefaultSquadronAssigner:
def __init__(
self, config: CampaignAirWingConfig, game: Game, coalition: Coalition
) -> None:
self.config = config
self.game = game
self.coalition = coalition
self.air_wing = coalition.air_wing
def assign(self) -> None:
for control_point in self.game.theater.control_points_for(
self.coalition.player
):
for squadron_config in self.config.by_location[control_point]:
squadron_def = self.find_squadron_for(squadron_config, control_point)
if squadron_def is None:
logging.info(
f"{self.coalition.faction.name} has no aircraft compatible "
f"with {squadron_config.primary} at {control_point}"
)
continue
squadron = Squadron.create_from(
squadron_def, control_point, self.coalition, self.game
)
squadron.set_auto_assignable_mission_types(
squadron_config.auto_assignable
)
self.air_wing.add_squadron(squadron)
def find_squadron_for(
self, config: SquadronConfig, control_point: ControlPoint
) -> Optional[SquadronDef]:
for preferred_aircraft in config.aircraft:
squadron_def = self.find_preferred_squadron(
preferred_aircraft, config.primary, control_point
)
if squadron_def is not None:
return squadron_def
# If we didn't find any of the preferred types we should use any squadron
# compatible with the primary task.
squadron_def = self.find_squadron_for_task(config.primary, control_point)
if squadron_def is not None:
return squadron_def
# If we can't find any squadron matching the requirement, we should
# create one.
return self.air_wing.squadron_def_generator.generate_for_task(
config.primary, control_point
)
def find_preferred_squadron(
self, preferred_aircraft: str, task: FlightType, control_point: ControlPoint
) -> Optional[SquadronDef]:
# Attempt to find a squadron with the name in the request.
squadron_def = self.find_squadron_by_name(
preferred_aircraft, task, control_point
)
if squadron_def is not None:
return squadron_def
# If the name didn't match a squadron available to this coalition, try to find
# an aircraft with the matching name that meets the requirements.
try:
aircraft = AircraftType.named(preferred_aircraft)
except KeyError:
# No aircraft with this name.
return None
if aircraft not in self.coalition.faction.aircrafts:
return None
squadron_def = self.find_squadron_for_airframe(aircraft, task, control_point)
if squadron_def is not None:
return squadron_def
# No premade squadron available for this aircraft that meets the requirements,
# so generate one if possible.
return self.air_wing.squadron_def_generator.generate_for_aircraft(aircraft)
@staticmethod
def squadron_compatible_with(
squadron: SquadronDef,
task: FlightType,
control_point: ControlPoint,
ignore_base_preference: bool = False,
) -> bool:
if ignore_base_preference:
return control_point.can_operate(squadron.aircraft)
return squadron.operates_from(control_point) and task in squadron.mission_types
def find_squadron_for_airframe(
self, aircraft: AircraftType, task: FlightType, control_point: ControlPoint
) -> Optional[SquadronDef]:
for squadron in self.air_wing.squadron_defs[aircraft]:
if not squadron.claimed and self.squadron_compatible_with(
squadron, task, control_point
):
return squadron
return None
def find_squadron_by_name(
self, name: str, task: FlightType, control_point: ControlPoint
) -> Optional[SquadronDef]:
for squadrons in self.air_wing.squadron_defs.values():
for squadron in squadrons:
if (
not squadron.claimed
and squadron.name == name
and self.squadron_compatible_with(
squadron, task, control_point, ignore_base_preference=True
)
):
return squadron
return None
def find_squadron_for_task(
self, task: FlightType, control_point: ControlPoint
) -> Optional[SquadronDef]:
for squadrons in self.air_wing.squadron_defs.values():
for squadron in squadrons:
if not squadron.claimed and self.squadron_compatible_with(
squadron, task, control_point
):
return squadron
return None

View File

@@ -0,0 +1,473 @@
from __future__ import annotations
import itertools
from functools import cached_property
from pathlib import Path
from typing import Iterator, List, Dict, Tuple, TYPE_CHECKING
from dcs import Mission
from dcs.countries import CombinedJointTaskForcesBlue, CombinedJointTaskForcesRed
from dcs.country import Country
from dcs.planes import F_15C
from dcs.ships import Stennis, LHA_Tarawa, HandyWind, USS_Arleigh_Burke_IIa
from dcs.statics import Fortification, Warehouse
from dcs.terrain import Airport
from dcs.unitgroup import PlaneGroup, ShipGroup, VehicleGroup, StaticGroup
from dcs.vehicles import Armor, Unarmed, MissilesSS, AirDefence
from game.point_with_heading import PointWithHeading
from game.positioned import Positioned
from game.profiling import logged_duration
from game.scenery_group import SceneryGroup
from game.utils import Distance, meters, Heading
from game.theater.controlpoint import (
Airfield,
Carrier,
ControlPoint,
Fob,
Lha,
OffMapSpawn,
)
if TYPE_CHECKING:
from game.theater.conflicttheater import ConflictTheater
class MizCampaignLoader:
BLUE_COUNTRY = CombinedJointTaskForcesBlue()
RED_COUNTRY = CombinedJointTaskForcesRed()
OFF_MAP_UNIT_TYPE = F_15C.id
CV_UNIT_TYPE = Stennis.id
LHA_UNIT_TYPE = LHA_Tarawa.id
FRONT_LINE_UNIT_TYPE = Armor.M_113.id
SHIPPING_LANE_UNIT_TYPE = HandyWind.id
FOB_UNIT_TYPE = Unarmed.SKP_11.id
FARP_HELIPADS_TYPE = ["Invisible FARP", "SINGLE_HELIPAD"]
OFFSHORE_STRIKE_TARGET_UNIT_TYPE = Fortification.Oil_platform.id
SHIP_UNIT_TYPE = USS_Arleigh_Burke_IIa.id
MISSILE_SITE_UNIT_TYPE = MissilesSS.Scud_B.id
COASTAL_DEFENSE_UNIT_TYPE = MissilesSS.Hy_launcher.id
# Multiple options for air defenses so campaign designers can more accurately see
# the coverage of their IADS for the expected type.
LONG_RANGE_SAM_UNIT_TYPES = {
AirDefence.Patriot_ln.id,
AirDefence.S_300PS_5P85C_ln.id,
AirDefence.S_300PS_5P85D_ln.id,
}
MEDIUM_RANGE_SAM_UNIT_TYPES = {
AirDefence.Hawk_ln.id,
AirDefence.S_75M_Volhov.id,
AirDefence._5p73_s_125_ln.id,
}
SHORT_RANGE_SAM_UNIT_TYPES = {
AirDefence.M1097_Avenger.id,
AirDefence.Rapier_fsa_launcher.id,
AirDefence._2S6_Tunguska.id,
AirDefence.Strela_1_9P31.id,
}
AAA_UNIT_TYPES = {
AirDefence.Flak18.id,
AirDefence.Vulcan.id,
AirDefence.ZSU_23_4_Shilka.id,
}
EWR_UNIT_TYPE = AirDefence._1L13_EWR.id
ARMOR_GROUP_UNIT_TYPE = Armor.M_1_Abrams.id
FACTORY_UNIT_TYPE = Fortification.Workshop_A.id
AMMUNITION_DEPOT_UNIT_TYPE = Warehouse._Ammunition_depot.id
STRIKE_TARGET_UNIT_TYPE = Fortification.Tech_combine.id
def __init__(self, miz: Path, theater: ConflictTheater) -> None:
self.theater = theater
self.mission = Mission()
with logged_duration("Loading miz"):
self.mission.load_file(str(miz))
self.control_point_id = itertools.count(1000)
# If there are no red carriers there usually aren't red units. Make sure
# both countries are initialized so we don't have to deal with None.
if self.mission.country(self.BLUE_COUNTRY.name) is None:
self.mission.coalition["blue"].add_country(self.BLUE_COUNTRY)
if self.mission.country(self.RED_COUNTRY.name) is None:
self.mission.coalition["red"].add_country(self.RED_COUNTRY)
@staticmethod
def control_point_from_airport(airport: Airport) -> ControlPoint:
cp = Airfield(airport, starts_blue=airport.is_blue())
# Use the unlimited aircraft option to determine if an airfield should
# be owned by the player when the campaign is "inverted".
cp.captured_invert = airport.unlimited_aircrafts
return cp
def country(self, blue: bool) -> Country:
country = self.mission.country(
self.BLUE_COUNTRY.name if blue else self.RED_COUNTRY.name
)
# Should be guaranteed because we initialized them.
assert country
return country
@property
def blue(self) -> Country:
return self.country(blue=True)
@property
def red(self) -> Country:
return self.country(blue=False)
def off_map_spawns(self, blue: bool) -> Iterator[PlaneGroup]:
for group in self.country(blue).plane_group:
if group.units[0].type == self.OFF_MAP_UNIT_TYPE:
yield group
def carriers(self, blue: bool) -> Iterator[ShipGroup]:
for group in self.country(blue).ship_group:
if group.units[0].type == self.CV_UNIT_TYPE:
yield group
def lhas(self, blue: bool) -> Iterator[ShipGroup]:
for group in self.country(blue).ship_group:
if group.units[0].type == self.LHA_UNIT_TYPE:
yield group
def fobs(self, blue: bool) -> Iterator[VehicleGroup]:
for group in self.country(blue).vehicle_group:
if group.units[0].type == self.FOB_UNIT_TYPE:
yield group
@property
def ships(self) -> Iterator[ShipGroup]:
for group in self.red.ship_group:
if group.units[0].type == self.SHIP_UNIT_TYPE:
yield group
@property
def offshore_strike_targets(self) -> Iterator[StaticGroup]:
for group in self.red.static_group:
if group.units[0].type == self.OFFSHORE_STRIKE_TARGET_UNIT_TYPE:
yield group
@property
def missile_sites(self) -> Iterator[VehicleGroup]:
for group in self.red.vehicle_group:
if group.units[0].type == self.MISSILE_SITE_UNIT_TYPE:
yield group
@property
def coastal_defenses(self) -> Iterator[VehicleGroup]:
for group in self.red.vehicle_group:
if group.units[0].type == self.COASTAL_DEFENSE_UNIT_TYPE:
yield group
@property
def long_range_sams(self) -> Iterator[VehicleGroup]:
for group in self.red.vehicle_group:
if group.units[0].type in self.LONG_RANGE_SAM_UNIT_TYPES:
yield group
@property
def medium_range_sams(self) -> Iterator[VehicleGroup]:
for group in self.red.vehicle_group:
if group.units[0].type in self.MEDIUM_RANGE_SAM_UNIT_TYPES:
yield group
@property
def short_range_sams(self) -> Iterator[VehicleGroup]:
for group in self.red.vehicle_group:
if group.units[0].type in self.SHORT_RANGE_SAM_UNIT_TYPES:
yield group
@property
def aaa(self) -> Iterator[VehicleGroup]:
for group in itertools.chain(self.blue.vehicle_group, self.red.vehicle_group):
if group.units[0].type in self.AAA_UNIT_TYPES:
yield group
@property
def ewrs(self) -> Iterator[VehicleGroup]:
for group in self.red.vehicle_group:
if group.units[0].type in self.EWR_UNIT_TYPE:
yield group
@property
def armor_groups(self) -> Iterator[VehicleGroup]:
for group in itertools.chain(self.blue.vehicle_group, self.red.vehicle_group):
if group.units[0].type in self.ARMOR_GROUP_UNIT_TYPE:
yield group
@property
def helipads(self) -> Iterator[StaticGroup]:
for group in itertools.chain(self.blue.static_group, self.red.static_group):
if group.units[0].type in self.FARP_HELIPADS_TYPE:
yield group
@property
def factories(self) -> Iterator[StaticGroup]:
for group in self.blue.static_group:
if group.units[0].type in self.FACTORY_UNIT_TYPE:
yield group
@property
def ammunition_depots(self) -> Iterator[StaticGroup]:
for group in itertools.chain(self.blue.static_group, self.red.static_group):
if group.units[0].type in self.AMMUNITION_DEPOT_UNIT_TYPE:
yield group
@property
def strike_targets(self) -> Iterator[StaticGroup]:
for group in itertools.chain(self.blue.static_group, self.red.static_group):
if group.units[0].type in self.STRIKE_TARGET_UNIT_TYPE:
yield group
@property
def scenery(self) -> List[SceneryGroup]:
return SceneryGroup.from_trigger_zones(self.mission.triggers._zones)
@cached_property
def control_points(self) -> Dict[int, ControlPoint]:
control_points = {}
for airport in self.mission.terrain.airport_list():
if airport.is_blue() or airport.is_red():
control_point = self.control_point_from_airport(airport)
control_points[control_point.id] = control_point
for blue in (False, True):
for group in self.off_map_spawns(blue):
control_point = OffMapSpawn(
next(self.control_point_id),
str(group.name),
group.position,
starts_blue=blue,
)
control_point.captured_invert = group.late_activation
control_points[control_point.id] = control_point
for ship in self.carriers(blue):
control_point = Carrier(
ship.name,
ship.position,
next(self.control_point_id),
starts_blue=blue,
)
control_point.captured_invert = ship.late_activation
control_points[control_point.id] = control_point
for ship in self.lhas(blue):
control_point = Lha(
ship.name,
ship.position,
next(self.control_point_id),
starts_blue=blue,
)
control_point.captured_invert = ship.late_activation
control_points[control_point.id] = control_point
for fob in self.fobs(blue):
control_point = Fob(
str(fob.name),
fob.position,
next(self.control_point_id),
starts_blue=blue,
)
control_point.captured_invert = fob.late_activation
control_points[control_point.id] = control_point
return control_points
@property
def front_line_path_groups(self) -> Iterator[VehicleGroup]:
for group in self.country(blue=True).vehicle_group:
if group.units[0].type == self.FRONT_LINE_UNIT_TYPE:
yield group
@property
def shipping_lane_groups(self) -> Iterator[ShipGroup]:
for group in self.country(blue=True).ship_group:
if group.units[0].type == self.SHIPPING_LANE_UNIT_TYPE:
yield group
def add_supply_routes(self) -> None:
for group in self.front_line_path_groups:
# The unit will have its first waypoint at the source CP and the final
# waypoint at the destination CP. Each waypoint defines the path of the
# cargo ship.
waypoints = [p.position for p in group.points]
origin = self.theater.closest_control_point(waypoints[0])
if origin is None:
raise RuntimeError(
f"No control point near the first waypoint of {group.name}"
)
destination = self.theater.closest_control_point(waypoints[-1])
if destination is None:
raise RuntimeError(
f"No control point near the final waypoint of {group.name}"
)
self.control_points[origin.id].create_convoy_route(destination, waypoints)
self.control_points[destination.id].create_convoy_route(
origin, list(reversed(waypoints))
)
def add_shipping_lanes(self) -> None:
for group in self.shipping_lane_groups:
# The unit will have its first waypoint at the source CP and the final
# waypoint at the destination CP. Each waypoint defines the path of the
# cargo ship.
waypoints = [p.position for p in group.points]
origin = self.theater.closest_control_point(waypoints[0])
if origin is None:
raise RuntimeError(
f"No control point near the first waypoint of {group.name}"
)
destination = self.theater.closest_control_point(waypoints[-1])
if destination is None:
raise RuntimeError(
f"No control point near the final waypoint of {group.name}"
)
self.control_points[origin.id].create_shipping_lane(destination, waypoints)
self.control_points[destination.id].create_shipping_lane(
origin, list(reversed(waypoints))
)
def objective_info(
self, near: Positioned, allow_naval: bool = False
) -> Tuple[ControlPoint, Distance]:
closest = self.theater.closest_control_point(near.position, allow_naval)
distance = meters(closest.position.distance_to_point(near.position))
return closest, distance
def add_preset_locations(self) -> None:
for static in self.offshore_strike_targets:
closest, distance = self.objective_info(static)
closest.preset_locations.offshore_strike_locations.append(
PointWithHeading.from_point(
static.position, Heading.from_degrees(static.units[0].heading)
)
)
for ship in self.ships:
closest, distance = self.objective_info(ship, allow_naval=True)
closest.preset_locations.ships.append(
PointWithHeading.from_point(
ship.position, Heading.from_degrees(ship.units[0].heading)
)
)
for group in self.missile_sites:
closest, distance = self.objective_info(group)
closest.preset_locations.missile_sites.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for group in self.coastal_defenses:
closest, distance = self.objective_info(group)
closest.preset_locations.coastal_defenses.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for group in self.long_range_sams:
closest, distance = self.objective_info(group)
closest.preset_locations.long_range_sams.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for group in self.medium_range_sams:
closest, distance = self.objective_info(group)
closest.preset_locations.medium_range_sams.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for group in self.short_range_sams:
closest, distance = self.objective_info(group)
closest.preset_locations.short_range_sams.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for group in self.aaa:
closest, distance = self.objective_info(group)
closest.preset_locations.aaa.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for group in self.ewrs:
closest, distance = self.objective_info(group)
closest.preset_locations.ewrs.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for group in self.armor_groups:
closest, distance = self.objective_info(group)
closest.preset_locations.armor_groups.append(
PointWithHeading.from_point(
group.position, Heading.from_degrees(group.units[0].heading)
)
)
for static in self.helipads:
closest, distance = self.objective_info(static)
closest.helipads.append(
PointWithHeading.from_point(
static.position, Heading.from_degrees(static.units[0].heading)
)
)
for static in self.factories:
closest, distance = self.objective_info(static)
closest.preset_locations.factories.append(
PointWithHeading.from_point(
static.position, Heading.from_degrees(static.units[0].heading)
)
)
for static in self.ammunition_depots:
closest, distance = self.objective_info(static)
closest.preset_locations.ammunition_depots.append(
PointWithHeading.from_point(
static.position, Heading.from_degrees(static.units[0].heading)
)
)
for static in self.strike_targets:
closest, distance = self.objective_info(static)
closest.preset_locations.strike_locations.append(
PointWithHeading.from_point(
static.position, Heading.from_degrees(static.units[0].heading)
)
)
for scenery_group in self.scenery:
closest, distance = self.objective_info(scenery_group)
closest.preset_locations.scenery.append(scenery_group)
def populate_theater(self) -> None:
for control_point in self.control_points.values():
self.theater.add_controlpoint(control_point)
self.add_preset_locations()
self.add_supply_routes()
self.add_shipping_lanes()

View File

@@ -0,0 +1,325 @@
from __future__ import annotations
import itertools
import random
from typing import TYPE_CHECKING, Optional
from game.dcs.aircrafttype import AircraftType
from game.squadrons.operatingbases import OperatingBases
from game.squadrons.squadrondef import SquadronDef
from game.theater import ControlPoint
from gen.flights.ai_flight_planner_db import aircraft_for_task, tasks_for_aircraft
from gen.flights.flight import FlightType
if TYPE_CHECKING:
from game.factions.faction import Faction
class SquadronDefGenerator:
def __init__(self, faction: Faction) -> None:
self.faction = faction
self.count = itertools.count(1)
self.used_nicknames: set[str] = set()
def generate_for_task(
self, task: FlightType, control_point: ControlPoint
) -> Optional[SquadronDef]:
aircraft_choice: Optional[AircraftType] = None
for aircraft in aircraft_for_task(task):
if aircraft not in self.faction.aircrafts:
continue
if not control_point.can_operate(aircraft):
continue
aircraft_choice = aircraft
# 50/50 chance to keep looking for an aircraft that isn't as far up the
# priority list to maintain some unit variety.
if random.choice([True, False]):
break
if aircraft_choice is None:
return None
return self.generate_for_aircraft(aircraft_choice)
def generate_for_aircraft(self, aircraft: AircraftType) -> SquadronDef:
return SquadronDef(
name=f"Squadron {next(self.count):03}",
nickname=self.random_nickname(),
country=self.faction.country,
role="Flying Squadron",
aircraft=aircraft,
livery=None,
mission_types=tuple(tasks_for_aircraft(aircraft)),
operating_bases=OperatingBases.default_for_aircraft(aircraft),
pilot_pool=[],
)
@staticmethod
def _make_random_nickname() -> str:
from gen.naming import ANIMALS
animal = random.choice(ANIMALS)
adjective = random.choice(
(
None,
"Aggressive",
"Alpha",
"Ancient",
"Angelic",
"Angry",
"Apoplectic",
"Aquamarine",
"Astral",
"Avenging",
"Azure",
"Badass",
"Barbaric",
"Battle",
"Battling",
"Bellicose",
"Belligerent",
"Big",
"Bionic",
"Black",
"Bladed",
"Blazoned",
"Blood",
"Bloody",
"Blue",
"Bold",
"Boxing",
"Brash",
"Brass",
"Brave",
"Brazen",
"Bronze",
"Brown",
"Brutal",
"Burning",
"Buzzing",
"Celestial",
"Clever",
"Cloud",
"Cobalt",
"Copper",
"Coral",
"Crazy",
"Crimson",
"Crouching",
"Cursed",
"Cyan",
"Danger",
"Dangerous",
"Dapper",
"Daring",
"Dark",
"Dawn",
"Day",
"Deadly",
"Death",
"Defiant",
"Demon",
"Desert",
"Devil",
"Devil's",
"Diabolical",
"Diamond",
"Dire",
"Dirty",
"Doom",
"Doomed",
"Double",
"Drunken",
"Dusk",
"Dusty",
"Eager",
"Ebony",
"Electric",
"Emerald",
"Eternal",
"Evil",
"Faithful",
"Famous",
"Fanged",
"Fearless",
"Feisty",
"Ferocious",
"Fierce",
"Fiery",
"Fighting",
"Fire",
"First",
"Flame",
"Flaming",
"Flying",
"Forest",
"Frenzied",
"Frosty",
"Frozen",
"Furious",
"Gallant",
"Ghost",
"Giant",
"Gigantic",
"Glaring",
"Global",
"Gold",
"Golden",
"Green",
"Grey",
"Grim",
"Grizzly",
"Growling",
"Grumpy",
"Hammer",
"Hard",
"Hardy",
"Heavy",
"Hell",
"Hell's",
"Hidden",
"Homicidal",
"Hostile",
"Howling",
"Hyper",
"Ice",
"Icy",
"Immortal",
"Indignant",
"Infamous",
"Invincible",
"Iron",
"Jolly",
"Laser",
"Lava",
"Lavender",
"Lethal",
"Light",
"Lightning",
"Livid",
"Lucky",
"Mad",
"Magenta",
"Magma",
"Maroon",
"Menacing",
"Merciless",
"Metal",
"Midnight",
"Mighty",
"Mithril",
"Mocking",
"Moon",
"Mountain",
"Muddy",
"Nasty",
"Naughty",
"Night",
"Nova",
"Nutty",
"Obsidian",
"Ocean",
"Oddball",
"Old",
"Omega",
"Onyx",
"Orange",
"Perky",
"Pink",
"Power",
"Prickly",
"Proud",
"Puckered",
"Pugnacious",
"Puking",
"Purple",
"Ragged",
"Raging",
"Rainbow",
"Rampant",
"Razor",
"Ready",
"Reaper",
"Reckless",
"Red",
"Roaring",
"Rocky",
"Rolling",
"Royal",
"Rusty",
"Sable",
"Salty",
"Sand",
"Sarcastic",
"Saucy",
"Scarlet",
"Scarred",
"Scary",
"Screaming",
"Scythed",
"Shadow",
"Shiny",
"Shocking",
"Silver",
"Sky",
"Smoke",
"Smokin'",
"Snapping",
"Snappy",
"Snarling",
"Snow",
"Soaring",
"Space",
"Spiky",
"Spiny",
"Star",
"Steady",
"Steel",
"Stone",
"Storm",
"Striking",
"Strong",
"Stubborn",
"Sun",
"Super",
"Terrible",
"Thorny",
"Thunder",
"Top",
"Tough",
"Toxic",
"Tricky",
"Turquoise",
"Typhoon",
"Ultimate",
"Ultra",
"Ultramarine",
"Vengeful",
"Venom",
"Vermillion",
"Vicious",
"Victorious",
"Vigilant",
"Violent",
"Violet",
"War",
"Water",
"Whistling",
"White",
"Wicked",
"Wild",
"Wizard",
"Wrathful",
"Yellow",
"Young",
)
)
if adjective is None:
return animal.title()
return f"{adjective} {animal}".title()
def random_nickname(self) -> str:
while True:
nickname = self._make_random_nickname()
if nickname not in self.used_nicknames:
self.used_nicknames.add(nickname)
return nickname

235
game/coalition.py Normal file
View File

@@ -0,0 +1,235 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
from dcs import Point
from faker import Faker
from game.campaignloader import CampaignAirWingConfig
from game.campaignloader.defaultsquadronassigner import DefaultSquadronAssigner
from game.commander import TheaterCommander
from game.commander.missionscheduler import MissionScheduler
from game.income import Income
from game.navmesh import NavMesh
from game.orderedset import OrderedSet
from game.profiling import logged_duration, MultiEventTracer
from game.squadrons import AirWing
from game.threatzones import ThreatZones
from game.transfers import PendingTransfers
if TYPE_CHECKING:
from game import Game
from game.data.doctrine import Doctrine
from game.factions.faction import Faction
from game.procurement import AircraftProcurementRequest, ProcurementAi
from game.theater.bullseye import Bullseye
from game.theater.transitnetwork import TransitNetwork, TransitNetworkBuilder
from gen.ato import AirTaskingOrder
class Coalition:
def __init__(
self, game: Game, faction: Faction, budget: float, player: bool
) -> None:
self.game = game
self.player = player
self.faction = faction
self.budget = budget
self.ato = AirTaskingOrder()
self.transit_network = TransitNetwork()
self.procurement_requests: OrderedSet[AircraftProcurementRequest] = OrderedSet()
self.bullseye = Bullseye(Point(0, 0))
self.faker = Faker(self.faction.locales)
self.air_wing = AirWing(player, game, self.faction)
self.transfers = PendingTransfers(game, player)
# Late initialized because the two coalitions in the game are mutually
# dependent, so must be both constructed before this property can be set.
self._opponent: Optional[Coalition] = None
# Volatile properties that are not persisted to the save file since they can be
# recomputed on load. Keeping this data out of the save file makes save compat
# breaks less frequent. Each of these properties has a non-underscore-prefixed
# @property that should be used for non-Optional access.
#
# All of these are late-initialized (whether via on_load or called later), but
# will be non-None after the game has finished loading.
self._threat_zone: Optional[ThreatZones] = None
self._navmesh: Optional[NavMesh] = None
self.on_load()
@property
def doctrine(self) -> Doctrine:
return self.faction.doctrine
@property
def coalition_id(self) -> int:
if self.player:
return 2
return 1
@property
def country_name(self) -> str:
return self.faction.country
@property
def opponent(self) -> Coalition:
assert self._opponent is not None
return self._opponent
@property
def threat_zone(self) -> ThreatZones:
assert self._threat_zone is not None
return self._threat_zone
@property
def nav_mesh(self) -> NavMesh:
assert self._navmesh is not None
return self._navmesh
def __getstate__(self) -> dict[str, Any]:
state = self.__dict__.copy()
# Avoid persisting any volatile types that can be deterministically
# recomputed on load for the sake of save compatibility.
del state["_threat_zone"]
del state["_navmesh"]
del state["faker"]
return state
def __setstate__(self, state: dict[str, Any]) -> None:
self.__dict__.update(state)
# Regenerate any state that was not persisted.
self.on_load()
def on_load(self) -> None:
self.faker = Faker(self.faction.locales)
def set_opponent(self, opponent: Coalition) -> None:
if self._opponent is not None:
raise RuntimeError("Double-initialization of Coalition.opponent")
self._opponent = opponent
def configure_default_air_wing(
self, air_wing_config: CampaignAirWingConfig
) -> None:
DefaultSquadronAssigner(air_wing_config, self.game, self).assign()
def adjust_budget(self, amount: float) -> None:
self.budget += amount
def compute_threat_zones(self) -> None:
self._threat_zone = ThreatZones.for_faction(self.game, self.player)
def compute_nav_meshes(self) -> None:
self._navmesh = NavMesh.from_threat_zones(
self.opponent.threat_zone, self.game.theater
)
def update_transit_network(self) -> None:
self.transit_network = TransitNetworkBuilder(
self.game.theater, self.player
).build()
def set_bullseye(self, bullseye: Bullseye) -> None:
self.bullseye = bullseye
def end_turn(self) -> None:
"""Processes coalition-specific turn finalization.
For more information on turn finalization in general, see the documentation for
`Game.finish_turn`.
"""
self.air_wing.end_turn()
self.budget += Income(self.game, self.player).total
# Need to recompute before transfers and deliveries to account for captures.
# This happens in in initialize_turn as well, because cheating doesn't advance a
# turn but can capture bases so we need to recompute there as well.
self.update_transit_network()
# Must happen *before* unit deliveries are handled, or else new units will spawn
# one hop ahead. ControlPoint.process_turn handles unit deliveries. The
# coalition-specific turn-end happens before the theater-wide turn-end, so this
# is handled correctly.
self.transfers.perform_transfers()
def preinit_turn_0(self) -> None:
"""Runs final Coalition initialization.
Final initialization occurs before Game.initialize_turn runs for turn 0.
"""
self.air_wing.populate_for_turn_0()
def initialize_turn(self) -> None:
"""Processes coalition-specific turn initialization.
For more information on turn initialization in general, see the documentation
for `Game.initialize_turn`.
"""
# Needs to happen *before* planning transfers so we don't cancel them.
self.ato.clear()
self.air_wing.reset()
self.refund_outstanding_orders()
self.procurement_requests.clear()
with logged_duration("Transit network identification"):
self.update_transit_network()
with logged_duration("Procurement of airlift assets"):
self.transfers.order_airlift_assets()
with logged_duration("Transport planning"):
self.transfers.plan_transports()
self.plan_missions()
self.plan_procurement()
def refund_outstanding_orders(self) -> None:
# TODO: Split orders between air and ground units.
# This isn't quite right. If the player has ground purchases automated we should
# be refunding the ground units, and if they have air automated but not ground
# we should be refunding air units.
if self.player and not self.game.settings.automate_aircraft_reinforcements:
return
for cp in self.game.theater.control_points_for(self.player):
cp.ground_unit_orders.refund_all(self)
for squadron in self.air_wing.iter_squadrons():
squadron.refund_orders()
def plan_missions(self) -> None:
color = "Blue" if self.player else "Red"
with MultiEventTracer() as tracer:
with tracer.trace(f"{color} mission planning"):
with tracer.trace(f"{color} mission identification"):
TheaterCommander(self.game, self.player).plan_missions(tracer)
with tracer.trace(f"{color} mission scheduling"):
MissionScheduler(
self, self.game.settings.desired_player_mission_duration
).schedule_missions()
def plan_procurement(self) -> None:
# The first turn needs to buy a *lot* of aircraft to fill CAPs, so it gets much
# more of the budget that turn. Otherwise budget (after repairs) is split evenly
# between air and ground. For the default starting budget of 2000 this gives 600
# to ground forces and 1400 to aircraft. After that the budget will be spent
# proportionally based on how much is already invested.
if self.player:
manage_runways = self.game.settings.automate_runway_repair
manage_front_line = self.game.settings.automate_front_line_reinforcements
manage_aircraft = self.game.settings.automate_aircraft_reinforcements
else:
manage_runways = True
manage_front_line = True
manage_aircraft = True
self.budget = ProcurementAi(
self.game,
self.player,
self.faction,
manage_runways,
manage_front_line,
manage_aircraft,
).spend_budget(self.budget)
def add_procurement_request(self, request: AircraftProcurementRequest) -> None:
self.procurement_requests.add(request)

View File

@@ -0,0 +1 @@
from .theatercommander import TheaterCommander

View File

@@ -0,0 +1,52 @@
from __future__ import annotations
from collections import Iterator
from dataclasses import dataclass
from game.theater import ControlPoint
from game.theater.theatergroundobject import VehicleGroupGroundObject
from game.utils import meters
@dataclass
class Garrisons:
blocking_capture: list[VehicleGroupGroundObject]
defending_front_line: list[VehicleGroupGroundObject]
@property
def in_priority_order(self) -> Iterator[VehicleGroupGroundObject]:
yield from self.blocking_capture
yield from self.defending_front_line
def eliminate(self, garrison: VehicleGroupGroundObject) -> None:
if garrison in self.blocking_capture:
self.blocking_capture.remove(garrison)
if garrison in self.defending_front_line:
self.defending_front_line.remove(garrison)
def __contains__(self, item: VehicleGroupGroundObject) -> bool:
return item in self.in_priority_order
@classmethod
def for_control_point(cls, control_point: ControlPoint) -> Garrisons:
"""Categorize garrison groups based on target priority.
Any garrisons blocking base capture are the highest priority.
"""
blocking = []
defending = []
garrisons = [
tgo
for tgo in control_point.ground_objects
if isinstance(tgo, VehicleGroupGroundObject) and not tgo.is_dead
]
for garrison in garrisons:
if (
meters(garrison.distance_to(control_point))
< ControlPoint.CAPTURE_DISTANCE
):
blocking.append(garrison)
else:
defending.append(garrison)
return Garrisons(blocking, defending)

View File

@@ -0,0 +1,58 @@
from dataclasses import field, dataclass
from enum import Enum, auto
from typing import Optional
from game.theater import MissionTarget
from gen.flights.flight import FlightType
class EscortType(Enum):
AirToAir = auto()
Sead = auto()
@dataclass(frozen=True)
class ProposedFlight:
"""A flight outline proposed by the mission planner.
Proposed flights haven't been assigned specific aircraft yet. They have only
a task, a required number of aircraft, and a maximum distance allowed
between the objective and the departure airfield.
"""
#: The flight's role.
task: FlightType
#: The number of aircraft required.
num_aircraft: int
#: The type of threat this flight defends against if it is an escort. Escort
#: flights will be pruned if the rest of the package is not threatened by
#: the threat they defend against. If this flight is not an escort, this
#: field is None.
escort_type: Optional[EscortType] = field(default=None)
def __str__(self) -> str:
return f"{self.task} {self.num_aircraft} ship"
@dataclass(frozen=True)
class ProposedMission:
"""A mission outline proposed by the mission planner.
Proposed missions haven't been assigned aircraft yet. They have only an
objective location and a list of proposed flights that are required for the
mission.
"""
#: The mission objective.
location: MissionTarget
#: The proposed flights that are required for the mission.
flights: list[ProposedFlight]
asap: bool = field(default=False)
def __str__(self) -> str:
flights = ", ".join([str(f) for f in self.flights])
return f"{self.location.name}: {flights}"

View File

@@ -0,0 +1,76 @@
from __future__ import annotations
import logging
import random
from collections import defaultdict
from datetime import timedelta
from typing import Iterator, Dict, TYPE_CHECKING
from game.theater import MissionTarget
from gen.flights.flight import FlightType
from gen.flights.traveltime import TotEstimator
if TYPE_CHECKING:
from game.coalition import Coalition
class MissionScheduler:
def __init__(self, coalition: Coalition, desired_mission_length: timedelta) -> None:
self.coalition = coalition
self.desired_mission_length = desired_mission_length
def schedule_missions(self) -> None:
"""Identifies and plans mission for the turn."""
def start_time_generator(
count: int, earliest: int, latest: int, margin: int
) -> Iterator[timedelta]:
interval = (latest - earliest) // count
for time in range(earliest, latest, interval):
error = random.randint(-margin, margin)
yield timedelta(seconds=max(0, time + error))
dca_types = {
FlightType.BARCAP,
FlightType.TARCAP,
}
previous_cap_end_time: Dict[MissionTarget, timedelta] = defaultdict(timedelta)
non_dca_packages = [
p for p in self.coalition.ato.packages if p.primary_task not in dca_types
]
start_time = start_time_generator(
count=len(non_dca_packages),
earliest=5 * 60,
latest=int(self.desired_mission_length.total_seconds()),
margin=5 * 60,
)
for package in self.coalition.ato.packages:
tot = TotEstimator(package).earliest_tot()
if package.primary_task in dca_types:
previous_end_time = previous_cap_end_time[package.target]
if tot > previous_end_time:
# Can't get there exactly on time, so get there ASAP. This
# will typically only happen for the first CAP at each
# target.
package.time_over_target = tot
else:
package.time_over_target = previous_end_time
departure_time = package.mission_departure_time
# Should be impossible for CAPs
if departure_time is None:
logging.error(f"Could not determine mission end time for {package}")
continue
previous_cap_end_time[package.target] = departure_time
elif package.auto_asap:
package.set_tot_asap()
else:
# But other packages should be spread out a bit. Note that take
# times are delayed, but all aircraft will become active at
# mission start. This makes it more worthwhile to attack enemy
# airfields to hit grounded aircraft, since they're more likely
# to be present. Runway and air started aircraft will be
# delayed until their takeoff time by AirConflictGenerator.
package.time_over_target = next(start_time) + tot

View File

@@ -0,0 +1,246 @@
from __future__ import annotations
import math
import operator
from collections import Iterator, Iterable
from typing import TypeVar, TYPE_CHECKING
from game.theater import (
ControlPoint,
OffMapSpawn,
MissionTarget,
Fob,
FrontLine,
Airfield,
)
from game.theater.theatergroundobject import (
BuildingGroundObject,
IadsGroundObject,
NavalGroundObject,
)
from game.utils import meters, nautical_miles
from gen.flights.closestairfields import ObjectiveDistanceCache, ClosestAirfields
if TYPE_CHECKING:
from game import Game
from game.transfers import CargoShip, Convoy
MissionTargetType = TypeVar("MissionTargetType", bound=MissionTarget)
class ObjectiveFinder:
"""Identifies potential objectives for the mission planner."""
# TODO: Merge into doctrine.
AIRFIELD_THREAT_RANGE = nautical_miles(150)
SAM_THREAT_RANGE = nautical_miles(100)
def __init__(self, game: Game, is_player: bool) -> None:
self.game = game
self.is_player = is_player
def enemy_air_defenses(self) -> Iterator[IadsGroundObject]:
"""Iterates over all enemy SAM sites."""
for cp in self.enemy_control_points():
for ground_object in cp.ground_objects:
if ground_object.is_dead:
continue
if isinstance(ground_object, IadsGroundObject):
yield ground_object
def enemy_ships(self) -> Iterator[NavalGroundObject]:
for cp in self.enemy_control_points():
for ground_object in cp.ground_objects:
if not isinstance(ground_object, NavalGroundObject):
continue
if ground_object.is_dead:
continue
yield ground_object
def threatening_ships(self) -> Iterator[NavalGroundObject]:
"""Iterates over enemy ships near friendly control points.
Groups are sorted by their closest proximity to any friendly control
point (airfield or fleet).
"""
return self._targets_by_range(self.enemy_ships())
def _targets_by_range(
self, targets: Iterable[MissionTargetType]
) -> Iterator[MissionTargetType]:
target_ranges: list[tuple[MissionTargetType, float]] = []
for target in targets:
ranges: list[float] = []
for cp in self.friendly_control_points():
ranges.append(target.distance_to(cp))
target_ranges.append((target, min(ranges)))
target_ranges = sorted(target_ranges, key=operator.itemgetter(1))
for target, _range in target_ranges:
yield target
def strike_targets(self) -> Iterator[BuildingGroundObject]:
"""Iterates over enemy strike targets.
Targets are sorted by their closest proximity to any friendly control
point (airfield or fleet).
"""
targets: list[tuple[BuildingGroundObject, float]] = []
# Building objectives are made of several individual TGOs (one per
# building).
found_targets: set[str] = set()
for enemy_cp in self.enemy_control_points():
for ground_object in enemy_cp.ground_objects:
# TODO: Reuse ground_object.mission_types.
# The mission types for ground objects are currently not
# accurate because we include things like strike and BAI for all
# targets since they have different planning behavior (waypoint
# generation is better for players with strike when the targets
# are stationary, AI behavior against weaker air defenses is
# better with BAI), so that's not a useful filter. Once we have
# better control over planning profiles and target dependent
# loadouts we can clean this up.
if not isinstance(ground_object, BuildingGroundObject):
# Other group types (like ships, SAMs, garrisons, etc) have better
# suited mission types like anti-ship, DEAD, and BAI.
continue
if isinstance(enemy_cp, Fob) and ground_object.is_control_point:
# This is the FOB structure itself. Can't be repaired or
# targeted by the player, so shouldn't be targetable by the
# AI.
continue
if ground_object.is_dead:
continue
if ground_object.name in found_targets:
continue
ranges: list[float] = []
for friendly_cp in self.friendly_control_points():
ranges.append(ground_object.distance_to(friendly_cp))
targets.append((ground_object, min(ranges)))
found_targets.add(ground_object.name)
targets = sorted(targets, key=operator.itemgetter(1))
for target, _range in targets:
yield target
def front_lines(self) -> Iterator[FrontLine]:
"""Iterates over all active front lines in the theater."""
yield from self.game.theater.conflicts()
def vulnerable_control_points(self) -> Iterator[ControlPoint]:
"""Iterates over friendly CPs that are vulnerable to enemy CPs.
Vulnerability is defined as any enemy CP within threat range of of the
CP.
"""
for cp in self.friendly_control_points():
if isinstance(cp, OffMapSpawn):
# Off-map spawn locations don't need protection.
continue
airfields_in_proximity = self.closest_airfields_to(cp)
airfields_in_threat_range = (
airfields_in_proximity.operational_airfields_within(
self.AIRFIELD_THREAT_RANGE
)
)
for airfield in airfields_in_threat_range:
if not airfield.is_friendly(self.is_player):
yield cp
break
def oca_targets(self, min_aircraft: int) -> Iterator[ControlPoint]:
airfields = []
for control_point in self.enemy_control_points():
if not isinstance(control_point, Airfield):
continue
if control_point.allocated_aircraft().total_present >= min_aircraft:
airfields.append(control_point)
return self._targets_by_range(airfields)
def convoys(self) -> Iterator[Convoy]:
for front_line in self.front_lines():
yield from self.game.coalition_for(
self.is_player
).transfers.convoys.travelling_to(
front_line.control_point_hostile_to(self.is_player)
)
def cargo_ships(self) -> Iterator[CargoShip]:
for front_line in self.front_lines():
yield from self.game.coalition_for(
self.is_player
).transfers.cargo_ships.travelling_to(
front_line.control_point_hostile_to(self.is_player)
)
def friendly_control_points(self) -> Iterator[ControlPoint]:
"""Iterates over all friendly control points."""
return (
c for c in self.game.theater.controlpoints if c.is_friendly(self.is_player)
)
def farthest_friendly_control_point(self) -> ControlPoint:
"""Finds the friendly control point that is farthest from any threats."""
threat_zones = self.game.threat_zone_for(not self.is_player)
farthest = None
max_distance = meters(0)
for cp in self.friendly_control_points():
if isinstance(cp, OffMapSpawn):
continue
distance = threat_zones.distance_to_threat(cp.position)
if distance > max_distance:
farthest = cp
max_distance = distance
if farthest is None:
raise RuntimeError("Found no friendly control points. You probably lost.")
return farthest
def closest_friendly_control_point(self) -> ControlPoint:
"""Finds the friendly control point that is closest to any threats."""
threat_zones = self.game.threat_zone_for(not self.is_player)
closest = None
min_distance = meters(math.inf)
for cp in self.friendly_control_points():
if isinstance(cp, OffMapSpawn):
continue
distance = threat_zones.distance_to_threat(cp.position)
if distance < min_distance:
closest = cp
min_distance = distance
if closest is None:
raise RuntimeError("Found no friendly control points. You probably lost.")
return closest
def enemy_control_points(self) -> Iterator[ControlPoint]:
"""Iterates over all enemy control points."""
return (
c
for c in self.game.theater.controlpoints
if not c.is_friendly(self.is_player)
)
def prioritized_unisolated_points(self) -> list[ControlPoint]:
prioritized = []
capturable_later = []
for cp in self.game.theater.control_points_for(not self.is_player):
if cp.is_isolated:
continue
if cp.has_active_frontline:
prioritized.append(cp)
else:
capturable_later.append(cp)
prioritized.extend(self._targets_by_range(capturable_later))
return prioritized
@staticmethod
def closest_airfields_to(location: MissionTarget) -> ClosestAirfields:
"""Returns the closest airfields to the given location."""
return ObjectiveDistanceCache.get_closest_airfields(location)

View File

@@ -0,0 +1,94 @@
from __future__ import annotations
from typing import Optional, TYPE_CHECKING
from game.utils import nautical_miles
from gen.ato import Package
from game.theater import MissionTarget, OffMapSpawn, ControlPoint
from gen.flights.flight import Flight
if TYPE_CHECKING:
from game.dcs.aircrafttype import AircraftType
from game.squadrons.airwing import AirWing
from gen.flights.closestairfields import ClosestAirfields
from .missionproposals import ProposedFlight
class PackageBuilder:
"""Builds a Package for the flights it receives."""
def __init__(
self,
location: MissionTarget,
closest_airfields: ClosestAirfields,
air_wing: AirWing,
is_player: bool,
package_country: str,
start_type: str,
asap: bool,
) -> None:
self.closest_airfields = closest_airfields
self.is_player = is_player
self.package_country = package_country
self.package = Package(location, auto_asap=asap)
self.air_wing = air_wing
self.start_type = start_type
def plan_flight(self, plan: ProposedFlight) -> bool:
"""Allocates aircraft for the given flight and adds them to the package.
If no suitable aircraft are available, False is returned. If the failed
flight was critical and the rest of the mission will be scrubbed, the
caller should return any previously planned flights to the inventory
using release_planned_aircraft.
"""
squadron = self.air_wing.best_squadron_for(
self.package.target, plan.task, plan.num_aircraft, this_turn=True
)
if squadron is None:
return False
start_type = squadron.location.required_aircraft_start_type
if start_type is None:
start_type = self.start_type
flight = Flight(
self.package,
self.package_country,
squadron,
plan.num_aircraft,
plan.task,
start_type,
divert=self.find_divert_field(squadron.aircraft, squadron.location),
)
self.package.add_flight(flight)
return True
def find_divert_field(
self, aircraft: AircraftType, arrival: ControlPoint
) -> Optional[ControlPoint]:
divert_limit = nautical_miles(150)
for airfield in self.closest_airfields.operational_airfields_within(
divert_limit
):
if airfield.captured != self.is_player:
continue
if airfield == arrival:
continue
if not airfield.can_operate(aircraft):
continue
if isinstance(airfield, OffMapSpawn):
continue
return airfield
return None
def build(self) -> Package:
"""Returns the built package."""
return self.package
def release_planned_aircraft(self) -> None:
"""Returns any planned flights to the inventory."""
flights = list(self.package.flights)
for flight in flights:
flight.return_pilots_and_aircraft()
self.package.remove_flight(flight)

View File

@@ -0,0 +1,221 @@
from __future__ import annotations
import logging
from collections import defaultdict
from typing import Set, Iterable, Dict, TYPE_CHECKING, Optional
from game.commander.missionproposals import ProposedMission, ProposedFlight, EscortType
from game.commander.packagebuilder import PackageBuilder
from game.data.doctrine import Doctrine
from game.procurement import AircraftProcurementRequest
from game.profiling import MultiEventTracer
from game.settings import Settings
from game.squadrons import AirWing
from game.theater import ConflictTheater
from game.threatzones import ThreatZones
from gen.ato import AirTaskingOrder, Package
from gen.flights.closestairfields import ObjectiveDistanceCache
from gen.flights.flight import FlightType
from gen.flights.flightplan import FlightPlanBuilder
if TYPE_CHECKING:
from game.coalition import Coalition
class PackageFulfiller:
"""Responsible for package aircraft allocation and flight plan layout."""
def __init__(
self, coalition: Coalition, theater: ConflictTheater, settings: Settings
) -> None:
self.coalition = coalition
self.theater = theater
self.player_missions_asap = settings.auto_ato_player_missions_asap
self.default_start_type = settings.default_start_type
@property
def is_player(self) -> bool:
return self.coalition.player
@property
def ato(self) -> AirTaskingOrder:
return self.coalition.ato
@property
def air_wing(self) -> AirWing:
return self.coalition.air_wing
@property
def doctrine(self) -> Doctrine:
return self.coalition.doctrine
@property
def threat_zones(self) -> ThreatZones:
return self.coalition.opponent.threat_zone
def add_procurement_request(self, request: AircraftProcurementRequest) -> None:
self.coalition.add_procurement_request(request)
def air_wing_can_plan(self, mission_type: FlightType) -> bool:
"""Returns True if it is possible for the air wing to plan this mission type.
Not all mission types can be fulfilled by all air wings. Many factions do not
have AEW&C aircraft, so they will never be able to plan those missions. It's
also possible for the player to exclude mission types from their squadron
designs.
"""
return self.air_wing.can_auto_plan(mission_type)
def plan_flight(
self,
mission: ProposedMission,
flight: ProposedFlight,
builder: PackageBuilder,
missing_types: Set[FlightType],
purchase_multiplier: int,
) -> None:
if not builder.plan_flight(flight):
missing_types.add(flight.task)
purchase_order = AircraftProcurementRequest(
near=mission.location,
task_capability=flight.task,
number=flight.num_aircraft * purchase_multiplier,
)
# Reserves are planned for critical missions, so prioritize those orders
# over aircraft needed for non-critical missions.
self.add_procurement_request(purchase_order)
def scrub_mission_missing_aircraft(
self,
mission: ProposedMission,
builder: PackageBuilder,
missing_types: Set[FlightType],
not_attempted: Iterable[ProposedFlight],
purchase_multiplier: int,
) -> None:
# Try to plan the rest of the mission just so we can count the missing
# types to buy.
for flight in not_attempted:
self.plan_flight(
mission, flight, builder, missing_types, purchase_multiplier
)
missing_types_str = ", ".join(sorted([t.name for t in missing_types]))
builder.release_planned_aircraft()
color = "Blue" if self.is_player else "Red"
logging.debug(
f"{color}: not enough aircraft in range for {mission.location.name} "
f"capable of: {missing_types_str}"
)
def check_needed_escorts(self, builder: PackageBuilder) -> Dict[EscortType, bool]:
threats = defaultdict(bool)
for flight in builder.package.flights:
if self.threat_zones.waypoints_threatened_by_aircraft(
flight.flight_plan.escorted_waypoints()
):
threats[EscortType.AirToAir] = True
if self.threat_zones.waypoints_threatened_by_radar_sam(
list(flight.flight_plan.escorted_waypoints())
):
threats[EscortType.Sead] = True
return threats
def plan_mission(
self,
mission: ProposedMission,
purchase_multiplier: int,
tracer: MultiEventTracer,
) -> Optional[Package]:
"""Allocates aircraft for a proposed mission and adds it to the ATO."""
builder = PackageBuilder(
mission.location,
ObjectiveDistanceCache.get_closest_airfields(mission.location),
self.air_wing,
self.is_player,
self.coalition.country_name,
self.default_start_type,
mission.asap,
)
# Attempt to plan all the main elements of the mission first. Escorts
# will be planned separately so we can prune escorts for packages that
# are not expected to encounter that type of threat.
missing_types: Set[FlightType] = set()
escorts = []
for proposed_flight in mission.flights:
if not self.air_wing_can_plan(proposed_flight.task):
# This air wing can never plan this mission type because they do not
# have compatible aircraft or squadrons. Skip fulfillment so that we
# don't place the purchase request.
continue
if proposed_flight.escort_type is not None:
# Escorts are planned after the primary elements of the package.
# If the package does not need escorts they may be pruned.
escorts.append(proposed_flight)
continue
with tracer.trace("Flight planning"):
self.plan_flight(
mission,
proposed_flight,
builder,
missing_types,
purchase_multiplier,
)
if missing_types:
self.scrub_mission_missing_aircraft(
mission, builder, missing_types, escorts, purchase_multiplier
)
return None
if not builder.package.flights:
# The non-escort part of this mission is unplannable by this faction. Scrub
# the mission and do not attempt planning escorts because there's no reason
# to buy them because this mission will never be planned.
return None
# Create flight plans for the main flights of the package so we can
# determine threats. This is done *after* creating all of the flights
# rather than as each flight is added because the flight plan for
# flights that will rendezvous with their package will be affected by
# the other flights in the package. Escorts will not be able to
# contribute to this.
flight_plan_builder = FlightPlanBuilder(
builder.package, self.coalition, self.theater
)
for flight in builder.package.flights:
with tracer.trace("Flight plan population"):
flight_plan_builder.populate_flight_plan(flight)
needed_escorts = self.check_needed_escorts(builder)
for escort in escorts:
# This list was generated from the not None set, so this should be
# impossible.
assert escort.escort_type is not None
if needed_escorts[escort.escort_type]:
with tracer.trace("Flight planning"):
self.plan_flight(
mission, escort, builder, missing_types, purchase_multiplier
)
# Check again for unavailable aircraft. If the escort was required and
# none were found, scrub the mission.
if missing_types:
self.scrub_mission_missing_aircraft(
mission, builder, missing_types, escorts, purchase_multiplier
)
return None
package = builder.build()
# Add flight plans for escorts.
for flight in package.flights:
if not flight.flight_plan.waypoints:
with tracer.trace("Flight plan population"):
flight_plan_builder.populate_flight_plan(flight)
if package.has_players and self.player_missions_asap:
package.auto_asap = True
package.set_tot_asap()
return package

View File

@@ -0,0 +1,11 @@
from collections import Iterator
from game.commander.tasks.primitive.aewc import PlanAewc
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
class PlanAewcSupport(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for target in state.aewc_targets:
yield [PlanAewc(target)]

View File

@@ -0,0 +1,15 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.primitive.oca import PlanOcaStrike
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
@dataclass(frozen=True)
class AttackAirInfrastructure(CompoundTask[TheaterState]):
aircraft_cold_start: bool
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for garrison in state.oca_targets:
yield [PlanOcaStrike(garrison, self.aircraft_cold_start)]

View File

@@ -0,0 +1,15 @@
from collections import Iterator
from game.commander.tasks.primitive.strike import PlanStrike
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
class AttackBuildings(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for building in state.strike_targets:
# Ammo depots are targeted based on the needs of the front line by
# ReduceEnemyFrontLineCapacity. No reason to target them before that front
# line is active.
if not building.is_ammo_depot:
yield [PlanStrike(building)]

View File

@@ -0,0 +1,12 @@
from collections import Iterator
from game.commander.tasks.primitive.bai import PlanBai
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
class AttackGarrisons(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for garrisons in state.enemy_garrisons.values():
for garrison in garrisons.in_priority_order:
yield [PlanBai(garrison)]

View File

@@ -0,0 +1,51 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.compound.destroyenemygroundunits import (
DestroyEnemyGroundUnits,
)
from game.commander.tasks.compound.reduceenemyfrontlinecapacity import (
ReduceEnemyFrontLineCapacity,
)
from game.commander.tasks.primitive.breakthroughattack import BreakthroughAttack
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
from game.theater import FrontLine, ControlPoint
@dataclass(frozen=True)
class CaptureBase(CompoundTask[TheaterState]):
front_line: FrontLine
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
yield [BreakthroughAttack(self.front_line, state.context.coalition.player)]
yield [DestroyEnemyGroundUnits(self.front_line)]
if self.worth_destroying_ammo_depots(state):
yield [ReduceEnemyFrontLineCapacity(self.enemy_cp(state))]
def enemy_cp(self, state: TheaterState) -> ControlPoint:
return self.front_line.control_point_hostile_to(state.context.coalition.player)
def units_deployable(self, state: TheaterState, player: bool) -> int:
cp = self.front_line.control_point_friendly_to(player)
ammo_depots = list(state.ammo_dumps_at(cp))
return cp.deployable_front_line_units_with(len(ammo_depots))
def unit_cap(self, state: TheaterState, player: bool) -> int:
cp = self.front_line.control_point_friendly_to(player)
ammo_depots = list(state.ammo_dumps_at(cp))
return cp.front_line_capacity_with(len(ammo_depots))
def enemy_has_ammo_dumps(self, state: TheaterState) -> bool:
return bool(state.ammo_dumps_at(self.enemy_cp(state)))
def worth_destroying_ammo_depots(self, state: TheaterState) -> bool:
if not self.enemy_has_ammo_dumps(state):
return False
friendly_cap = self.unit_cap(state, state.context.coalition.player)
enemy_deployable = self.units_deployable(state, state.context.coalition.player)
# If the enemy can currently deploy 50% more units than we possibly could, it's
# worth killing an ammo depot.
return enemy_deployable / friendly_cap > 1.5

View File

@@ -0,0 +1,13 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.compound.capturebase import CaptureBase
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
@dataclass(frozen=True)
class CaptureBases(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for front in state.active_front_lines:
yield [CaptureBase(front)]

View File

@@ -0,0 +1,19 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.primitive.cas import PlanCas
from game.commander.tasks.primitive.defensivestance import DefensiveStance
from game.commander.tasks.primitive.retreatstance import RetreatStance
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
from game.theater import FrontLine
@dataclass(frozen=True)
class DefendBase(CompoundTask[TheaterState]):
front_line: FrontLine
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
yield [DefensiveStance(self.front_line, state.context.coalition.player)]
yield [RetreatStance(self.front_line, state.context.coalition.player)]
yield [PlanCas(self.front_line)]

View File

@@ -0,0 +1,13 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.compound.defendbase import DefendBase
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
@dataclass(frozen=True)
class DefendBases(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for front in state.active_front_lines:
yield [DefendBase(front)]

View File

@@ -0,0 +1,24 @@
from collections import Iterator
from typing import Union
from game.commander.tasks.primitive.antiship import PlanAntiShip
from game.commander.tasks.primitive.dead import PlanDead
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
from game.theater.theatergroundobject import IadsGroundObject, NavalGroundObject
class DegradeIads(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for air_defense in state.threatening_air_defenses:
yield [self.plan_against(air_defense)]
for detector in state.detecting_air_defenses:
yield [self.plan_against(detector)]
@staticmethod
def plan_against(
target: Union[IadsGroundObject, NavalGroundObject]
) -> Union[PlanDead, PlanAntiShip]:
if isinstance(target, IadsGroundObject):
return PlanDead(target)
return PlanAntiShip(target)

View File

@@ -0,0 +1,19 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.primitive.aggressiveattack import AggressiveAttack
from game.commander.tasks.primitive.cas import PlanCas
from game.commander.tasks.primitive.eliminationattack import EliminationAttack
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
from game.theater import FrontLine
@dataclass(frozen=True)
class DestroyEnemyGroundUnits(CompoundTask[TheaterState]):
front_line: FrontLine
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
yield [EliminationAttack(self.front_line, state.context.coalition.player)]
yield [AggressiveAttack(self.front_line, state.context.coalition.player)]
yield [PlanCas(self.front_line)]

View File

@@ -0,0 +1,11 @@
from collections import Iterator
from game.commander.tasks.primitive.cas import PlanCas
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
class FrontLineDefense(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for front_line in state.vulnerable_front_lines:
yield [PlanCas(front_line)]

View File

@@ -0,0 +1,27 @@
from collections import Iterator
from game.commander.tasks.primitive.antishipping import PlanAntiShipping
from game.commander.tasks.primitive.convoyinterdiction import PlanConvoyInterdiction
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
class InterdictReinforcements(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
# These will only rarely get planned. When a convoy is travelling multiple legs,
# they're targetable after the first leg. The reason for this is that
# procurement happens *after* mission planning so that the missions that could
# not be filled will guide the procurement process. Procurement is the stage
# that convoys are created (because they're created to move ground units that
# were just purchased), so we haven't created any yet. Any incomplete transfers
# from the previous turn (multi-leg journeys) will still be present though so
# they can be targeted.
#
# Even after this is fixed, the player's convoys that were created through the
# UI will never be targeted on the first turn of their journey because the AI
# stops planning after the start of the turn. We could potentially fix this by
# moving opfor mission planning until the takeoff button is pushed.
for convoy in state.enemy_convoys:
yield [PlanConvoyInterdiction(convoy)]
for ship in state.enemy_shipping:
yield [PlanAntiShipping(ship)]

View File

@@ -0,0 +1,34 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.compound.attackairinfrastructure import (
AttackAirInfrastructure,
)
from game.commander.tasks.compound.attackbuildings import AttackBuildings
from game.commander.tasks.compound.attackgarrisons import AttackGarrisons
from game.commander.tasks.compound.capturebases import CaptureBases
from game.commander.tasks.compound.defendbases import DefendBases
from game.commander.tasks.compound.degradeiads import DegradeIads
from game.commander.tasks.compound.interdictreinforcements import (
InterdictReinforcements,
)
from game.commander.tasks.compound.protectairspace import ProtectAirSpace
from game.commander.tasks.compound.theatersupport import TheaterSupport
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
@dataclass(frozen=True)
class PlanNextAction(CompoundTask[TheaterState]):
aircraft_cold_start: bool
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
yield [TheaterSupport()]
yield [ProtectAirSpace()]
yield [CaptureBases()]
yield [DefendBases()]
yield [InterdictReinforcements()]
yield [AttackGarrisons()]
yield [AttackAirInfrastructure(self.aircraft_cold_start)]
yield [AttackBuildings()]
yield [DegradeIads()]

View File

@@ -0,0 +1,12 @@
from collections import Iterator
from game.commander.tasks.primitive.barcap import PlanBarcap
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
class ProtectAirSpace(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for cp, needed in state.barcaps_needed.items():
if needed > 0:
yield [PlanBarcap(cp, needed)]

View File

@@ -0,0 +1,16 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.primitive.strike import PlanStrike
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
from game.theater import ControlPoint
@dataclass(frozen=True)
class ReduceEnemyFrontLineCapacity(CompoundTask[TheaterState]):
control_point: ControlPoint
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for ammo_dump in state.ammo_dumps_at(self.control_point):
yield [PlanStrike(ammo_dump)]

View File

@@ -0,0 +1,11 @@
from collections import Iterator
from game.commander.tasks.primitive.refueling import PlanRefueling
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
class PlanRefuelingSupport(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
for target in state.refueling_targets:
yield [PlanRefueling(target)]

View File

@@ -0,0 +1,14 @@
from collections import Iterator
from dataclasses import dataclass
from game.commander.tasks.compound.aewcsupport import PlanAewcSupport
from game.commander.tasks.compound.refuelingsupport import PlanRefuelingSupport
from game.commander.theaterstate import TheaterState
from game.htn import CompoundTask, Method
@dataclass(frozen=True)
class TheaterSupport(CompoundTask[TheaterState]):
def each_valid_method(self, state: TheaterState) -> Iterator[Method[TheaterState]]:
yield [PlanAewcSupport()]
yield [PlanRefuelingSupport()]

View File

@@ -0,0 +1,77 @@
from __future__ import annotations
import math
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING
from game.commander.tasks.theatercommandertask import TheaterCommanderTask
from game.commander.theaterstate import TheaterState
from game.theater import FrontLine
from gen.ground_forces.combat_stance import CombatStance
if TYPE_CHECKING:
from game.coalition import Coalition
class FrontLineStanceTask(TheaterCommanderTask, ABC):
def __init__(self, front_line: FrontLine, player: bool) -> None:
self.front_line = front_line
self.friendly_cp = self.front_line.control_point_friendly_to(player)
self.enemy_cp = self.front_line.control_point_hostile_to(player)
@property
@abstractmethod
def stance(self) -> CombatStance:
...
@staticmethod
def management_allowed(state: TheaterState) -> bool:
return (
not state.context.coalition.player
or state.context.settings.automate_front_line_stance
)
def better_stance_already_set(self, state: TheaterState) -> bool:
current_stance = state.front_line_stances[self.front_line]
if current_stance is None:
return False
preference = (
CombatStance.RETREAT,
CombatStance.DEFENSIVE,
CombatStance.AMBUSH,
CombatStance.AGGRESSIVE,
CombatStance.ELIMINATION,
CombatStance.BREAKTHROUGH,
)
current_rating = preference.index(current_stance)
new_rating = preference.index(self.stance)
return current_rating >= new_rating
@property
@abstractmethod
def have_sufficient_front_line_advantage(self) -> bool:
...
@property
def ground_force_balance(self) -> float:
# TODO: Planned CAS missions should reduce the expected opposing force size.
friendly_forces = self.friendly_cp.deployable_front_line_units
enemy_forces = self.enemy_cp.deployable_front_line_units
if enemy_forces == 0:
return math.inf
return friendly_forces / enemy_forces
def preconditions_met(self, state: TheaterState) -> bool:
if not self.management_allowed(state):
return False
if self.better_stance_already_set(state):
return False
if self.friendly_cp.deployable_front_line_units == 0:
return False
return self.have_sufficient_front_line_advantage
def apply_effects(self, state: TheaterState) -> None:
state.front_line_stances[self.front_line] = self.stance
def execute(self, coalition: Coalition) -> None:
self.friendly_cp.stances[self.enemy_cp.id] = self.stance

View File

@@ -0,0 +1,174 @@
from __future__ import annotations
import itertools
import operator
from abc import abstractmethod
from dataclasses import dataclass, field
from enum import unique, IntEnum, auto
from typing import TYPE_CHECKING, Optional, Generic, TypeVar, Iterator, Union
from game.commander.missionproposals import ProposedFlight, EscortType, ProposedMission
from game.commander.packagefulfiller import PackageFulfiller
from game.commander.tasks.theatercommandertask import TheaterCommanderTask
from game.commander.theaterstate import TheaterState
from game.settings import AutoAtoBehavior
from game.theater import MissionTarget
from game.theater.theatergroundobject import IadsGroundObject, NavalGroundObject
from game.utils import Distance, meters
from gen.ato import Package
from gen.flights.flight import FlightType
if TYPE_CHECKING:
from game.coalition import Coalition
MissionTargetT = TypeVar("MissionTargetT", bound=MissionTarget)
@unique
class RangeType(IntEnum):
Detection = auto()
Threat = auto()
# TODO: Refactor so that we don't need to call up to the mission planner.
# Bypass type checker due to https://github.com/python/mypy/issues/5374
@dataclass # type: ignore
class PackagePlanningTask(TheaterCommanderTask, Generic[MissionTargetT]):
target: MissionTargetT
flights: list[ProposedFlight] = field(init=False)
package: Optional[Package] = field(init=False, default=None)
def __post_init__(self) -> None:
self.flights = []
self.package = Package(self.target)
def preconditions_met(self, state: TheaterState) -> bool:
if (
state.context.coalition.player
and state.context.settings.auto_ato_behavior is AutoAtoBehavior.Disabled
):
return False
return self.fulfill_mission(state)
def execute(self, coalition: Coalition) -> None:
if self.package is None:
raise RuntimeError("Attempted to execute failed package planning task")
coalition.ato.add_package(self.package)
@abstractmethod
def propose_flights(self) -> None:
...
def propose_flight(
self,
task: FlightType,
num_aircraft: int,
escort_type: Optional[EscortType] = None,
) -> None:
self.flights.append(ProposedFlight(task, num_aircraft, escort_type))
@property
def asap(self) -> bool:
return False
@property
def purchase_multiplier(self) -> int:
"""The multiplier for aircraft quantity when missions could not be fulfilled.
For missions that do not schedule in rounds like BARCAPs do, this should be one
to ensure that the we only purchase enough aircraft to plan the mission once.
For missions that repeat within the same turn, however, we may need to buy for
the same mission more than once. If three rounds of BARCAP still need to be
fulfilled, this would return 3, and we'd triplicate the purchase order.
There is a small misbehavior here that's not symptomatic for our current mission
planning: multi-round, multi-flight packages will only purchase multiple sets of
aircraft for whatever is unavailable for the *first* failed package. For
example, if we extend this to CAS and have no CAS aircraft but enough TARCAP
aircraft for one round, we'll order CAS for every round but will not order any
TARCAP aircraft, since we can't know that TARCAP aircraft are needed until we
attempt to plan the second mission *without returning the first round aircraft*.
"""
return 1
def fulfill_mission(self, state: TheaterState) -> bool:
self.propose_flights()
fulfiller = PackageFulfiller(
state.context.coalition,
state.context.theater,
state.context.settings,
)
self.package = fulfiller.plan_mission(
ProposedMission(self.target, self.flights),
self.purchase_multiplier,
state.context.tracer,
)
return self.package is not None
def propose_common_escorts(self) -> None:
self.propose_flight(FlightType.SEAD_ESCORT, 2, EscortType.Sead)
self.propose_flight(FlightType.ESCORT, 2, EscortType.AirToAir)
def iter_iads_ranges(
self, state: TheaterState, range_type: RangeType
) -> Iterator[Union[IadsGroundObject, NavalGroundObject]]:
target_ranges: list[
tuple[Union[IadsGroundObject, NavalGroundObject], Distance]
] = []
all_iads: Iterator[
Union[IadsGroundObject, NavalGroundObject]
] = itertools.chain(state.enemy_air_defenses, state.enemy_ships)
for target in all_iads:
distance = meters(target.distance_to(self.target))
if range_type is RangeType.Detection:
target_range = target.max_detection_range()
elif range_type is RangeType.Threat:
target_range = target.max_threat_range()
else:
raise ValueError(f"Unknown RangeType: {range_type}")
if not target_range:
continue
# IADS out of range of our target area will have a positive
# distance_to_threat and should be pruned. The rest have a decreasing
# distance_to_threat as overlap increases. The most negative distance has
# the greatest coverage of the target and should be treated as the highest
# priority threat.
distance_to_threat = distance - target_range
if distance_to_threat > meters(0):
continue
target_ranges.append((target, distance_to_threat))
# TODO: Prioritize IADS by vulnerability?
target_ranges = sorted(target_ranges, key=operator.itemgetter(1))
for target, _range in target_ranges:
yield target
def iter_detecting_iads(
self, state: TheaterState
) -> Iterator[Union[IadsGroundObject, NavalGroundObject]]:
return self.iter_iads_ranges(state, RangeType.Detection)
def iter_iads_threats(
self, state: TheaterState
) -> Iterator[Union[IadsGroundObject, NavalGroundObject]]:
return self.iter_iads_ranges(state, RangeType.Threat)
def target_area_preconditions_met(
self, state: TheaterState, ignore_iads: bool = False
) -> bool:
"""Checks if the target area has been cleared of threats."""
threatened = False
# Non-blocking, but analyzed so we can pick detectors worth eliminating.
for detector in self.iter_detecting_iads(state):
if detector not in state.detecting_air_defenses:
state.detecting_air_defenses.append(detector)
if not ignore_iads:
for iads_threat in self.iter_iads_threats(state):
threatened = True
if iads_threat not in state.threatening_air_defenses:
state.threatening_air_defenses.append(iads_threat)
return not threatened

View File

@@ -0,0 +1,27 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater import MissionTarget
from gen.flights.flight import FlightType
@dataclass
class PlanAewc(PackagePlanningTask[MissionTarget]):
def preconditions_met(self, state: TheaterState) -> bool:
if not super().preconditions_met(state):
return False
return self.target in state.aewc_targets
def apply_effects(self, state: TheaterState) -> None:
state.aewc_targets.remove(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.AEWC, 1)
@property
def asap(self) -> bool:
# Supports all the early CAP flights, so should be in the air ASAP.
return True

View File

@@ -0,0 +1,14 @@
from __future__ import annotations
from game.commander.tasks.frontlinestancetask import FrontLineStanceTask
from gen.ground_forces.combat_stance import CombatStance
class AggressiveAttack(FrontLineStanceTask):
@property
def stance(self) -> CombatStance:
return CombatStance.AGGRESSIVE
@property
def have_sufficient_front_line_advantage(self) -> bool:
return self.ground_force_balance >= 0.8

View File

@@ -0,0 +1,26 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.missionproposals import EscortType
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater.theatergroundobject import NavalGroundObject
from gen.flights.flight import FlightType
@dataclass
class PlanAntiShip(PackagePlanningTask[NavalGroundObject]):
def preconditions_met(self, state: TheaterState) -> bool:
if self.target not in state.threatening_air_defenses:
return False
if not self.target_area_preconditions_met(state, ignore_iads=True):
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.eliminate_ship(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.ANTISHIP, 2)
self.propose_flight(FlightType.ESCORT, 2, EscortType.AirToAir)

View File

@@ -0,0 +1,25 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.transfers import CargoShip
from gen.flights.flight import FlightType
@dataclass
class PlanAntiShipping(PackagePlanningTask[CargoShip]):
def preconditions_met(self, state: TheaterState) -> bool:
if self.target not in state.enemy_shipping:
return False
if not self.target_area_preconditions_met(state):
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.enemy_shipping.remove(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.ANTISHIP, 2)
self.propose_common_escorts()

View File

@@ -0,0 +1,25 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater.theatergroundobject import VehicleGroupGroundObject
from gen.flights.flight import FlightType
@dataclass
class PlanBai(PackagePlanningTask[VehicleGroupGroundObject]):
def preconditions_met(self, state: TheaterState) -> bool:
if not state.has_garrison(self.target):
return False
if not self.target_area_preconditions_met(state):
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.eliminate_garrison(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.BAI, 2)
self.propose_common_escorts()

View File

@@ -0,0 +1,28 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater import ControlPoint
from gen.flights.flight import FlightType
@dataclass
class PlanBarcap(PackagePlanningTask[ControlPoint]):
max_orders: int
def preconditions_met(self, state: TheaterState) -> bool:
if not state.barcaps_needed[self.target]:
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.barcaps_needed[self.target] -= 1
def propose_flights(self) -> None:
self.propose_flight(FlightType.BARCAP, 2)
@property
def purchase_multiplier(self) -> int:
return self.max_orders

View File

@@ -0,0 +1,28 @@
from __future__ import annotations
from game.commander.tasks.frontlinestancetask import FrontLineStanceTask
from game.commander.theaterstate import TheaterState
from gen.ground_forces.combat_stance import CombatStance
class BreakthroughAttack(FrontLineStanceTask):
@property
def stance(self) -> CombatStance:
return CombatStance.BREAKTHROUGH
@property
def have_sufficient_front_line_advantage(self) -> bool:
return self.ground_force_balance >= 2.0
def opposing_garrisons_eliminated(self, state: TheaterState) -> bool:
garrisons = state.enemy_garrisons[self.enemy_cp]
return not bool(garrisons.blocking_capture)
def preconditions_met(self, state: TheaterState) -> bool:
if not super().preconditions_met(state):
return False
return self.opposing_garrisons_eliminated(state)
def apply_effects(self, state: TheaterState) -> None:
super().apply_effects(state)
state.active_front_lines.remove(self.front_line)

View File

@@ -0,0 +1,33 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater import FrontLine
from gen.flights.flight import FlightType
@dataclass
class PlanCas(PackagePlanningTask[FrontLine]):
def preconditions_met(self, state: TheaterState) -> bool:
if self.target not in state.vulnerable_front_lines:
return False
# Do not bother planning CAS when there are no enemy ground units at the front.
# An exception is made for turn zero since that's not being truly planned, but
# just to determine what missions should be planned on turn 1 (when there *will*
# be ground units) and what aircraft should be ordered.
enemy_cp = self.target.control_point_friendly_to(
player=not state.context.coalition.player
)
if enemy_cp.deployable_front_line_units == 0 and state.context.turn > 0:
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.vulnerable_front_lines.remove(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.CAS, 2)
self.propose_flight(FlightType.TARCAP, 2)

View File

@@ -0,0 +1,26 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.data.doctrine import Doctrine
from game.transfers import Convoy
from gen.flights.flight import FlightType
@dataclass
class PlanConvoyInterdiction(PackagePlanningTask[Convoy]):
def preconditions_met(self, state: TheaterState) -> bool:
if self.target not in state.enemy_convoys:
return False
if not self.target_area_preconditions_met(state):
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.enemy_convoys.remove(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.BAI, 2)
self.propose_common_escorts()

View File

@@ -0,0 +1,46 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.missionproposals import EscortType
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater.theatergroundobject import IadsGroundObject
from gen.flights.flight import FlightType
@dataclass
class PlanDead(PackagePlanningTask[IadsGroundObject]):
def preconditions_met(self, state: TheaterState) -> bool:
if (
self.target not in state.threatening_air_defenses
and self.target not in state.detecting_air_defenses
):
return False
if not self.target_area_preconditions_met(state, ignore_iads=True):
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.eliminate_air_defense(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.DEAD, 2)
# Only include SEAD against SAMs that still have emitters. No need to
# suppress an EWR, and SEAD isn't useful against a SAM that no longer has a
# working track radar.
#
# For SAMs without track radars and EWRs, we still want a SEAD escort if
# needed.
#
# Note that there is a quirk here: we should potentially be included a SEAD
# escort *and* SEAD when the target is a radar SAM but the flight path is
# also threatened by SAMs. We don't want to include a SEAD escort if the
# package is *only* threatened by the target though. Could be improved, but
# needs a decent refactor to the escort planning to do so.
if self.target.has_live_radar_sam:
self.propose_flight(FlightType.SEAD, 2)
else:
self.propose_flight(FlightType.SEAD_ESCORT, 2, EscortType.Sead)
self.propose_flight(FlightType.ESCORT, 2, EscortType.AirToAir)

View File

@@ -0,0 +1,14 @@
from __future__ import annotations
from game.commander.tasks.frontlinestancetask import FrontLineStanceTask
from gen.ground_forces.combat_stance import CombatStance
class DefensiveStance(FrontLineStanceTask):
@property
def stance(self) -> CombatStance:
return CombatStance.DEFENSIVE
@property
def have_sufficient_front_line_advantage(self) -> bool:
return self.ground_force_balance >= 0.5

View File

@@ -0,0 +1,14 @@
from __future__ import annotations
from game.commander.tasks.frontlinestancetask import FrontLineStanceTask
from gen.ground_forces.combat_stance import CombatStance
class EliminationAttack(FrontLineStanceTask):
@property
def stance(self) -> CombatStance:
return CombatStance.ELIMINATION
@property
def have_sufficient_front_line_advantage(self) -> bool:
return self.ground_force_balance >= 1.5

View File

@@ -0,0 +1,29 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater import ControlPoint
from gen.flights.flight import FlightType
@dataclass
class PlanOcaStrike(PackagePlanningTask[ControlPoint]):
aircraft_cold_start: bool
def preconditions_met(self, state: TheaterState) -> bool:
if self.target not in state.oca_targets:
return False
if not self.target_area_preconditions_met(state):
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.oca_targets.remove(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.OCA_RUNWAY, 2)
if self.aircraft_cold_start:
self.propose_flight(FlightType.OCA_AIRCRAFT, 2)
self.propose_common_escorts()

View File

@@ -0,0 +1,22 @@
from __future__ import annotations
from dataclasses import dataclass
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater import MissionTarget
from gen.flights.flight import FlightType
@dataclass
class PlanRefueling(PackagePlanningTask[MissionTarget]):
def preconditions_met(self, state: TheaterState) -> bool:
if not super().preconditions_met(state):
return False
return self.target in state.refueling_targets
def apply_effects(self, state: TheaterState) -> None:
state.refueling_targets.remove(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.REFUELING, 1)

View File

@@ -0,0 +1,14 @@
from __future__ import annotations
from game.commander.tasks.frontlinestancetask import FrontLineStanceTask
from gen.ground_forces.combat_stance import CombatStance
class RetreatStance(FrontLineStanceTask):
@property
def stance(self) -> CombatStance:
return CombatStance.RETREAT
@property
def have_sufficient_front_line_advantage(self) -> bool:
return True

View File

@@ -0,0 +1,26 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from game.commander.tasks.packageplanningtask import PackagePlanningTask
from game.commander.theaterstate import TheaterState
from game.theater.theatergroundobject import TheaterGroundObject
from gen.flights.flight import FlightType
@dataclass
class PlanStrike(PackagePlanningTask[TheaterGroundObject[Any]]):
def preconditions_met(self, state: TheaterState) -> bool:
if self.target not in state.strike_targets:
return False
if not self.target_area_preconditions_met(state):
return False
return super().preconditions_met(state)
def apply_effects(self, state: TheaterState) -> None:
state.strike_targets.remove(self.target)
def propose_flights(self) -> None:
self.propose_flight(FlightType.STRIKE, 2)
self.propose_common_escorts()

View File

@@ -0,0 +1,16 @@
from __future__ import annotations
from abc import abstractmethod
from typing import TYPE_CHECKING
from game.commander.theaterstate import TheaterState
from game.htn import PrimitiveTask
if TYPE_CHECKING:
from game.coalition import Coalition
class TheaterCommanderTask(PrimitiveTask[TheaterState]):
@abstractmethod
def execute(self, coalition: Coalition) -> None:
...

View File

@@ -0,0 +1,88 @@
"""The Theater Commander is the highest level campaign AI.
Target selection is performed with a hierarchical-task-network (HTN, linked below).
These work by giving the planner an initial "task" which decomposes into other tasks
until a concrete set of actions is formed. For example, the "capture base" task may
decompose in the following manner:
* Defend
* Reinforce front line
* Set front line stance to defend
* Destroy enemy front line units
* Set front line stance to elimination
* Plan CAS at front line
* Prepare
* Destroy enemy IADS
* Plan DEAD against SAM Armadillo
* ...
* Destroy enemy front line units
* Set front line stance to elimination
* Plan CAS at front line
* Inhibit
* Destroy enemy unit production infrastructure
* Destroy factory at Palmyra
* ...
* Destroy enemy front line units
* Set front line stance to elimination
* Plan CAS at front line
* Attack
* Set front line stance to breakthrough
* Destroy enemy front line units
* Set front line stance to elimination
* Plan CAS at front line
This is not a reflection of the actual task composition but illustrates the capability
of the system. Each task has preconditions which are checked before the task is
decomposed. If preconditions are not met the task is ignored and the next is considered.
For example the task to destroy the factory at Palmyra might be excluded until the air
defenses protecting it are eliminated; or defensive air operations might be excluded if
the enemy does not have sufficient air forces, or if the protected target has sufficient
SAM coverage.
Each action updates the world state, which causes each action to account for the result
of the tasks executed before it. Above, the preconditions for attacking the factory at
Palmyra may not have been met due to the IADS coverage, leading the planning to decide
on an attack against the IADS in the area instead. When planning the next task in the
same turn, the world state will have been updated to account for the (hopefully)
destroyed SAM sites, allowing the planner to choose the mission to attack the factory.
Preconditions can be aware of previous actions as well. A precondition for "Plan CAS at
front line" can be "No CAS missions planned at front line" to avoid over-planning CAS
even though it is a primitive task used by many other tasks.
https://en.wikipedia.org/wiki/Hierarchical_task_network
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from game.commander.tasks.compound.nextaction import PlanNextAction
from game.commander.tasks.theatercommandertask import TheaterCommanderTask
from game.commander.theaterstate import TheaterState
from game.htn import Planner
from game.profiling import MultiEventTracer
if TYPE_CHECKING:
from game import Game
class TheaterCommander(Planner[TheaterState, TheaterCommanderTask]):
def __init__(self, game: Game, player: bool) -> None:
super().__init__(
PlanNextAction(
aircraft_cold_start=game.settings.default_start_type == "Cold"
)
)
self.game = game
self.player = player
def plan_missions(self, tracer: MultiEventTracer) -> None:
state = TheaterState.from_game(self.game, self.player, tracer)
while True:
result = self.plan(state)
if result is None:
# Planned all viable tasks this turn.
return
for task in result.tasks:
task.execute(self.game.coalition_for(self.player))
state = result.end_state

View File

@@ -0,0 +1,176 @@
from __future__ import annotations
import dataclasses
import itertools
import math
from collections import Iterator
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Union, Optional
from game.commander.garrisons import Garrisons
from game.commander.objectivefinder import ObjectiveFinder
from game.htn import WorldState
from game.profiling import MultiEventTracer
from game.settings import Settings
from game.squadrons import AirWing
from game.theater import ControlPoint, FrontLine, MissionTarget, ConflictTheater
from game.theater.theatergroundobject import (
TheaterGroundObject,
NavalGroundObject,
IadsGroundObject,
VehicleGroupGroundObject,
BuildingGroundObject,
)
from game.threatzones import ThreatZones
from gen.ground_forces.combat_stance import CombatStance
if TYPE_CHECKING:
from game import Game
from game.coalition import Coalition
from game.transfers import Convoy, CargoShip
@dataclass(frozen=True)
class PersistentContext:
coalition: Coalition
theater: ConflictTheater
turn: int
settings: Settings
tracer: MultiEventTracer
@dataclass
class TheaterState(WorldState["TheaterState"]):
context: PersistentContext
barcaps_needed: dict[ControlPoint, int]
active_front_lines: list[FrontLine]
front_line_stances: dict[FrontLine, Optional[CombatStance]]
vulnerable_front_lines: list[FrontLine]
aewc_targets: list[MissionTarget]
refueling_targets: list[MissionTarget]
enemy_air_defenses: list[IadsGroundObject]
threatening_air_defenses: list[Union[IadsGroundObject, NavalGroundObject]]
detecting_air_defenses: list[Union[IadsGroundObject, NavalGroundObject]]
enemy_convoys: list[Convoy]
enemy_shipping: list[CargoShip]
enemy_ships: list[NavalGroundObject]
enemy_garrisons: dict[ControlPoint, Garrisons]
oca_targets: list[ControlPoint]
strike_targets: list[TheaterGroundObject[Any]]
enemy_barcaps: list[ControlPoint]
threat_zones: ThreatZones
def _rebuild_threat_zones(self) -> None:
"""Recreates the theater's threat zones based on the current planned state."""
self.threat_zones = ThreatZones.for_threats(
self.context.coalition.opponent.doctrine,
barcap_locations=self.enemy_barcaps,
air_defenses=itertools.chain(self.enemy_air_defenses, self.enemy_ships),
)
def eliminate_air_defense(self, target: IadsGroundObject) -> None:
if target in self.threatening_air_defenses:
self.threatening_air_defenses.remove(target)
if target in self.detecting_air_defenses:
self.detecting_air_defenses.remove(target)
self.enemy_air_defenses.remove(target)
self._rebuild_threat_zones()
def eliminate_ship(self, target: NavalGroundObject) -> None:
if target in self.threatening_air_defenses:
self.threatening_air_defenses.remove(target)
if target in self.detecting_air_defenses:
self.detecting_air_defenses.remove(target)
self.enemy_ships.remove(target)
self._rebuild_threat_zones()
def has_garrison(self, target: VehicleGroupGroundObject) -> bool:
return target in self.enemy_garrisons[target.control_point]
def eliminate_garrison(self, target: VehicleGroupGroundObject) -> None:
self.enemy_garrisons[target.control_point].eliminate(target)
def ammo_dumps_at(
self, control_point: ControlPoint
) -> Iterator[BuildingGroundObject]:
for target in self.strike_targets:
if target.control_point != control_point:
continue
if target.is_ammo_depot:
assert isinstance(target, BuildingGroundObject)
yield target
def clone(self) -> TheaterState:
# Do not use copy.deepcopy. Copying every TGO, control point, etc is absurdly
# expensive.
return TheaterState(
context=self.context,
barcaps_needed=dict(self.barcaps_needed),
active_front_lines=list(self.active_front_lines),
front_line_stances=dict(self.front_line_stances),
vulnerable_front_lines=list(self.vulnerable_front_lines),
aewc_targets=list(self.aewc_targets),
refueling_targets=list(self.refueling_targets),
enemy_air_defenses=list(self.enemy_air_defenses),
enemy_convoys=list(self.enemy_convoys),
enemy_shipping=list(self.enemy_shipping),
enemy_ships=list(self.enemy_ships),
enemy_garrisons={
cp: dataclasses.replace(g) for cp, g in self.enemy_garrisons.items()
},
oca_targets=list(self.oca_targets),
strike_targets=list(self.strike_targets),
enemy_barcaps=list(self.enemy_barcaps),
threat_zones=self.threat_zones,
# Persistent properties are not copied. These are a way for failed subtasks
# to communicate requirements to other tasks. For example, the task to
# attack enemy garrisons might fail because the target area has IADS
# protection. In that case, the preconditions of PlanBai would fail, but
# would add the IADS that prevented it from being planned to the list of
# IADS threats so that DegradeIads will consider it a threat later.
threatening_air_defenses=self.threatening_air_defenses,
detecting_air_defenses=self.detecting_air_defenses,
)
@classmethod
def from_game(
cls, game: Game, player: bool, tracer: MultiEventTracer
) -> TheaterState:
coalition = game.coalition_for(player)
finder = ObjectiveFinder(game, player)
ordered_capturable_points = finder.prioritized_unisolated_points()
context = PersistentContext(
coalition, game.theater, game.turn, game.settings, tracer
)
# Plan enough rounds of CAP that the target has coverage over the expected
# mission duration.
mission_duration = game.settings.desired_player_mission_duration.total_seconds()
barcap_duration = coalition.doctrine.cap_duration.total_seconds()
barcap_rounds = math.ceil(mission_duration / barcap_duration)
return TheaterState(
context=context,
barcaps_needed={
cp: barcap_rounds for cp in finder.vulnerable_control_points()
},
active_front_lines=list(finder.front_lines()),
front_line_stances={f: None for f in finder.front_lines()},
vulnerable_front_lines=list(finder.front_lines()),
aewc_targets=[finder.farthest_friendly_control_point()],
refueling_targets=[finder.closest_friendly_control_point()],
enemy_air_defenses=list(finder.enemy_air_defenses()),
threatening_air_defenses=[],
detecting_air_defenses=[],
enemy_convoys=list(finder.convoys()),
enemy_shipping=list(finder.cargo_ships()),
enemy_ships=list(finder.enemy_ships()),
enemy_garrisons={
cp: Garrisons.for_control_point(cp) for cp in ordered_capturable_points
},
oca_targets=list(finder.oca_targets(min_aircraft=20)),
strike_targets=list(finder.strike_targets()),
enemy_barcaps=list(game.theater.control_points_for(not player)),
threat_zones=game.threat_zone_for(not player),
)

0
game/data/__init__.py Normal file
View File

View File

@@ -1,22 +0,0 @@
from dcs.vehicles import AirDefence
AAA_UNITS = [
AirDefence.SPAAA_Gepard,
AirDefence.SPAAA_ZSU_23_4_Shilka_Gun_Dish,
AirDefence.SPAAA_Vulcan_M163,
AirDefence.AAA_ZU_23_Closed_Emplacement,
AirDefence.AAA_ZU_23_Emplacement,
AirDefence.SPAAA_ZU_23_2_Mounted_Ural_375,
AirDefence.AAA_ZU_23_Closed_Emplacement_Insurgent,
AirDefence.SPAAA_ZU_23_2_Insurgent_Mounted_Ural_375,
AirDefence.AAA_ZU_23_Insurgent,
AirDefence.AAA_8_8cm_Flak_18,
AirDefence.AAA_Flak_38_20mm,
AirDefence.AAA_8_8cm_Flak_36,
AirDefence.AAA_8_8cm_Flak_37,
AirDefence.AAA_Flak_Vierling_38_Quad_20mm,
AirDefence.AAA_SP_Kdo_G_40,
AirDefence.AAA_8_8cm_Flak_41,
AirDefence.AAA_40mm_Bofors,
AirDefence.AAA_S_60_57mm,
]

42
game/data/alic.py Normal file
View File

@@ -0,0 +1,42 @@
from dcs.unit import Unit
from dcs.vehicles import AirDefence
class AlicCodes:
CODES = {
AirDefence._1L13_EWR.id: 101,
AirDefence._55G6_EWR.id: 102,
AirDefence.S_300PS_40B6MD_sr.id: 103,
AirDefence.S_300PS_64H6E_sr.id: 104,
AirDefence.SA_11_Buk_SR_9S18M1.id: 107,
AirDefence.Kub_1S91_str.id: 108,
AirDefence.Dog_Ear_radar.id: 109,
AirDefence.S_300PS_40B6M_tr.id: 110,
AirDefence.SA_11_Buk_LN_9A310M1.id: 115,
AirDefence.Osa_9A33_ln.id: 117,
AirDefence.Strela_10M3.id: 118,
AirDefence.Tor_9A331.id: 119,
AirDefence._2S6_Tunguska.id: 120,
AirDefence.ZSU_23_4_Shilka.id: 121,
AirDefence.P_19_s_125_sr.id: 122,
AirDefence.Snr_s_125_tr.id: 123,
AirDefence.Rapier_fsa_blindfire_radar.id: 124,
AirDefence.Rapier_fsa_launcher.id: 125,
AirDefence.SNR_75V.id: 126,
AirDefence.HQ_7_LN_SP.id: 127,
AirDefence.HQ_7_STR_SP.id: 128,
AirDefence.RLS_19J6.id: 130,
AirDefence.Roland_ADS.id: 201,
AirDefence.Patriot_str.id: 202,
AirDefence.Hawk_sr.id: 203,
AirDefence.Hawk_tr.id: 204,
AirDefence.Roland_Radar.id: 205,
AirDefence.Hawk_cwar.id: 206,
AirDefence.Gepard.id: 207,
AirDefence.Vulcan.id: 208,
AirDefence.NASAMS_Radar_MPQ64F1.id: 209,
}
@classmethod
def code_for(cls, unit: Unit) -> int:
return cls.CODES[unit.type]

View File

@@ -3,37 +3,30 @@ import dcs
DEFAULT_AVAILABLE_BUILDINGS = [
"fuel",
"ammo",
"comms",
"oil",
"ware",
"farp",
"fob",
"power",
"factory",
"derrick",
]
WW2_FREE = ["fuel", "factory", "ware", "fob"]
WW2_FREE = ["fuel", "ware"]
WW2_GERMANY_BUILDINGS = [
"fuel",
"factory",
"ww2bunker",
"ww2bunker",
"ww2bunker",
"allycamp",
"allycamp",
"fob",
]
WW2_ALLIES_BUILDINGS = [
"fuel",
"factory",
"allycamp",
"allycamp",
"allycamp",
"allycamp",
"allycamp",
"fob",
]
FORTIFICATION_BUILDINGS = [

View File

@@ -1,51 +0,0 @@
from dcs.planes import (
Bf_109K_4,
C_101CC,
FW_190A8,
FW_190D9,
F_5E_3,
F_86F_Sabre,
I_16,
L_39ZA,
MiG_15bis,
MiG_19P,
MiG_21Bis,
P_47D_30,
P_47D_30bl1,
P_47D_40,
P_51D,
P_51D_30_NA,
SpitfireLFMkIX,
SpitfireLFMkIXCW,
)
from pydcs_extensions.a4ec.a4ec import A_4E_C
"""
This list contains the aircraft that do not use the guns as the last resort weapons, but as a main weapon
They'll RTB when they don't have gun ammo left
"""
GUNFIGHTERS = [
# Cold War
MiG_15bis,
MiG_19P,
MiG_21Bis,
F_86F_Sabre,
A_4E_C,
F_5E_3,
# Trainers
C_101CC,
L_39ZA,
# WW2
P_51D_30_NA,
P_51D,
P_47D_30,
P_47D_30bl1,
P_47D_40,
SpitfireLFMkIXCW,
SpitfireLFMkIX,
Bf_109K_4,
FW_190D9,
FW_190A8,
I_16,
]

View File

@@ -1,9 +1,21 @@
from dataclasses import dataclass
from datetime import timedelta
from game.data.groundunitclass import GroundUnitClass
from game.utils import Distance, feet, nautical_miles
@dataclass
class GroundUnitProcurementRatios:
ratios: dict[GroundUnitClass, float]
def for_unit_class(self, unit_class: GroundUnitClass) -> float:
try:
return self.ratios[unit_class] / sum(self.ratios.values())
except KeyError:
return 0.0
@dataclass(frozen=True)
class Doctrine:
cas: bool
@@ -13,13 +25,26 @@ class Doctrine:
antiship: bool
rendezvous_altitude: Distance
#: The minimum distance between the departure airfield and the hold point.
hold_distance: Distance
#: The minimum distance between the hold point and the join point.
push_distance: Distance
#: The distance between the join point and the ingress point. Only used for the
#: fallback flight plan layout (when the departure airfield is near a threat zone).
join_distance: Distance
split_distance: Distance
ingress_egress_distance: Distance
#: The maximum distance between the ingress point (beginning of the attack) and
#: target.
max_ingress_distance: Distance
#: The minimum distance between the ingress point (beginning of the attack) and
#: target.
min_ingress_distance: Distance
ingress_altitude: Distance
egress_altitude: Distance
min_patrol_altitude: Distance
max_patrol_altitude: Distance
@@ -50,6 +75,8 @@ class Doctrine:
sweep_distance: Distance
ground_unit_procurement_ratios: GroundUnitProcurementRatios
MODERN_DOCTRINE = Doctrine(
cap=True,
@@ -58,13 +85,12 @@ MODERN_DOCTRINE = Doctrine(
strike=True,
antiship=True,
rendezvous_altitude=feet(25000),
hold_distance=nautical_miles(15),
hold_distance=nautical_miles(25),
push_distance=nautical_miles(20),
join_distance=nautical_miles(20),
split_distance=nautical_miles(20),
ingress_egress_distance=nautical_miles(45),
max_ingress_distance=nautical_miles(45),
min_ingress_distance=nautical_miles(10),
ingress_altitude=feet(20000),
egress_altitude=feet(20000),
min_patrol_altitude=feet(15000),
max_patrol_altitude=feet(33000),
pattern_altitude=feet(5000),
@@ -76,6 +102,17 @@ MODERN_DOCTRINE = Doctrine(
cap_engagement_range=nautical_miles(50),
cas_duration=timedelta(minutes=30),
sweep_distance=nautical_miles(60),
ground_unit_procurement_ratios=GroundUnitProcurementRatios(
{
GroundUnitClass.Tank: 3,
GroundUnitClass.Atgm: 2,
GroundUnitClass.Apc: 2,
GroundUnitClass.Ifv: 3,
GroundUnitClass.Artillery: 1,
GroundUnitClass.Shorads: 2,
GroundUnitClass.Recon: 1,
}
),
)
COLDWAR_DOCTRINE = Doctrine(
@@ -85,13 +122,12 @@ COLDWAR_DOCTRINE = Doctrine(
strike=True,
antiship=True,
rendezvous_altitude=feet(22000),
hold_distance=nautical_miles(10),
hold_distance=nautical_miles(15),
push_distance=nautical_miles(10),
join_distance=nautical_miles(10),
split_distance=nautical_miles(10),
ingress_egress_distance=nautical_miles(30),
max_ingress_distance=nautical_miles(30),
min_ingress_distance=nautical_miles(10),
ingress_altitude=feet(18000),
egress_altitude=feet(18000),
min_patrol_altitude=feet(10000),
max_patrol_altitude=feet(24000),
pattern_altitude=feet(5000),
@@ -103,6 +139,17 @@ COLDWAR_DOCTRINE = Doctrine(
cap_engagement_range=nautical_miles(35),
cas_duration=timedelta(minutes=30),
sweep_distance=nautical_miles(40),
ground_unit_procurement_ratios=GroundUnitProcurementRatios(
{
GroundUnitClass.Tank: 4,
GroundUnitClass.Atgm: 2,
GroundUnitClass.Apc: 3,
GroundUnitClass.Ifv: 2,
GroundUnitClass.Artillery: 1,
GroundUnitClass.Shorads: 2,
GroundUnitClass.Recon: 1,
}
),
)
WWII_DOCTRINE = Doctrine(
@@ -111,14 +158,13 @@ WWII_DOCTRINE = Doctrine(
sead=False,
strike=True,
antiship=True,
hold_distance=nautical_miles(5),
hold_distance=nautical_miles(10),
push_distance=nautical_miles(5),
join_distance=nautical_miles(5),
split_distance=nautical_miles(5),
rendezvous_altitude=feet(10000),
ingress_egress_distance=nautical_miles(7),
max_ingress_distance=nautical_miles(7),
min_ingress_distance=nautical_miles(5),
ingress_altitude=feet(8000),
egress_altitude=feet(8000),
min_patrol_altitude=feet(4000),
max_patrol_altitude=feet(15000),
pattern_altitude=feet(5000),
@@ -130,4 +176,14 @@ WWII_DOCTRINE = Doctrine(
cap_engagement_range=nautical_miles(20),
cas_duration=timedelta(minutes=30),
sweep_distance=nautical_miles(10),
ground_unit_procurement_ratios=GroundUnitProcurementRatios(
{
GroundUnitClass.Tank: 3,
GroundUnitClass.Atgm: 3,
GroundUnitClass.Apc: 3,
GroundUnitClass.Artillery: 1,
GroundUnitClass.Shorads: 3,
GroundUnitClass.Recon: 1,
}
),
)

View File

@@ -0,0 +1,17 @@
from __future__ import annotations
from enum import unique, Enum
@unique
class GroundUnitClass(Enum):
Tank = "Tank"
Atgm = "ATGM"
Ifv = "IFV"
Apc = "APC"
Artillery = "Artillery"
Logistics = "Logistics"
Recon = "Recon"
Infantry = "Infantry"
Shorads = "SHORADS"
Manpads = "MANPADS"

View File

@@ -1,72 +1,117 @@
from dcs.ships import (
Battlecruiser_1144_2_Pyotr_Velikiy,
Cruiser_1164_Moskva,
CVN_70_Carl_Vinson,
CVN_71_Theodore_Roosevelt,
CVN_72_Abraham_Lincoln,
CVN_73_George_Washington,
CVN_74_John_C__Stennis,
CV_1143_5_Admiral_Kuznetsov,
CV_1143_5_Admiral_Kuznetsov_2017,
Frigate_11540_Neustrashimy,
Corvette_1124_4_Grisha,
Frigate_1135M_Rezky,
Corvette_1241_1_Molniya,
LHA_1_Tarawa,
FFG_Oliver_Hazzard_Perry,
CG_Ticonderoga,
Type_052B_Destroyer,
Type_052C_Destroyer,
Type_054A_Frigate,
DDG_Arleigh_Burke_IIa,
Forrestal,
PIOTR,
MOSCOW,
VINSON,
CVN_71,
CVN_72,
CVN_73,
Stennis,
KUZNECOW,
CV_1143_5,
NEUSTRASH,
ALBATROS,
REZKY,
MOLNIYA,
LHA_Tarawa,
PERRY,
TICONDEROG,
Type_052B,
Type_052C,
Type_054A,
USS_Arleigh_Burke_IIa,
)
from dcs.vehicles import AirDefence
UNITS_WITH_RADAR = [
TELARS = {
AirDefence._2S6_Tunguska,
AirDefence.SA_11_Buk_LN_9A310M1,
AirDefence.Osa_9A33_ln,
AirDefence.Tor_9A331,
AirDefence.Roland_ADS,
}
TRACK_RADARS = {
AirDefence.Kub_1S91_str,
AirDefence.Snr_s_125_tr,
AirDefence.S_300PS_40B6M_tr,
AirDefence.Hawk_tr,
AirDefence.Patriot_str,
AirDefence.SNR_75V,
AirDefence.RPC_5N62V,
AirDefence.Rapier_fsa_blindfire_radar,
AirDefence.HQ_7_STR_SP,
AirDefence.NASAMS_Radar_MPQ64F1,
}
LAUNCHER_TRACKER_PAIRS = {
AirDefence.Kub_2P25_ln: AirDefence.Kub_1S91_str,
AirDefence._5p73_s_125_ln: AirDefence.Snr_s_125_tr,
AirDefence.S_300PS_5P85C_ln: AirDefence.S_300PS_40B6M_tr,
AirDefence.S_300PS_5P85D_ln: AirDefence.S_300PS_40B6M_tr,
AirDefence.Hawk_ln: AirDefence.Hawk_tr,
AirDefence.Patriot_ln: AirDefence.Patriot_str,
AirDefence.S_75M_Volhov: AirDefence.SNR_75V,
AirDefence.Rapier_fsa_launcher: AirDefence.Rapier_fsa_blindfire_radar,
AirDefence.HQ_7_LN_SP: AirDefence.HQ_7_STR_SP,
AirDefence.S_200_Launcher: AirDefence.RPC_5N62V,
AirDefence.NASAMS_LN_B: AirDefence.NASAMS_Radar_MPQ64F1,
AirDefence.NASAMS_LN_C: AirDefence.NASAMS_Radar_MPQ64F1,
}
UNITS_WITH_RADAR = {
# Radars
AirDefence.SAM_SA_15_Tor_Gauntlet,
AirDefence.SAM_SA_11_Buk_Gadfly_C2,
AirDefence.SAM_Patriot_CR__AMG_AN_MRC_137,
AirDefence.SAM_Patriot_ECS,
AirDefence.SPAAA_Gepard,
AirDefence.SPAAA_Vulcan_M163,
AirDefence.SPAAA_ZSU_23_4_Shilka_Gun_Dish,
AirDefence.EWR_1L13,
AirDefence.SAM_SA_6_Kub_Long_Track_STR,
AirDefence.SAM_SA_10_S_300_Grumble_Flap_Lid_TR,
AirDefence.SAM_SA_10_S_300_Grumble_Clam_Shell_SR,
AirDefence.EWR_55G6,
AirDefence.SAM_SA_10_S_300_Grumble_Big_Bird_SR,
AirDefence.SAM_SA_11_Buk_Gadfly_Snow_Drift_SR,
AirDefence.MCC_SR_Sborka_Dog_Ear_SR,
AirDefence.SAM_Hawk_TR__AN_MPQ_46,
AirDefence.SAM_Hawk_SR__AN_MPQ_50,
AirDefence.SAM_Patriot_STR,
AirDefence.SAM_Hawk_CWAR_AN_MPQ_55,
AirDefence.SAM_P19_Flat_Face_SR__SA_2_3,
AirDefence.SAM_Roland_EWR,
AirDefence.SAM_SA_3_S_125_Low_Blow_TR,
AirDefence.SAM_SA_2_S_75_Fan_Song_TR,
AirDefence.HQ_7_Self_Propelled_STR,
AirDefence._2S6_Tunguska,
AirDefence.SA_11_Buk_LN_9A310M1,
AirDefence.Osa_9A33_ln,
AirDefence.Tor_9A331,
AirDefence.Gepard,
AirDefence.Vulcan,
AirDefence.Roland_ADS,
AirDefence.ZSU_23_4_Shilka,
AirDefence._1L13_EWR,
AirDefence.Kub_1S91_str,
AirDefence.S_300PS_40B6M_tr,
AirDefence.S_300PS_40B6MD_sr,
AirDefence._55G6_EWR,
AirDefence.S_300PS_64H6E_sr,
AirDefence.SA_11_Buk_SR_9S18M1,
AirDefence.Dog_Ear_radar,
AirDefence.Hawk_tr,
AirDefence.Hawk_sr,
AirDefence.Patriot_str,
AirDefence.Hawk_cwar,
AirDefence.P_19_s_125_sr,
AirDefence.Roland_Radar,
AirDefence.Snr_s_125_tr,
AirDefence.SNR_75V,
AirDefence.RLS_19J6,
AirDefence.RPC_5N62V,
AirDefence.Rapier_fsa_blindfire_radar,
AirDefence.HQ_7_LN_SP,
AirDefence.HQ_7_STR_SP,
AirDefence.FuMG_401,
AirDefence.FuSe_65,
# Ships
CVN_70_Carl_Vinson,
FFG_Oliver_Hazzard_Perry,
CG_Ticonderoga,
Corvette_1124_4_Grisha,
CV_1143_5_Admiral_Kuznetsov,
Corvette_1241_1_Molniya,
Cruiser_1164_Moskva,
Frigate_11540_Neustrashimy,
Battlecruiser_1144_2_Pyotr_Velikiy,
Frigate_1135M_Rezky,
CV_1143_5_Admiral_Kuznetsov_2017,
CVN_74_John_C__Stennis,
CVN_71_Theodore_Roosevelt,
CVN_72_Abraham_Lincoln,
CVN_73_George_Washington,
DDG_Arleigh_Burke_IIa,
LHA_1_Tarawa,
Type_052B_Destroyer,
Type_054A_Frigate,
Type_052C_Destroyer,
]
ALBATROS,
CVN_71,
CVN_72,
CVN_73,
CV_1143_5,
Forrestal,
KUZNECOW,
LHA_Tarawa,
MOLNIYA,
MOSCOW,
NEUSTRASH,
PERRY,
PIOTR,
REZKY,
Stennis,
TICONDEROG,
Type_052B,
Type_052C,
Type_054A,
USS_Arleigh_Burke_IIa,
VINSON,
}

File diff suppressed because it is too large Load Diff

1407
game/db.py

File diff suppressed because it is too large Load Diff

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

@@ -0,0 +1,396 @@
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.dcs.unittype import UnitType
from game.radio.channels import (
ApacheChannelNamer,
ChannelNamer,
RadioChannelAllocator,
CommonRadioChannelAllocator,
HueyChannelNamer,
SCR522ChannelNamer,
ViggenChannelNamer,
ViperChannelNamer,
TomcatChannelNamer,
MirageChannelNamer,
SingleRadioChannelNamer,
FarmerRadioChannelAllocator,
SCR522RadioChannelAllocator,
ViggenRadioChannelAllocator,
NoOpChannelAllocator,
)
from game.utils import (
Distance,
SPEED_OF_SOUND_AT_SEA_LEVEL,
Speed,
feet,
kph,
knots,
nautical_miles,
)
if TYPE_CHECKING:
from gen.aircraft import FlightData
from gen.airsupport import AirSupport
from gen.radios import Radio, RadioFrequency, RadioRegistry
@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
allocator_type: Type[RadioChannelAllocator] = {
"SCR-522": SCR522RadioChannelAllocator,
"common": CommonRadioChannelAllocator,
"farmer": FarmerRadioChannelAllocator,
"noop": NoOpChannelAllocator,
"viggen": ViggenRadioChannelAllocator,
}[alloc_type]
return allocator_type.from_cfg(data)
@classmethod
def make_namer(cls, config: dict[str, Any]) -> Type[ChannelNamer]:
return {
"SCR-522": SCR522ChannelNamer,
"default": ChannelNamer,
"huey": HueyChannelNamer,
"mirage": MirageChannelNamer,
"single": SingleRadioChannelNamer,
"tomcat": TomcatChannelNamer,
"viggen": ViggenChannelNamer,
"viper": ViperChannelNamer,
"apache": ApacheChannelNamer,
}[config.get("namer", "default")]
@dataclass(frozen=True)
class PatrolConfig:
altitude: Optional[Distance]
speed: Optional[Speed]
@classmethod
def from_data(cls, data: dict[str, Any]) -> PatrolConfig:
altitude = data.get("altitude", None)
speed = data.get("speed", None)
return PatrolConfig(
feet(altitude) if altitude is not None else None,
knots(speed) if speed is not None else None,
)
@dataclass(frozen=True)
class FuelConsumption:
#: The estimated taxi fuel requirement, in pounds.
taxi: int
#: The estimated fuel consumption for a takeoff climb, in pounds per nautical mile.
climb: float
#: The estimated fuel consumption for cruising, in pounds per nautical mile.
cruise: float
#: The estimated fuel consumption for combat speeds, in pounds per nautical mile.
combat: float
#: The minimum amount of fuel that the aircraft should land with, in pounds. This is
#: a reserve amount for landing delays or emergencies.
min_safe: int
@classmethod
def from_data(cls, data: dict[str, Any]) -> FuelConsumption:
return FuelConsumption(
int(data["taxi"]),
float(data["climb_ppm"]),
float(data["cruise_ppm"]),
float(data["combat_ppm"]),
int(data["min_safe"]),
)
# TODO: Split into PlaneType and HelicopterType?
@dataclass(frozen=True)
class AircraftType(UnitType[Type[FlyingType]]):
carrier_capable: bool
lha_capable: bool
always_keeps_gun: bool
# If true, the aircraft does not use the guns as the last resort weapons, but as a
# main weapon. It'll RTB when it doesn't have gun ammo left.
gunfighter: bool
max_group_size: int
patrol_altitude: Optional[Distance]
patrol_speed: Optional[Speed]
#: The maximum range between the origin airfield and the target for which the auto-
#: planner will consider this aircraft usable for a mission.
max_mission_range: Distance
fuel_consumption: Optional[FuelConsumption]
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
@property
def helicopter(self) -> bool:
return self.dcs_unit_type.helicopter
@cached_property
def max_speed(self) -> Speed:
return kph(self.dcs_unit_type.max_speed)
@property
def preferred_patrol_altitude(self) -> Distance:
if self.patrol_altitude is not None:
return self.patrol_altitude
else:
# Estimate based on max speed.
# Aircaft with max speed 600 kph will prefer patrol at 10 000 ft
# Aircraft with max speed 2800 kph will prefer pratrol at 33 000 ft
altitude_for_lowest_speed = feet(10 * 1000)
altitude_for_highest_speed = feet(33 * 1000)
lowest_speed = kph(600)
highest_speed = kph(2800)
factor = (self.max_speed - lowest_speed).kph / (
highest_speed - lowest_speed
).kph
altitude = (
altitude_for_lowest_speed
+ (altitude_for_highest_speed - altitude_for_lowest_speed) * factor
)
logging.debug(
f"Preferred patrol altitude for {self.dcs_unit_type.id}: {altitude.feet}"
)
rounded_altitude = feet(round(1000 * round(altitude.feet / 1000)))
return max(
altitude_for_lowest_speed,
min(altitude_for_highest_speed, rounded_altitude),
)
def preferred_patrol_speed(self, altitude: Distance) -> Speed:
"""Preferred true airspeed when patrolling"""
if self.patrol_speed is not None:
return self.patrol_speed
else:
# Estimate based on max speed.
max_speed = self.max_speed
if max_speed > SPEED_OF_SOUND_AT_SEA_LEVEL * 1.6:
# Fast airplanes, should manage pretty high patrol speed
return (
Speed.from_mach(0.85, altitude)
if altitude.feet > 20000
else Speed.from_mach(0.7, altitude)
)
elif max_speed > SPEED_OF_SOUND_AT_SEA_LEVEL * 1.2:
# Medium-fast like F/A-18C
return (
Speed.from_mach(0.8, altitude)
if altitude.feet > 20000
else Speed.from_mach(0.65, altitude)
)
elif max_speed > SPEED_OF_SOUND_AT_SEA_LEVEL * 0.7:
# Semi-fast like airliners or similar
return (
Speed.from_mach(0.5, altitude)
if altitude.feet > 20000
else Speed.from_mach(0.4, altitude)
)
else:
# Slow like warbirds or helicopters
# Use whichever is slowest - mach 0.35 or 70% of max speed
logging.debug(f"{self.name} max_speed * 0.7 is {max_speed * 0.7}")
return min(Speed.from_mach(0.35, altitude), max_speed * 0.7)
def alloc_flight_radio(self, radio_registry: RadioRegistry) -> RadioFrequency:
from gen.radios import ChannelInUseError, kHz
if self.intra_flight_radio is not None:
return radio_registry.alloc_for_radio(self.intra_flight_radio)
# The default radio frequency is set in megahertz. For some aircraft, it is a
# floating point value. For all current aircraft, adjusting to kilohertz will be
# sufficient to convert to an integer.
in_khz = float(self.dcs_unit_type.radio_frequency) * 1000
if not in_khz.is_integer():
logging.warning(
f"Found unexpected sub-kHz default radio for {self}: {in_khz} kHz. "
"Truncating to integer. The truncated frequency may not be valid for "
"the aircraft."
)
freq = kHz(int(in_khz))
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)
def __setstate__(self, state: dict[str, Any]) -> None:
# Update any existing models with new data on load.
updated = AircraftType.named(state["name"])
state.update(updated.__dict__)
self.__dict__.update(state)
@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]:
if not cls._loaded:
cls._load_all()
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(encoding="utf-8") 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", {}))
patrol_config = PatrolConfig.from_data(data.get("patrol", {}))
try:
mission_range = nautical_miles(int(data["max_range"]))
except (KeyError, ValueError):
mission_range = (
nautical_miles(50) if aircraft.helicopter else nautical_miles(150)
)
logging.warning(
f"{aircraft.id} does not specify a max_range. Defaulting to "
f"{mission_range.nautical_miles}NM"
)
fuel_data = data.get("fuel")
if fuel_data is not None:
fuel_consumption: Optional[FuelConsumption] = FuelConsumption.from_data(
fuel_data
)
else:
fuel_consumption = None
try:
introduction = data["introduced"]
if introduction is None:
introduction = "N/A"
except KeyError:
introduction = "No data."
for variant in data.get("variants", [aircraft.id]):
yield AircraftType(
dcs_unit_type=aircraft,
name=variant,
description=data.get(
"description",
f"No data. <a href=\"https://google.com/search?q=DCS+{variant.replace(' ', '+')}\"><span style=\"color:#FFFFFF\">Google {variant}</span></a>",
),
year_introduced=introduction,
country_of_origin=data.get("origin", "No data."),
manufacturer=data.get("manufacturer", "No data."),
role=data.get("role", "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),
gunfighter=data.get("gunfighter", False),
max_group_size=data.get("max_group_size", aircraft.group_size_max),
patrol_altitude=patrol_config.altitude,
patrol_speed=patrol_config.speed,
max_mission_range=mission_range,
fuel_consumption=fuel_consumption,
intra_flight_radio=radio_config.intra_flight,
channel_allocator=radio_config.channel_allocator,
channel_namer=radio_config.channel_namer,
)

100
game/dcs/groundunittype.py Normal file
View File

@@ -0,0 +1,100 @@
from __future__ import annotations
import logging
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Type, Optional, ClassVar, Iterator
import yaml
from dcs.unittype import VehicleType
from dcs.vehicles import vehicle_map
from game.data.groundunitclass import GroundUnitClass
from game.dcs.unittype import UnitType
@dataclass(frozen=True)
class GroundUnitType(UnitType[Type[VehicleType]]):
unit_class: Optional[GroundUnitClass]
spawn_weight: int
_by_name: ClassVar[dict[str, GroundUnitType]] = {}
_by_unit_type: ClassVar[
dict[Type[VehicleType], list[GroundUnitType]]
] = 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
@classmethod
def register(cls, aircraft_type: GroundUnitType) -> 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) -> GroundUnitType:
if not cls._loaded:
cls._load_all()
return cls._by_name[name]
@classmethod
def for_dcs_type(cls, dcs_unit_type: Type[VehicleType]) -> Iterator[GroundUnitType]:
if not cls._loaded:
cls._load_all()
yield from cls._by_unit_type[dcs_unit_type]
@staticmethod
def _each_unit_type() -> Iterator[Type[VehicleType]]:
yield from vehicle_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, vehicle: Type[VehicleType]) -> Iterator[GroundUnitType]:
data_path = Path("resources/units/ground_units") / f"{vehicle.id}.yaml"
if not data_path.exists():
logging.warning(f"No data for {vehicle.id}; it will not be available")
return
with data_path.open(encoding="utf-8") as data_file:
data = yaml.safe_load(data_file)
try:
introduction = data["introduced"]
if introduction is None:
introduction = "N/A"
except KeyError:
introduction = "No data."
class_name = data.get("class")
unit_class: Optional[GroundUnitClass] = None
if class_name is not None:
unit_class = GroundUnitClass(class_name)
for variant in data.get("variants", [vehicle.id]):
yield GroundUnitType(
dcs_unit_type=vehicle,
unit_class=unit_class,
spawn_weight=data.get("spawn_weight", 0),
name=variant,
description=data.get(
"description",
f"No data. <a href=\"https://google.com/search?q=DCS+{variant.replace(' ', '+')}\"><span style=\"color:#FFFFFF\">Google {variant}</span></a>",
),
year_introduced=introduction,
country_of_origin=data.get("origin", "No data."),
manufacturer=data.get("manufacturer", "No data."),
role=data.get("role", "No data."),
price=data.get("price", 1),
)

26
game/dcs/unittype.py Normal file
View File

@@ -0,0 +1,26 @@
from dataclasses import dataclass
from functools import cached_property
from typing import TypeVar, Generic, Type
from dcs.unittype import UnitType as DcsUnitType
DcsUnitTypeT = TypeVar("DcsUnitTypeT", bound=Type[DcsUnitType])
@dataclass(frozen=True)
class UnitType(Generic[DcsUnitTypeT]):
dcs_unit_type: DcsUnitTypeT
name: str
description: str
year_introduced: str
country_of_origin: str
manufacturer: str
role: str
price: int
def __str__(self) -> str:
return self.name
@cached_property
def eplrs_capable(self) -> bool:
return getattr(self.dcs_unit_type, "eplrs", False)

View File

@@ -14,15 +14,23 @@ from typing import (
Dict,
Iterator,
List,
Type,
TYPE_CHECKING,
Union,
)
from dcs.unittype import FlyingType, UnitType
from game import db
from game.dcs.aircrafttype import AircraftType
from game.dcs.groundunittype import GroundUnitType
from game.theater import Airfield, ControlPoint
from game.unitmap import Building, FrontLineUnit, GroundObjectUnit, UnitMap
from game.transfers import CargoShip
from game.unitmap import (
AirliftUnits,
Building,
ConvoyUnit,
FrontLineUnit,
GroundObjectUnit,
UnitMap,
FlyingUnit,
)
from gen.flights.flight import Flight
if TYPE_CHECKING:
@@ -33,24 +41,24 @@ DEBRIEFING_LOG_EXTENSION = "log"
@dataclass(frozen=True)
class AirLosses:
player: List[Flight]
enemy: List[Flight]
player: List[FlyingUnit]
enemy: List[FlyingUnit]
@property
def losses(self) -> Iterator[Flight]:
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.unit_type] += 1
losses_by_type[loss.flight.unit_type] += 1
return losses_by_type
def surviving_flight_members(self, flight: Flight) -> int:
losses = 0
for loss in self.losses:
if loss == flight:
if loss.flight == flight:
losses += 1
return flight.count - losses
@@ -60,8 +68,17 @@ class GroundLosses:
player_front_line: List[FrontLineUnit] = field(default_factory=list)
enemy_front_line: List[FrontLineUnit] = field(default_factory=list)
player_ground_objects: List[GroundObjectUnit] = field(default_factory=list)
enemy_ground_objects: List[GroundObjectUnit] = field(default_factory=list)
player_convoy: List[ConvoyUnit] = field(default_factory=list)
enemy_convoy: List[ConvoyUnit] = field(default_factory=list)
player_cargo_ships: List[CargoShip] = field(default_factory=list)
enemy_cargo_ships: List[CargoShip] = field(default_factory=list)
player_airlifts: List[AirliftUnits] = field(default_factory=list)
enemy_airlifts: List[AirliftUnits] = field(default_factory=list)
player_ground_objects: List[GroundObjectUnit[Any]] = field(default_factory=list)
enemy_ground_objects: List[GroundObjectUnit[Any]] = field(default_factory=list)
player_buildings: List[Building] = field(default_factory=list)
enemy_buildings: List[Building] = field(default_factory=list)
@@ -70,6 +87,12 @@ class GroundLosses:
enemy_airfields: List[Airfield] = field(default_factory=list)
@dataclass(frozen=True)
class BaseCaptureEvent:
control_point: ControlPoint
captured_by_player: bool
@dataclass(frozen=True)
class StateData:
#: True if the mission ended. If False, the mission exited abnormally.
@@ -78,11 +101,12 @@ class StateData:
#: Names of aircraft units that were killed during the mission.
killed_aircraft: List[str]
#: Names of vehicle (and ship) units that were killed during the mission.
#: Names of vehicles, ships or buildings that were killed during the mission.
killed_ground_units: List[str]
#: Names of static units that were destroyed during the mission.
destroyed_statics: List[str]
#: List of descriptions of destroyed statics. Format of each element is a mapping of
#: the coordinate type ("x", "y", "z", "type", "orientation") to the value.
destroyed_statics: List[dict[str, Union[float, str]]]
#: Mangled names of bases that were captured during the mission.
base_capture_events: List[str]
@@ -94,7 +118,10 @@ class StateData:
killed_aircraft=data["killed_aircrafts"],
# Airfields emit a new "dead" event every time a bomb is dropped on
# them when they've already dead. Dedup.
killed_ground_units=list(set(data["killed_ground_units"])),
#
# Also normalize dead map objects (which are ints) to strings. The unit map
# only stores strings.
killed_ground_units=list({str(u) for u in data["killed_ground_units"]}),
destroyed_statics=data["destroyed_objects_positions"],
base_capture_events=data["base_capture_events"],
)
@@ -105,15 +132,15 @@ class Debriefing:
self, state_data: Dict[str, Any], game: Game, unit_map: UnitMap
) -> None:
self.state_data = StateData.from_json(state_data)
self.game = game
self.unit_map = unit_map
self.player_country = game.player_country
self.enemy_country = game.enemy_country
self.player_country_id = db.country_id_from_name(game.player_country)
self.enemy_country_id = db.country_id_from_name(game.enemy_country)
self.player_country = game.blue.country_name
self.enemy_country = game.red.country_name
self.air_losses = self.dead_aircraft()
self.ground_losses = self.dead_ground_units()
self.base_captures = self.base_capture_events()
@property
def front_line_losses(self) -> Iterator[FrontLineUnit]:
@@ -121,7 +148,22 @@ class Debriefing:
yield from self.ground_losses.enemy_front_line
@property
def ground_object_losses(self) -> Iterator[GroundObjectUnit]:
def convoy_losses(self) -> Iterator[ConvoyUnit]:
yield from self.ground_losses.player_convoy
yield from self.ground_losses.enemy_convoy
@property
def cargo_ship_losses(self) -> Iterator[CargoShip]:
yield from self.ground_losses.player_cargo_ships
yield from self.ground_losses.enemy_cargo_ships
@property
def airlift_losses(self) -> Iterator[AirliftUnits]:
yield from self.ground_losses.player_airlifts
yield from self.ground_losses.enemy_airlifts
@property
def ground_object_losses(self) -> Iterator[GroundObjectUnit[Any]]:
yield from self.ground_losses.player_ground_objects
yield from self.ground_losses.enemy_ground_objects
@@ -138,8 +180,8 @@ class Debriefing:
def casualty_count(self, control_point: ControlPoint) -> int:
return len([x for x in self.front_line_losses if x.origin == control_point])
def front_line_losses_by_type(self, player: bool) -> Dict[Type[UnitType], int]:
losses_by_type: Dict[Type[UnitType], int] = defaultdict(int)
def front_line_losses_by_type(self, player: bool) -> dict[GroundUnitType, int]:
losses_by_type: dict[GroundUnitType, int] = defaultdict(int)
if player:
losses = self.ground_losses.player_front_line
else:
@@ -148,6 +190,38 @@ class Debriefing:
losses_by_type[loss.unit_type] += 1
return losses_by_type
def convoy_losses_by_type(self, player: bool) -> dict[GroundUnitType, int]:
losses_by_type: dict[GroundUnitType, int] = defaultdict(int)
if player:
losses = self.ground_losses.player_convoy
else:
losses = self.ground_losses.enemy_convoy
for loss in losses:
losses_by_type[loss.unit_type] += 1
return losses_by_type
def cargo_ship_losses_by_type(self, player: bool) -> dict[GroundUnitType, int]:
losses_by_type: dict[GroundUnitType, int] = defaultdict(int)
if player:
ships = self.ground_losses.player_cargo_ships
else:
ships = self.ground_losses.enemy_cargo_ships
for ship in ships:
for unit_type, count in ship.units.items():
losses_by_type[unit_type] += count
return losses_by_type
def airlift_losses_by_type(self, player: bool) -> dict[GroundUnitType, int]:
losses_by_type: dict[GroundUnitType, int] = defaultdict(int)
if player:
losses = self.ground_losses.player_airlifts
else:
losses = self.ground_losses.enemy_airlifts
for loss in losses:
for unit_type in loss.cargo:
losses_by_type[unit_type] += 1
return losses_by_type
def building_losses_by_type(self, player: bool) -> Dict[str, int]:
losses_by_type: Dict[str, int] = defaultdict(int)
if player:
@@ -165,14 +239,14 @@ class Debriefing:
player_losses = []
enemy_losses = []
for unit_name in self.state_data.killed_aircraft:
flight = self.unit_map.flight(unit_name)
if flight is None:
aircraft = self.unit_map.flight(unit_name)
if aircraft is None:
logging.error(f"Could not find Flight matching {unit_name}")
continue
if flight.departure.captured:
player_losses.append(flight)
if aircraft.flight.departure.captured:
player_losses.append(aircraft)
else:
enemy_losses.append(flight)
enemy_losses.append(aircraft)
return AirLosses(player_losses, enemy_losses)
def dead_ground_units(self) -> GroundLosses:
@@ -186,6 +260,22 @@ class Debriefing:
losses.enemy_front_line.append(front_line_unit)
continue
convoy_unit = self.unit_map.convoy_unit(unit_name)
if convoy_unit is not None:
if convoy_unit.convoy.player_owned:
losses.player_convoy.append(convoy_unit)
else:
losses.enemy_convoy.append(convoy_unit)
continue
cargo_ship = self.unit_map.cargo_ship(unit_name)
if cargo_ship is not None:
if cargo_ship.player_owned:
losses.player_cargo_ships.append(cargo_ship)
else:
losses.enemy_cargo_ships.append(cargo_ship)
continue
ground_object_unit = self.unit_map.ground_object_unit(unit_name)
if ground_object_unit is not None:
if ground_object_unit.ground_object.control_point.captured:
@@ -224,17 +314,46 @@ class Debriefing:
"have no effect. This may be normal behavior."
)
for unit_name in self.state_data.killed_aircraft:
airlift_unit = self.unit_map.airlift_unit(unit_name)
if airlift_unit is not None:
if airlift_unit.transfer.player:
losses.player_airlifts.append(airlift_unit)
else:
losses.enemy_airlifts.append(airlift_unit)
continue
return losses
@property
def base_capture_events(self):
def base_capture_events(self) -> List[BaseCaptureEvent]:
"""Keeps only the last instance of a base capture event for each base ID."""
reversed_captures = list(reversed(self.state_data.base_capture_events))
last_base_cap_indexes = []
for idx, base in enumerate(i.split("||")[0] for i in reversed_captures):
if base not in [x[1] for x in last_base_cap_indexes]:
last_base_cap_indexes.append((idx, base))
return [reversed_captures[idx[0]] for idx in last_base_cap_indexes]
blue_coalition_id = 2
seen = set()
captures = []
for capture in reversed(self.state_data.base_capture_events):
cp_id_str, new_owner_id_str, _name = capture.split("||")
cp_id = int(cp_id_str)
# Only the most recent capture event matters.
if cp_id in seen:
continue
seen.add(cp_id)
try:
control_point = self.game.theater.find_control_point_by_id(cp_id)
except KeyError:
# Captured base is not a part of the campaign. This happens when neutral
# bases are near the conflict. Nothing to do.
continue
captured_by_player = int(new_owner_id_str) == blue_coalition_id
if control_point.is_friendly(to_player=captured_by_player):
# Base is currently friendly to the new owner. Was captured and
# recaptured in the same mission. Nothing to do.
continue
captures.append(BaseCaptureEvent(control_point, captured_by_player))
return captures
class PollDebriefingFileThread(threading.Thread):
@@ -250,32 +369,38 @@ class PollDebriefingFileThread(threading.Thread):
self.game = game
self.unit_map = unit_map
def stop(self):
def stop(self) -> None:
self._stop_event.set()
def stopped(self):
def stopped(self) -> bool:
return self._stop_event.is_set()
def run(self):
def run(self) -> None:
if os.path.isfile("state.json"):
last_modified = os.path.getmtime("state.json")
else:
last_modified = 0
while not self.stopped():
if (
os.path.isfile("state.json")
and os.path.getmtime("state.json") > last_modified
):
with open("state.json", "r") as json_file:
json_data = json.load(json_file)
debriefing = Debriefing(json_data, self.game, self.unit_map)
self.callback(debriefing)
break
try:
if (
os.path.isfile("state.json")
and os.path.getmtime("state.json") > last_modified
):
with open("state.json", "r", encoding="utf-8") as json_file:
json_data = json.load(json_file)
debriefing = Debriefing(json_data, self.game, self.unit_map)
self.callback(debriefing)
break
except json.JSONDecodeError:
logging.exception(
"Failed to decode state.json. Probably attempted read while DCS "
"was still writing the file. Will retry in 5 seconds."
)
time.sleep(5)
def wait_for_debriefing(
callback: Callable[[Debriefing], None], game: Game, unit_map
callback: Callable[[Debriefing], None], game: Game, unit_map: UnitMap
) -> PollDebriefingFileThread:
thread = PollDebriefingFileThread(callback, game, unit_map)
thread.start()

View File

@@ -1,14 +1,10 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from .event import Event
if TYPE_CHECKING:
from game.theater import ConflictTheater
class AirWarEvent(Event):
"""Event handler for the air battle"""
def __str__(self):
def __str__(self) -> str:
return "AirWar"

View File

@@ -1,21 +1,17 @@
from __future__ import annotations
import logging
import math
from typing import Dict, Iterator, List, TYPE_CHECKING, Tuple, Type
from typing import List, TYPE_CHECKING, Type
from dcs.mapping import Point
from dcs.task import Task
from dcs.unittype import UnitType, VehicleType
from game import persistency
from game.debriefing import AirLosses, Debriefing
from game.infos.information import Information
from game.debriefing import Debriefing
from game.operation.operation import Operation
from game.theater import ControlPoint
from gen import AirTaskingOrder
from gen.ato import AirTaskingOrder
from gen.ground_forces.combat_stance import CombatStance
from ..db import PRICES
from ..unitmap import UnitMap
if TYPE_CHECKING:
@@ -39,13 +35,13 @@ class Event:
def __init__(
self,
game,
game: Game,
from_cp: ControlPoint,
target_cp: ControlPoint,
location: Point,
attacker_name: str,
defender_name: str,
):
) -> None:
self.game = game
self.from_cp = from_cp
self.to_cp = target_cp
@@ -55,7 +51,7 @@ class Event:
@property
def is_player_attacking(self) -> bool:
return self.attacker_name == self.game.player_name
return self.attacker_name == self.game.blue.faction.name
@property
def tasks(self) -> List[Type[Task]]:
@@ -69,74 +65,42 @@ class Event:
)
return unit_map
@staticmethod
def _transfer_aircraft(
ato: AirTaskingOrder, losses: AirLosses, for_player: bool
) -> None:
for package in ato.packages:
for flight in package.flights:
# No need to transfer to the same location.
if flight.departure == flight.arrival:
continue
# Don't transfer to bases that were captured. Note that if the
# airfield was back-filling transfers it may overflow. We could
# attempt to be smarter in the future by performing transfers in
# order up a graph to prevent transfers to full airports and
# send overflow off-map, but overflow is fine for now.
if flight.arrival.captured != for_player:
logging.info(
f"Not transferring {flight} because {flight.arrival} "
"was captured"
)
continue
transfer_count = losses.surviving_flight_members(flight)
if transfer_count < 0:
logging.error(
f"{flight} had {flight.count} aircraft but "
f"{transfer_count} losses were recorded."
)
continue
aircraft = flight.unit_type
available = flight.departure.base.total_units_of_type(aircraft)
if available < transfer_count:
logging.error(
f"Found killed {aircraft} from {flight.departure} but "
f"that airbase has only {available} available."
)
continue
flight.departure.base.aircraft[aircraft] -= transfer_count
if aircraft not in flight.arrival.base.aircraft:
# TODO: Should use defaultdict.
flight.arrival.base.aircraft[aircraft] = 0
flight.arrival.base.aircraft[aircraft] += transfer_count
def complete_aircraft_transfers(self, debriefing: Debriefing) -> None:
self._transfer_aircraft(
self.game.blue_ato, debriefing.air_losses, for_player=True
)
self._transfer_aircraft(
self.game.red_ato, debriefing.air_losses, for_player=False
)
@staticmethod
def commit_air_losses(debriefing: Debriefing) -> None:
def commit_air_losses(self, debriefing: Debriefing) -> None:
for loss in debriefing.air_losses.losses:
aircraft = loss.unit_type
cp = loss.departure
available = cp.base.total_units_of_type(aircraft)
if loss.pilot is not None and (
not loss.pilot.player
or not self.game.settings.invulnerable_player_pilots
):
loss.pilot.kill()
squadron = loss.flight.squadron
aircraft = loss.flight.unit_type
available = squadron.owned_aircraft
if available <= 0:
logging.error(
f"Found killed {aircraft} from {cp} but that airbase has "
f"Found killed {aircraft} from {squadron} but that airbase has "
"none available."
)
continue
logging.info(f"{aircraft} destroyed from {cp}")
cp.base.aircraft[aircraft] -= 1
logging.info(f"{aircraft} destroyed from {squadron}")
squadron.owned_aircraft -= 1
@staticmethod
def _commit_pilot_experience(ato: AirTaskingOrder) -> None:
for package in ato.packages:
for flight in package.flights:
for idx, pilot in enumerate(flight.roster.pilots):
if pilot is None:
logging.error(
f"Cannot award experience to pilot #{idx} of {flight} "
"because no pilot is assigned"
)
continue
pilot.record.missions_flown += 1
def commit_pilot_experience(self) -> None:
self._commit_pilot_experience(self.game.blue.ato)
self._commit_pilot_experience(self.game.red.ato)
@staticmethod
def commit_front_line_losses(debriefing: Debriefing) -> None:
@@ -154,26 +118,64 @@ class Event:
logging.info(f"{unit_type} destroyed from {control_point}")
control_point.base.armor[unit_type] -= 1
@staticmethod
def commit_convoy_losses(debriefing: Debriefing) -> None:
for loss in debriefing.convoy_losses:
unit_type = loss.unit_type
convoy = loss.convoy
available = loss.convoy.units.get(unit_type, 0)
convoy_name = f"convoy from {convoy.origin} to {convoy.destination}"
if available <= 0:
logging.error(
f"Found killed {unit_type} in {convoy_name} but that convoy has "
"none available."
)
continue
logging.info(f"{unit_type} destroyed in {convoy_name}")
convoy.kill_unit(unit_type)
@staticmethod
def commit_cargo_ship_losses(debriefing: Debriefing) -> None:
for ship in debriefing.cargo_ship_losses:
logging.info(
f"All units destroyed in cargo ship from {ship.origin} to "
f"{ship.destination}."
)
ship.kill_all()
@staticmethod
def commit_airlift_losses(debriefing: Debriefing) -> None:
for loss in debriefing.airlift_losses:
transfer = loss.transfer
airlift_name = f"airlift from {transfer.origin} to {transfer.destination}"
for unit_type in loss.cargo:
try:
transfer.kill_unit(unit_type)
logging.info(f"{unit_type} destroyed in {airlift_name}")
except KeyError:
logging.exception(
f"Found killed {unit_type} in {airlift_name} but that airlift "
"has none available."
)
@staticmethod
def commit_ground_object_losses(debriefing: Debriefing) -> None:
for loss in debriefing.ground_object_losses:
# TODO: This should be stored in the TGO, not in the pydcs Group.
if not hasattr(loss.group, "units_losts"):
loss.group.units_losts = []
loss.group.units_losts = [] # type: ignore
loss.group.units.remove(loss.unit)
loss.group.units_losts.append(loss.unit)
loss.group.units_losts.append(loss.unit) # type: ignore
def commit_building_losses(self, debriefing: Debriefing) -> None:
for loss in debriefing.building_losses:
loss.ground_object.kill()
self.game.informations.append(
Information(
"Building destroyed",
f"{loss.ground_object.dcs_identifier} has been destroyed at "
f"location {loss.ground_object.obj_name}",
self.game.turn,
)
self.game.message(
"Building destroyed",
f"{loss.ground_object.dcs_identifier} has been destroyed at "
f"location {loss.ground_object.obj_name}",
)
@staticmethod
@@ -181,63 +183,39 @@ class Event:
for damaged_runway in debriefing.damaged_runways:
damaged_runway.damage_runway()
def commit(self, debriefing: Debriefing):
logging.info("Committing mission results")
self.commit_air_losses(debriefing)
self.commit_front_line_losses(debriefing)
self.commit_ground_object_losses(debriefing)
self.commit_building_losses(debriefing)
self.commit_damaged_runways(debriefing)
# ------------------------------
# Captured bases
# if self.game.player_country in db.BLUEFOR_FACTIONS:
coalition = 2 # Value in DCS mission event for BLUE
# else:
# coalition = 1 # Value in DCS mission event for RED
for captured in debriefing.base_capture_events:
def commit_captures(self, debriefing: Debriefing) -> None:
for captured in debriefing.base_captures:
try:
id = int(captured.split("||")[0])
new_owner_coalition = int(captured.split("||")[1])
if captured.captured_by_player:
self.game.message(
f"{captured.control_point} captured!",
f"We took control of {captured.control_point}.",
)
else:
self.game.message(
f"{captured.control_point} lost!",
f"The enemy took control of {captured.control_point}.",
)
captured_cps = []
for cp in self.game.theater.controlpoints:
if cp.id == id:
if cp.captured and new_owner_coalition != coalition:
for_player = False
info = Information(
cp.name + " lost !",
"The ennemy took control of "
+ cp.name
+ "\nShame on us !",
self.game.turn,
)
self.game.informations.append(info)
captured_cps.append(cp)
elif not (cp.captured) and new_owner_coalition == coalition:
for_player = True
info = Information(
cp.name + " captured !",
"We took control of " + cp.name + "! Great job !",
self.game.turn,
)
self.game.informations.append(info)
captured_cps.append(cp)
else:
continue
cp.capture(self.game, for_player)
for cp in captured_cps:
logging.info("Will run redeploy for " + cp.name)
self.redeploy_units(cp)
captured.control_point.capture(self.game, captured.captured_by_player)
logging.info(f"Will run redeploy for {captured.control_point}")
self.redeploy_units(captured.control_point)
except Exception:
logging.exception(f"Could not process base capture {captured}")
self.complete_aircraft_transfers(debriefing)
def commit(self, debriefing: Debriefing) -> None:
logging.info("Committing mission results")
self.commit_air_losses(debriefing)
self.commit_pilot_experience()
self.commit_front_line_losses(debriefing)
self.commit_convoy_losses(debriefing)
self.commit_cargo_ship_losses(debriefing)
self.commit_airlift_losses(debriefing)
self.commit_ground_object_losses(debriefing)
self.commit_building_losses(debriefing)
self.commit_damaged_runways(debriefing)
self.commit_captures(debriefing)
# Destroyed units carcass
# -------------------------
@@ -258,15 +236,16 @@ class Event:
delta = 0.0
player_won = True
status_msg: str = ""
ally_casualties = debriefing.casualty_count(cp)
enemy_casualties = debriefing.casualty_count(enemy_cp)
ally_units_alive = cp.base.total_armor
enemy_units_alive = enemy_cp.base.total_armor
print(ally_units_alive)
print(enemy_units_alive)
print(ally_casualties)
print(enemy_casualties)
print(f"Remaining allied units: {ally_units_alive}")
print(f"Remaining enemy units: {enemy_units_alive}")
print(f"Allied casualties {ally_casualties}")
print(f"Enemy casualties {enemy_casualties}")
ratio = (1.0 + enemy_casualties) / (1.0 + ally_casualties)
@@ -279,24 +258,31 @@ class Event:
if ally_units_alive == 0:
player_won = False
delta = STRONG_DEFEAT_INFLUENCE
status_msg = f"No allied units alive at {cp.name}-{enemy_cp.name} frontline. Allied ground forces suffer a strong defeat."
elif enemy_units_alive == 0:
player_won = True
delta = STRONG_DEFEAT_INFLUENCE
status_msg = f"No enemy units alive at {cp.name}-{enemy_cp.name} frontline. Allied ground forces win a strong victory."
elif cp.stances[enemy_cp.id] == CombatStance.RETREAT:
player_won = False
delta = STRONG_DEFEAT_INFLUENCE
status_msg = f"Allied forces are retreating along the {cp.name}-{enemy_cp.name} frontline, suffering a strong defeat."
else:
if enemy_casualties > ally_casualties:
player_won = True
if cp.stances[enemy_cp.id] == CombatStance.BREAKTHROUGH:
delta = STRONG_DEFEAT_INFLUENCE
status_msg = f"Allied forces break through the {cp.name}-{enemy_cp.name} frontline, winning a strong victory"
else:
if ratio > 3:
delta = STRONG_DEFEAT_INFLUENCE
status_msg = f"Enemy casualties massively outnumber allied casualties along the {cp.name}-{enemy_cp.name} frontline. Allied forces win a strong victory."
elif ratio < 1.5:
delta = MINOR_DEFEAT_INFLUENCE
status_msg = f"Enemy casualties minorly outnumber allied casualties along the {cp.name}-{enemy_cp.name} frontline. Allied forces win a minor victory."
else:
delta = DEFEAT_INFLUENCE
status_msg = f"Enemy casualties outnumber allied casualties along the {cp.name}-{enemy_cp.name} frontline. Allied forces claim a victory."
elif ally_casualties > enemy_casualties:
if (
@@ -306,54 +292,60 @@ class Event:
# Even with casualties if the enemy is overwhelmed, they are going to lose ground
player_won = True
delta = MINOR_DEFEAT_INFLUENCE
status_msg = f"Despite suffering losses, allied forces still outnumber enemy forces along the {cp.name}-{enemy_cp.name} frontline. Due to allied force's aggressive posture, allied forces claim a minor victory."
elif (
ally_units_alive > 3 * enemy_units_alive
and player_aggresive
):
player_won = True
delta = STRONG_DEFEAT_INFLUENCE
status_msg = f"Despite suffering losses, allied forces still heavily outnumber enemy forces along the {cp.name}-{enemy_cp.name} frontline. Due to allied force's aggressive posture, allied forces claim a major victory."
else:
# But is the enemy is not outnumbered, we lose
# But if the enemy is not outnumbered, we lose
player_won = False
if cp.stances[enemy_cp.id] == CombatStance.BREAKTHROUGH:
delta = STRONG_DEFEAT_INFLUENCE
status_msg = f"Allied casualties outnumber enemy casualties along the {cp.name}-{enemy_cp.name} frontline. Allied forces have overextended themselves, suffering a major defeat."
else:
delta = STRONG_DEFEAT_INFLUENCE
delta = DEFEAT_INFLUENCE
status_msg = f"Allied casualties outnumber enemy casualties along the {cp.name}-{enemy_cp.name} frontline. Allied forces suffer a defeat."
# No progress with defensive strategies
if player_won and cp.stances[enemy_cp.id] in [
CombatStance.DEFENSIVE,
CombatStance.AMBUSH,
]:
print("Defensive stance, progress is limited")
print(
f"Allied forces have adopted a defensive stance along the {cp.name}-{enemy_cp.name} "
f"frontline, making only limited progress."
)
delta = MINOR_DEFEAT_INFLUENCE
if player_won:
print(cp.name + " won ! factor > " + str(delta))
cp.base.affect_strength(delta)
enemy_cp.base.affect_strength(-delta)
info = Information(
# Handle the case where there are no casualties at all on either side but both sides still have units
if delta == 0.0:
print(status_msg)
self.game.message(
"Frontline Report",
"Our ground forces from "
+ cp.name
+ " are making progress toward "
+ enemy_cp.name,
self.game.turn,
f"Our ground forces from {cp.name} reached a stalemate with enemy forces from {enemy_cp.name}.",
)
self.game.informations.append(info)
else:
print(cp.name + " lost ! factor > " + str(delta))
enemy_cp.base.affect_strength(delta)
cp.base.affect_strength(-delta)
info = Information(
"Frontline Report",
"Our ground forces from "
+ cp.name
+ " are losing ground against the enemy forces from "
+ enemy_cp.name,
self.game.turn,
)
self.game.informations.append(info)
if player_won:
print(status_msg)
cp.base.affect_strength(delta)
enemy_cp.base.affect_strength(-delta)
self.game.message(
"Frontline Report",
f"Our ground forces from {cp.name} are making progress toward {enemy_cp.name}. {status_msg}",
)
else:
print(status_msg)
enemy_cp.base.affect_strength(delta)
cp.base.affect_strength(-delta)
self.game.message(
"Frontline Report",
f"Our ground forces from {cp.name} are losing ground against the enemy forces from "
f"{enemy_cp.name}. {status_msg}",
)
def redeploy_units(self, cp: ControlPoint) -> None:
""" "
@@ -395,86 +387,19 @@ class Event:
moved_units[frontline_unit] = int(count * move_factor)
total_units_redeployed = total_units_redeployed + int(count * move_factor)
destination.base.commision_units(moved_units)
destination.base.commission_units(moved_units)
source.base.commit_losses(moved_units)
# Also transfer pending deliveries.
for unit_type, count in source.pending_unit_deliveries.units.items():
if not issubclass(unit_type, VehicleType):
continue
if count <= 0:
# Don't transfer *sales*...
continue
for unit_type, count in source.ground_unit_orders.units.items():
move_count = int(count * move_factor)
source.pending_unit_deliveries.sell({unit_type: move_count})
destination.pending_unit_deliveries.order({unit_type: move_count})
source.ground_unit_orders.sell({unit_type: move_count})
destination.ground_unit_orders.order({unit_type: move_count})
total_units_redeployed += move_count
if total_units_redeployed > 0:
text = (
self.game.message(
"Units redeployed",
f"{total_units_redeployed} units have been redeployed from "
f"{source.name} to {destination.name}"
f"{source.name} to {destination.name}",
)
info = Information("Units redeployed", text, self.game.turn)
self.game.informations.append(info)
logging.info(text)
class UnitsDeliveryEvent:
def __init__(self, control_point: ControlPoint) -> None:
self.to_cp = control_point
self.units: Dict[Type[UnitType], int] = {}
def __str__(self) -> str:
return "Pending delivery to {}".format(self.to_cp)
def order(self, units: Dict[Type[UnitType], int]) -> None:
for k, v in units.items():
self.units[k] = self.units.get(k, 0) + v
def sell(self, units: Dict[Type[UnitType], int]) -> None:
for k, v in units.items():
self.units[k] = self.units.get(k, 0) - v
def consume_each_order(self) -> Iterator[Tuple[Type[UnitType], int]]:
while self.units:
yield self.units.popitem()
def refund_all(self, game: Game) -> None:
for unit_type, count in self.consume_each_order():
try:
price = PRICES[unit_type]
except KeyError:
logging.error(f"Could not refund {unit_type.id}, price unknown")
continue
logging.info(f"Refunding {count} {unit_type.id} at {self.to_cp.name}")
game.adjust_budget(price * count, player=self.to_cp.captured)
def available_next_turn(self, unit_type: Type[UnitType]) -> int:
pending_units = self.units.get(unit_type)
if pending_units is None:
pending_units = 0
current_units = self.to_cp.base.total_units_of_type(unit_type)
return pending_units + current_units
def process(self, game: Game) -> None:
bought_units: Dict[Type[UnitType], int] = {}
sold_units: Dict[Type[UnitType], int] = {}
for unit_type, count in self.units.items():
coalition = "Ally" if self.to_cp.captured else "Enemy"
aircraft = unit_type.id
name = self.to_cp.name
if count >= 0:
bought_units[unit_type] = count
game.message(
f"{coalition} reinforcements: {aircraft} x {count} at {name}"
)
else:
sold_units[unit_type] = -count
game.message(f"{coalition} sold: {aircraft} x {-count} at {name}")
self.to_cp.base.commision_units(bought_units)
self.to_cp.base.commit_losses(sold_units)
self.units = {}
bought_units = {}
sold_units = {}

View File

@@ -8,5 +8,5 @@ class FrontlineAttackEvent(Event):
future unique Event handling
"""
def __str__(self):
def __str__(self) -> str:
return "Frontline attack"

View File

@@ -1,14 +1,13 @@
from __future__ import annotations
import itertools
import logging
from dataclasses import dataclass, field
from typing import Optional, Dict, Type, List, Any, cast
from typing import Optional, Dict, Type, List, Any, Iterator, TYPE_CHECKING
import dcs
from dcs.countries import country_dict
from dcs.planes import plane_map
from dcs.unittype import FlyingType, ShipType, VehicleType, UnitType
from dcs.vehicles import Armor, Unarmed, Infantry, Artillery, AirDefence
from dcs.unittype import ShipType, UnitType
from game.data.building_data import (
WW2_ALLIES_BUILDINGS,
@@ -22,11 +21,19 @@ 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 game.dcs.groundunittype import GroundUnitType
if TYPE_CHECKING:
from game.theater.start_generator import ModSettings
@dataclass
class Faction:
#: List of locales to use when generating random names. If not set, Faker will
#: choose the default locale.
locales: Optional[List[str]]
# Country used by this faction
country: str = field(default="")
@@ -41,25 +48,25 @@ 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)
frontline_units: List[GroundUnitType] = field(default_factory=list)
# Available artillery units
artillery_units: List[Type[VehicleType]] = field(default_factory=list)
artillery_units: List[GroundUnitType] = field(default_factory=list)
# Infantry units used
infantry_units: List[Type[VehicleType]] = field(default_factory=list)
infantry_units: List[GroundUnitType] = field(default_factory=list)
# Logistics units used
logistics_units: List[Type[VehicleType]] = field(default_factory=list)
logistics_units: List[GroundUnitType] = field(default_factory=list)
# Possible SAMS site generators for this faction
air_defenses: List[str] = field(default_factory=list)
@@ -77,10 +84,10 @@ class Faction:
requirements: Dict[str, str] = field(default_factory=dict)
# possible aircraft carrier units
aircraft_carrier: List[Type[UnitType]] = field(default_factory=list)
aircraft_carrier: List[Type[ShipType]] = field(default_factory=list)
# possible helicopter carrier units
helicopter_carrier: List[Type[UnitType]] = field(default_factory=list)
helicopter_carrier: List[Type[ShipType]] = field(default_factory=list)
# Possible carrier names
carrier_names: List[str] = field(default_factory=list)
@@ -110,7 +117,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)
@@ -119,7 +126,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
@@ -130,10 +137,15 @@ class Faction:
#: both will use it.
unrestricted_satnav: bool = False
def has_access_to_unittype(self, unit_class: GroundUnitClass) -> bool:
for vehicle in itertools.chain(self.frontline_units, self.artillery_units):
if vehicle.unit_class is unit_class:
return True
return False
@classmethod
def from_json(cls: Type[Faction], json: Dict[str, Any]) -> Faction:
faction = Faction()
faction = Faction(locales=json.get("locales"))
faction.country = json.get("country", "/")
if faction.country not in [c.name for c in country_dict.values()]:
@@ -150,14 +162,26 @@ 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.frontline_units = load_all_vehicles(json.get("frontline_units", []))
faction.artillery_units = load_all_vehicles(json.get("artillery_units", []))
faction.infantry_units = load_all_vehicles(json.get("infantry_units", []))
faction.logistics_units = load_all_vehicles(json.get("logistics_units", []))
faction.aircrafts = list(
set(faction.aircrafts + faction.awacs + faction.tankers)
)
faction.frontline_units = [
GroundUnitType.named(n) for n in json.get("frontline_units", [])
]
faction.artillery_units = [
GroundUnitType.named(n) for n in json.get("artillery_units", [])
]
faction.infantry_units = [
GroundUnitType.named(n) for n in json.get("infantry_units", [])
]
faction.logistics_units = [
GroundUnitType.named(n) for n in json.get("logistics_units", [])
]
faction.ewrs = json.get("ewrs", [])
@@ -181,7 +205,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))
@@ -215,90 +239,120 @@ 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 units(self) -> List[Type[UnitType]]:
return (
self.infantry_units
+ self.aircrafts
+ self.awacs
+ self.artillery_units
+ self.frontline_units
+ self.tankers
+ self.logistics_units
)
def ground_units(self) -> Iterator[GroundUnitType]:
yield from self.artillery_units
yield from self.frontline_units
yield from self.logistics_units
def infantry_with_class(
self, unit_class: GroundUnitClass
) -> Iterator[GroundUnitType]:
for unit in self.infantry_units:
if unit.unit_class is unit_class:
yield unit
def unit_loader(unit: str, class_repository: List[Any]) -> Optional[Type[UnitType]]:
"""
Find unit by name
:param unit: Unit name as string
:param class_repository: Repository of classes (Either a module, a class, or a list of classes)
:return: The unit as a PyDCS type
"""
if unit is None:
return None
elif unit in plane_map.keys():
return plane_map[unit]
else:
for mother_class in class_repository:
if getattr(mother_class, unit, None) is not None:
return getattr(mother_class, unit)
if type(mother_class) is list:
for m in mother_class:
if m.__name__ == unit:
return m
logging.error(f"FACTION ERROR : Unable to find {unit} in pydcs")
return None
def apply_mod_settings(self, mod_settings: ModSettings) -> Faction:
# aircraft
if not mod_settings.a4_skyhawk:
self.remove_aircraft("A-4E-C")
if not mod_settings.hercules:
self.remove_aircraft("Hercules")
if not mod_settings.uh_60l:
self.remove_aircraft("UH-60L")
self.remove_aircraft("KC130J")
if not mod_settings.f22_raptor:
self.remove_aircraft("F-22A")
if not mod_settings.f104_starfighter:
self.remove_aircraft("VSN_F104G")
self.remove_aircraft("VSN_F104S")
self.remove_aircraft("VSN_F104S_AG")
if not mod_settings.jas39_gripen:
self.remove_aircraft("JAS39Gripen")
self.remove_aircraft("JAS39Gripen_AG")
if not mod_settings.su57_felon:
self.remove_aircraft("Su-57")
# frenchpack
if not mod_settings.frenchpack:
self.remove_vehicle("AMX10RCR")
self.remove_vehicle("SEPAR")
self.remove_vehicle("ERC")
self.remove_vehicle("M120")
self.remove_vehicle("AA20")
self.remove_vehicle("TRM2000")
self.remove_vehicle("TRM2000_Citerne")
self.remove_vehicle("TRM2000_AA20")
self.remove_vehicle("TRMMISTRAL")
self.remove_vehicle("VABH")
self.remove_vehicle("VAB_RADIO")
self.remove_vehicle("VAB_50")
self.remove_vehicle("VIB_VBR")
self.remove_vehicle("VAB_HOT")
self.remove_vehicle("VAB_MORTIER")
self.remove_vehicle("VBL50")
self.remove_vehicle("VBLANF1")
self.remove_vehicle("VBL-radio")
self.remove_vehicle("VBAE")
self.remove_vehicle("VBAE_MMP")
self.remove_vehicle("AMX-30B2")
self.remove_vehicle("Tracma")
self.remove_vehicle("JTACFP")
self.remove_vehicle("SHERIDAN")
self.remove_vehicle("Leclerc_XXI")
self.remove_vehicle("Toyota_bleu")
self.remove_vehicle("Toyota_vert")
self.remove_vehicle("Toyota_desert")
self.remove_vehicle("Kamikaze")
self.remove_vehicle("AMX1375")
self.remove_vehicle("AMX1390")
self.remove_vehicle("VBCI")
self.remove_vehicle("T62")
self.remove_vehicle("T64BV")
self.remove_vehicle("T72M")
self.remove_vehicle("KORNET")
# high digit sams
if not mod_settings.high_digit_sams:
self.remove_air_defenses("SA10BGenerator")
self.remove_air_defenses("SA12Generator")
self.remove_air_defenses("SA20Generator")
self.remove_air_defenses("SA20BGenerator")
self.remove_air_defenses("SA23Generator")
self.remove_air_defenses("SA17Generator")
self.remove_air_defenses("KS19Generator")
return self
def remove_aircraft(self, name: str) -> None:
for i in self.aircrafts:
if i.dcs_unit_type.id == name:
self.aircrafts.remove(i)
def load_aircraft(name: str) -> Optional[Type[FlyingType]]:
return cast(
Optional[FlyingType],
unit_loader(name, [dcs.planes, dcs.helicopters, MODDED_AIRPLANES]),
)
def remove_air_defenses(self, name: str) -> None:
for i in self.air_defenses:
if i == name:
self.air_defenses.remove(i)
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],
unit_loader(
name, [Infantry, Unarmed, Armor, AirDefence, Artillery, MODDED_VEHICLES]
),
)
def load_all_vehicles(data) -> List[Type[VehicleType]]:
items = []
for name in data:
item = load_vehicle(name)
if item is not None:
items.append(item)
return items
def remove_vehicle(self, name: str) -> None:
for i in self.frontline_units:
if i.dcs_unit_type.id == name:
self.frontline_units.remove(i)
def load_ship(name: str) -> Optional[Type[ShipType]]:
return cast(Optional[FlyingType], unit_loader(name, [dcs.ships]))
if (ship := getattr(dcs.ships, name, None)) is not None:
return ship
logging.error(f"FACTION ERROR : Unable to find {name} in dcs.ships")
return None
def load_all_ships(data) -> List[Type[ShipType]]:
def load_all_ships(data: list[str]) -> List[Type[ShipType]]:
items = []
for name in data:
item = load_ship(name)

View File

@@ -2,8 +2,9 @@ from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Dict, Iterator, Optional, Type
from typing import Dict, Iterator, List, Optional, Type
from game import persistency
from game.factions.faction import Faction
FACTION_DIRECTORY = Path("./resources/factions/")
@@ -23,9 +24,16 @@ class FactionLoader:
if self._factions is None:
self._factions = self.load_factions()
@staticmethod
def find_faction_files_in(path: Path) -> List[Path]:
return [f for f in path.glob("*.json") if f.is_file()]
@classmethod
def load_factions(cls: Type[FactionLoader]) -> Dict[str, Faction]:
files = [f for f in FACTION_DIRECTORY.glob("*.json") if f.is_file()]
user_faction_path = Path(persistency.base_path()) / "Liberation/Factions"
files = cls.find_faction_files_in(
FACTION_DIRECTORY
) + cls.find_faction_files_in(user_faction_path)
factions = {}
for f in files:

View File

@@ -0,0 +1,3 @@
from .holdzonegeometry import HoldZoneGeometry
from .ipzonegeometry import IpZoneGeometry
from .joinzonegeometry import JoinZoneGeometry

View File

@@ -0,0 +1,108 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import shapely.ops
from dcs import Point
from shapely.geometry import Point as ShapelyPoint, Polygon, MultiPolygon
from game.theater import ConflictTheater
from game.utils import nautical_miles
if TYPE_CHECKING:
from game.coalition import Coalition
class HoldZoneGeometry:
"""Defines the zones used for finding optimal hold point placement.
The zones themselves are stored in the class rather than just the resulting hold
point so that the zones can be drawn in the map for debugging purposes.
"""
def __init__(
self,
target: Point,
home: Point,
ip: Point,
join: Point,
coalition: Coalition,
theater: ConflictTheater,
) -> None:
# Hold points are placed one of two ways. Either approach guarantees:
#
# * Safe hold point.
# * Minimum distance to the join point.
# * Not closer to the target than the join point.
#
# 1. As near the join point as possible with a specific distance from the
# departure airfield. This prevents loitering directly above the airfield but
# also keeps the hold point close to the departure airfield.
#
# 2. Alternatively, if the entire home zone is excluded by the above criteria,
# as neat the departure airfield as possible within a minimum distance from
# the join point, with a restricted turn angle at the join point. This
# handles the case where we need to backtrack from the departure airfield and
# the join point to place the hold point, but the turn angle limit restricts
# the maximum distance of the backtrack while maintaining the direction of
# the flight plan.
self.threat_zone = coalition.opponent.threat_zone.all
self.home = ShapelyPoint(home.x, home.y)
self.join = ShapelyPoint(join.x, join.y)
self.join_bubble = self.join.buffer(coalition.doctrine.push_distance.meters)
join_to_target_distance = join.distance_to_point(target)
self.target_bubble = ShapelyPoint(target.x, target.y).buffer(
join_to_target_distance
)
self.home_bubble = self.home.buffer(coalition.doctrine.hold_distance.meters)
excluded_zones = shapely.ops.unary_union(
[self.join_bubble, self.target_bubble, self.threat_zone]
)
if not isinstance(excluded_zones, MultiPolygon):
excluded_zones = MultiPolygon([excluded_zones])
self.excluded_zones = excluded_zones
join_heading = ip.heading_between_point(join)
# Arbitrarily large since this is later constrained by the map boundary, and
# we'll be picking a location close to the IP anyway. Just used to avoid real
# distance calculations to project to the map edge.
large_distance = nautical_miles(400).meters
turn_limit = 40
join_limit_ccw = join.point_from_heading(
join_heading - turn_limit, large_distance
)
join_limit_cw = join.point_from_heading(
join_heading + turn_limit, large_distance
)
join_direction_limit_wedge = Polygon(
[
(join.x, join.y),
(join_limit_ccw.x, join_limit_ccw.y),
(join_limit_cw.x, join_limit_cw.y),
]
)
permissible_zones = (
coalition.nav_mesh.map_bounds(theater)
.intersection(join_direction_limit_wedge)
.difference(self.excluded_zones)
.difference(self.home_bubble)
)
if not isinstance(permissible_zones, MultiPolygon):
permissible_zones = MultiPolygon([permissible_zones])
self.permissible_zones = permissible_zones
self.preferred_lines = self.home_bubble.boundary.difference(self.excluded_zones)
def find_best_hold_point(self) -> Point:
if self.preferred_lines.is_empty:
hold, _ = shapely.ops.nearest_points(self.permissible_zones, self.home)
else:
hold, _ = shapely.ops.nearest_points(self.preferred_lines, self.join)
return Point(hold.x, hold.y)

View File

@@ -0,0 +1,118 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import shapely.ops
from dcs import Point
from shapely.geometry import Point as ShapelyPoint, MultiPolygon
from game.utils import nautical_miles, meters
if TYPE_CHECKING:
from game.coalition import Coalition
class IpZoneGeometry:
"""Defines the zones used for finding optimal IP placement.
The zones themselves are stored in the class rather than just the resulting IP so
that the zones can be drawn in the map for debugging purposes.
"""
def __init__(
self,
target: Point,
home: Point,
coalition: Coalition,
) -> None:
self.threat_zone = coalition.opponent.threat_zone.all
self.home = ShapelyPoint(home.x, home.y)
max_ip_distance = coalition.doctrine.max_ingress_distance
min_ip_distance = coalition.doctrine.min_ingress_distance
# The minimum distance between the home location and the IP.
min_distance_from_home = nautical_miles(5)
# The distance that is expected to be needed between the beginning of the attack
# and weapon release. This buffers the threat zone to give a 5nm window between
# the edge of the "safe" zone and the actual threat so that "safe" IPs are less
# likely to end up with the attacker entering a threatened area.
attack_distance_buffer = nautical_miles(5)
home_threatened = coalition.opponent.threat_zone.threatened(home)
shapely_target = ShapelyPoint(target.x, target.y)
home_to_target_distance = meters(home.distance_to_point(target))
self.home_bubble = self.home.buffer(home_to_target_distance.meters).difference(
self.home.buffer(min_distance_from_home.meters)
)
# If the home zone is not threatened and home is within LAR, constrain the max
# range to the home-to-target distance to prevent excessive backtracking.
#
# If the home zone *is* threatened, we need to back out of the zone to
# rendezvous anyway.
if not home_threatened and (
min_ip_distance < home_to_target_distance < max_ip_distance
):
max_ip_distance = home_to_target_distance
max_ip_bubble = shapely_target.buffer(max_ip_distance.meters)
min_ip_bubble = shapely_target.buffer(min_ip_distance.meters)
self.ip_bubble = max_ip_bubble.difference(min_ip_bubble)
# The intersection of the home bubble and IP bubble will be all the points that
# are within the valid IP range that are not farther from home than the target
# is. However, if the origin airfield is threatened but there are safe
# placements for the IP, we should not constrain to the home zone. In this case
# we'll either end up with a safe zone outside the home zone and pick the
# closest point in to to home (minimizing backtracking), or we'll have no safe
# IP anywhere within range of the target, and we'll later pick the IP nearest
# the edge of the threat zone.
if home_threatened:
self.permissible_zone = self.ip_bubble
else:
self.permissible_zone = self.ip_bubble.intersection(self.home_bubble)
if self.permissible_zone.is_empty:
# If home is closer to the target than the min range, there will not be an
# IP solution that's close enough to home, in which case we need to ignore
# the home bubble.
self.permissible_zone = self.ip_bubble
safe_zones = self.permissible_zone.difference(
self.threat_zone.buffer(attack_distance_buffer.meters)
)
if not isinstance(safe_zones, MultiPolygon):
safe_zones = MultiPolygon([safe_zones])
self.safe_zones = safe_zones
def _unsafe_ip(self) -> ShapelyPoint:
unthreatened_home_zone = self.home_bubble.difference(self.threat_zone)
if unthreatened_home_zone.is_empty:
# Nowhere in our home zone is safe. The package will need to exit the
# threatened area to hold and rendezvous. Pick the IP closest to the
# edge of the threat zone.
return shapely.ops.nearest_points(
self.permissible_zone, self.threat_zone.boundary
)[0]
# No safe point in the IP zone, but the home zone is safe. Pick the max-
# distance IP that's closest to the untreatened home zone.
return shapely.ops.nearest_points(
self.permissible_zone, unthreatened_home_zone
)[0]
def _safe_ip(self) -> ShapelyPoint:
# We have a zone of possible IPs that are safe, close enough, and in range. Pick
# the IP in the zone that's closest to the target.
return shapely.ops.nearest_points(self.safe_zones, self.home)[0]
def find_best_ip(self) -> Point:
if self.safe_zones.is_empty:
ip = self._unsafe_ip()
else:
ip = self._safe_ip()
return Point(ip.x, ip.y)

View File

@@ -0,0 +1,103 @@
from __future__ import annotations
from typing import TYPE_CHECKING
import shapely.ops
from dcs import Point
from shapely.geometry import (
Point as ShapelyPoint,
Polygon,
MultiPolygon,
MultiLineString,
)
from game.utils import nautical_miles
if TYPE_CHECKING:
from game.coalition import Coalition
class JoinZoneGeometry:
"""Defines the zones used for finding optimal join point placement.
The zones themselves are stored in the class rather than just the resulting join
point so that the zones can be drawn in the map for debugging purposes.
"""
def __init__(
self, target: Point, home: Point, ip: Point, coalition: Coalition
) -> None:
# Normal join placement is based on the path from home to the IP. If no path is
# found it means that the target is on a direct path. In that case we instead
# want to enforce that the join point is:
#
# * Not closer to the target than the IP.
# * Not too close to the home airfield.
# * Not threatened.
# * A minimum distance from the IP.
# * Not too sharp a turn at the ingress point.
self.ip = ShapelyPoint(ip.x, ip.y)
self.threat_zone = coalition.opponent.threat_zone.all
self.home = ShapelyPoint(home.x, home.y)
self.ip_bubble = self.ip.buffer(coalition.doctrine.join_distance.meters)
ip_distance = ip.distance_to_point(target)
self.target_bubble = ShapelyPoint(target.x, target.y).buffer(ip_distance)
# The minimum distance between the home location and the IP.
min_distance_from_home = nautical_miles(5)
self.home_bubble = self.home.buffer(min_distance_from_home.meters)
excluded_zones = shapely.ops.unary_union(
[self.ip_bubble, self.target_bubble, self.threat_zone]
)
if not isinstance(excluded_zones, MultiPolygon):
excluded_zones = MultiPolygon([excluded_zones])
self.excluded_zones = excluded_zones
ip_heading = target.heading_between_point(ip)
# Arbitrarily large since this is later constrained by the map boundary, and
# we'll be picking a location close to the IP anyway. Just used to avoid real
# distance calculations to project to the map edge.
large_distance = nautical_miles(400).meters
turn_limit = 40
ip_limit_ccw = ip.point_from_heading(ip_heading - turn_limit, large_distance)
ip_limit_cw = ip.point_from_heading(ip_heading + turn_limit, large_distance)
ip_direction_limit_wedge = Polygon(
[
(ip.x, ip.y),
(ip_limit_ccw.x, ip_limit_ccw.y),
(ip_limit_cw.x, ip_limit_cw.y),
]
)
permissible_zones = ip_direction_limit_wedge.difference(
self.excluded_zones
).difference(self.home_bubble)
if permissible_zones.is_empty:
permissible_zones = MultiPolygon([])
if not isinstance(permissible_zones, MultiPolygon):
permissible_zones = MultiPolygon([permissible_zones])
self.permissible_zones = permissible_zones
preferred_lines = ip_direction_limit_wedge.intersection(
self.excluded_zones.boundary
).difference(self.home_bubble)
if preferred_lines.is_empty:
preferred_lines = MultiLineString([])
if not isinstance(preferred_lines, MultiLineString):
preferred_lines = MultiLineString([preferred_lines])
self.preferred_lines = preferred_lines
def find_best_join_point(self) -> Point:
if self.preferred_lines.is_empty:
join, _ = shapely.ops.nearest_points(self.permissible_zones, self.ip)
else:
join, _ = shapely.ops.nearest_points(self.preferred_lines, self.home)
return Point(join.x, join.y)

View File

@@ -1,42 +1,49 @@
from __future__ import annotations
import itertools
import logging
import random
import sys
import math
from collections import Iterator
from datetime import date, datetime, timedelta
from enum import Enum
from typing import Any, Dict, List
from typing import Any, List, Type, Union, cast, TYPE_CHECKING
from dcs.action import Coalition
from dcs.countries import Switzerland, UnitedNationsPeacekeepers, USAFAggressors
from dcs.country import Country
from dcs.mapping import Point
from dcs.task import CAP, CAS, PinpointStrike
from dcs.vehicles import AirDefence
from faker import Faker
from game import db
from game.inventory import GlobalAircraftInventory
from game.models.game_stats import GameStats
from game.plugins import LuaPluginManager
from gen import naming
from gen.ato import AirTaskingOrder
from gen.conflictgen import Conflict
from gen.flights.ai_flight_planner import CoalitionMissionPlanner
from gen.flights.closestairfields import ObjectiveDistanceCache
from gen.flights.flight import FlightType
from gen.ground_forces.ai_ground_planner import GroundPlanner
from . import persistency
from .campaignloader import CampaignAirWingConfig
from .coalition import Coalition
from .debriefing import Debriefing
from .event.event import Event, UnitsDeliveryEvent
from .event.event import Event
from .event.frontlineattack import FrontlineAttackEvent
from .factions.faction import Faction
from .income import Income
from .infos.information import Information
from .navmesh import NavMesh
from .procurement import ProcurementAi
from .profiling import logged_duration
from .settings import Settings
from .theater import ConflictTheater, ControlPoint, TheaterGroundObject
from game.theater.theatergroundobject import MissileSiteGroundObject
from .theater import ConflictTheater, ControlPoint
from .theater.bullseye import Bullseye
from .theater.transitnetwork import TransitNetwork, TransitNetworkBuilder
from .threatzones import ThreatZones
from .unitmap import UnitMap
from .weather import Conditions, TimeOfDay
if TYPE_CHECKING:
from .squadrons import AirWing
COMMISION_UNIT_VARIETY = 4
COMMISION_LIMITS_SCALE = 1.5
COMMISION_LIMITS_FACTORS = {
@@ -80,9 +87,10 @@ class TurnState(Enum):
class Game:
def __init__(
self,
player_name: str,
enemy_name: str,
player_faction: Faction,
enemy_faction: Faction,
theater: ConflictTheater,
air_wing_config: CampaignAirWingConfig,
start_date: datetime,
settings: Settings,
player_budget: float,
@@ -91,145 +99,136 @@ class Game:
self.settings = settings
self.events: List[Event] = []
self.theater = theater
self.player_name = player_name
self.player_country = db.FACTIONS[player_name].country
self.enemy_name = enemy_name
self.enemy_country = db.FACTIONS[enemy_name].country
self.turn = 0
# NB: This is the *start* date. It is never updated.
self.date = date(start_date.year, start_date.month, start_date.day)
self.game_stats = GameStats()
self.game_stats.update(self)
self.ground_planners: Dict[int, GroundPlanner] = {}
self.informations = []
self.informations.append(Information("Game Start", "-" * 40, 0))
self.notes = ""
self.ground_planners: dict[int, GroundPlanner] = {}
self.informations: list[Information] = []
self.message("Game Start", "-" * 40)
# Culling Zones are for areas around points of interest that contain things we may not wish to cull.
self.__culling_zones: List[Point] = []
# Culling Points are for individual theater ground objects that we don't wish to cull.
self.__culling_points: List[Point] = []
self.__destroyed_units: List[str] = []
self.__destroyed_units: list[dict[str, Union[float, str]]] = []
self.savepath = ""
self.budget = player_budget
self.enemy_budget = enemy_budget
self.current_unit_id = 0
self.current_group_id = 0
self.name_generator = naming.namegen
self.conditions = self.generate_conditions()
self.blue_ato = AirTaskingOrder()
self.red_ato = AirTaskingOrder()
self.sanitize_sides(player_faction, enemy_faction)
self.blue = Coalition(self, player_faction, player_budget, player=True)
self.red = Coalition(self, enemy_faction, enemy_budget, player=False)
self.blue.set_opponent(self.red)
self.red.set_opponent(self.blue)
self.aircraft_inventory = GlobalAircraftInventory(self.theater.controlpoints)
for control_point in self.theater.controlpoints:
control_point.finish_init(self)
self.sanitize_sides()
self.blue.configure_default_air_wing(air_wing_config)
self.red.configure_default_air_wing(air_wing_config)
self.on_load()
self.on_load(game_still_initializing=True)
# Turn 0 procurement. We don't actually have any missions to plan, but
# the planner will tell us what it would like to plan so we can use that
# to drive purchase decisions.
blue_planner = CoalitionMissionPlanner(self, is_player=True)
blue_planner.plan_missions()
red_planner = CoalitionMissionPlanner(self, is_player=False)
red_planner.plan_missions()
self.plan_procurement(blue_planner, red_planner)
def __getstate__(self) -> Dict[str, Any]:
state = self.__dict__.copy()
# Avoid persisting any volatile types that can be deterministically
# recomputed on load for the sake of save compatibility.
del state["blue_threat_zone"]
del state["red_threat_zone"]
del state["blue_navmesh"]
del state["red_navmesh"]
return state
def __setstate__(self, state: Dict[str, Any]) -> None:
def __setstate__(self, state: dict[str, Any]) -> None:
self.__dict__.update(state)
# Regenerate any state that was not persisted.
self.on_load()
@property
def coalitions(self) -> Iterator[Coalition]:
yield self.blue
yield self.red
def ato_for(self, player: bool) -> AirTaskingOrder:
return self.coalition_for(player).ato
def transit_network_for(self, player: bool) -> TransitNetwork:
return self.coalition_for(player).transit_network
def generate_conditions(self) -> Conditions:
return Conditions.generate(
self.theater, self.current_day, self.current_turn_time_of_day, self.settings
)
def sanitize_sides(self):
@staticmethod
def sanitize_sides(player_faction: Faction, enemy_faction: Faction) -> None:
"""
Make sure the opposing factions are using different countries
:return:
"""
if self.player_country == self.enemy_country:
if self.player_country == "USA":
self.enemy_country = "USAF Aggressors"
elif self.player_country == "Russia":
self.enemy_country = "USSR"
if player_faction.country == enemy_faction.country:
if player_faction.country == "USA":
enemy_faction.country = "USAF Aggressors"
elif player_faction.country == "Russia":
enemy_faction.country = "USSR"
else:
self.enemy_country = "Russia"
@property
def player_faction(self) -> Faction:
return db.FACTIONS[self.player_name]
@property
def enemy_faction(self) -> Faction:
return db.FACTIONS[self.enemy_name]
enemy_faction.country = "Russia"
def faction_for(self, player: bool) -> Faction:
if player:
return self.player_faction
return self.enemy_faction
return self.coalition_for(player).faction
def _roll(self, prob, mult):
if self.settings.version == "dev":
# always generate all events for dev
return 100
else:
return random.randint(1, 100) <= prob * mult
def faker_for(self, player: bool) -> Faker:
return self.coalition_for(player).faker
def _generate_player_event(self, event_class, player_cp, enemy_cp):
def air_wing_for(self, player: bool) -> AirWing:
return self.coalition_for(player).air_wing
def country_for(self, player: bool) -> str:
return self.coalition_for(player).country_name
def bullseye_for(self, player: bool) -> Bullseye:
return self.coalition_for(player).bullseye
def _generate_player_event(
self, event_class: Type[Event], player_cp: ControlPoint, enemy_cp: ControlPoint
) -> None:
self.events.append(
event_class(
self,
player_cp,
enemy_cp,
enemy_cp.position,
self.player_name,
self.enemy_name,
self.blue.faction.name,
self.red.faction.name,
)
)
def _generate_events(self):
for front_line in self.theater.conflicts(True):
@property
def neutral_country(self) -> Type[Country]:
"""Return the best fitting country that can be used as neutral faction in the generated mission"""
countries_in_use = [self.red.country_name, self.blue.country_name]
if UnitedNationsPeacekeepers not in countries_in_use:
return UnitedNationsPeacekeepers
elif Switzerland.name not in countries_in_use:
return Switzerland
else:
return USAFAggressors
def _generate_events(self) -> None:
for front_line in self.theater.conflicts():
self._generate_player_event(
FrontlineAttackEvent,
front_line.control_point_a,
front_line.control_point_b,
front_line.blue_cp,
front_line.red_cp,
)
def adjust_budget(self, amount: float, player: bool) -> None:
def coalition_for(self, player: bool) -> Coalition:
if player:
self.budget += amount
else:
self.enemy_budget += amount
return self.blue
return self.red
def process_player_income(self):
self.budget += Income(self, player=True).total
def adjust_budget(self, amount: float, player: bool) -> None:
self.coalition_for(player).adjust_budget(amount)
def process_enemy_income(self):
# TODO: Clean up save compat.
if not hasattr(self, "enemy_budget"):
self.enemy_budget = 0
self.enemy_budget += Income(self, player=False).total
def initiate_event(self, event: Event) -> UnitMap:
@staticmethod
def initiate_event(event: Event) -> UnitMap:
# assert event in self.events
logging.info("Generating {} (regular)".format(event))
return event.generate()
def finish_event(self, event: Event, debriefing: Debriefing):
def finish_event(self, event: Event, debriefing: Debriefing) -> None:
logging.info("Finishing event {}".format(event))
event.commit(debriefing)
@@ -238,52 +237,92 @@ class Game:
else:
logging.info("finish_event: event not in the events!")
def is_player_attack(self, event):
if isinstance(event, Event):
return (
event
and event.attacker_name
and event.attacker_name == self.player_name
)
else:
raise RuntimeError(f"{event} was passed when an Event type was expected")
def on_load(self) -> None:
def on_load(self, game_still_initializing: bool = False) -> None:
if not hasattr(self, "name_generator"):
self.name_generator = naming.namegen
# Hack: Replace the global name generator state with the state from the save
# game.
#
# We need to persist this state so that names generated after game load don't
# conflict with those generated before exit.
naming.namegen = self.name_generator
LuaPluginManager.load_settings(self.settings)
ObjectiveDistanceCache.set_theater(self.theater)
self.compute_conflicts_position()
self.compute_threat_zones()
self.compute_unculled_zones()
if not game_still_initializing:
self.compute_threat_zones()
def pass_turn(self, no_action: bool = False) -> None:
logging.info("Pass turn")
self.informations.append(
Information("End of turn #" + str(self.turn), "-" * 40, 0)
)
def finish_turn(self, skipped: bool = False) -> None:
"""Finalizes the current turn and advances to the next turn.
This handles the turn-end portion of passing a turn. Initialization of the next
turn is handled by `initialize_turn`. These are separate processes because while
turns may be initialized more than once under some circumstances (see the
documentation for `initialize_turn`), `finish_turn` performs the work that
should be guaranteed to happen only once per turn:
* Turn counter increment.
* Delivering units ordered the previous turn.
* Transfer progress.
* Squadron replenishment.
* Income distribution.
* Base strength (front line position) adjustment.
* Weather/time-of-day generation.
Some actions (like transit network assembly) will happen both here and in
`initialize_turn`. We need the network to be up to date so we can account for
base captures when processing the transfers that occurred last turn, but we also
need it to be up to date in the case of a re-initialization in `initialize_turn`
(such as to account for a cheat base capture) so that orders are only placed
where a supply route exists to the destination. This is a relatively cheap
operation so duplicating the effort is not a problem.
Args:
skipped: True if the turn was skipped.
"""
self.message("End of turn #" + str(self.turn), "-" * 40)
self.turn += 1
# The coalition-specific turn finalization *must* happen before unit deliveries,
# since the coalition-specific finalization handles transit network updates and
# transfer processing. If in the other order, units may be delivered to captured
# bases, and freshly delivered units will spawn one leg through their journey.
self.blue.end_turn()
self.red.end_turn()
for control_point in self.theater.controlpoints:
control_point.process_turn(self)
self.process_enemy_income()
self.process_player_income()
if not no_action and self.turn > 1:
if not skipped:
for cp in self.theater.player_points():
cp.base.affect_strength(+PLAYER_BASE_STRENGTH_RECOVERY)
else:
for cp in self.theater.player_points():
if not cp.is_carrier and not cp.is_lha:
cp.base.affect_strength(-PLAYER_BASE_STRENGTH_RECOVERY)
self.conditions = self.generate_conditions()
def begin_turn_0(self) -> None:
"""Initialization for the first turn of the game."""
self.blue.preinit_turn_0()
self.red.preinit_turn_0()
self.initialize_turn()
def pass_turn(self, no_action: bool = False) -> None:
"""Ends the current turn and initializes the new turn.
Called both when skipping a turn or by ending the turn as the result of combat.
Args:
no_action: True if the turn was skipped.
"""
logging.info("Pass turn")
with logged_duration("Turn finalization"):
self.finish_turn(no_action)
with logged_duration("Turn initialization"):
self.initialize_turn()
# Autosave progress
persistency.autosave(self)
def check_win_loss(self):
def check_win_loss(self) -> TurnState:
player_airbases = {
cp for cp in self.theater.player_points() if cp.runway_is_operational()
}
@@ -298,76 +337,81 @@ class Game:
return TurnState.CONTINUE
def initialize_turn(self) -> None:
def set_bullseye(self) -> None:
player_cp, enemy_cp = self.theater.closest_opposing_control_points()
self.blue.bullseye = Bullseye(enemy_cp.position)
self.red.bullseye = Bullseye(player_cp.position)
def initialize_turn(self, for_red: bool = True, for_blue: bool = True) -> None:
"""Performs turn initialization for the specified players.
Turn initialization performs all of the beginning-of-turn actions. *End-of-turn*
processing happens in `pass_turn` (despite the name, it's called both for
skipping the turn and ending the turn after combat).
Special care needs to be taken here because initialization can occur more than
once per turn. A number of events can require re-initializing a turn:
* Cheat capture. Bases changing hands invalidates many missions in both ATOs,
purchase orders, threat zones, transit networks, etc. Practically speaking,
after a base capture the turn needs to be treated as fully new. The game might
even be over after a capture.
* Cheat front line position. CAS missions are no longer in the correct location,
and the ground planner may also need changes.
* Selling/buying units at TGOs. Selling a TGO might leave missions in the ATO
with invalid targets. Buying a new SAM (or even replacing some units in a SAM)
potentially changes the threat zone and may alter mission priorities and
flight planning.
Most of the work is delegated to initialize_turn_for, which handles the
coalition-specific turn initialization. In some cases only one coalition will be
(re-) initialized. This is the case when buying or selling TGO units, since we
don't want to force the player to redo all their planning just because they
repaired a SAM, but should replan opfor when that happens. On the other hand,
base captures are significant enough (and likely enough to be the first thing
the player does in a turn) that we replan blue as well. Front lines are less
impactful but also likely to be early, so they also cause a blue replan.
Args:
for_red: True if opfor should be re-initialized.
for_blue: True if the player coalition should be re-initialized.
"""
self.events = []
self._generate_events()
self.set_bullseye()
# Update statistics
self.game_stats.update(self)
self.aircraft_inventory.reset()
for cp in self.theater.controlpoints:
self.aircraft_inventory.set_from_control_point(cp)
# Check for win or loss condition
turn_state = self.check_win_loss()
if turn_state in (TurnState.LOSS, TurnState.WIN):
return self.process_win_loss(turn_state)
# Plan flights & combat for next turn
self.compute_conflicts_position()
self.compute_threat_zones()
with logged_duration("Threat zone computation"):
self.compute_threat_zones()
# Plan Coalition specific turn
if for_blue:
self.blue.initialize_turn()
if for_red:
self.red.initialize_turn()
# Plan GroundWar
self.ground_planners = {}
self.blue_ato.clear()
self.red_ato.clear()
blue_planner = CoalitionMissionPlanner(self, is_player=True)
blue_planner.plan_missions()
red_planner = CoalitionMissionPlanner(self, is_player=False)
red_planner.plan_missions()
for cp in self.theater.controlpoints:
if cp.has_frontline:
gplanner = GroundPlanner(cp, self)
gplanner.plan_groundwar()
self.ground_planners[cp.id] = gplanner
self.plan_procurement(blue_planner, red_planner)
# Update cull zones
with logged_duration("Computing culling positions"):
self.compute_unculled_zones()
def plan_procurement(
self,
blue_planner: CoalitionMissionPlanner,
red_planner: CoalitionMissionPlanner,
) -> None:
# The first turn needs to buy a *lot* of aircraft to fill CAPs, so it
# gets much more of the budget that turn. Otherwise budget (after
# repairs) is split evenly between air and ground. For the default
# starting budget of 2000 this gives 600 to ground forces and 1400 to
# aircraft.
ground_portion = 0.3 if self.turn == 0 else 0.5
self.budget = ProcurementAi(
self,
for_player=True,
faction=self.player_faction,
manage_runways=self.settings.automate_runway_repair,
manage_front_line=self.settings.automate_front_line_reinforcements,
manage_aircraft=self.settings.automate_aircraft_reinforcements,
front_line_budget_share=ground_portion,
).spend_budget(self.budget, blue_planner.procurement_requests)
self.enemy_budget = ProcurementAi(
self,
for_player=False,
faction=self.enemy_faction,
manage_runways=True,
manage_front_line=True,
manage_aircraft=True,
front_line_budget_share=ground_portion,
).spend_budget(self.enemy_budget, red_planner.procurement_requests)
def message(self, text: str) -> None:
self.informations.append(Information(text, turn=self.turn))
def message(self, title: str, text: str = "") -> None:
self.informations.append(Information(title, text, turn=self.turn))
@property
def current_turn_time_of_day(self) -> TimeOfDay:
@@ -377,63 +421,49 @@ class Game:
def current_day(self) -> date:
return self.date + timedelta(days=self.turn // 4)
def next_unit_id(self):
def next_unit_id(self) -> int:
"""
Next unit id for pre-generated units
"""
self.current_unit_id += 1
return self.current_unit_id
def next_group_id(self):
def next_group_id(self) -> int:
"""
Next unit id for pre-generated units
"""
self.current_group_id += 1
return self.current_group_id
def compute_transit_network_for(self, player: bool) -> TransitNetwork:
return TransitNetworkBuilder(self.theater, player).build()
def compute_threat_zones(self) -> None:
self.blue_threat_zone = ThreatZones.for_faction(self, player=True)
self.red_threat_zone = ThreatZones.for_faction(self, player=False)
self.blue_navmesh = NavMesh.from_threat_zones(
self.red_threat_zone, self.theater
)
self.red_navmesh = NavMesh.from_threat_zones(
self.blue_threat_zone, self.theater
)
self.blue.compute_threat_zones()
self.red.compute_threat_zones()
self.blue.compute_nav_meshes()
self.red.compute_nav_meshes()
def threat_zone_for(self, player: bool) -> ThreatZones:
if player:
return self.blue_threat_zone
return self.red_threat_zone
return self.coalition_for(player).threat_zone
def navmesh_for(self, player: bool) -> NavMesh:
if player:
return self.blue_navmesh
return self.red_navmesh
return self.coalition_for(player).nav_mesh
def compute_conflicts_position(self):
def compute_unculled_zones(self) -> None:
"""
Compute the current conflict center position(s), mainly used for culling calculation
:return: List of points of interests
Compute the current conflict position(s) used for culling calculation
"""
zones = []
points = []
# By default, use the existing frontline conflict position
for front_line in self.theater.conflicts():
position = Conflict.frontline_position(
front_line.control_point_a, front_line.control_point_b, self.theater
)
position = Conflict.frontline_position(front_line, self.theater)
zones.append(position[0])
zones.append(front_line.control_point_a.position)
zones.append(front_line.control_point_b.position)
zones.append(front_line.blue_cp.position)
zones.append(front_line.red_cp.position)
for cp in self.theater.controlpoints:
# Don't cull missile sites - their range is long enough to make them
# easily culled despite being a threat.
for tgo in cp.ground_objects:
if isinstance(tgo, MissileSiteGroundObject):
points.append(tgo.position)
# If do_not_cull_carrier is enabled, add carriers as culling point
if self.settings.perf_do_not_cull_carrier:
if cp.is_carrier or cp.is_lha:
@@ -442,7 +472,7 @@ class Game:
# If there is no conflict take the center point between the two nearest opposing bases
if len(zones) == 0:
cpoint = None
min_distance = sys.maxsize
min_distance = math.inf
for cp in self.theater.player_points():
for cp2 in self.theater.enemy_points():
d = cp.position.distance_to_point(cp2.position)
@@ -460,7 +490,7 @@ class Game:
if cpoint is not None:
zones.append(cpoint)
packages = itertools.chain(self.blue_ato.packages, self.red_ato.packages)
packages = itertools.chain(self.blue.ato.packages, self.red.ato.packages)
for package in packages:
if package.primary_task is FlightType.BARCAP:
# BARCAPs will be planned at most locations on smaller theaters,
@@ -477,75 +507,39 @@ class Game:
zones.append(Point(0, 0))
self.__culling_zones = zones
self.__culling_points = points
def add_destroyed_units(self, data):
pos = Point(data["x"], data["z"])
def add_destroyed_units(self, data: dict[str, Union[float, str]]) -> None:
pos = Point(cast(float, data["x"]), cast(float, data["z"]))
if self.theater.is_on_land(pos):
self.__destroyed_units.append(data)
def get_destroyed_units(self):
def get_destroyed_units(self) -> list[dict[str, Union[float, str]]]:
return self.__destroyed_units
def position_culled(self, pos):
def position_culled(self, pos: Point) -> bool:
"""
Check if unit can be generated at given position depending on culling performance settings
:param pos: Position you are tryng to spawn stuff at
:return: True if units can not be added at given position
"""
if self.settings.perf_culling == False:
if not self.settings.perf_culling:
return False
else:
for z in self.__culling_zones:
if (
z.distance_to_point(pos)
< self.settings.perf_culling_distance * 1000
):
return False
for p in self.__culling_points:
if p.distance_to_point(pos) < 2500:
return False
return True
for z in self.__culling_zones:
if z.distance_to_point(pos) < self.settings.perf_culling_distance * 1000:
return False
return True
def get_culling_zones(self):
def get_culling_zones(self) -> list[Point]:
"""
Check culling points
:return: List of culling zones
"""
return self.__culling_zones
def get_culling_points(self):
"""
Check culling points
:return: List of culling points
"""
return self.__culling_points
# 1 = red, 2 = blue
def get_player_coalition_id(self):
return 2
def get_enemy_coalition_id(self):
return 1
def get_player_coalition(self):
return Coalition.Blue
def get_enemy_coalition(self):
return Coalition.Red
def get_player_color(self):
return "blue"
def get_enemy_color(self):
return "red"
def process_win_loss(self, turn_state: TurnState):
def process_win_loss(self, turn_state: TurnState) -> None:
if turn_state is TurnState.WIN:
return self.message(
"Congratulations, you are victorious! Start a new campaign to continue."
self.message(
"Congratulations, you are victorious! Start a new campaign to continue."
)
elif turn_state is TurnState.LOSS:
return self.message(
"Game Over, you lose. Start a new campaign to continue."
)
self.message("Game Over, you lose. Start a new campaign to continue.")

150
game/groundunitorders.py Normal file
View File

@@ -0,0 +1,150 @@
from __future__ import annotations
import logging
from collections import defaultdict
from typing import Optional, TYPE_CHECKING
from game.theater import ControlPoint
from .coalition import Coalition
from .dcs.groundunittype import GroundUnitType
from .theater.transitnetwork import (
NoPathError,
TransitNetwork,
)
from .transfers import TransferOrder
if TYPE_CHECKING:
from .game import Game
class GroundUnitOrders:
def __init__(self, destination: ControlPoint) -> None:
self.destination = destination
# Maps unit type to order quantity.
self.units: dict[GroundUnitType, int] = defaultdict(int)
def __str__(self) -> str:
return f"Pending ground unit delivery to {self.destination}"
def order(self, units: dict[GroundUnitType, int]) -> None:
for k, v in units.items():
self.units[k] += v
def sell(self, units: dict[GroundUnitType, int]) -> None:
for k, v in units.items():
self.units[k] -= v
if self.units[k] == 0:
del self.units[k]
def refund_all(self, coalition: Coalition) -> None:
self._refund(coalition, self.units)
self.units = defaultdict(int)
def _refund(self, coalition: Coalition, units: dict[GroundUnitType, int]) -> None:
for unit_type, count in units.items():
logging.info(f"Refunding {count} {unit_type} at {self.destination.name}")
coalition.adjust_budget(unit_type.price * count)
def pending_orders(self, unit_type: GroundUnitType) -> int:
pending_units = self.units.get(unit_type)
if pending_units is None:
pending_units = 0
return pending_units
def process(self, game: Game) -> None:
coalition = game.coalition_for(self.destination.captured)
ground_unit_source = self.find_ground_unit_source(game)
if ground_unit_source is None:
game.message(
f"{self.destination.name} lost its source for ground unit "
"reinforcements. Refunding purchase price."
)
self.refund_all(coalition)
bought_units: dict[GroundUnitType, int] = {}
units_needing_transfer: dict[GroundUnitType, int] = {}
for unit_type, count in self.units.items():
allegiance = "Ally" if self.destination.captured else "Enemy"
d: dict[GroundUnitType, int]
if self.destination != ground_unit_source:
source = ground_unit_source
d = units_needing_transfer
else:
source = self.destination
d = bought_units
if count < 0:
logging.error(
f"Attempted sale of {unit_type} at {self.destination} but ground "
"units cannot be sold"
)
elif count > 0:
d[unit_type] = count
game.message(
f"{allegiance} reinforcements: {unit_type} x {count} at {source}"
)
self.units = defaultdict(int)
self.destination.base.commission_units(bought_units)
if units_needing_transfer:
if ground_unit_source is None:
raise RuntimeError(
f"Ground unit source could not be found for {self.destination} but "
"still tried to transfer units to there"
)
ground_unit_source.base.commission_units(units_needing_transfer)
self.create_transfer(coalition, ground_unit_source, units_needing_transfer)
def create_transfer(
self,
coalition: Coalition,
source: ControlPoint,
units: dict[GroundUnitType, int],
) -> None:
coalition.transfers.new_transfer(TransferOrder(source, self.destination, units))
def find_ground_unit_source(self, game: Game) -> Optional[ControlPoint]:
# This is running *after* the turn counter has been incremented, so this is the
# reaction to turn 0. On turn zero we allow units to be recruited anywhere for
# delivery on turn 1 so that turn 1 always starts with units on the front line.
if game.turn == 1:
return self.destination
# Fast path if the destination is a valid source.
if self.destination.can_recruit_ground_units(game):
return self.destination
try:
return self.find_ground_unit_source_in_network(
game.transit_network_for(self.destination.captured), game
)
except NoPathError:
return None
def find_ground_unit_source_in_network(
self, network: TransitNetwork, game: Game
) -> Optional[ControlPoint]:
sources = []
for control_point in game.theater.control_points_for(self.destination.captured):
if control_point.can_recruit_ground_units(
game
) and network.has_path_between(self.destination, control_point):
sources.append(control_point)
if not sources:
return None
# Fast path to skip the distance calculation if we have only one option.
if len(sources) == 1:
return sources[0]
closest = sources[0]
_, cost = network.shortest_path_with_cost(self.destination, closest)
for source in sources:
_, new_cost = network.shortest_path_with_cost(self.destination, source)
if new_cost < cost:
closest = source
cost = new_cost
return closest

127
game/htn.py Normal file
View File

@@ -0,0 +1,127 @@
from __future__ import annotations
from abc import ABC, abstractmethod
from collections import Iterator, deque, Sequence
from dataclasses import dataclass
from typing import Any, Generic, Optional, TypeVar
WorldStateT = TypeVar("WorldStateT", bound="WorldState[Any]")
class WorldState(ABC, Generic[WorldStateT]):
@abstractmethod
def clone(self) -> WorldStateT:
...
class Task(Generic[WorldStateT]):
pass
Method = Sequence[Task[WorldStateT]]
class PrimitiveTask(Task[WorldStateT], Generic[WorldStateT], ABC):
@abstractmethod
def preconditions_met(self, state: WorldStateT) -> bool:
...
@abstractmethod
def apply_effects(self, state: WorldStateT) -> None:
...
class CompoundTask(Task[WorldStateT], Generic[WorldStateT], ABC):
@abstractmethod
def each_valid_method(self, state: WorldStateT) -> Iterator[Method[WorldStateT]]:
...
PrimitiveTaskT = TypeVar("PrimitiveTaskT", bound=PrimitiveTask[Any])
@dataclass
class PlanningState(Generic[WorldStateT, PrimitiveTaskT]):
state: WorldStateT
tasks_to_process: deque[Task[WorldStateT]]
plan: list[PrimitiveTaskT]
methods: Optional[Iterator[Method[WorldStateT]]]
@dataclass(frozen=True)
class PlanningResult(Generic[WorldStateT, PrimitiveTaskT]):
tasks: list[PrimitiveTaskT]
end_state: WorldStateT
class PlanningHistory(Generic[WorldStateT, PrimitiveTaskT]):
def __init__(self) -> None:
self.states: list[PlanningState[WorldStateT, PrimitiveTaskT]] = []
def push(self, planning_state: PlanningState[WorldStateT, PrimitiveTaskT]) -> None:
self.states.append(planning_state)
def pop(self) -> PlanningState[WorldStateT, PrimitiveTaskT]:
return self.states.pop()
class Planner(Generic[WorldStateT, PrimitiveTaskT]):
def __init__(self, main_task: Task[WorldStateT]) -> None:
self.main_task = main_task
def plan(
self, initial_state: WorldStateT
) -> Optional[PlanningResult[WorldStateT, PrimitiveTaskT]]:
planning_state: PlanningState[WorldStateT, PrimitiveTaskT] = PlanningState(
initial_state, deque([self.main_task]), [], None
)
history: PlanningHistory[WorldStateT, PrimitiveTaskT] = PlanningHistory()
while planning_state.tasks_to_process:
task = planning_state.tasks_to_process.popleft()
if isinstance(task, PrimitiveTask):
if task.preconditions_met(planning_state.state):
task.apply_effects(planning_state.state)
# Ignore type erasure. We've already verified that this is a Planner
# with a WorldStateT and a PrimitiveTaskT, so we know that the task
# list is a list of CompoundTask[WorldStateT] and PrimitiveTaskT. We
# could scatter more unions throughout to be more explicit but
# there's no way around the type erasure that mypy uses for
# isinstance.
planning_state.plan.append(task) # type: ignore
else:
planning_state = history.pop()
else:
assert isinstance(task, CompoundTask)
# If the methods field of our current state is not None that means we're
# resuming a prior attempt to execute this task after a subtask of the
# previously selected method failed.
#
# Otherwise this is the first exectution of this task so we need to
# create the generator.
if planning_state.methods is None:
methods = task.each_valid_method(planning_state.state)
else:
methods = planning_state.methods
try:
method = next(methods)
# Push the current node back onto the stack so that we resume
# handling this task when we pop back to this state.
resume_tasks: deque[Task[WorldStateT]] = deque([task])
resume_tasks.extend(planning_state.tasks_to_process)
history.push(
PlanningState(
planning_state.state.clone(),
resume_tasks,
planning_state.plan,
methods,
)
)
planning_state.methods = None
planning_state.tasks_to_process.extendleft(reversed(method))
except StopIteration:
try:
planning_state = history.pop()
except IndexError:
# No valid plan was found.
return None
return PlanningResult(planning_state.plan, planning_state.state)

View File

@@ -14,10 +14,10 @@ class BuildingIncome:
name: str
category: str
number: int
income_per_building: int
income_per_building: float
@property
def income(self) -> int:
def income(self) -> float:
return self.number * self.income_per_building

View File

@@ -2,13 +2,13 @@ import datetime
class Information:
def __init__(self, title="", text="", turn=0):
def __init__(self, title: str = "", text: str = "", turn: int = 0) -> None:
self.title = title
self.text = text
self.turn = turn
self.timestamp = datetime.datetime.now()
def __str__(self):
def __str__(self) -> str:
return "[{}][{}] {} {}".format(
self.timestamp.strftime("%Y-%m-%d %H:%M:%S")
if self.timestamp is not None

View File

@@ -1,130 +0,0 @@
"""Inventory management APIs."""
from __future__ import annotations
from collections import defaultdict
from typing import Dict, Iterable, Iterator, Set, Tuple, TYPE_CHECKING, Type
from dcs.unittype import FlyingType
from gen.flights.flight import Flight
if TYPE_CHECKING:
from game.theater import ControlPoint
class ControlPointAircraftInventory:
"""Aircraft inventory for a single control point."""
def __init__(self, control_point: ControlPoint) -> None:
self.control_point = control_point
self.inventory: Dict[Type[FlyingType], int] = defaultdict(int)
def add_aircraft(self, aircraft: Type[FlyingType], count: int) -> None:
"""Adds aircraft to the inventory.
Args:
aircraft: The type of aircraft to add.
count: The number of aircraft to add.
"""
self.inventory[aircraft] += count
def remove_aircraft(self, aircraft: Type[FlyingType], count: int) -> None:
"""Removes aircraft from the inventory.
Args:
aircraft: The type of aircraft to remove.
count: The number of aircraft to remove.
Raises:
ValueError: The control point cannot fulfill the requested number of
aircraft.
"""
available = self.inventory[aircraft]
if available < count:
raise ValueError(
f"Cannot remove {count} {aircraft.id} from "
f"{self.control_point.name}. Only have {available}."
)
self.inventory[aircraft] -= count
def available(self, aircraft: Type[FlyingType]) -> int:
"""Returns the number of available aircraft of the given type.
Args:
aircraft: The type of aircraft to query.
"""
try:
return self.inventory[aircraft]
except KeyError:
return 0
@property
def types_available(self) -> Iterator[Type[FlyingType]]:
"""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]]:
"""Iterates over all available aircraft types, including amounts."""
for aircraft, count in self.inventory.items():
if count > 0:
yield aircraft, count
def clear(self) -> None:
"""Clears all aircraft from the inventory."""
self.inventory.clear()
class GlobalAircraftInventory:
"""Game-wide aircraft inventory."""
def __init__(self, control_points: Iterable[ControlPoint]) -> None:
self.inventories: Dict[ControlPoint, ControlPointAircraftInventory] = {
cp: ControlPointAircraftInventory(cp) for cp in control_points
}
def reset(self) -> None:
"""Clears all control points and their inventories."""
for inventory in self.inventories.values():
inventory.clear()
def set_from_control_point(self, control_point: ControlPoint) -> None:
"""Set the control point's aircraft inventory.
If the inventory for the given control point has already been set for
the turn, it will be overwritten.
"""
inventory = self.inventories[control_point]
for aircraft, count in control_point.base.aircraft.items():
inventory.add_aircraft(aircraft, count)
def for_control_point(
self, control_point: ControlPoint
) -> ControlPointAircraftInventory:
"""Returns the inventory specific to the given control point."""
return self.inventories[control_point]
@property
def available_types_for_player(self) -> Iterator[Type[FlyingType]]:
"""Iterates over all aircraft types available to the player."""
seen: Set[Type[FlyingType]] = set()
for control_point, inventory in self.inventories.items():
if control_point.captured:
for aircraft in inventory.types_available:
if not control_point.can_operate(aircraft):
continue
if aircraft not in seen:
seen.add(aircraft)
yield aircraft
def claim_for_flight(self, flight: Flight) -> None:
"""Removes aircraft from the inventory for the given flight."""
inventory = self.for_control_point(flight.from_cp)
inventory.remove_aircraft(flight.unit_type, flight.count)
def return_from_flight(self, flight: Flight) -> None:
"""Returns a flight's aircraft to the inventory."""
inventory = self.for_control_point(flight.from_cp)
inventory.add_aircraft(flight.unit_type, flight.count)

View File

@@ -1,13 +0,0 @@
class DestroyedUnit:
"""
Store info about a destroyed unit
"""
x: int
y: int
name: str
def __init__(self, x, y, name):
self.x = x
self.y = y
self.name = name

View File

@@ -1,13 +0,0 @@
from game.theater import ControlPoint
class FrontlineData:
"""
This Data structure will store information about an existing frontline
"""
def __init__(self, from_cp: ControlPoint, to_cp: ControlPoint):
self.to_cp = to_cp
self.from_cp = from_cp
self.enemy_units_position = []
self.blue_units_position = []

View File

@@ -1,4 +1,9 @@
from typing import List
from __future__ import annotations
from typing import List, TYPE_CHECKING
if TYPE_CHECKING:
from game import Game
class FactionTurnMetadata:
@@ -10,7 +15,7 @@ class FactionTurnMetadata:
vehicles_count: int = 0
sam_count: int = 0
def __init__(self):
def __init__(self) -> None:
self.aircraft_count = 0
self.vehicles_count = 0
self.sam_count = 0
@@ -24,7 +29,7 @@ class GameTurnMetadata:
allied_units: FactionTurnMetadata
enemy_units: FactionTurnMetadata
def __init__(self):
def __init__(self) -> None:
self.allied_units = FactionTurnMetadata()
self.enemy_units = FactionTurnMetadata()
@@ -34,23 +39,29 @@ class GameStats:
Store statistics for the current game
"""
def __init__(self):
def __init__(self) -> None:
self.data_per_turn: List[GameTurnMetadata] = []
def update(self, game):
def update(self, game: Game) -> None:
"""
Save data for current turn
:param game: Game we want to save the data about
"""
# Remove the current turn if its just an update for this turn
if 0 < game.turn < len(self.data_per_turn):
del self.data_per_turn[-1]
turn_data = GameTurnMetadata()
for cp in game.theater.controlpoints:
if cp.captured:
turn_data.allied_units.aircraft_count += sum(cp.base.aircraft.values())
for squadron in cp.squadrons:
turn_data.allied_units.aircraft_count += squadron.owned_aircraft
turn_data.allied_units.vehicles_count += sum(cp.base.armor.values())
else:
turn_data.enemy_units.aircraft_count += sum(cp.base.aircraft.values())
for squadron in cp.squadrons:
turn_data.enemy_units.aircraft_count += squadron.owned_aircraft
turn_data.enemy_units.vehicles_count += sum(cp.base.armor.values())
self.data_per_turn.append(turn_data)

View File

@@ -103,7 +103,7 @@ class NavMesh:
# currently.
p = ShapelyPoint(point.x, point.y)
for navpoly in self.polys:
if navpoly.poly.contains(p):
if navpoly.poly.intersects(p):
return navpoly
return None

View File

@@ -1,10 +1,9 @@
from __future__ import annotations
from game.theater.theatergroundobject import TheaterGroundObject
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING, Iterable, List, Optional, Set
from typing import List, Set, TYPE_CHECKING, cast
from dcs import Mission
from dcs.action import DoScript, DoScriptFile
@@ -14,25 +13,33 @@ from dcs.lua.parse import loads
from dcs.mapping import Point
from dcs.translation import String
from dcs.triggers import TriggerStart
from game.plugins import LuaPluginManager
from gen import Conflict, FlightType, VisualGenerator
from gen.aircraft import AIRCRAFT_DATA, AircraftConflictGenerator, FlightData
from game.theater.theatergroundobject import TheaterGroundObject
from gen.aircraft import AircraftConflictGenerator, FlightData
from gen.airfields import AIRFIELD_DATA
from gen.airsupportgen import AirSupport, AirSupportConflictGenerator
from gen.armor import GroundConflictGenerator, JtacInfo
from gen.airsupport import AirSupport
from gen.airsupportgen import AirSupportConflictGenerator
from gen.armor import GroundConflictGenerator
from gen.beacons import load_beacons_for_terrain
from gen.briefinggen import BriefingGenerator, MissionInfoGenerator
from gen.cargoshipgen import CargoShipGenerator
from gen.conflictgen import Conflict
from gen.convoygen import ConvoyGenerator
from gen.environmentgen import EnvironmentGenerator
from gen.flights.flight import FlightType
from gen.forcedoptionsgen import ForcedOptionsGenerator
from gen.groundobjectsgen import GroundObjectsGenerator
from gen.kneeboard import KneeboardGenerator
from gen.lasercoderegistry import LaserCodeRegistry
from gen.naming import namegen
from gen.radios import RadioFrequency, RadioRegistry
from gen.tacan import TacanRegistry
from gen.tacan import TacanRegistry, TacanUsage
from gen.triggergen import TRIGGER_RADIUS_MEDIUM, TriggersGenerator
from gen.visualgen import VisualGenerator
from .. import db
from ..theater import Airfield
from ..theater import Airfield, FrontLine
from ..theater.bullseye import Bullseye
from ..unitmap import UnitMap
if TYPE_CHECKING:
@@ -42,18 +49,14 @@ if TYPE_CHECKING:
class Operation:
"""Static class for managing the final Mission generation"""
current_mission = None # type: Mission
airgen = None # type: AircraftConflictGenerator
triggersgen = None # type: TriggersGenerator
airsupportgen = None # type: AirSupportConflictGenerator
visualgen = None # type: VisualGenerator
groundobjectgen = None # type: GroundObjectsGenerator
briefinggen = None # type: BriefingGenerator
forcedoptionsgen = None # type: ForcedOptionsGenerator
radio_registry: Optional[RadioRegistry] = None
tacan_registry: Optional[TacanRegistry] = None
game = None # type: Game
environment_settings = None
current_mission: Mission
airgen: AircraftConflictGenerator
airsupportgen: AirSupportConflictGenerator
groundobjectgen: GroundObjectsGenerator
radio_registry: RadioRegistry
tacan_registry: TacanRegistry
laser_code_registry: LaserCodeRegistry
game: Game
trigger_radius = TRIGGER_RADIUS_MEDIUM
is_quick = None
player_awacs_enabled = True
@@ -61,33 +64,18 @@ class Operation:
enemy_awacs_enabled = True
ca_slots = 1
unit_map: UnitMap
jtacs: List[JtacInfo] = []
plugin_scripts: List[str] = []
air_support = AirSupport()
@classmethod
def prepare(cls, game: Game):
with open("resources/default_options.lua", "r") as f:
def prepare(cls, game: Game) -> None:
with open("resources/default_options.lua", "r", encoding="utf-8") as f:
options_dict = loads(f.read())["options"]
cls._set_mission(Mission(game.theater.terrain))
cls.game = game
cls._setup_mission_coalitions()
cls.current_mission.options.load_from_dict(options_dict)
@classmethod
def conflicts(cls) -> Iterable[Conflict]:
assert cls.game
for frontline in cls.game.theater.conflicts():
yield Conflict(
cls.game.theater,
frontline.control_point_a,
frontline.control_point_b,
cls.game.player_name,
cls.game.enemy_name,
cls.game.player_country,
cls.game.enemy_country,
frontline.position,
)
@classmethod
def air_conflict(cls) -> Conflict:
assert cls.game
@@ -98,12 +86,11 @@ class Operation:
)
return Conflict(
cls.game.theater,
player_cp,
enemy_cp,
cls.game.player_name,
cls.game.enemy_name,
cls.game.player_country,
cls.game.enemy_country,
FrontLine(player_cp, enemy_cp),
cls.game.blue.faction.name,
cls.game.red.faction.name,
cls.current_mission.country(cls.game.blue.country_name),
cls.current_mission.country(cls.game.red.country_name),
mid_point,
)
@@ -112,12 +99,19 @@ class Operation:
cls.current_mission = mission
@classmethod
def _setup_mission_coalitions(cls):
cls.current_mission.coalition["blue"] = Coalition("blue")
cls.current_mission.coalition["red"] = Coalition("red")
def _setup_mission_coalitions(cls) -> None:
cls.current_mission.coalition["blue"] = Coalition(
"blue", bullseye=cls.game.blue.bullseye.to_pydcs()
)
cls.current_mission.coalition["red"] = Coalition(
"red", bullseye=cls.game.red.bullseye.to_pydcs()
)
cls.current_mission.coalition["neutrals"] = Coalition(
"neutrals", bullseye=Bullseye(Point(0, 0)).to_pydcs()
)
p_country = cls.game.player_country
e_country = cls.game.enemy_country
p_country = cls.game.blue.country_name
e_country = cls.game.red.country_name
cls.current_mission.coalition["blue"].add_country(
country_dict[db.country_id_from_name(p_country)]()
)
@@ -125,6 +119,16 @@ class Operation:
country_dict[db.country_id_from_name(e_country)]()
)
belligerents = [
db.country_id_from_name(p_country),
db.country_id_from_name(e_country),
]
for country in country_dict.keys():
if country not in belligerents:
cls.current_mission.coalition["neutrals"].add_country(
country_dict[country]()
)
@classmethod
def inject_lua_trigger(cls, contents: str, comment: str) -> None:
trigger = TriggerStart(comment=comment)
@@ -161,10 +165,9 @@ class Operation:
def notify_info_generators(
cls,
groundobjectgen: GroundObjectsGenerator,
airsupportgen: AirSupportConflictGenerator,
jtacs: List[JtacInfo],
air_support: AirSupport,
airgen: AircraftConflictGenerator,
):
) -> None:
"""Generates subscribed MissionInfoGenerator objects (currently kneeboards and briefings)"""
gens: List[MissionInfoGenerator] = [
@@ -175,14 +178,17 @@ class Operation:
for dynamic_runway in groundobjectgen.runways.values():
gen.add_dynamic_runway(dynamic_runway)
for tanker in airsupportgen.air_support.tankers:
gen.add_tanker(tanker)
for tanker in air_support.tankers:
if tanker.blue:
gen.add_tanker(tanker)
for aewc in airsupportgen.air_support.awacs:
gen.add_awacs(aewc)
for aewc in air_support.awacs:
if aewc.blue:
gen.add_awacs(aewc)
for jtac in jtacs:
gen.add_jtac(jtac)
for jtac in air_support.jtacs:
if jtac.blue:
gen.add_jtac(jtac)
for flight in airgen.flights:
gen.add_flight(flight)
@@ -205,6 +211,10 @@ class Operation:
for frequency in unique_map_frequencies:
cls.radio_registry.reserve(frequency)
@classmethod
def create_laser_code_registry(cls) -> None:
cls.laser_code_registry = LaserCodeRegistry()
@classmethod
def assign_channels_to_flights(
cls, flights: List[FlightData], air_support: AirSupport
@@ -213,23 +223,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(
@@ -248,7 +242,7 @@ class Operation:
if beacon.channel is None:
logging.error(f"TACAN beacon has no channel: {beacon.callsign}")
else:
cls.tacan_registry.reserve(beacon.tacan_channel)
cls.tacan_registry.mark_unavailable(beacon.tacan_channel)
@classmethod
def _create_radio_registry(
@@ -265,7 +259,7 @@ class Operation:
# beacon list.
@classmethod
def _generate_ground_units(cls):
def _generate_ground_units(cls) -> None:
cls.groundobjectgen = GroundObjectsGenerator(
cls.current_mission,
cls.game,
@@ -280,18 +274,23 @@ class Operation:
"""Add destroyed units to the Mission"""
for d in cls.game.get_destroyed_units():
try:
utype = db.unit_type_from_name(d["type"])
type_name = d["type"]
if not isinstance(type_name, str):
raise TypeError(
"Expected the type of the destroyed static to be a string"
)
utype = db.unit_type_from_name(type_name)
except KeyError:
continue
pos = Point(d["x"], d["z"])
pos = Point(cast(float, d["x"]), cast(float, d["z"]))
if (
utype is not None
and not cls.game.position_culled(pos)
and cls.game.settings.perf_destroyed_units
):
cls.current_mission.static_group(
country=cls.current_mission.country(cls.game.player_country),
country=cls.current_mission.country(cls.game.blue.country_name),
name="",
_type=utype,
hidden=True,
@@ -303,17 +302,22 @@ class Operation:
@classmethod
def generate(cls) -> UnitMap:
"""Build the final Mission to be exported"""
cls.air_support = AirSupport()
cls.create_unit_map()
cls.create_radio_registries()
cls.create_laser_code_registry()
# Set mission time and weather conditions.
EnvironmentGenerator(cls.current_mission, cls.game.conditions).generate()
cls._generate_ground_units()
cls._generate_transports()
cls._generate_destroyed_units()
# Generate ground conflicts first so the JTACs get the first laser code (1688)
# rather than the first player flight with a TGP.
cls._generate_ground_conflicts()
cls._generate_air_units()
cls.assign_channels_to_flights(
cls.airgen.flights, cls.airsupportgen.air_support
)
cls._generate_ground_conflicts()
# Triggers
triggersgen = TriggersGenerator(cls.current_mission, cls.game)
@@ -321,13 +325,8 @@ class Operation:
# Setup combined arms parameters
cls.current_mission.groundControl.pilot_can_control_vehicles = cls.ca_slots > 0
if cls.game.player_country in [
country.name
for country in cls.current_mission.coalition["blue"].countries.values()
]:
cls.current_mission.groundControl.blue_tactical_commander = cls.ca_slots
else:
cls.current_mission.groundControl.red_tactical_commander = cls.ca_slots
cls.current_mission.groundControl.blue_tactical_commander = cls.ca_slots
cls.current_mission.groundControl.blue_observer = 1
# Options
forcedoptionsgen = ForcedOptionsGenerator(cls.current_mission, cls.game)
@@ -338,7 +337,7 @@ class Operation:
if cls.game.settings.perf_smoke_gen:
visualgen.generate()
cls.generate_lua(cls.airgen, cls.airsupportgen, cls.jtacs)
cls.generate_lua(cls.airgen, cls.air_support)
# Inject Plugins Lua Scripts and data
cls.plugin_scripts.clear()
@@ -350,9 +349,7 @@ class Operation:
cls.assign_channels_to_flights(
cls.airgen.flights, cls.airsupportgen.air_support
)
cls.notify_info_generators(
cls.groundobjectgen, cls.airsupportgen, cls.jtacs, cls.airgen
)
cls.notify_info_generators(cls.groundobjectgen, cls.air_support, cls.airgen)
cls.reset_naming_ids()
return cls.unit_map
@@ -368,6 +365,7 @@ class Operation:
cls.game,
cls.radio_registry,
cls.tacan_registry,
cls.air_support,
)
cls.airsupportgen.generate()
@@ -377,40 +375,42 @@ class Operation:
cls.game.settings,
cls.game,
cls.radio_registry,
cls.tacan_registry,
cls.laser_code_registry,
cls.unit_map,
air_support=cls.airsupportgen.air_support,
helipads=cls.groundobjectgen.helipads,
)
cls.airgen.clear_parking_slots()
cls.airgen.generate_flights(
cls.current_mission.country(cls.game.player_country),
cls.game.blue_ato,
cls.current_mission.country(cls.game.blue.country_name),
cls.game.blue.ato,
cls.groundobjectgen.runways,
)
cls.airgen.generate_flights(
cls.current_mission.country(cls.game.enemy_country),
cls.game.red_ato,
cls.current_mission.country(cls.game.red.country_name),
cls.game.red.ato,
cls.groundobjectgen.runways,
)
cls.airgen.spawn_unused_aircraft(
cls.current_mission.country(cls.game.player_country),
cls.current_mission.country(cls.game.enemy_country),
cls.current_mission.country(cls.game.blue.country_name),
cls.current_mission.country(cls.game.red.country_name),
)
@classmethod
def _generate_ground_conflicts(cls) -> None:
"""For each frontline in the Operation, generate the ground conflicts and JTACs"""
for front_line in cls.game.theater.conflicts(True):
player_cp = front_line.control_point_a
enemy_cp = front_line.control_point_b
for front_line in cls.game.theater.conflicts():
player_cp = front_line.blue_cp
enemy_cp = front_line.red_cp
conflict = Conflict.frontline_cas_conflict(
cls.game.player_name,
cls.game.enemy_name,
cls.current_mission.country(cls.game.player_country),
cls.current_mission.country(cls.game.enemy_country),
player_cp,
enemy_cp,
cls.game.blue.faction.name,
cls.game.red.faction.name,
cls.current_mission.country(cls.game.blue.country_name),
cls.current_mission.country(cls.game.red.country_name),
front_line,
cls.game.theater,
)
# Generate frontline ops
@@ -423,21 +423,27 @@ class Operation:
player_gp,
enemy_gp,
player_cp.stances[enemy_cp.id],
enemy_cp.stances[player_cp.id],
cls.unit_map,
cls.radio_registry,
cls.air_support,
cls.laser_code_registry,
)
ground_conflict_gen.generate()
cls.jtacs.extend(ground_conflict_gen.jtacs)
@classmethod
def reset_naming_ids(cls):
def _generate_transports(cls) -> None:
"""Generates convoys for unit transfers by road."""
ConvoyGenerator(cls.current_mission, cls.game, cls.unit_map).generate()
CargoShipGenerator(cls.current_mission, cls.game, cls.unit_map).generate()
@classmethod
def reset_naming_ids(cls) -> None:
namegen.reset_numbers()
@classmethod
def generate_lua(
cls,
airgen: AircraftConflictGenerator,
airsupportgen: AirSupportConflictGenerator,
jtacs: List[JtacInfo],
cls, airgen: AircraftConflictGenerator, air_support: AirSupport
) -> None:
# TODO: Refactor this
luaData = {
@@ -450,32 +456,32 @@ class Operation:
"BlueAA": {},
} # type: ignore
for tanker in airsupportgen.air_support.tankers:
luaData["Tankers"][tanker.callsign] = {
"dcsGroupName": tanker.dcsGroupName,
for i, tanker in enumerate(air_support.tankers):
luaData["Tankers"][i] = {
"dcsGroupName": tanker.group_name,
"callsign": tanker.callsign,
"variant": tanker.variant,
"radio": tanker.freq.mhz,
"tacan": str(tanker.tacan.number) + tanker.tacan.band.name,
}
if airsupportgen.air_support.awacs:
for awacs in airsupportgen.air_support.awacs:
luaData["AWACs"][awacs.callsign] = {
"dcsGroupName": awacs.dcsGroupName,
"callsign": awacs.callsign,
"radio": awacs.freq.mhz,
}
for i, awacs in enumerate(air_support.awacs):
luaData["AWACs"][i] = {
"dcsGroupName": awacs.group_name,
"callsign": awacs.callsign,
"radio": awacs.freq.mhz,
}
for jtac in jtacs:
luaData["JTACs"][jtac.callsign] = {
"dcsGroupName": jtac.dcsGroupName,
for i, jtac in enumerate(air_support.jtacs):
luaData["JTACs"][i] = {
"dcsGroupName": jtac.group_name,
"callsign": jtac.callsign,
"zone": jtac.region,
"dcsUnit": jtac.unit_name,
"laserCode": jtac.code,
"radio": jtac.freq.mhz,
}
flight_count = 0
for flight in airgen.flights:
if flight.friendly and flight.flight_type in [
FlightType.ANTISHIP,
@@ -496,7 +502,7 @@ class Operation:
elif hasattr(flightTarget, "name"):
flightTargetName = flightTarget.name
flightTargetType = flightType + " TGT (Airbase)"
luaData["TargetPoints"][flightTargetName] = {
luaData["TargetPoints"][flight_count] = {
"name": flightTargetName,
"type": flightTargetType,
"position": {
@@ -504,6 +510,7 @@ class Operation:
"y": flightTarget.position.y,
},
}
flight_count += 1
for cp in cls.game.theater.controlpoints:
for ground_object in cp.ground_objects:
@@ -589,8 +596,8 @@ class Operation:
zone = data["zone"]
laserCode = data["laserCode"]
dcsUnit = data["dcsUnit"]
lua += f" {{dcsGroupName='{dcsGroupName}', callsign='{callsign}', zone='{zone}', laserCode='{laserCode}', dcsUnit='{dcsUnit}' }}, \n"
# lua += f" {{name='{dcsGroupName}', description='JTAC {callsign} ', information='Laser:{laserCode}', jtac={laserCode} }}, \n"
radio = data["radio"]
lua += f" {{dcsGroupName='{dcsGroupName}', callsign='{callsign}', zone={repr(zone)}, laserCode='{laserCode}', dcsUnit='{dcsUnit}', radio='{radio}' }}, \n"
lua += "}"
# Process the Target Points

Some files were not shown because too many files have changed in this diff Show More