def main() -> None:
    if liberation_install.init():
        print("Set up Liberation first.")
        return

    args = parse_args()
    terrain = ARG_TO_TERRAIN_MAP[args.map]
    mission = create_mission(terrain)
    with mission_scripting():
        input(
            f"Created {mission} and replaced MissionScript.lua. Open DCS and load the "
            "mission. Once the mission starts running, close it and press enter."
        )
    coords_path = Path(persistency.base_path()) / "coords.json"
    parameters = compute_tmerc_parameters(coords_path, args.map)
    out_file = THIS_DIR.parent.parent / "game/theater" / f"{args.map}.py"
    out_file.write_text(
        textwrap.dedent(f"""\
            from game.theater.projections import TransverseMercator

            PARAMETERS = TransverseMercator(
                central_meridian={parameters.central_meridian},
                false_easting={parameters.false_easting},
                false_northing={parameters.false_northing},
                scale_factor={parameters.scale_factor},
            )
            """))
示例#2
0
def create_game(
    campaign_path: Path,
    blue: str,
    red: str,
    supercarrier: bool,
    auto_procurement: bool,
    inverted: bool,
    cheats: bool,
) -> Game:
    first_start = liberation_install.init()
    if first_start:
        sys.exit(
            "Cannot generate campaign without configuring DCS Liberation. Start the UI "
            "for the first run configuration.")

    # This needs to run before the pydcs payload cache is created, which happens
    # extremely early. It's not a problem that we inject these paths twice because we'll
    # get the same answers each time.
    #
    # Without this, it is not possible to use next turn (or anything that needs to check
    # for loadouts) without saving the generated campaign and reloading it the normal
    # way.
    inject_custom_payloads(Path(persistency.base_path()))
    campaign = Campaign.from_json(campaign_path)
    generator = GameGenerator(
        FACTIONS[blue],
        FACTIONS[red],
        campaign.load_theater(),
        Settings(
            supercarrier=supercarrier,
            automate_runway_repair=auto_procurement,
            automate_front_line_reinforcements=auto_procurement,
            automate_aircraft_reinforcements=auto_procurement,
            enable_frontline_cheats=cheats,
            enable_base_capture_cheat=cheats,
        ),
        GeneratorSettings(
            start_date=datetime.today(),
            player_budget=DEFAULT_BUDGET,
            enemy_budget=DEFAULT_BUDGET,
            midgame=False,
            inverted=inverted,
            no_carrier=False,
            no_lha=False,
            no_player_navy=False,
            no_enemy_navy=False,
        ),
        ModSettings(
            a4_skyhawk=False,
            f22_raptor=False,
            hercules=False,
            jas39_gripen=False,
            su57_felon=False,
            frenchpack=False,
            high_digit_sams=False,
        ),
    )
    return generator.generate()
    def load_factions(cls: Type[FactionLoader]) -> Dict[str, Faction]:
        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:
            try:
                with f.open("r", encoding="utf-8") as fdata:
                    data = json.load(fdata)
                    factions[data["name"]] = Faction.from_json(data)
                    logging.info("Loaded faction : " + str(f))
            except Exception:
                logging.exception(f"Unable to load faction : {f}")

        return factions
示例#4
0
 def load_templates(self) -> None:
     """This will load all pre-loaded layouts from a pickle file.
     If pickle can not be loaded it will import and dump the layouts"""
     # We use a pickle for performance reasons. Importing takes many seconds
     file = Path(persistency.base_path()) / TEMPLATE_DUMP
     if file.is_file():
         # Load from pickle if existing
         with file.open("rb") as f:
             try:
                 version, self._layouts = pickle.load(f)
                 # Check if the game version of the dump is identical to the current
                 if version == VERSION:
                     return
             except Exception as e:
                 logging.exception(
                     f"Error {e} reading layouts dump. Recreating.")
     # If no dump is available or game version is different create a new dump
     self.import_templates()
示例#5
0
    def squadron_directories() -> Iterator[Path]:
        from game import persistency

        yield Path(persistency.base_path()) / "Liberation/Squadrons"
        yield Path("resources/squadrons")
示例#6
0
def run_ui(game: Optional[Game] = None) -> None:
    os.environ[
        "QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"  # Potential fix for 4K screens
    app = QApplication(sys.argv)

    # init the theme and load the stylesheet based on the theme index
    liberation_theme.init()
    with open("./resources/stylesheets/" +
              liberation_theme.get_theme_css_file()) as stylesheet:
        logging.info('Loading stylesheet: %s',
                     liberation_theme.get_theme_css_file())
        app.setStyleSheet(stylesheet.read())

    # Inject custom payload in pydcs framework
    custom_payloads = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   "..\\resources\\customized_payloads")
    if os.path.exists(custom_payloads):
        dcs.unittype.FlyingType.payload_dirs.append(custom_payloads)
    else:
        # For release version the path is different.
        custom_payloads = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "resources\\customized_payloads")
        if os.path.exists(custom_payloads):
            dcs.unittype.FlyingType.payload_dirs.append(custom_payloads)

    first_start = liberation_install.init()
    if first_start:
        window = QLiberationFirstStartWindow()
        window.exec_()

    logging.info("Using {} as 'Saved Game Folder'".format(
        persistency.base_path()))
    logging.info("Using {} as 'DCS installation folder'".format(
        liberation_install.get_dcs_install_directory()))

    # Splash screen setup
    pixmap = QPixmap("./resources/ui/splash_screen.png")
    splash = QSplashScreen(pixmap)
    splash.show()

    # Once splash screen is up : load resources & setup stuff
    uiconstants.load_icons()
    uiconstants.load_event_icons()
    uiconstants.load_aircraft_icons()
    uiconstants.load_vehicle_icons()
    uiconstants.load_aircraft_banners()
    uiconstants.load_vehicle_banners()

    # Replace DCS Mission scripting file to allow DCS Liberation to work
    try:
        liberation_install.replace_mission_scripting_file()
    except:
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.setWindowTitle("Wrong DCS installation directory.")
        error_dialog.showMessage(
            "Unable to modify Mission Scripting file. Possible issues with rights. Try running as admin, or please perform the modification of the MissionScripting file manually."
        )
        error_dialog.exec_()

    # Apply CSS (need works)
    GameUpdateSignal()

    # Start window
    window = QLiberationWindow(game)
    window.showMaximized()
    splash.finish(window)
    qt_execution_code = app.exec_()

    # Restore Mission Scripting file
    logging.info("QT App terminated with status code : " +
                 str(qt_execution_code))
    logging.info("Attempt to restore original mission scripting file")
    liberation_install.restore_original_mission_scripting()
    logging.info("QT process exited with code : " + str(qt_execution_code))
示例#7
0
 def debriefing_directory_location(self) -> str:
     return os.path.join(base_path(), "liberation_debriefings")
示例#8
0
        dcs.planes.FlyingType.payload_dirs.append(custom_payloads)
    else:
        # For release version the path is different.
        custom_payloads = os.path.join(
            os.path.dirname(os.path.realpath(__file__)),
            "resources\\customized_payloads")
        if os.path.exists(custom_payloads):
            dcs.planes.FlyingType.payload_dirs.append(custom_payloads)

    first_start = liberation_install.init()
    if first_start:
        window = QLiberationFirstStartWindow()
        window.exec_()

    logging.info("Using {} as 'Saved Game Folder'".format(
        persistency.base_path()))
    logging.info("Using {} as 'DCS installation folder'".format(
        liberation_install.get_dcs_install_directory()))

    # Splash screen setup
    pixmap = QPixmap("./resources/ui/splash_screen.png")
    splash = QSplashScreen(pixmap)
    splash.show()

    # Once splash screen is up : load resources & setup stuff
    uiconstants.load_icons()
    uiconstants.load_event_icons()
    uiconstants.load_aircraft_icons()
    uiconstants.load_vehicle_icons()

    # Replace DCS Mission scripting file to allow DCS Liberation to work
示例#9
0
def run_ui(game: Game | None, dev: bool) -> None:
    os.environ[
        "QT_ENABLE_HIGHDPI_SCALING"] = "1"  # Potential fix for 4K screens
    QApplication.setHighDpiScaleFactorRoundingPolicy(
        Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)

    app = QApplication(sys.argv)

    app.setAttribute(Qt.AA_DisableWindowContextHelpButton)
    app.setAttribute(Qt.AA_EnableHighDpiScaling,
                     True)  # enable highdpi scaling
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)  # use highdpi icons

    # init the theme and load the stylesheet based on the theme index
    liberation_theme.init()
    with open(
            "./resources/stylesheets/" + liberation_theme.get_theme_css_file(),
            encoding="utf-8",
    ) as stylesheet:
        logging.info("Loading stylesheet: %s",
                     liberation_theme.get_theme_css_file())
        app.setStyleSheet(stylesheet.read())

    first_start = liberation_install.init()
    if first_start:
        window = QLiberationFirstStartWindow()
        window.exec_()

    logging.info("Using {} as 'Saved Game Folder'".format(
        persistency.base_path()))
    logging.info("Using {} as 'DCS installation folder'".format(
        liberation_install.get_dcs_install_directory()))

    inject_custom_payloads(Path(persistency.base_path()))

    # Splash screen setup
    pixmap = QPixmap("./resources/ui/splash_screen.png")
    splash = QSplashScreen(pixmap)
    splash.show()

    # Developers are launching the game in a loop hundreds of times. We've read it.
    if not dev:
        # Give enough time to read splash screen
        time.sleep(3)

    # Once splash screen is up : load resources & setup stuff
    uiconstants.load_icons()
    uiconstants.load_event_icons()
    uiconstants.load_aircraft_icons()
    uiconstants.load_vehicle_icons()
    uiconstants.load_aircraft_banners()
    uiconstants.load_vehicle_banners()

    # Show warning if no DCS Installation directory was set
    if liberation_install.get_dcs_install_directory() == "":
        logging.warning(
            "DCS Installation directory is empty. MissionScripting file will not be replaced!"
        )
        if not liberation_install.ignore_empty_install_directory():
            ignore_checkbox = QCheckBox("Do not show again")
            ignore_checkbox.stateChanged.connect(
                set_ignore_empty_install_directory)
            message_box = QtWidgets.QMessageBox(parent=splash)
            message_box.setIcon(QtWidgets.QMessageBox.Icon.Warning)
            message_box.setWindowTitle("No DCS installation directory.")
            message_box.setText(
                "The DCS Installation directory is not set correctly. "
                "This will prevent DCS Liberation to work properly as the MissionScripting "
                "file will not be modified."
                "<br/><br/>To solve this problem, you can set the Installation directory "
                "within the preferences menu. You can also manually edit or replace the "
                "following file:"
                "<br/><br/><strong>&lt;dcs_installation_directory&gt;/Scripts/MissionScripting.lua</strong>"
                "<br/><br/>The easiest way to do it is to replace the original file with the file in dcs-liberation distribution (&lt;dcs_liberation_installation&gt;/resources/scripts/MissionScripting.lua)."
                "<br/><br/>You can find more information on how to manually change this file in the Liberation Wiki (Page: Dedicated Server Guide) on GitHub.</p>"
            )
            message_box.setDefaultButton(
                QtWidgets.QMessageBox.StandardButton.Ok)
            message_box.setCheckBox(ignore_checkbox)
            message_box.exec_()
    # Replace DCS Mission scripting file to allow DCS Liberation to work
    try:
        liberation_install.replace_mission_scripting_file()
    except:
        error_dialog = QtWidgets.QErrorMessage()
        error_dialog.setWindowTitle("Wrong DCS installation directory.")
        error_dialog.showMessage(
            "Unable to modify Mission Scripting file. Possible issues with rights. Try running as admin, or please perform the modification of the MissionScripting file manually."
        )
        error_dialog.exec_()

    # Apply CSS (need works)
    GameUpdateSignal()
    GameUpdateSignal.get_instance().game_loaded.connect(on_game_load)

    # Start window
    window = QLiberationWindow(game, dev)
    window.showMaximized()
    splash.finish(window)
    qt_execution_code = app.exec_()

    # Restore Mission Scripting file
    logging.info("QT App terminated with status code : " +
                 str(qt_execution_code))
    logging.info("Attempt to restore original mission scripting file")
    liberation_install.restore_original_mission_scripting()
    logging.info("QT process exited with code : " + str(qt_execution_code))
示例#10
0
 def _dump_templates(self) -> None:
     file = Path(persistency.base_path()) / TEMPLATE_DUMP
     dump = (VERSION, self._layouts)
     with file.open("wb") as fdata:
         pickle.dump(dump, fdata)