From 93ce94655dd89bb2aab704d9685d9e1424354b9f Mon Sep 17 00:00:00 2001 From: Dunedan Date: Tue, 30 Dec 2025 09:57:37 +0100 Subject: [PATCH] Use @stylistic/brace-style for eslint Up to now `eslint-plugin-brace-rules` was used to enforce a common brace style for JavaScript code. This plugin was however updated the last time over 9 years ago and will be incompatible with ESLint v10, as that [removes `context.getSourceCode()`][1], the plugin relies on. To keep the eslint config working with ESLint v10, this replaces `eslint-plugin-brace-rules` with the [`@stylistic/brace-style`][2] rule from `@stylistic/eslint-plugin`, a package we already use. While `@stylistic/brace-style` doesn't offer an option to format braces in exactly the same way as before, the "allman" style seems to be the one closest to the existing code. [1]: https://eslint.org/blog/2025/11/eslint-v10.0.0-alpha.0-released/#removed-deprecated-rule-context-members [2]: https://eslint.style/rules/brace-style --- .pre-commit-config.yaml | 5 +- .../data/mods/_test.gui/gui/event/event.js | 3 +- .../_test.scriptinterface/exception/catch.js | 2 +- .../_test.scriptinterface/promises/simple.js | 3 +- .../components/addentity/test-addentity.js | 6 +- .../simulation/components/test-entityid.js | 15 +- .../simulation/components/test-helper.js | 3 +- .../simulation/components/test-hotload1.js | 12 +- .../simulation/components/test-hotload2.js | 6 +- .../simulation/components/test-modding1.js | 6 +- .../simulation/components/test-modding2.js | 3 +- .../simulation/components/test-msg.js | 24 +- .../simulation/components/test-param.js | 24 +- .../simulation/components/test-query.js | 12 +- .../simulation/components/test-serialize.js | 48 +- .../_test.sim/simulation/components/test.js | 21 +- .../mods/mod/gui/colormixer/colormixer.js | 9 +- .../data/mods/mod/gui/common/utilities.js | 6 +- .../incompatible_mods/incompatible_mods.js | 3 +- binaries/data/mods/mod/gui/modio/modio.js | 39 +- .../data/mods/mod/gui/modmod/help/help.js | 3 +- binaries/data/mods/mod/gui/modmod/modmod.js | 3 +- .../mods/mod/gui/termsdialog/termsdialog.js | 15 +- binaries/data/mods/mod/hwdetect/test.js | 3 +- .../data/mods/mod/tools/dap/commands/dap.js | 21 +- .../data/mods/mod/tools/dap/daphandler.js | 20 +- .../data/mods/mod/tools/dap/jsdebugger.js | 52 +- binaries/data/mods/mod/tools/dap/logger.js | 27 +- .../mods/mod/tools/dap/managers/attach.js | 18 +- .../mods/mod/tools/dap/managers/breakpoint.js | 42 +- .../data/mods/mod/tools/dap/managers/frame.js | 51 +- .../mods/mod/tools/dap/managers/inspector.js | 38 +- .../mods/mod/tools/dap/managers/sources.js | 24 +- binaries/data/mods/mod/tools/dap/plugin.js | 6 +- .../mods/public/autostart/autostart_client.js | 2 +- .../mods/public/autostart/autostart_host.js | 2 +- .../mods/public/autostart/cmd_line_args.js | 3 +- .../gamesettings/attributes/PlayerColor.js | 3 +- .../gamesettings/attributes/PlayerName.js | 3 +- .../mods/public/globalscripts/DamageTypes.js | 3 +- .../globalscripts/ModificationTemplates.js | 62 +- .../mods/public/globalscripts/Templates.js | 9 +- .../campaigns/default_menu/CampaignMenu.js | 7 +- .../gui/campaigns/load_modal/LoadModal.js | 5 +- .../campaigns/new_modal/NewCampaignModal.js | 6 +- .../gui/campaigns/setup/CampaignSetupPage.js | 6 +- .../data/mods/public/gui/common/Observable.js | 3 +- .../data/mods/public/gui/common/Profilable.js | 6 +- .../mods/public/gui/common/campaigns/utils.js | 6 +- .../public/gui/common/functions_utility.js | 2 +- .../mods/public/gui/common/gamedescription.js | 3 +- .../data/mods/public/gui/common/network.js | 3 +- .../data/mods/public/gui/common/settings.js | 6 +- .../mods/public/gui/common/tab_buttons.js | 3 +- binaries/data/mods/public/gui/common/timer.js | 7 +- .../data/mods/public/gui/common/tooltips.js | 6 +- .../data/mods/public/gui/credits/credits.js | 6 +- .../Controllers/GameSettingsController.js | 10 +- .../GameSettings/GameSettingControlSlider.js | 3 +- .../GameSettings/PerPlayer/AIConfigButton.js | 3 +- .../PerPlayer/Dropdowns/PlayerAssignment.js | 4 +- .../PerPlayer/Dropdowns/PlayerColor.js | 3 +- .../Single/Dropdowns/MapSelection.js | 3 +- .../Single/Dropdowns/PopulationCap.js | 3 +- .../public/gui/gamesetup_mp/gamesetup_mp.js | 22 +- .../mods/public/gui/hotkeys/HotkeyMetadata.js | 3 +- .../mods/public/gui/hotkeys/HotkeyPicker.js | 21 +- .../mods/public/gui/hotkeys/HotkeysPage.js | 18 +- .../public/gui/loadgame/SavegameDeleter.js | 3 +- .../mods/public/gui/loadgame/SavegameList.js | 15 +- .../public/gui/loadgame/SavegameLoader.js | 3 +- .../mods/public/gui/loadgame/SavegamePage.js | 3 +- .../public/gui/loadgame/SavegameWriter.js | 9 +- .../AccountSettingsPage.js | 14 +- .../lobby/LeaderboardPage/LeaderboardList.js | 3 +- .../LobbyPage/Chat/ChatCommandHandler.js | 24 +- .../StatusMessages/StatusMessageEvents.js | 48 +- .../mods/public/gui/lobby/LobbyPage/Game.js | 2 +- .../public/gui/lobby/LobbyPage/GameList.js | 6 +- .../public/gui/lobby/LobbyPage/PlayerList.js | 3 +- binaries/data/mods/public/gui/lobby/lobby.js | 3 +- .../data/mods/public/gui/locale/locale.js | 6 +- .../gui/locale_advanced/locale_advanced.js | 6 +- .../data/mods/public/gui/manual/manual.js | 3 +- .../mapbrowser/controls/MapBrowserControls.js | 3 +- .../maps/mapbrowser/controls/MapFiltering.js | 3 +- .../gui/maps/mapbrowser/utils/MatchSort.js | 3 +- .../data/mods/public/gui/options/options.js | 66 +- .../public/gui/pregame/MainMenuItemHandler.js | 6 +- .../mods/public/gui/pregame/MainMenuItems.js | 73 +- .../mods/public/gui/pregame/MainMenuPage.js | 3 +- .../public/gui/pregame/ProjectInformation.js | 18 +- .../data/mods/public/gui/pregame/mainmenu.js | 3 +- .../gui/pregame/userreport/userreport.js | 9 +- .../gui/prelobby/common/feedback/feedback.js | 6 +- .../gui/prelobby/common/terms/termslobby.js | 6 +- .../public/gui/prelobby/entrance/entrance.js | 3 +- .../gui/reference/common/TemplateLoader.js | 3 +- .../gui/reference/tips/sections/TipDisplay.js | 3 +- .../mods/public/gui/reference/tips/tips.js | 3 +- .../public/gui/replaymenu/replay_filters.js | 9 +- .../mods/public/gui/replaymenu/replay_menu.js | 6 +- .../mods/public/gui/session/AutoFormation.js | 3 +- binaries/data/mods/public/gui/session/Menu.js | 6 +- .../mods/public/gui/session/PanelEntity.js | 3 +- .../public/gui/session/PanelEntityManager.js | 3 +- .../data/mods/public/gui/session/chat/Chat.js | 6 +- .../chat/ChatMessageFormatSimulation.js | 6 +- .../public/gui/session/chat/ChatWindow.js | 3 +- .../developer_overlay/DeveloperOverlay.js | 6 +- .../DeveloperOverlayControlCheckboxes.js | 3 +- .../data/mods/public/gui/session/input.js | 27 +- .../session/message_box/QuitConfirmation.js | 28 +- .../message_box/QuitConfirmationMenu.js | 24 +- .../message_box/QuitConfirmationReplay.js | 28 +- .../session/message_box/ResignConfirmation.js | 3 +- .../data/mods/public/gui/session/messages.js | 349 +- .../public/gui/session/minimap/MiniMap.js | 3 +- .../data/mods/public/gui/session/selection.js | 3 +- .../public/gui/session/selection_details.js | 9 +- .../public/gui/session/selection_panels.js | 33 +- .../gui/session/selection_panels_helpers.js | 30 +- .../data/mods/public/gui/session/session.js | 9 +- .../public/gui/session/trade/TradeButton.js | 6 +- .../gui/session/trade/TraderStatusText.js | 3 +- .../mods/public/gui/session/unit_actions.js | 3442 +++++++++-------- .../public/gui/splashscreen/splashscreen.js | 3 +- .../data/mods/public/gui/summary/counters.js | 3 +- .../data/mods/public/gui/summary/layout.js | 3 +- .../data/mods/public/gui/summary/summary.js | 12 +- .../public/maps/random/belgian_uplands.js | 6 +- .../public/maps/random/caledonian_meadows.js | 6 +- .../data/mods/public/maps/random/danubius.js | 6 +- .../public/maps/random/english_channel.js | 6 +- .../public/maps/random/fields_of_meroe.js | 6 +- .../mods/public/maps/random/flood_triggers.js | 3 +- .../public/maps/random/guadalquivir_river.js | 3 +- .../public/maps/random/hyrcanian_shores.js | 3 +- .../mods/public/maps/random/jebel_barkal.js | 6 +- .../maps/random/jebel_barkal_triggers.js | 3 +- .../data/mods/public/maps/random/kerala.js | 3 +- .../data/mods/public/maps/random/latium.js | 3 +- .../data/mods/public/maps/random/lions_den.js | 3 +- .../public/maps/random/polar_sea_triggers.js | 9 +- .../data/mods/public/maps/random/rivers.js | 3 +- .../public/maps/random/rmbiome/randombiome.js | 3 +- .../public/maps/random/rmgen-common/player.js | 12 +- .../public/maps/random/rmgen/TileClass.js | 3 +- .../mods/public/maps/random/rmgen/library.js | 12 +- .../maps/random/rmgen/painter/CityPainter.js | 3 +- .../random/rmgen/painter/LayeredPainter.js | 3 +- .../rmgen/painter/SmoothElevationPainter.js | 3 +- .../maps/random/tests/test_Constraint.js | 3 +- .../maps/random/tests/test_DiskPlacer.js | 3 +- .../maps/random/tests/test_LayeredPainter.js | 3 +- .../random/tests/test_RecoverableError.js | 2 +- .../maps/random/tests/test_RectPlacer.js | 3 +- .../random/tests/test_SmoothingPainter.js | 3 +- .../maps/random/tests/test_TileClass.js | 3 +- .../data/mods/public/maps/random/the_nile.js | 6 +- .../data/mods/public/maps/random/unknown.js | 36 +- .../scenarios/pickup_test_map_triggers.js | 3 +- .../scenarios/unit_chasing_test_triggers.js | 6 +- .../scenarios/unit_dancing_test_triggers.js | 24 +- .../scenarios/unit_motion_integration_test.js | 69 +- .../maps/scenarios/unit_pushing_test.js | 63 +- .../data/mods/public/maps/scripts/Regicide.js | 3 +- .../mods/public/maps/scripts/TriggerHelper.js | 3 +- .../maps/tutorials/introductory_tutorial.js | 9 +- .../public/simulation/ai/common-api/entity.js | 249 +- .../simulation/ai/common-api/filters.js | 6 +- .../simulation/ai/common-api/gamestate.js | 36 +- .../public/simulation/ai/petra/attackPlan.js | 27 +- .../public/simulation/ai/petra/baseManager.js | 42 +- .../simulation/ai/petra/basesManager.js | 9 +- .../mods/public/simulation/ai/petra/config.js | 208 +- .../simulation/ai/petra/defenseManager.js | 9 +- .../simulation/ai/petra/emergencyManager.js | 3 +- .../simulation/ai/petra/headquarters.js | 12 +- .../public/simulation/ai/petra/mapModule.js | 3 +- .../simulation/ai/petra/navalManager.js | 15 +- .../simulation/ai/petra/queueManager.js | 3 +- .../simulation/ai/petra/queueplanBuilding.js | 3 +- .../simulation/ai/petra/queueplanTraining.js | 3 +- .../simulation/ai/petra/startingStrategy.js | 9 +- .../simulation/ai/petra/tradeManager.js | 6 +- .../simulation/ai/petra/transportPlan.js | 3 +- .../simulation/ai/petra/victoryManager.js | 3 +- .../mods/public/simulation/ai/petra/worker.js | 15 +- .../simulation/components/AlertRaiser.js | 6 +- .../public/simulation/components/Attack.js | 9 +- .../public/simulation/components/Auras.js | 3 +- .../simulation/components/BuildingAI.js | 6 +- .../public/simulation/components/Formation.js | 20 +- .../simulation/components/GarrisonHolder.js | 3 +- .../simulation/components/GuiInterface.js | 9 +- .../simulation/components/ModifiersManager.js | 30 +- .../simulation/components/MotionBall.js | 6 +- .../components/PopulationCapManager.js | 3 +- .../simulation/components/SkirmishReplacer.js | 14 +- .../components/TechnologyManager.js | 6 +- .../components/TerritoryDecayManager.js | 2 +- .../public/simulation/components/Timer.js | 5 +- .../public/simulation/components/Trainer.js | 9 +- .../public/simulation/components/Trigger.js | 44 +- .../public/simulation/components/UnitAI.js | 810 ++-- .../simulation/components/tests/setup.js | 6 +- .../components/tests/test_Attack.js | 21 +- .../simulation/components/tests/test_Auras.js | 27 +- .../components/tests/test_Barter.js | 9 +- .../components/tests/test_Builder.js | 3 +- .../components/tests/test_Capturable.js | 39 +- .../components/tests/test_Damage.js | 57 +- .../components/tests/test_EntityLimits.js | 6 +- .../components/tests/test_Formation.js | 6 +- .../components/tests/test_Foundation.js | 36 +- .../components/tests/test_GarrisonHolder.js | 3 +- .../components/tests/test_Garrisoning.js | 3 +- .../components/tests/test_GuiInterface.js | 24 +- .../simulation/components/tests/test_Heal.js | 18 +- .../components/tests/test_Health.js | 3 +- .../simulation/components/tests/test_Loot.js | 15 +- .../components/tests/test_Looter.js | 6 +- .../components/tests/test_ModifiersManager.js | 3 +- .../simulation/components/tests/test_Pack.js | 3 +- .../components/tests/test_Player.js | 3 +- .../components/tests/test_RallyPoint.js | 18 +- .../components/tests/test_Researcher.js | 12 +- .../components/tests/test_Resistance.js | 30 +- .../components/tests/test_ResourceDropsite.js | 3 +- .../components/tests/test_ResourceGatherer.js | 27 +- .../components/tests/test_ResourceSupply.js | 3 +- .../components/tests/test_ResourceTrickle.js | 21 +- .../components/tests/test_Resources.js | 9 +- .../tests/test_StatusEffectsReceiver.js | 3 +- .../components/tests/test_Technologies.js | 12 +- .../tests/test_TechnologyManager.js | 9 +- .../simulation/components/tests/test_Timer.js | 6 +- .../components/tests/test_Trainer.js | 15 +- .../components/tests/test_Treasure.js | 3 +- .../components/tests/test_Treasures.js | 6 +- .../components/tests/test_TurretHolder.js | 6 +- .../components/tests/test_Turrets.js | 3 +- .../components/tests/test_UnitAI.js | 60 +- .../tests/test_UpgradeModification.js | 9 +- .../components/tests/test_Upkeep.js | 27 +- .../tests/test_ValueModificationHelper.js | 3 +- .../components/tests/test_VisionSharing.js | 3 +- .../public/simulation/helpers/Commands.js | 75 +- .../mods/public/simulation/helpers/Player.js | 3 +- .../simulation/helpers/tests/test_Attack.js | 30 +- binaries/data/tests/test_setup.js | 7 +- eslint.config.mjs | 36 +- package.json | 5 +- source/tools/profiler2/Profiler2Report.js | 23 +- source/tools/profiler2/ReportDraw.js | 17 +- source/tools/profiler2/profiler2.js | 8 +- source/tools/profiler2/utilities.js | 11 +- source/tools/replayprofile/graph.js | 9 +- 259 files changed, 4643 insertions(+), 3421 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b320bf2103..a980dcf2b0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -83,13 +83,12 @@ repos: args: - --strict - repo: https://github.com/eslint/eslint - rev: v9.33.0 + rev: v9.39.2 hooks: - id: eslint language_version: 22.14.0 additional_dependencies: - - eslint-plugin-brace-rules@0.1.6 - - "@stylistic/eslint-plugin@4.4.0" + - "@stylistic/eslint-plugin@5.6.1" args: - --max-warnings=0 - --no-warn-ignored diff --git a/binaries/data/mods/_test.gui/gui/event/event.js b/binaries/data/mods/_test.gui/gui/event/event.js index 4af0543af9..35b4fbe03d 100644 --- a/binaries/data/mods/_test.gui/gui/event/event.js +++ b/binaries/data/mods/_test.gui/gui/event/event.js @@ -6,7 +6,8 @@ var obj1 = Engine.GetGUIObjectByName("obj1"); var obj3 = Engine.GetGUIObjectByName("obj3"); obj1.onTick = () => { ++called1; }; -Engine.GetGUIObjectByName("obj2").onTick = () => { +Engine.GetGUIObjectByName("obj2").onTick = () => +{ ++called2; delete obj1.onTick; delete obj3.onTick; diff --git a/binaries/data/mods/_test.scriptinterface/exception/catch.js b/binaries/data/mods/_test.scriptinterface/exception/catch.js index ef716ea765..fc211de6cf 100644 --- a/binaries/data/mods/_test.scriptinterface/exception/catch.js +++ b/binaries/data/mods/_test.scriptinterface/exception/catch.js @@ -2,7 +2,7 @@ try { Engine.callback(); } -catch (e) +catch(e) { log(e.message); } diff --git a/binaries/data/mods/_test.scriptinterface/promises/simple.js b/binaries/data/mods/_test.scriptinterface/promises/simple.js index 7f4dcd4a92..2d036369a8 100644 --- a/binaries/data/mods/_test.scriptinterface/promises/simple.js +++ b/binaries/data/mods/_test.scriptinterface/promises/simple.js @@ -13,7 +13,8 @@ async function waitAndIncrement(promise) { let resolve; - const promise = new Promise(res => { + const promise = new Promise(res => + { incrementTest(); resolve = res; }); diff --git a/binaries/data/mods/_test.sim/simulation/components/addentity/test-addentity.js b/binaries/data/mods/_test.sim/simulation/components/addentity/test-addentity.js index 4fd0585196..8fed4738a8 100644 --- a/binaries/data/mods/_test.sim/simulation/components/addentity/test-addentity.js +++ b/binaries/data/mods/_test.sim/simulation/components/addentity/test-addentity.js @@ -2,11 +2,13 @@ function TestScript2A() {} TestScript2A.prototype.Schema = ""; -TestScript2A.prototype.Init = function() { +TestScript2A.prototype.Init = function() +{ this.x = eval(this.template.y); }; -TestScript2A.prototype.GetX = function() { +TestScript2A.prototype.GetX = function() +{ return this.x; }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-entityid.js b/binaries/data/mods/_test.sim/simulation/components/test-entityid.js index e245f2cb94..caccf01b35 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-entityid.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-entityid.js @@ -1,15 +1,20 @@ function TestScript1A() {} -TestScript1A.prototype.GetX = function() { +TestScript1A.prototype.GetX = function() +{ // Test that .entity is readonly - try { + try + { delete this.entity; Engine.TS_FAIL("Missed exception"); - } catch (e) { /* noop */ } - try { + } + catch(e) { /* noop */ } + try + { this.entity = -1; Engine.TS_FAIL("Missed exception"); - } catch (e) { /* noop */ } + } + catch(e) { /* noop */ } // and return the value return this.entity; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-helper.js b/binaries/data/mods/_test.sim/simulation/components/test-helper.js index ea491d4134..a4187d5333 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-helper.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-helper.js @@ -1,6 +1,7 @@ function TestScript1_Helper() {} -TestScript1_Helper.prototype.GetX = function() { +TestScript1_Helper.prototype.GetX = function() +{ return AdditionHelper(1, 2); }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-hotload1.js b/binaries/data/mods/_test.sim/simulation/components/test-hotload1.js index dcdd8b5313..1a41fccd93 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-hotload1.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-hotload1.js @@ -2,11 +2,13 @@ function HotloadA() {} HotloadA.prototype.Schema = ""; -HotloadA.prototype.Init = function() { +HotloadA.prototype.Init = function() +{ this.x = +this.template.x; }; -HotloadA.prototype.GetX = function() { +HotloadA.prototype.GetX = function() +{ return this.x; }; @@ -15,11 +17,13 @@ Engine.RegisterComponentType(IID_Test1, "HotloadA", HotloadA); function HotloadB() {} -HotloadB.prototype.Init = function() { +HotloadB.prototype.Init = function() +{ this.x = +this.template.x; }; -HotloadB.prototype.GetX = function() { +HotloadB.prototype.GetX = function() +{ return this.x * 2; }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-hotload2.js b/binaries/data/mods/_test.sim/simulation/components/test-hotload2.js index 0646ae6608..3323831462 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-hotload2.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-hotload2.js @@ -2,11 +2,13 @@ function HotloadA() {} HotloadA.prototype.Schema = ""; -HotloadA.prototype.Init = function() { +HotloadA.prototype.Init = function() +{ this.x = +this.template.x; }; -HotloadA.prototype.GetX = function() { +HotloadA.prototype.GetX = function() +{ return this.x*10; }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-modding1.js b/binaries/data/mods/_test.sim/simulation/components/test-modding1.js index e013d1bf64..fcdbedbe77 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-modding1.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-modding1.js @@ -2,11 +2,13 @@ function Modding() {} Modding.prototype.Schema = ""; -Modding.prototype.Init = function() { +Modding.prototype.Init = function() +{ this.x = +this.template.x; }; -Modding.prototype.GetX = function() { +Modding.prototype.GetX = function() +{ return this.x; }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-modding2.js b/binaries/data/mods/_test.sim/simulation/components/test-modding2.js index 4d6ee6a329..2e912d353b 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-modding2.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-modding2.js @@ -1,4 +1,5 @@ -Modding.prototype.GetX = function() { +Modding.prototype.GetX = function() +{ return this.x * 10; }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-msg.js b/binaries/data/mods/_test.sim/simulation/components/test-msg.js index f0271b71dd..8ff57a80db 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-msg.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-msg.js @@ -1,14 +1,17 @@ function TestScript1A() {} -TestScript1A.prototype.Init = function() { +TestScript1A.prototype.Init = function() +{ this.x = 100; }; -TestScript1A.prototype.GetX = function() { +TestScript1A.prototype.GetX = function() +{ return this.x; }; -TestScript1A.prototype.OnUpdate = function(msg) { +TestScript1A.prototype.OnUpdate = function(msg) +{ this.x += msg.turnLength; }; @@ -18,15 +21,18 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1A", TestScript1A); function TestScript1B() {} -TestScript1B.prototype.Init = function() { +TestScript1B.prototype.Init = function() +{ this.x = 100; }; -TestScript1B.prototype.GetX = function() { +TestScript1B.prototype.GetX = function() +{ return this.x; }; -TestScript1B.prototype.OnGlobalUpdate = function(msg) { +TestScript1B.prototype.OnGlobalUpdate = function(msg) +{ this.x += msg.turnLength; }; @@ -36,11 +42,13 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1B", TestScript1B); function TestScript2A() {} -TestScript2A.prototype.Init = function() { +TestScript2A.prototype.Init = function() +{ this.x = 200; }; -TestScript2A.prototype.GetX = function() { +TestScript2A.prototype.GetX = function() +{ Engine.BroadcastMessage(MT_Update, { "turnLength": 50 }); Engine.PostMessage(1, MT_Update, { "turnLength": 500 }); Engine.PostMessage(2, MT_Update, { "turnLength": 5000 }); diff --git a/binaries/data/mods/_test.sim/simulation/components/test-param.js b/binaries/data/mods/_test.sim/simulation/components/test-param.js index 3756c273e0..b25a3d3fe3 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-param.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-param.js @@ -1,6 +1,7 @@ function TestScript1_Init() {} -TestScript1_Init.prototype.Init = function() { +TestScript1_Init.prototype.Init = function() +{ var param = this.template; // print("# ",uneval(param),"\n"); if (param) @@ -9,7 +10,8 @@ TestScript1_Init.prototype.Init = function() { this.x = 100; }; -TestScript1_Init.prototype.GetX = function() { +TestScript1_Init.prototype.GetX = function() +{ return this.x; }; @@ -19,12 +21,18 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1_Init", TestScript1_Init); function TestScript1_readonly() {} -TestScript1_readonly.prototype.GetX = function() { - try { this.template = null; } catch (e) { /* noop */ } - try { delete this.template; } catch (e) { /* noop */ } - try { this.template.x += 1000; } catch (e) { /* noop */ } - try { delete this.template.x; } catch (e) { /* noop */ } - try { this.template.y = 2000; } catch (e) { /* noop */ } +TestScript1_readonly.prototype.GetX = function() +{ + try { this.template = null; } + catch(e) { /* noop */ } + try { delete this.template; } + catch(e) { /* noop */ } + try { this.template.x += 1000; } + catch(e) { /* noop */ } + try { delete this.template.x; } + catch(e) { /* noop */ } + try { this.template.y = 2000; } + catch(e) { /* noop */ } return +(this.template.x || 1) + +(this.template.y || 2); }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-query.js b/binaries/data/mods/_test.sim/simulation/components/test-query.js index c33be54e67..3045bcd63a 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-query.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-query.js @@ -1,10 +1,12 @@ function TestScript1A() {} -TestScript1A.prototype.Init = function() { +TestScript1A.prototype.Init = function() +{ this.x = 100; }; -TestScript1A.prototype.GetX = function() { +TestScript1A.prototype.GetX = function() +{ var test2 = Engine.QueryInterface(this.entity, IID_Test2); return test2.GetX() + (test2.x || 0); }; @@ -15,11 +17,13 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1A", TestScript1A); function TestScript2A() {} -TestScript2A.prototype.Init = function() { +TestScript2A.prototype.Init = function() +{ this.x = 200; }; -TestScript2A.prototype.GetX = function() { +TestScript2A.prototype.GetX = function() +{ return this.x; }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test-serialize.js b/binaries/data/mods/_test.sim/simulation/components/test-serialize.js index 9e572a58f2..a88b63df83 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test-serialize.js +++ b/binaries/data/mods/_test.sim/simulation/components/test-serialize.js @@ -1,12 +1,14 @@ function TestScript1_values() {} -TestScript1_values.prototype.Init = function() { +TestScript1_values.prototype.Init = function() +{ this.x = +this.template.x; this.str = "this is a string"; this.things = { "a": 1, "b": "2", "c": [3, "4", [5, []]] }; }; -TestScript1_values.prototype.GetX = function() { +TestScript1_values.prototype.GetX = function() +{ // print(uneval(this)); return this.x; }; @@ -17,16 +19,21 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1_values", TestScript1_values function TestScript1_entity() {} -TestScript1_entity.prototype.GetX = function() { +TestScript1_entity.prototype.GetX = function() +{ // Test that .entity is readonly - try { + try + { delete this.entity; Engine.TS_FAIL("Missed exception"); - } catch (e) { /* OK */ } - try { + } + catch(e) { /* OK */ } + try + { this.entity = -1; Engine.TS_FAIL("Missed exception"); - } catch (e) { /* OK */ } + } + catch(e) { /* OK */ } // and return the value return this.entity; @@ -38,13 +45,15 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1_entity", TestScript1_entity function TestScript1_nontree() {} -TestScript1_nontree.prototype.Init = function() { +TestScript1_nontree.prototype.Init = function() +{ var n = [1]; this.x = [n, n, null, { "y": n }]; this.x[2] = this.x; }; -TestScript1_nontree.prototype.GetX = function() { +TestScript1_nontree.prototype.GetX = function() +{ // print(uneval(this)+"\n"); this.x[0][0] += 1; return this.x[0][0] + this.x[1][0] + this.x[2][0][0] + this.x[3].y[0]; @@ -56,15 +65,18 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1_nontree", TestScript1_nontr function TestScript1_custom() {} -TestScript1_custom.prototype.Init = function() { +TestScript1_custom.prototype.Init = function() +{ this.y = 2; }; -TestScript1_custom.prototype.Serialize = function() { +TestScript1_custom.prototype.Serialize = function() +{ return { "c": 1 }; }; -TestScript1_custom.prototype.Deserialize = function(data) { +TestScript1_custom.prototype.Deserialize = function(data) +{ this.c = data.c; }; @@ -74,7 +86,8 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1_custom", TestScript1_custom function TestScript1_getter() {} -TestScript1_getter.prototype.Init = function() { +TestScript1_getter.prototype.Init = function() +{ this.x = 100; this.__defineGetter__('x', function() { print("FAIL\n"); die(); return 200; }); }; @@ -87,17 +100,20 @@ function TestScript1_consts() {} TestScript1_consts.prototype.Schema = ""; -TestScript1_consts.prototype.Init = function() { +TestScript1_consts.prototype.Init = function() +{ this.cached = (+this.entity) + (+this.template.x); }; TestScript1_consts.prototype.Serialize = null; -TestScript1_consts.prototype.Deserialize = function(data) { +TestScript1_consts.prototype.Deserialize = function(data) +{ this.Init(); }; -TestScript1_consts.prototype.GetX = function() { +TestScript1_consts.prototype.GetX = function() +{ return this.cached; }; diff --git a/binaries/data/mods/_test.sim/simulation/components/test.js b/binaries/data/mods/_test.sim/simulation/components/test.js index 582e8455be..4a5514cacc 100644 --- a/binaries/data/mods/_test.sim/simulation/components/test.js +++ b/binaries/data/mods/_test.sim/simulation/components/test.js @@ -1,14 +1,17 @@ function TestScript1A() {} -TestScript1A.prototype.Init = function() { +TestScript1A.prototype.Init = function() +{ this.x = 101000; }; -TestScript1A.prototype.GetX = function() { +TestScript1A.prototype.GetX = function() +{ return this.x; }; -TestScript1A.prototype.OnTurnStart = function(msg) { +TestScript1A.prototype.OnTurnStart = function(msg) +{ this.x += 1; }; @@ -20,7 +23,8 @@ function TestScript1B() {} TestScript1B.prototype = Object.create(TestScript1A.prototype); -TestScript1B.prototype.Init = function() { +TestScript1B.prototype.Init = function() +{ this.x = 102000; }; @@ -30,15 +34,18 @@ Engine.RegisterComponentType(IID_Test1, "TestScript1B", TestScript1B); function TestScript2A() {} -TestScript2A.prototype.Init = function() { +TestScript2A.prototype.Init = function() +{ this.x = 201000; }; -TestScript2A.prototype.GetX = function() { +TestScript2A.prototype.GetX = function() +{ return this.x; }; -TestScript2A.prototype.OnUpdate = function(msg) { +TestScript2A.prototype.OnUpdate = function(msg) +{ this.x += msg.turnLength; }; diff --git a/binaries/data/mods/mod/gui/colormixer/colormixer.js b/binaries/data/mods/mod/gui/colormixer/colormixer.js index 6072d664f1..c6939d2fc3 100644 --- a/binaries/data/mods/mod/gui/colormixer/colormixer.js +++ b/binaries/data/mods/mod/gui/colormixer/colormixer.js @@ -41,7 +41,8 @@ export async function init(initialColor) const splitColor = initialColor.split(" "); - const chanels = labels.map((label, i) => { + const chanels = labels.map((label, i) => + { Engine.GetGUIObjectByName("colorLabel[" + i + "]").caption = label; resizeChanel(i); @@ -70,8 +71,10 @@ export async function init(initialColor) while (true) { colorDisplay.sprite = "color:" + currentColor(); - const chanelPromises = chanels.map(chanel => { - return new Promise(resolve => { + const chanelPromises = chanels.map(chanel => + { + return new Promise(resolve => + { chanel.slider.onValueChange = resolve.bind(undefined, { "value": chanel }); }); }); diff --git a/binaries/data/mods/mod/gui/common/utilities.js b/binaries/data/mods/mod/gui/common/utilities.js index d32771c244..04e4c8ebc6 100644 --- a/binaries/data/mods/mod/gui/common/utilities.js +++ b/binaries/data/mods/mod/gui/common/utilities.js @@ -23,8 +23,10 @@ function distributeButtonsHorizontally(button, captions) function setButtonCaptionsAndVisibility(buttons, captions, cancelHotkey, name) { - return new Promise(resolve => { - captions.forEach((caption, i) => { + return new Promise(resolve => + { + captions.forEach((caption, i) => + { buttons[i] = Engine.GetGUIObjectByName(name + (i + 1)); buttons[i].caption = caption; buttons[i].hidden = false; diff --git a/binaries/data/mods/mod/gui/incompatible_mods/incompatible_mods.js b/binaries/data/mods/mod/gui/incompatible_mods/incompatible_mods.js index 4df0f388d0..b573bc6f74 100644 --- a/binaries/data/mods/mod/gui/incompatible_mods/incompatible_mods.js +++ b/binaries/data/mods/mod/gui/incompatible_mods/incompatible_mods.js @@ -3,7 +3,8 @@ var g_IncompatibleModsFile = "gui/incompatible_mods/incompatible_mods.txt"; function init(data) { Engine.GetGUIObjectByName("mainText").caption = Engine.TranslateLines(Engine.ReadFile(g_IncompatibleModsFile)); - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("btnClose").onPress = closePageCallback; }); } diff --git a/binaries/data/mods/mod/gui/modio/modio.js b/binaries/data/mods/mod/gui/modio/modio.js index 6a2372a9be..13f7508c59 100644 --- a/binaries/data/mods/mod/gui/modio/modio.js +++ b/binaries/data/mods/mod/gui/modio/modio.js @@ -27,12 +27,14 @@ var g_ModIOState = { /** * Finished status indicators */ - "ready": (progressData, closePageCallback) => { + "ready": (progressData, closePageCallback) => + { // GameID acquired, ready to fetch mod list if (!g_RequestCancelled) updateModList(closePageCallback); }, - "listed": progressData => { + "listed": progressData => + { // List of available mods acquired // Only run this once (for each update). @@ -44,7 +46,8 @@ var g_ModIOState = { g_ModsAvailableOnline = Engine.ModIoGetMods(); displayMods(); }, - "success": progressData => { + "success": progressData => + { // Successfully acquired a mod file hideDialog(); Engine.GetGUIObjectByName("downloadButton").enabled = true; @@ -52,20 +55,24 @@ var g_ModIOState = { /** * In-progress status indicators. */ - "gameid": progressData => { + "gameid": progressData => + { // Acquiring GameID from mod.io }, - "listing": progressData => { + "listing": progressData => + { // Acquiring list of available mods from mod.io }, - "downloading": progressData => { + "downloading": progressData => + { // Downloading a mod file updateProgressBar(progressData.progress, g_ModsAvailableOnline[selectedModIndex()].filesize); }, /** * Error/Failure status indicators. */ - "failed_gameid": async(progressData, closePageCallback) => { + "failed_gameid": async(progressData, closePageCallback) => + { // Game ID couldn't be retrieved const promise = showErrorMessageBox( sprintf(translateWithContext("mod.io error message", "Game ID could not be retrieved.\n\n%(technicalDetails)s"), { @@ -80,7 +87,8 @@ var g_ModIOState = { else init(); }, - "failed_listing": async(progressData, closePageCallback) => { + "failed_listing": async(progressData, closePageCallback) => + { // Mod list couldn't be retrieved const promise = showErrorMessageBox( sprintf(translateWithContext("mod.io error message", "Mod List could not be retrieved.\n\n%(technicalDetails)s"), { @@ -95,7 +103,8 @@ var g_ModIOState = { else updateModList(closePageCallback); }, - "failed_downloading": async(progressData) => { + "failed_downloading": async(progressData) => + { // File couldn't be retrieved const promise = showErrorMessageBox( sprintf(translateWithContext("mod.io error message", "File download failed.\n\n%(technicalDetails)s"), { @@ -110,7 +119,8 @@ var g_ModIOState = { else downloadMod(); }, - "failed_filecheck": async(progressData) => { + "failed_filecheck": async(progressData) => + { // The file is corrupted const promise = showErrorMessageBox( sprintf(translateWithContext("mod.io error message", "File verification error.\n\n%(technicalDetails)s"), { @@ -126,7 +136,8 @@ var g_ModIOState = { /** * Default */ - "none": progressData => { + "none": progressData => + { // Nothing has happened yet. } }; @@ -144,7 +155,8 @@ function init(data) return Promise.race([ promise, - new Promise(closePageCallback => { + new Promise(closePageCallback => + { Engine.GetGUIObjectByName("backButton").onPress = closePageCallback; Engine.GetGUIObjectByName("modio").onTick = onTick.bind(null, closePageCallback); }) @@ -327,7 +339,8 @@ async function progressDialog(dialogCaption, dialogTitle, showProgressBar, butto const downloadDialog_button = Engine.GetGUIObjectByName("downloadDialog_button"); downloadDialog_button.caption = buttonCaption; - await new Promise(resolve => { + await new Promise(resolve => + { downloadDialog_button.onPress = resolve; }); cancelRequest(); diff --git a/binaries/data/mods/mod/gui/modmod/help/help.js b/binaries/data/mods/mod/gui/modmod/help/help.js index 513aee2136..693a00be6a 100644 --- a/binaries/data/mods/mod/gui/modmod/help/help.js +++ b/binaries/data/mods/mod/gui/modmod/help/help.js @@ -1,7 +1,8 @@ function init(data) { Engine.GetGUIObjectByName("mainText").caption = Engine.TranslateLines(Engine.ReadFile("gui/modmod/help/help.txt")); - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("closeButton").onPress = closePageCallback; }); } diff --git a/binaries/data/mods/mod/gui/modmod/modmod.js b/binaries/data/mods/mod/gui/modmod/modmod.js index e4e9b7ffa9..7c1518f965 100644 --- a/binaries/data/mods/mod/gui/modmod/modmod.js +++ b/binaries/data/mods/mod/gui/modmod/modmod.js @@ -68,7 +68,8 @@ function init(data, hotloadData) if (g_HasIncompatibleMods) Engine.OpenChildPage("page_incompatible_mods.xml", {}); - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("quitButton").onPress = closePageCallback; }); } diff --git a/binaries/data/mods/mod/gui/termsdialog/termsdialog.js b/binaries/data/mods/mod/gui/termsdialog/termsdialog.js index 6997b7aabd..416f93ddfd 100644 --- a/binaries/data/mods/mod/gui/termsdialog/termsdialog.js +++ b/binaries/data/mods/mod/gui/termsdialog/termsdialog.js @@ -21,7 +21,8 @@ async function init(data) initURLButtons(data.termsURL, data.urlButtons); initLanguageSelection(); - const accepted = await new Promise(resolve => { + const accepted = await new Promise(resolve => + { Engine.GetGUIObjectByName("cancelButton").onPress = resolve.bind(null, false); Engine.GetGUIObjectByName("connectButton").onPress = resolve.bind(null, true); }); @@ -40,14 +41,16 @@ function initURLButtons(termsURL, urlButtons) "url": termsURL }); - urlButtons.forEach((urlButton, i) => { + urlButtons.forEach((urlButton, i) => + { const button = Engine.GetGUIObjectByName("button[" + i + "]"); button.caption = urlButton.caption; button.hidden = false; button.tooltip = sprintf(translate("Open %(url)s in the browser."), { "url": urlButton.url }); - button.onPress = () => { + button.onPress = () => + { openURL(urlButton.url); }; }); @@ -62,7 +65,8 @@ function initLanguageSelection() const languageDropdown = Engine.GetGUIObjectByName("languageDropdown"); languageDropdown.size = (languageLabelWidth + 10) + " 4 100% 100%"; - languageDropdown.list = (() => { + languageDropdown.list = (() => + { const displayNames = Engine.GetSupportedLocaleDisplayNames(); const baseNames = Engine.GetSupportedLocaleBaseNames(); @@ -80,7 +84,8 @@ function initLanguageSelection() return list; })(); - languageDropdown.onSelectionChange = () => { + languageDropdown.onSelectionChange = () => + { Engine.GetGUIObjectByName("mainText").caption = sprintf( languageDropdown.selected == 1 ? diff --git a/binaries/data/mods/mod/hwdetect/test.js b/binaries/data/mods/mod/hwdetect/test.js index 92e5796769..54c2d9e3ca 100644 --- a/binaries/data/mods/mod/hwdetect/test.js +++ b/binaries/data/mods/mod/hwdetect/test.js @@ -14,7 +14,8 @@ print("GL_RENDERER"); print("Output"); print("Warnings"); -hwdetectTestData.sort(function(a, b) { +hwdetectTestData.sort(function(a, b) +{ if (a.renderer_backend.GL_RENDERER < b.renderer_backend.GL_RENDERER) return -1; if (b.renderer_backend.GL_RENDERER < a.renderer_backend.GL_RENDERER) diff --git a/binaries/data/mods/mod/tools/dap/commands/dap.js b/binaries/data/mods/mod/tools/dap/commands/dap.js index efac4bde81..0c9ad9dd14 100644 --- a/binaries/data/mods/mod/tools/dap/commands/dap.js +++ b/binaries/data/mods/mod/tools/dap/commands/dap.js @@ -1,11 +1,14 @@ import { Plugin } from 'tools/dap/plugin.js'; -class DapCommands extends Plugin { - constructor(jsDebugger, dapHandler) { +class DapCommands extends Plugin +{ + constructor(jsDebugger, dapHandler) + { super('DapCommonCommand', 'command'); jsDebugger.registerHookName('onInitialize', this.name); - dapHandler.registerCommand('initialize', (req) => { + dapHandler.registerCommand('initialize', (req) => + { this.logger.info('Handling initialize command'); return dapHandler.successResponse(req, { 'supportsConfigurationDoneRequest': true, @@ -13,26 +16,30 @@ class DapCommands extends Plugin { }); }); - dapHandler.registerCommand('disconnect', (req) => { + dapHandler.registerCommand('disconnect', (req) => + { this.logger.info('Handling disconnect command'); jsDebugger.setAttached(false); Engine.EndWaitingForMessage(); return dapHandler.successResponse(req, undefined); }); - dapHandler.registerCommand('attach', (req) => { + dapHandler.registerCommand('attach', (req) => + { this.logger.info('Handling attach command'); jsDebugger.setAttached(true); jsDebugger.pushEvent('initialized', undefined, this.name); return dapHandler.successResponse(req, undefined); }); - dapHandler.registerCommand('configurationDone', (req) => { + dapHandler.registerCommand('configurationDone', (req) => + { this.logger.info('Handling configurationDone command'); return dapHandler.successResponse(req, undefined); }); - dapHandler.registerCommand('threads', (req) => { + dapHandler.registerCommand('threads', (req) => + { this.logger.info('Handling threads command'); jsDebugger.triggerHook('onInitialize', undefined); return dapHandler.successResponse(req, { diff --git a/binaries/data/mods/mod/tools/dap/daphandler.js b/binaries/data/mods/mod/tools/dap/daphandler.js index 75325a8339..549c740ff2 100644 --- a/binaries/data/mods/mod/tools/dap/daphandler.js +++ b/binaries/data/mods/mod/tools/dap/daphandler.js @@ -1,18 +1,22 @@ import { logger } from 'tools/dap/logger.js'; -export class DapProtocolHandler { - constructor(jsDebugger) { +export class DapProtocolHandler +{ + constructor(jsDebugger) + { this.commands = {}; this.jsDebugger = jsDebugger; this.logger = logger.getLogger("DAPProtocolHandler"); } - registerCommand(name, fn) { + registerCommand(name, fn) + { this.logger.info(`Registering command: ${name}`); this.commands[name] = fn; } - handleRequest(req) { + handleRequest(req) + { if (req.type !== 'request' || !req.command) { this.logger.error(`Invalid request: ${JSON.stringify(req)}`); @@ -28,7 +32,7 @@ export class DapProtocolHandler { this.logger.info(`Handling command: ${req.command}`); return handler(req); } - catch (error) + catch(error) { this.logger.error(`Error handling command ${req.command}:`, error); this.logger.error(uneval(error.stack)); @@ -36,7 +40,8 @@ export class DapProtocolHandler { } } - successResponse(req, result) { + successResponse(req, result) + { this.logger.info(`Response to ${req.command}`, result); const response = { 'type': 'response', @@ -48,7 +53,8 @@ export class DapProtocolHandler { return response; } - errorResponse(req, error) { + errorResponse(req, error) + { this.logger.error(`Error in ${req.command}: ${error}`); const response = { 'type': 'response', diff --git a/binaries/data/mods/mod/tools/dap/jsdebugger.js b/binaries/data/mods/mod/tools/dap/jsdebugger.js index 8f47f1657e..117dbb6be2 100644 --- a/binaries/data/mods/mod/tools/dap/jsdebugger.js +++ b/binaries/data/mods/mod/tools/dap/jsdebugger.js @@ -1,7 +1,9 @@ import { logger } from 'tools/dap/logger.js'; -export class JsDebugger { - constructor() { +export class JsDebugger +{ + constructor() + { this.debugger = new Debugger(); this.logger = logger.getLogger("SpiderDebugger"); this.events = []; @@ -19,30 +21,36 @@ export class JsDebugger { 'onRsumeInFrame': [], }; - this.debugger.uncaughtExceptionHook = (e) => { + this.debugger.uncaughtExceptionHook = (e) => + { this._runHooks('onUncaughtException', e); }; - this.debugger.onNewGlobalObject = (global) => { + this.debugger.onNewGlobalObject = (global) => + { this._runHooks('onNewGlobalObject', global); }; - this.debugger.onDebuggerStatement = (frame) => { + this.debugger.onDebuggerStatement = (frame) => + { this._runHooks('onDebuggerStatement', frame); }; - this.debugger.onNewScript = (script, global) => { + this.debugger.onNewScript = (script, global) => + { this._runHooks('onNewScript', { script, global }); }; - this.debugger.onEnterFrame = (frame) => { + this.debugger.onEnterFrame = (frame) => + { this._runHooks('onEnterFrame', frame); }; this.debuggerAttached = false; } - _runHooks(event, data) { + _runHooks(event, data) + { this.logger.trace(`Running hook for ${event}`); for (const hookInfo of this.hooks[event]) { @@ -53,16 +61,20 @@ export class JsDebugger { continue; } - try { + try + { hookInfo.callback(data); - } catch (e) { + } + catch(e) + { this.logger.error(`Error in hook for ${hookInfo.source}-${event}: ${e.message}`); this.logger.error(uneval(e.stack)); } } } - on(event, callback, source) { + on(event, callback, source) + { if (!event || typeof event !== 'string') { this.logger.warn('Invalid event name'); @@ -90,11 +102,13 @@ export class JsDebugger { this.logger.debug(`Hook added for event: ${event}`); } - get instance() { + get instance() + { return this.debugger; } - setAttached(attached) { + setAttached(attached) + { this.debuggerAttached = attached; if (attached) { @@ -108,7 +122,8 @@ export class JsDebugger { } } - pushEvent(eventName, eventData, source) { + pushEvent(eventName, eventData, source) + { if (!eventName || typeof eventName !== 'string') { this.logger.warn('Invalid event name'); @@ -128,7 +143,8 @@ export class JsDebugger { }); } - stopInframe(frame, onHandler) { + stopInframe(frame, onHandler) + { if (!frame || !(frame instanceof Debugger.Frame)) { this.logger.error('Invalid frame provided to stopInframe'); @@ -150,7 +166,8 @@ export class JsDebugger { this.logger.debug("Client continue"); } - registerHookName(event, source) { + registerHookName(event, source) + { if (!event || typeof event !== 'string') { this.logger.warn('Invalid event name'); @@ -173,7 +190,8 @@ export class JsDebugger { this.logger.debug(`Hook registered for event: ${event} from source: ${source}`); } - triggerHook(event, data) { + triggerHook(event, data) + { if (!event || typeof event !== 'string') { this.logger.warn('Invalid event name'); diff --git a/binaries/data/mods/mod/tools/dap/logger.js b/binaries/data/mods/mod/tools/dap/logger.js index e022818247..01ca476f91 100644 --- a/binaries/data/mods/mod/tools/dap/logger.js +++ b/binaries/data/mods/mod/tools/dap/logger.js @@ -1,9 +1,11 @@ -class Logger { +class Logger +{ levels = ['trace', 'debug', 'info', 'warn', 'error']; // Default = 'info'. levelIndex = 2; - setLevel(level) { + setLevel(level) + { const index = this.levels.indexOf(level); if (index === -1) { @@ -12,9 +14,12 @@ class Logger { this.levelIndex = index; } - constructor() { - this.levels.forEach((level, index) => { - this[level] = (...args) => { + constructor() + { + this.levels.forEach((level, index) => + { + this[level] = (...args) => + { if (index < this.levelIndex) return; @@ -28,14 +33,18 @@ class Logger { }); } - getLevel() { + getLevel() + { return this.levels[this.levelIndex]; } - getLogger(className) { + getLogger(className) + { const scopedLogger = {}; - this.levels.forEach((level) => { - scopedLogger[level] = (msg) => { + this.levels.forEach((level) => + { + scopedLogger[level] = (msg) => + { this[level](`[${className}]`, msg); }; }); diff --git a/binaries/data/mods/mod/tools/dap/managers/attach.js b/binaries/data/mods/mod/tools/dap/managers/attach.js index 7881acbfc7..ad70ae7ab8 100644 --- a/binaries/data/mods/mod/tools/dap/managers/attach.js +++ b/binaries/data/mods/mod/tools/dap/managers/attach.js @@ -1,21 +1,26 @@ import { Plugin } from 'tools/dap/plugin.js'; -class AttachManager extends Plugin { - constructor(jsDebugger, dapHandler) { +class AttachManager extends Plugin +{ + constructor(jsDebugger, dapHandler) + { super('AttachManager', 'manager'); this.logger.debug('Setting up AttachManager'); - jsDebugger.on('onDebuggerAttached', () => { + jsDebugger.on('onDebuggerAttached', () => + { this.logger.debug('Debugger attached'); jsDebugger.instance.addAllGlobalsAsDebuggees(); }, this.name); - jsDebugger.on('onDebuggerDetached', () => { + jsDebugger.on('onDebuggerDetached', () => + { this.logger.debug('Debugger detached'); jsDebugger.instance.removeAllDebuggees(); }, this.name); - jsDebugger.on('onNewGlobalObject', (global) => { + jsDebugger.on('onNewGlobalObject', (global) => + { if (!jsDebugger.debuggerAttached) return; @@ -23,7 +28,8 @@ class AttachManager extends Plugin { jsDebugger.instance.addDebuggee(global); }, this.name); - jsDebugger.on('onUncaughtException', (e) => { + jsDebugger.on('onUncaughtException', (e) => + { this.logger.error(`Uncaught exception: ${e}`); }, this.name); } diff --git a/binaries/data/mods/mod/tools/dap/managers/breakpoint.js b/binaries/data/mods/mod/tools/dap/managers/breakpoint.js index d12b1c81fc..29aa244f1c 100644 --- a/binaries/data/mods/mod/tools/dap/managers/breakpoint.js +++ b/binaries/data/mods/mod/tools/dap/managers/breakpoint.js @@ -1,14 +1,17 @@ import { Plugin } from 'tools/dap/plugin.js'; -class BreakpointManager extends Plugin { - constructor(jsDebugger, dapHandler) { +class BreakpointManager extends Plugin +{ + constructor(jsDebugger, dapHandler) + { super('BreakpointManager', 'manager'); this.breakpoints = []; this.dbg = jsDebugger.instance; this.jsDebugger = jsDebugger; this.logger.debug('Setting up BreakpointManager'); - jsDebugger.on('onNewScript', ({ script, global }) => { + jsDebugger.on('onNewScript', ({ script, global }) => + { if (!jsDebugger.debuggerAttached) return; @@ -24,7 +27,8 @@ class BreakpointManager extends Plugin { this.logger.debug(`Setting breakpoints for script: ${script.url}`); const sourceReferenceIndex = jsDebugger.sourcesReferences.findIndex((src) => src.path === url); - this.breakpoints[index].lines.forEach((bp, i) => { + this.breakpoints[index].lines.forEach((bp, i) => + { jsDebugger.pushEvent('breakpoint', { 'reason': 'changed', 'breakpoint': { @@ -40,13 +44,15 @@ class BreakpointManager extends Plugin { }); }, this.name); - jsDebugger.on('onDebuggerDetached', () => { + jsDebugger.on('onDebuggerDetached', () => + { this.logger.debug('Debugger detached'); this.dbg.clearAllBreakpoints(); this.breakpoints = []; }, this.name); - dapHandler.registerCommand('setBreakpoints', (req) => { + dapHandler.registerCommand('setBreakpoints', (req) => + { const path = req.arguments.source.path; const name = req.arguments.source.name; this.logger.debug(`Handling setBreakpoints command for source: ${req.arguments.source.path}`); @@ -76,7 +82,8 @@ class BreakpointManager extends Plugin { }); } - createOrUpdateBreakpoint(name, url, lines) { + createOrUpdateBreakpoint(name, url, lines) + { let index = this.breakpoints.findIndex((bp) => (!name || bp.name === name) && bp.url === url); if (index === -1) { @@ -89,7 +96,8 @@ class BreakpointManager extends Plugin { return index + 1; } - addBreakpointsByPath(path, instance_script) { + addBreakpointsByPath(path, instance_script) + { const infoBk = this.breakpoints.find((bp) => bp.url === path); if (!infoBk) @@ -100,15 +108,18 @@ class BreakpointManager extends Plugin { return false; this.logger.trace(`Found ${scripts.length} scripts for path: ${path}`); - this.scriptTreeWalk(scripts, (script) => { + this.scriptTreeWalk(scripts, (script) => + { script.clearAllBreakpoints(); }); - infoBk.lines.forEach((bp) => { + infoBk.lines.forEach((bp) => + { this.logger.debug(`Setting breakpoint at: ${uneval(bp)}`); bp.verified = false; bp.message = "No offset found"; - this.scriptTreeWalk(scripts, (script) => { + this.scriptTreeWalk(scripts, (script) => + { const offsets = script.getPossibleBreakpointOffsets({ 'line': bp.line, }); @@ -128,7 +139,8 @@ class BreakpointManager extends Plugin { return true; } - scriptTreeWalk(script, callback) { + scriptTreeWalk(script, callback) + { if (!script || script.length === 0) return; @@ -143,8 +155,10 @@ class BreakpointManager extends Plugin { } } - handleBreakpoint(frame) { - this.jsDebugger.stopInframe(frame, () => { + handleBreakpoint(frame) + { + this.jsDebugger.stopInframe(frame, () => + { this.jsDebugger.pushEvent('stopped', { 'reason': 'breakpoint', 'threadId': 1, diff --git a/binaries/data/mods/mod/tools/dap/managers/frame.js b/binaries/data/mods/mod/tools/dap/managers/frame.js index 574cac6377..b0bdfc9b3e 100644 --- a/binaries/data/mods/mod/tools/dap/managers/frame.js +++ b/binaries/data/mods/mod/tools/dap/managers/frame.js @@ -1,7 +1,9 @@ import { Plugin } from 'tools/dap/plugin.js'; -class FrameManager extends Plugin { - constructor(jsDebugger, dapHandler) { +class FrameManager extends Plugin +{ + constructor(jsDebugger, dapHandler) + { super('FrameManager', 'manager'); this.logger.debug('Setting up FrameManager'); @@ -12,7 +14,8 @@ class FrameManager extends Plugin { jsDebugger.registerHookName('onStepIn', this.name); jsDebugger.registerHookName('onStepOut', this.name); - jsDebugger.on('onDebuggerDetached', () => { + jsDebugger.on('onDebuggerDetached', () => + { this.logger.debug('Debugger detached'); let frame = jsDebugger.currentFrame; while (frame) @@ -24,8 +27,10 @@ class FrameManager extends Plugin { jsDebugger.currentFrame = undefined; }, this.name); - jsDebugger.on('onDebuggerStatement', (frame) => { - jsDebugger.stopInframe(frame, () => { + jsDebugger.on('onDebuggerStatement', (frame) => + { + jsDebugger.stopInframe(frame, () => + { this.logger.debug(`Paused on debugger statement in frame: ${frame.script.url}`); jsDebugger.pushEvent('stopped', { 'reason': 'debugger', @@ -35,7 +40,8 @@ class FrameManager extends Plugin { }); }, this.name); - jsDebugger.on('onEnterFrame', (frame) => { + jsDebugger.on('onEnterFrame', (frame) => + { if (!frame || !frame.older || !frame.older.stepIn || frame.onStep !== undefined) return; @@ -43,7 +49,8 @@ class FrameManager extends Plugin { this.hookFrameDebugger(frame, "stepIn", "Paused on stepIn"); }, this.name); - dapHandler.registerCommand('stackTrace', (req) => { + dapHandler.registerCommand('stackTrace', (req) => + { this.logger.debug('Handling stackTrace command'); if (!jsDebugger.currentFrame) { @@ -71,7 +78,8 @@ class FrameManager extends Plugin { return dapHandler.successResponse(req, { 'stackFrames': stackFrames }); }); - dapHandler.registerCommand('continue', (req) => { + dapHandler.registerCommand('continue', (req) => + { this.logger.debug('Handling continue command'); let frame = jsDebugger.currentFrame; while (frame) @@ -84,7 +92,8 @@ class FrameManager extends Plugin { return dapHandler.successResponse(req, { 'allThreadsContinued': true }); }); - dapHandler.registerCommand('next', (req) => { + dapHandler.registerCommand('next', (req) => + { this.logger.debug('Handling next command'); if (!jsDebugger.currentFrame) { @@ -103,7 +112,8 @@ class FrameManager extends Plugin { return dapHandler.successResponse(req, undefined); }); - dapHandler.registerCommand('stepIn', (req) => { + dapHandler.registerCommand('stepIn', (req) => + { this.logger.debug('Handling stepIn command'); if (!jsDebugger.currentFrame) { @@ -122,7 +132,8 @@ class FrameManager extends Plugin { return dapHandler.successResponse(req, undefined); }); - dapHandler.registerCommand('stepOut', (req) => { + dapHandler.registerCommand('stepOut', (req) => + { this.logger.debug('Handling stepOut command'); if (!jsDebugger.currentFrame) { @@ -142,28 +153,32 @@ class FrameManager extends Plugin { }); } - extractScriptName(url) { + extractScriptName(url) + { if (!url) return "[No Name]"; const parts = url.split('\\'); return parts[parts.length - 1] || "[No Name]"; } - hookFrameDebugger(frame, reason, msg) { + hookFrameDebugger(frame, reason, msg) + { if (!frame) return; const that = this; if (frame.onStep === undefined) { - frame.onStep = function() { + frame.onStep = function() + { if (this.stepOut === true && this.stepOver !== true) return; const currentLocation = this.script.getOffsetLocation(frame.offset); if (this.currentLocation?.lineNumber === currentLocation.lineNumber) return; - that.jsDebugger.stopInframe(this, () => { + that.jsDebugger.stopInframe(this, () => + { that.jsDebugger.pushEvent('stopped', { 'reason': reason, 'threadId': 1, @@ -176,7 +191,8 @@ class FrameManager extends Plugin { if (frame.onPop === undefined) { - frame.onPop = function() { + frame.onPop = function() + { if (this.stepIn || this.stepOut) that.hookFrameDebugger(this.older, reason, msg); that.cleanFrameDebugger(this); @@ -184,7 +200,8 @@ class FrameManager extends Plugin { } } - cleanFrameDebugger(frame) { + cleanFrameDebugger(frame) + { if (!frame) return; diff --git a/binaries/data/mods/mod/tools/dap/managers/inspector.js b/binaries/data/mods/mod/tools/dap/managers/inspector.js index 134f81f64a..90f0bc5120 100644 --- a/binaries/data/mods/mod/tools/dap/managers/inspector.js +++ b/binaries/data/mods/mod/tools/dap/managers/inspector.js @@ -1,23 +1,28 @@ import { Plugin } from 'tools/dap/plugin.js'; -class InspectorManager extends Plugin { - constructor(jsDebugger, dapHandler) { +class InspectorManager extends Plugin +{ + constructor(jsDebugger, dapHandler) + { super('InspectorManager', 'manager'); this.variableReferences = []; this.logger.debug('Setting up InspectorManager'); - jsDebugger.on('onDebuggerDetached', () => { + jsDebugger.on('onDebuggerDetached', () => + { this.logger.debug('Debugger attached'); this.variableReferences = []; }, this.name); - jsDebugger.on('onContinue', () => { + jsDebugger.on('onContinue', () => + { this.logger.debug('Continuing execution'); this.variableReferences = []; }, this.name); - dapHandler.registerCommand('scopes', (req) => { + dapHandler.registerCommand('scopes', (req) => + { this.logger.debug('Handling scopes command'); if (!jsDebugger.currentFrame) { @@ -49,7 +54,8 @@ class InspectorManager extends Plugin { return dapHandler.successResponse(req, { 'scopes': this.createScopeAndVariableReferences(frame, req.arguments.frameId) }); }); - dapHandler.registerCommand('variables', (req) => { + dapHandler.registerCommand('variables', (req) => + { this.logger.debug('Handling variables command'); if (!jsDebugger.currentFrame) { @@ -61,7 +67,8 @@ class InspectorManager extends Plugin { return dapHandler.successResponse(req, { 'variables': variables }); }); - dapHandler.registerCommand('evaluate', (req) => { + dapHandler.registerCommand('evaluate', (req) => + { this.logger.debug('Handling evaluate command'); if (!jsDebugger.currentFrame) { @@ -91,7 +98,7 @@ class InspectorManager extends Plugin { }); return dapHandler.successResponse(req, { 'result': JSON.stringify(result) || "null", 'variablesReference': 0 }); } - catch (error) + catch(error) { this.logger.error(`Error evaluating expression: ${error.message}`); return dapHandler.errorResponse(req, `Error evaluating expression: ${error.message}`); @@ -99,7 +106,8 @@ class InspectorManager extends Plugin { }); } - createOrUpdateVariableReference(name, data) { + createOrUpdateVariableReference(name, data) + { let index = this.variableReferences.findIndex((ref) => ref.name === name); if (index === -1) { @@ -112,7 +120,8 @@ class InspectorManager extends Plugin { return index + 1; } - createScopeAndVariableReferences(frame, frameId) { + createScopeAndVariableReferences(frame, frameId) + { if (!frame || !frame.onStack || frame.terminated) { this.logger.error(`Invalid frame: ${frameId}`); @@ -181,7 +190,8 @@ class InspectorManager extends Plugin { return scopes; } - describeJSObjectCallable(jsObject, varName) { + describeJSObjectCallable(jsObject, varName) + { if (!jsObject || !(jsObject instanceof Debugger.Object) || !jsObject.callable) { this.logger.error('Invalid JS Object for callable description'); @@ -221,7 +231,8 @@ class InspectorManager extends Plugin { return variable; } - describeJSObjectVariable(jsObject, varRefName, varReference, varName) { + describeJSObjectVariable(jsObject, varRefName, varReference, varName) + { if (!jsObject || !(jsObject instanceof Debugger.Object)) { this.logger.error('Invalid JS Object for description'); @@ -307,7 +318,8 @@ class InspectorManager extends Plugin { return variable; } - expandVariableReference(variableReferenceIndex, frame) { + expandVariableReference(variableReferenceIndex, frame) + { if (variableReferenceIndex === 0 || this.variableReferences.length < variableReferenceIndex - 1) { this.logger.warn(`Invalid variable reference index: ${variableReferenceIndex}`); diff --git a/binaries/data/mods/mod/tools/dap/managers/sources.js b/binaries/data/mods/mod/tools/dap/managers/sources.js index fa85e8ac65..0671584253 100644 --- a/binaries/data/mods/mod/tools/dap/managers/sources.js +++ b/binaries/data/mods/mod/tools/dap/managers/sources.js @@ -1,12 +1,15 @@ import { Plugin } from 'tools/dap/plugin.js'; -class SourcesManager extends Plugin { - constructor(jsDebugger, dapHandler) { +class SourcesManager extends Plugin +{ + constructor(jsDebugger, dapHandler) + { super('SourcesManager', 'manager'); this.jsDebugger = jsDebugger; this.logger.debug('Setting up SourcesManager'); - jsDebugger.on('onNewScript', ({ script, global }) => { + jsDebugger.on('onNewScript', ({ script, global }) => + { if (!jsDebugger.debuggerAttached) return; @@ -31,15 +34,18 @@ class SourcesManager extends Plugin { }, this.name); }, this.name); - jsDebugger.on('onDebuggerDetached', () => { + jsDebugger.on('onDebuggerDetached', () => + { this.logger.debug('Debugger detached'); this.jsDebugger.sourcesReferences = []; }, this.name); - jsDebugger.on('onDebuggerAttached', () => { + jsDebugger.on('onDebuggerAttached', () => + { this.logger.debug('Debugger attached'); this.jsDebugger.sourcesReferences = []; - this.jsDebugger.instance.findSources().forEach((source) => { + this.jsDebugger.instance.findSources().forEach((source) => + { const url = source.url; if (this.jsDebugger.sourcesReferences.some((src) => src.path === url)) return; @@ -50,7 +56,8 @@ class SourcesManager extends Plugin { }); }, this.name); - dapHandler.registerCommand('loadedSources', (req) => { + dapHandler.registerCommand('loadedSources', (req) => + { if (!jsDebugger.debuggerAttached) { this.logger.error('Debugger not attached, cannot handle loadedSources command'); @@ -66,7 +73,8 @@ class SourcesManager extends Plugin { return dapHandler.successResponse(req, { 'sources': sources }); }); - dapHandler.registerCommand('source', (req) => { + dapHandler.registerCommand('source', (req) => + { if (!jsDebugger.debuggerAttached) { this.logger.error('Debugger not attached, cannot handle source command'); diff --git a/binaries/data/mods/mod/tools/dap/plugin.js b/binaries/data/mods/mod/tools/dap/plugin.js index 61d3c3ee62..0386d7b4c2 100644 --- a/binaries/data/mods/mod/tools/dap/plugin.js +++ b/binaries/data/mods/mod/tools/dap/plugin.js @@ -1,7 +1,9 @@ import { logger } from 'tools/dap/logger.js'; -export class Plugin { - constructor(name, type) { +export class Plugin +{ + constructor(name, type) + { this.name = name; this.type = type; this.logger = logger.getLogger(name); diff --git a/binaries/data/mods/public/autostart/autostart_client.js b/binaries/data/mods/public/autostart/autostart_client.js index 32e79f3980..472f35d20b 100644 --- a/binaries/data/mods/public/autostart/autostart_client.js +++ b/binaries/data/mods/public/autostart/autostart_client.js @@ -11,7 +11,7 @@ class AutoStartClient const port = +(cmdLineArgs['autostart-port'] ?? 5073); Engine.StartNetworkJoin(playerName, ip, port, !('autostart-disable-replay' in cmdLineArgs)); } - catch (e) + catch(e) { const message = sprintf(translate("Cannot join game: %(message)s."), { "message": e.message }); messageBox(400, 200, message, translate("Error")); diff --git a/binaries/data/mods/public/autostart/autostart_host.js b/binaries/data/mods/public/autostart/autostart_host.js index 17b71657b6..26606ad76d 100644 --- a/binaries/data/mods/public/autostart/autostart_host.js +++ b/binaries/data/mods/public/autostart/autostart_host.js @@ -16,7 +16,7 @@ class AutoStartHost // Password not implemented for autostart. Engine.StartNetworkHost(playerName, port, "", false, !('autostart-disable-replay' in cmdLineArgs)); } - catch (e) + catch(e) { const message = sprintf(translate("Cannot host game: %(message)s."), { "message": e.message }); messageBox(400, 200, message, translate("Error")); diff --git a/binaries/data/mods/public/autostart/cmd_line_args.js b/binaries/data/mods/public/autostart/cmd_line_args.js index 279c53457f..1e93a9b71c 100644 --- a/binaries/data/mods/public/autostart/cmd_line_args.js +++ b/binaries/data/mods/public/autostart/cmd_line_args.js @@ -120,7 +120,8 @@ function parseCmdLineArgs(settings, cmdLineArgs) settings.playerCount.setNb(+cmdLineArgs['autostart-players']); } - const getPlayer = (key, i) => { + const getPlayer = (key, i) => + { if (!(('autostart-' + key) in cmdLineArgs)) return undefined; var value = cmdLineArgs['autostart-' + key]; diff --git a/binaries/data/mods/public/gamesettings/attributes/PlayerColor.js b/binaries/data/mods/public/gamesettings/attributes/PlayerColor.js index 946f7e9cc9..6f10198403 100644 --- a/binaries/data/mods/public/gamesettings/attributes/PlayerColor.js +++ b/binaries/data/mods/public/gamesettings/attributes/PlayerColor.js @@ -183,7 +183,8 @@ GameSettings.prototype.Attributes.PlayerColor = class PlayerColor extends GameSe _getUnusedColor() { - return this.available.find(color => { + return this.available.find(color => + { return this.values.every(otherColor => !otherColor || !sameColor(color, otherColor)); }); } diff --git a/binaries/data/mods/public/gamesettings/attributes/PlayerName.js b/binaries/data/mods/public/gamesettings/attributes/PlayerName.js index 61af52521a..b724f359c1 100644 --- a/binaries/data/mods/public/gamesettings/attributes/PlayerName.js +++ b/binaries/data/mods/public/gamesettings/attributes/PlayerName.js @@ -94,7 +94,8 @@ GameSettings.prototype.Attributes.PlayerName = class PlayerName extends GameSett const translatedCountLabel = this.settings.isNetworked ? this.CountLabel : translate(this.CountLabel); const translatedChosenName = this.settings.isNetworked ? chosenName : translate(chosenName); - const duplicateNameCount = AIPlayerNamesList.reduce((count, name) => { + const duplicateNameCount = AIPlayerNamesList.reduce((count, name) => + { if (name == chosenName) count++; return count; diff --git a/binaries/data/mods/public/globalscripts/DamageTypes.js b/binaries/data/mods/public/globalscripts/DamageTypes.js index a4716abc6c..6e0f33ddac 100644 --- a/binaries/data/mods/public/globalscripts/DamageTypes.js +++ b/binaries/data/mods/public/globalscripts/DamageTypes.js @@ -28,7 +28,8 @@ class DamageTypesMetadata } const hasMetadata = (a) => this.damageTypeData[a] ? -1 : 1; - this._sort = (a, b) => { + this._sort = (a, b) => + { if (this.damageTypeData[a] && this.damageTypeData[b]) return this.damageTypeData[a].order - this.damageTypeData[b].order; return hasMetadata(a) - hasMetadata(b); diff --git a/binaries/data/mods/public/globalscripts/ModificationTemplates.js b/binaries/data/mods/public/globalscripts/ModificationTemplates.js index 3f015239e3..53e676544e 100644 --- a/binaries/data/mods/public/globalscripts/ModificationTemplates.js +++ b/binaries/data/mods/public/globalscripts/ModificationTemplates.js @@ -118,41 +118,41 @@ function DeriveModificationsFromTechnologies(techsDataArray) * Common definition of the XML schema for in-template modifications. */ const ModificationSchema = -"" + - "" + - "" + - "tokens" + - "" + - "" + - "" + - "" + - "" + - "tokens" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + - "" + + "" + + "" + + "" + + "tokens" + + "" + "" + "" + - "" + -""; + "" + + "" + + "tokens" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + "" + + ""; const ModificationsSchema = -"" + - "" + - "" + - "" + - ModificationSchema + - "" + - "" + -""; + "" + + "" + + "" + + "" + + ModificationSchema + + "" + + "" + + ""; /** * Derives a single modification (to be applied to entities) from a given XML template. diff --git a/binaries/data/mods/public/globalscripts/Templates.js b/binaries/data/mods/public/globalscripts/Templates.js index 5ca3cee7aa..1a781fe547 100644 --- a/binaries/data/mods/public/globalscripts/Templates.js +++ b/binaries/data/mods/public/globalscripts/Templates.js @@ -165,7 +165,8 @@ function GetTemplateDataHelper(template, player, auraTemplates, resources, modif // @param {string} value_path - Route to the value within the template. // @param {string} mod_key - Modification key, if not the same as the value_path. // @param {number} default_value - A value to use if one is not specified in the template. - const getEntityValue = function(value_path, mod_key, default_value = 0) { + const getEntityValue = function(value_path, mod_key, default_value = 0) + { return GetModifiedTemplateDataValue(template, value_path, mod_key, player, modifiers, default_value); }; @@ -197,7 +198,8 @@ function GetTemplateDataHelper(template, player, auraTemplates, resources, modif } } - const getAttackEffects = (temp, path) => { + const getAttackEffects = (temp, path) => + { const effects = {}; if (temp.Capture) effects.Capture = getEntityValue(path + "/Capture"); @@ -220,7 +222,8 @@ function GetTemplateDataHelper(template, player, auraTemplates, resources, modif ret.attack = {}; for (const type in template.Attack) { - const getAttackStat = function(stat) { + const getAttackStat = function(stat) + { return getEntityValue("Attack/" + type + "/" + stat); }; diff --git a/binaries/data/mods/public/gui/campaigns/default_menu/CampaignMenu.js b/binaries/data/mods/public/gui/campaigns/default_menu/CampaignMenu.js index 3ff7979984..170e404b16 100644 --- a/binaries/data/mods/public/gui/campaigns/default_menu/CampaignMenu.js +++ b/binaries/data/mods/public/gui/campaigns/default_menu/CampaignMenu.js @@ -237,12 +237,15 @@ var g_CampaignMenu; function init(initData) { let run = initData?.filename || CampaignRun.getCurrentRunFilename(); - try { + try + { run = new CampaignRun(run).load(); if (!run.isCurrent()) run.setCurrent(); g_CampaignMenu = new CampaignMenu(run); - } catch (err) { + } + catch(err) + { error(sprintf("Error loading campaign run %s: %s.", CampaignRun.getCurrentRunFilename(), err)); Engine.SwitchGuiPage("page_pregame.xml", {}); } diff --git a/binaries/data/mods/public/gui/campaigns/load_modal/LoadModal.js b/binaries/data/mods/public/gui/campaigns/load_modal/LoadModal.js index 68fede49a3..e1d68c0ed9 100644 --- a/binaries/data/mods/public/gui/campaigns/load_modal/LoadModal.js +++ b/binaries/data/mods/public/gui/campaigns/load_modal/LoadModal.js @@ -47,7 +47,8 @@ class LoadModal extends AutoWatcher this.selectedRun = -1; this.runSelection = Engine.GetGUIObjectByName("runSelection"); - this.runSelection.onSelectionChange = () => { + this.runSelection.onSelectionChange = () => + { this.selectedRun = this.runSelection.selected; if (this.selectedRun === -1) Engine.GetGUIObjectByName('runDescription').caption = ""; @@ -71,7 +72,7 @@ class LoadModal extends AutoWatcher { out.push(new CampaignRun(name).load()); } - catch (err) + catch(err) { warn(err.toString()); out.push(new BrokenRun(name)); diff --git a/binaries/data/mods/public/gui/campaigns/new_modal/NewCampaignModal.js b/binaries/data/mods/public/gui/campaigns/new_modal/NewCampaignModal.js index 63a4790992..fe69d0017a 100644 --- a/binaries/data/mods/public/gui/campaigns/new_modal/NewCampaignModal.js +++ b/binaries/data/mods/public/gui/campaigns/new_modal/NewCampaignModal.js @@ -12,7 +12,8 @@ class NewCampaignModal Engine.GetGUIObjectByName('cancelButton').onPress = closePageCallback; Engine.GetGUIObjectByName('startButton').onPress = () => this.createAndStartCampaign(); Engine.GetGUIObjectByName('runDescription').caption = translateWithContext("Campaign Template", this.template.Name); - Engine.GetGUIObjectByName('runDescription').onTextEdit = () => { + Engine.GetGUIObjectByName('runDescription').onTextEdit = () => + { Engine.GetGUIObjectByName('startButton').enabled = Engine.GetGUIObjectByName('runDescription').caption.length > 0; }; Engine.GetGUIObjectByName('runDescription').focus(); @@ -38,7 +39,8 @@ var g_NewCampaignModal; function init(campaign_template_data) { - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { g_NewCampaignModal = new NewCampaignModal(campaign_template_data, closePageCallback); }); } diff --git a/binaries/data/mods/public/gui/campaigns/setup/CampaignSetupPage.js b/binaries/data/mods/public/gui/campaigns/setup/CampaignSetupPage.js index f16b892c58..8a8d8d0d8c 100644 --- a/binaries/data/mods/public/gui/campaigns/setup/CampaignSetupPage.js +++ b/binaries/data/mods/public/gui/campaigns/setup/CampaignSetupPage.js @@ -15,12 +15,14 @@ class CampaignSetupPage extends AutoWatcher Engine.GetGUIObjectByName("startCampButton").onPress = () => Engine.OpenChildPage("campaigns/new_modal/page.xml", this.selectedTemplate); this.campaignSelection = Engine.GetGUIObjectByName("campaignSelection"); - this.campaignSelection.onMouseLeftDoubleClickItem = () => { + this.campaignSelection.onMouseLeftDoubleClickItem = () => + { if (this.selectedIndex === -1) return; Engine.OpenChildPage("campaigns/new_modal/page.xml", this.selectedTemplate); }; - this.campaignSelection.onSelectionChange = () => { + this.campaignSelection.onSelectionChange = () => + { this.selectedIndex = this.campaignSelection.selected; if (this.selectedIndex !== -1) this.selectedTemplate = this.templates[this.selectedIndex]; diff --git a/binaries/data/mods/public/gui/common/Observable.js b/binaries/data/mods/public/gui/common/Observable.js index 0c4fbbf432..4a5e4bbe15 100644 --- a/binaries/data/mods/public/gui/common/Observable.js +++ b/binaries/data/mods/public/gui/common/Observable.js @@ -21,7 +21,8 @@ var ObservableMixin = (Parent) => class Observable extends (() => Parent || Obje "enumerable": false, }); return new Proxy(this, { - "set": (target, key, value) => { + "set": (target, key, value) => + { let old; let hasOld = false; if (Reflect.has(target, key)) diff --git a/binaries/data/mods/public/gui/common/Profilable.js b/binaries/data/mods/public/gui/common/Profilable.js index 6c331766d6..4b97c13171 100644 --- a/binaries/data/mods/public/gui/common/Profilable.js +++ b/binaries/data/mods/public/gui/common/Profilable.js @@ -14,13 +14,15 @@ var ProfilableMixin = (Parent) => class Profilable extends (() => Parent || Obje { super(); return new Proxy(this, { - "get": (target, prop, receiver) => { + "get": (target, prop, receiver) => + { let ret = Reflect.get(target, prop); if (typeof ret !== 'function') return ret; { ret = ret.bind(receiver); - return (...a) => { + return (...a) => + { Engine.ProfileStart(target.constructor.name + ":" + prop); const ret2 = ret(...a); Engine.ProfileStop(); diff --git a/binaries/data/mods/public/gui/common/campaigns/utils.js b/binaries/data/mods/public/gui/common/campaigns/utils.js index d75c9e518d..486408da9a 100644 --- a/binaries/data/mods/public/gui/common/campaigns/utils.js +++ b/binaries/data/mods/public/gui/common/campaigns/utils.js @@ -7,10 +7,12 @@ function _watch(object, callback) { return new Proxy(object, { - "get": (obj, key) => { + "get": (obj, key) => + { return obj[key]; }, - "set": (obj, key, value) => { + "set": (obj, key, value) => + { obj[key] = value; callback(key); return true; diff --git a/binaries/data/mods/public/gui/common/functions_utility.js b/binaries/data/mods/public/gui/common/functions_utility.js index d1c495f301..f0db93a93e 100644 --- a/binaries/data/mods/public/gui/common/functions_utility.js +++ b/binaries/data/mods/public/gui/common/functions_utility.js @@ -104,7 +104,7 @@ function stringifiedTeamListToPlayerData(stringifiedTeamList) { teamList = JSON.parse(unescapeText(stringifiedTeamList)); } - catch (e) + catch(e) { // Ignore invalid input from remote users return []; diff --git a/binaries/data/mods/public/gui/common/gamedescription.js b/binaries/data/mods/public/gui/common/gamedescription.js index 664261a5a6..8a163baca8 100644 --- a/binaries/data/mods/public/gui/common/gamedescription.js +++ b/binaries/data/mods/public/gui/common/gamedescription.js @@ -153,7 +153,8 @@ function formatPlayerInfo(playerDataArray, playerStates) // If there are teams, merge "Team N:" + playerDescriptions else - teamDescription = teams.map(team => { + teamDescription = teams.map(team => + { const teamCaption = team == -1 ? translate("No Team") : diff --git a/binaries/data/mods/public/gui/common/network.js b/binaries/data/mods/public/gui/common/network.js index 3299650d53..ba42a6697d 100644 --- a/binaries/data/mods/public/gui/common/network.js +++ b/binaries/data/mods/public/gui/common/network.js @@ -211,7 +211,8 @@ function kickObservers(ban) */ function sortGUIDsByPlayerID() { - return Object.keys(g_PlayerAssignments).sort((guidA, guidB) => { + return Object.keys(g_PlayerAssignments).sort((guidA, guidB) => + { const playerIdA = g_PlayerAssignments[guidA].player; const playerIdB = g_PlayerAssignments[guidB].player; diff --git a/binaries/data/mods/public/gui/common/settings.js b/binaries/data/mods/public/gui/common/settings.js index 6afcfa3406..4ad854f885 100644 --- a/binaries/data/mods/public/gui/common/settings.js +++ b/binaries/data/mods/public/gui/common/settings.js @@ -201,7 +201,8 @@ function loadMapTypes() function loadBiomes() { - return listFiles(g_BiomesDirectory, ".json", true).filter(biomeID => biomeID != "defaultbiome").map(biomeID => { + return listFiles(g_BiomesDirectory, ".json", true).filter(biomeID => biomeID != "defaultbiome").map(biomeID => + { const description = Engine.ReadJSONFile(g_BiomesDirectory + biomeID + ".json").Description; return { "Id": biomeID, @@ -221,7 +222,8 @@ function loadVictoryConditions() { const subdir = "victory_conditions/"; - const victoryConditions = listFiles(g_SettingsDirectory + subdir, ".json", false).map(victoryScriptName => { + const victoryConditions = listFiles(g_SettingsDirectory + subdir, ".json", false).map(victoryScriptName => + { const victoryCondition = loadSettingValuesFile(subdir + victoryScriptName + ".json"); if (victoryCondition) victoryCondition.Name = victoryScriptName; diff --git a/binaries/data/mods/public/gui/common/tab_buttons.js b/binaries/data/mods/public/gui/common/tab_buttons.js index c995329459..3764180590 100644 --- a/binaries/data/mods/public/gui/common/tab_buttons.js +++ b/binaries/data/mods/public/gui/common/tab_buttons.js @@ -90,7 +90,8 @@ function selectNextTab(direction) function selectPanel(category) { g_TabCategorySelected = category; - Engine.GetGUIObjectByName("tabButtons").children.forEach((button, j) => { + Engine.GetGUIObjectByName("tabButtons").children.forEach((button, j) => + { button.sprite = g_TabHorizontal ? category == j ? "ModernTabHorizontalForeground" : diff --git a/binaries/data/mods/public/gui/common/timer.js b/binaries/data/mods/public/gui/common/timer.js index e40dfde577..8c33829a0d 100644 --- a/binaries/data/mods/public/gui/common/timer.js +++ b/binaries/data/mods/public/gui/common/timer.js @@ -57,9 +57,12 @@ function updateTimers() if (!t) continue; // an earlier timer might have cancelled this one, so skip it - try { + try + { t[1](); - } catch (e) { + } + catch(e) + { var stack = e.stack.trimRight().replace(/^/mg, ' '); // indent the stack trace error(sprintf("Error in timer: %(error)s", { "error": e }) + "\n" + stack + "\n"); } diff --git a/binaries/data/mods/public/gui/common/tooltips.js b/binaries/data/mods/public/gui/common/tooltips.js index d9eb86a415..64deed2bbd 100644 --- a/binaries/data/mods/public/gui/common/tooltips.js +++ b/binaries/data/mods/public/gui/common/tooltips.js @@ -14,7 +14,8 @@ var g_ShowSecondaryNames = Engine.ConfigDB_GetValue("user", "gui.session.howtosh function initDisplayedNames() { - registerConfigChangeHandler(changes => { + registerConfigChangeHandler(changes => + { if (changes.has("gui.session.howtoshownames")) updateDisplayedNames(); }); @@ -269,7 +270,8 @@ function getStatusEffectsResistanceTooltip(resistanceTypeTemplate) "label": headerFont(translate("Status Effects:")), "details": Object.keys(resistanceTypeTemplate).map( - statusEffect => { + statusEffect => + { if (resistanceTypeTemplate[statusEffect].blockChance == 1) return sprintf(translate("Blocks %(name)s"), { "name": unitFont(translateWithContext("status effect", g_StatusEffectsMetadata.getName(statusEffect))) diff --git a/binaries/data/mods/public/gui/credits/credits.js b/binaries/data/mods/public/gui/credits/credits.js index a85091194b..246df0fce1 100644 --- a/binaries/data/mods/public/gui/credits/credits.js +++ b/binaries/data/mods/public/gui/credits/credits.js @@ -56,11 +56,13 @@ function init() g_TabButtonHeight, g_TabButtonDist, selectPanel, - category => { + category => + { Engine.GetGUIObjectByName("creditsText").caption = g_PanelData[category].content; }); - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("closeButton").onPress = closePageCallback; }); } diff --git a/binaries/data/mods/public/gui/gamesetup/Controllers/GameSettingsController.js b/binaries/data/mods/public/gui/gamesetup/Controllers/GameSettingsController.js index 90ee8d9ff3..8d8b02ef3c 100644 --- a/binaries/data/mods/public/gui/gamesetup/Controllers/GameSettingsController.js +++ b/binaries/data/mods/public/gui/gamesetup/Controllers/GameSettingsController.js @@ -84,7 +84,8 @@ class GameSettingsController // and particularly could fail with mods that change persistent settings, so this is // difficult to fully fix from the gameSettings code. // Also include hotloaded data because that can also fail and having to restart isn't very useful. - try { + try + { if (hotloadData) this.parseSettings(hotloadData.initAttributes, false); else if (g_IsController && (initData?.gameSettings || this.persistentMatchSettings.enabled)) @@ -96,7 +97,9 @@ class GameSettingsController if (settings) this.parseSettings(settings, true); } - } catch (err) { + } + catch(err) + { error("There was an error loading game settings. You may need to disable persistent match settings."); warn(err?.toString() ?? uneval(err)); if (err.stack) @@ -231,7 +234,8 @@ class GameSettingsController { if (this.layoutTimer) return; - this.layoutTimer = setTimeout(() => { + this.layoutTimer = setTimeout(() => + { for (const handler of this.updateLayoutHandlers) handler(); delete this.layoutTimer; diff --git a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/GameSettingControlSlider.js b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/GameSettingControlSlider.js index c341ad6564..9880b52c40 100644 --- a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/GameSettingControlSlider.js +++ b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/GameSettingControlSlider.js @@ -61,7 +61,8 @@ class GameSettingControlSlider extends GameSettingControl onValueChangeSuper() { if (!this.isInGuiUpdate && !this.timer) - this.timer = setTimeout(() => { + this.timer = setTimeout(() => + { this.onValueChange(this.slider.value); delete this.timer; }, this.Timeout); diff --git a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/AIConfigButton.js b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/AIConfigButton.js index 3f611190cc..c475f63737 100644 --- a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/AIConfigButton.js +++ b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/AIConfigButton.js @@ -5,7 +5,8 @@ PlayerSettingControls.AIConfigButton = class AIConfigButton extends GameSettingC super(...args); this.aiConfigButton = Engine.GetGUIObjectByName("aiConfigButton[" + this.playerIndex + "]"); - this.aiConfigButton.onPress = () => { + this.aiConfigButton.onPress = () => + { this.setupWindow.pages.AIConfigPage.openPage(this.playerIndex, this.enabled); }; diff --git a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerAssignment.js b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerAssignment.js index c50dca249d..7ade41516a 100644 --- a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerAssignment.js +++ b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerAssignment.js @@ -314,8 +314,8 @@ PlayerSettingControls.PlayerAssignment.prototype.AutocompleteOrder = 100; }; PlayerAssignmentItem.Removed.prototype.Label = - translate("Removed"); + translate("Removed"); PlayerAssignmentItem.Removed.prototype.Tags = - { "color": "255 140 140" }; + { "color": "255 140 140" }; } diff --git a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerColor.js b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerColor.js index 40df57dae7..dfbf75eeee 100644 --- a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerColor.js +++ b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/PerPlayer/Dropdowns/PlayerColor.js @@ -30,7 +30,8 @@ PlayerSettingControls.PlayerColor = class PlayerColor extends GameSettingControl this.values = g_GameSettings.playerColor.available; this.dropdown.list = this.values.map(color => coloredText(this.ColorIcon, rgbToGuiColor(color))); this.dropdown.list_data = this.values.map((color, i) => i); - this.setSelectedValue(this.values.map((color, i) => { + this.setSelectedValue(this.values.map((color, i) => + { if (color.r === value.r && color.g === value.g && color.b === value.b) return i; return undefined; diff --git a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/MapSelection.js b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/MapSelection.js index 3139fc045c..0ed6be22dd 100644 --- a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/MapSelection.js +++ b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/MapSelection.js @@ -120,7 +120,8 @@ GameSettingControls.MapSelection = class MapSelection extends GameSettingControl // which takes a few ms, but this could only be done once per frame anyways. // NB: this technically makes it possible to start the game without the change going through // but it's essentially impossible to trigger accidentally. - const call = () => { + const call = () => + { g_GameSettings.map.selectMap(this.values.file[itemIdx]); this.gameSettingsController.setNetworkInitAttributes(); delete this.reRenderTimeout; diff --git a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/PopulationCap.js b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/PopulationCap.js index c79e9376d4..51d614a375 100644 --- a/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/PopulationCap.js +++ b/binaries/data/mods/public/gui/gamesetup/Pages/GameSetupPage/GameSettings/Single/Dropdowns/PopulationCap.js @@ -48,7 +48,8 @@ GameSettingControls.PopulationCap = class PopulationCap extends GameSettingContr { const popCap = g_GameSettings.population.currentData.Options.List[this.dropdown.hovered]; const nbPlayers = g_GameSettings.playerCount.nbPlayers; - const nbTeams = g_GameSettings.playerTeam.values.reduce((teamList, team) => { + const nbTeams = g_GameSettings.playerTeam.values.reduce((teamList, team) => + { if (!teamList.includes(team) || team == -1) teamList.push(team); return teamList; diff --git a/binaries/data/mods/public/gui/gamesetup_mp/gamesetup_mp.js b/binaries/data/mods/public/gui/gamesetup_mp/gamesetup_mp.js index d4838878c8..0b2d824ed0 100644 --- a/binaries/data/mods/public/gui/gamesetup_mp/gamesetup_mp.js +++ b/binaries/data/mods/public/gui/gamesetup_mp/gamesetup_mp.js @@ -31,7 +31,8 @@ const cancelTag = Symbol("cancelTag"); */ function cancelOr(costumPromise) { - return Promise.race([costumPromise, new Promise(resolve => { + return Promise.race([costumPromise, new Promise(resolve => + { Engine.GetGUIObjectByName("cancelButton").onPress = resolve.bind(undefined, cancelTag); })]); } @@ -42,7 +43,8 @@ async function waitOnEvent(loadSavedGame, joinFromLobby) { if (!joinFromLobby) { - const continueResult = await cancelOr(new Promise(resolve => { + const continueResult = await cancelOr(new Promise(resolve => + { Engine.GetGUIObjectByName("continueButton").onPress = resolve; })); if (continueResult === cancelTag) @@ -55,7 +57,7 @@ async function waitOnEvent(loadSavedGame, joinFromLobby) { confirmSetup(loadSavedGame); } - catch (e) + catch(e) { if (cancelSetup()) return; @@ -64,7 +66,8 @@ async function waitOnEvent(loadSavedGame, joinFromLobby) } while (true) { - const tickResult = await cancelOr(new Promise(resolve => { + const tickResult = await cancelOr(new Promise(resolve => + { Engine.GetGUIObjectByName("multiplayerPages").onTick = resolve; })); if (tickResult === cancelTag || await onTick(loadSavedGame)) @@ -92,7 +95,8 @@ async function init(attribs) { g_ServerName = attribs.name; switchSetupPage("pagePassword"); - const passwordResult = await cancelOr(new Promise(resolve => { + const passwordResult = await cancelOr(new Promise(resolve => + { Engine.GetGUIObjectByName("confirmPasswordButton").onPress = resolve; })); if (passwordResult === cancelTag) @@ -104,7 +108,7 @@ async function init(attribs) attribs.hasPassword ? Engine.GetGUIObjectByName("clientPassword").caption : ""); switchSetupPage("pageConnecting"); } - catch (e) + catch(e) { if (cancelSetup()) return; @@ -439,7 +443,7 @@ function startHost(playername, servername, port, password, loadSavedGame) Engine.StartNetworkHost(playername + (g_UserRating ? " (" + g_UserRating + ")" : ""), port, password, loadSavedGame, true); } - catch (e) + catch(e) { messageBox( 400, 200, @@ -465,7 +469,7 @@ function startJoin(playername, ip, port) { Engine.StartNetworkJoin(playername, ip, port, true); } - catch (e) + catch(e) { messageBox( 400, 200, @@ -507,7 +511,7 @@ function startJoinFromLobby(playername, hostJID, password) { Engine.StartNetworkJoinLobby(playername + (g_UserRating ? " (" + g_UserRating + ")" : ""), hostJID, password); } - catch (e) + catch(e) { messageBox( 400, 200, diff --git a/binaries/data/mods/public/gui/hotkeys/HotkeyMetadata.js b/binaries/data/mods/public/gui/hotkeys/HotkeyMetadata.js index 6d49529221..63ca3fd41d 100644 --- a/binaries/data/mods/public/gui/hotkeys/HotkeyMetadata.js +++ b/binaries/data/mods/public/gui/hotkeys/HotkeyMetadata.js @@ -48,7 +48,8 @@ class HotkeyMetadata } // Sort categories (JS objects are (in this case) sorted by insertion order). this.categories = {}; - const keys = Object.keys(categories).sort((a, b) => { + const keys = Object.keys(categories).sort((a, b) => + { if (a === this.DEFAULT_CATEGORY || b === this.DEFAULT_CATEGORY) return a === this.DEFAULT_CATEGORY ? 1 : -1; if (categories[a].order === undefined || categories[b].order === undefined) diff --git a/binaries/data/mods/public/gui/hotkeys/HotkeyPicker.js b/binaries/data/mods/public/gui/hotkeys/HotkeyPicker.js index ae712ee24a..ccbbcc8a4c 100644 --- a/binaries/data/mods/public/gui/hotkeys/HotkeyPicker.js +++ b/binaries/data/mods/public/gui/hotkeys/HotkeyPicker.js @@ -28,7 +28,8 @@ class HotkeyPicker this.setupCombinations(); this.render(); - Engine.GetGUIObjectByName("hotkeyPickerReset").onPress = () => { + Engine.GetGUIObjectByName("hotkeyPickerReset").onPress = () => + { // This is a bit "using a bazooka to kill a fly" Engine.ConfigDB_RemoveValueAndSave("user", "hotkey." + this.name); Engine.ReloadHotkeys(); @@ -37,10 +38,12 @@ class HotkeyPicker this.setupCombinations(); this.render(); }; - Engine.GetGUIObjectByName("hotkeyPickerCancel").onPress = () => { + Engine.GetGUIObjectByName("hotkeyPickerCancel").onPress = () => + { onClose(this, false); }; - Engine.GetGUIObjectByName("hotkeyPickerSave").onPress = () => { + Engine.GetGUIObjectByName("hotkeyPickerSave").onPress = () => + { onClose(this, true); }; } @@ -61,24 +64,28 @@ class HotkeyPicker const input = Engine.GetGUIObjectByName("combMapping[" + i + "]"); const picker = Engine.GetGUIObjectByName("picker[" + i + "]"); - Engine.GetGUIObjectByName("combMappingBtn[" + i + "]").onPress = () => { + Engine.GetGUIObjectByName("combMappingBtn[" + i + "]").onPress = () => + { this.enteringInput = i; picker.focus(); this.render(); }; - picker.onKeyChange = keys => { + picker.onKeyChange = keys => + { input.caption = (keys.length ? formatHotkeyCombination(keys) + translate(" (hold to register)") : translate("Enter new Hotkey, hold to register.")); }; - Engine.GetGUIObjectByName("deleteComb[" + i + "]").onPress = (j => () => { + Engine.GetGUIObjectByName("deleteComb[" + i + "]").onPress = (j => () => + { this.combinations[j] = []; this.render(); })(i); - picker.onCombination = (j => keys => { + picker.onCombination = (j => keys => + { this.combinations[j] = keys; this.enteringInput = -1; picker.blur(); diff --git a/binaries/data/mods/public/gui/hotkeys/HotkeysPage.js b/binaries/data/mods/public/gui/hotkeys/HotkeysPage.js index c6565e8c81..25e3cc1caa 100644 --- a/binaries/data/mods/public/gui/hotkeys/HotkeysPage.js +++ b/binaries/data/mods/public/gui/hotkeys/HotkeysPage.js @@ -4,7 +4,8 @@ class HotkeysPage { this.metadata = metadata; - Engine.GetGUIObjectByName("hotkeyList").onMouseLeftDoubleClickItem = () => { + Engine.GetGUIObjectByName("hotkeyList").onMouseLeftDoubleClickItem = () => + { const idx = Engine.GetGUIObjectByName("hotkeyList").selected; const picker = new HotkeyPicker( this.metadata, @@ -25,7 +26,8 @@ class HotkeysPage Engine.GetGUIObjectByName("hotkeyClose").onPress = closePageCallback; Engine.GetGUIObjectByName("hotkeyReset").onPress = () => this.resetUserHotkeys(); - this.saveButton.onPress = () => { + this.saveButton.onPress = () => + { this.saveUserHotkeys(); this.saveButton.enabled = false; }; @@ -55,7 +57,8 @@ class HotkeysPage categories[this.metadata.DEFAULT_CATEGORY].hotkeys.push(hotkeyName); } for (const cat in categories) - categories[cat].hotkeys.sort((a, b) => { + categories[cat].hotkeys.sort((a, b) => + { if (!this.metadata.hotkeys[a] || !this.metadata.hotkeys[b]) return !this.metadata.hotkeys[a] ? 1 : -1; return this.metadata.hotkeys[a].order - this.metadata.hotkeys[b].order; @@ -89,7 +92,8 @@ class HotkeysPage hotkeys = this.categories[dropdown.list_data[dropdown.selected]].hotkeys; else hotkeys = Object.values(this.categories).map(x => x.hotkeys).flat(); - hotkeys = hotkeys.filter(x => { + hotkeys = hotkeys.filter(x => + { return x.indexOf(textFilter) !== -1 || translateWithContext("hotkey metadata", this.metadata.hotkeys[x]?.name || x).toLowerCase().indexOf(textFilter) !== -1; }); @@ -151,7 +155,8 @@ class HotkeysPage return; for (const cat in this.categories) - this.categories[cat].hotkeys.forEach((name) => { + this.categories[cat].hotkeys.forEach((name) => + { Engine.ConfigDB_RemoveValue("user", "hotkey." + name); }); Engine.ConfigDB_SaveChanges("user"); @@ -181,7 +186,8 @@ class HotkeysPage function init() { - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { // FIXME: There are proposals to remove init and allowing to specify // controller classes in the gui xml, therefore leave it as a class and // suppress the warning. diff --git a/binaries/data/mods/public/gui/loadgame/SavegameDeleter.js b/binaries/data/mods/public/gui/loadgame/SavegameDeleter.js index 5b3de424f2..dcda1cfab2 100644 --- a/binaries/data/mods/public/gui/loadgame/SavegameDeleter.js +++ b/binaries/data/mods/public/gui/loadgame/SavegameDeleter.js @@ -23,7 +23,8 @@ class SavegameDeleter onSelectionChange(gameID, metadata, label) { this.deleteGameButton.enabled = !!metadata; - this.deleteGameButton.onPress = () => { + this.deleteGameButton.onPress = () => + { this.deleteGame(gameID, label); }; } diff --git a/binaries/data/mods/public/gui/loadgame/SavegameList.js b/binaries/data/mods/public/gui/loadgame/SavegameList.js index 8c28d35f15..dbaf729506 100644 --- a/binaries/data/mods/public/gui/loadgame/SavegameList.js +++ b/binaries/data/mods/public/gui/loadgame/SavegameList.js @@ -35,7 +35,8 @@ class SavegameList this.gameSelection.onSelectionColumnChange = () => { this.updateSavegameList(); }; this.gameSelection.onMouseLeftDoubleClickItem = () => { this.confirmButton.onPress(); }; - this.gameSelection.onSelectionChange = () => { + this.gameSelection.onSelectionChange = () => + { const gameId = this.gameSelection.list_data[this.gameSelection.selected]; const metadata = this.savedGamesMetadata[this.gameSelection.selected]; const label = this.generateSavegameLabel(metadata, engineInfo); @@ -74,7 +75,8 @@ class SavegameList const engineInfo = Engine.GetEngineInfo(); if (this.compatibilityFilter.checked) - savedGames = savedGames.filter(game => { + savedGames = savedGames.filter(game => + { return this.isCompatibleSavegame(game.metadata, engineInfo) && this.campaignFilter(game.metadata, this.campaignRun); }); @@ -88,7 +90,8 @@ class SavegameList const selectedGameId = this.gameSelection.list_data[this.gameSelection.selected]; // Save metadata for the detailed view - this.savedGamesMetadata = savedGames.map(game => { + this.savedGamesMetadata = savedGames.map(game => + { game.metadata.id = game.id; return game.metadata; }); @@ -96,7 +99,8 @@ class SavegameList const sortKey = this.gameSelection.selected_column; const sortOrder = this.gameSelection.selected_column_order; - this.savedGamesMetadata = this.savedGamesMetadata.sort((a, b) => { + this.savedGamesMetadata = this.savedGamesMetadata.sort((a, b) => + { let cmpA, cmpB; switch (sortKey) { @@ -128,7 +132,8 @@ class SavegameList return 0; }); - let list = this.savedGamesMetadata.map(metadata => { + let list = this.savedGamesMetadata.map(metadata => + { const isCompatible = this.isCompatibleSavegame(metadata, engineInfo) && this.campaignFilter(metadata, this.campaignRun); // Backwards compatibility for pre-A25 savegames diff --git a/binaries/data/mods/public/gui/loadgame/SavegameLoader.js b/binaries/data/mods/public/gui/loadgame/SavegameLoader.js index 154df3ca1f..956cb38eb8 100644 --- a/binaries/data/mods/public/gui/loadgame/SavegameLoader.js +++ b/binaries/data/mods/public/gui/loadgame/SavegameLoader.js @@ -14,7 +14,8 @@ class SavegameLoader onSelectionChange(gameID, metadata, label) { this.confirmButton.enabled = !!metadata; - this.confirmButton.onPress = () => { + this.confirmButton.onPress = () => + { this.loadGame(gameID, metadata); }; } diff --git a/binaries/data/mods/public/gui/loadgame/SavegamePage.js b/binaries/data/mods/public/gui/loadgame/SavegamePage.js index db6c717d67..4ad069a245 100644 --- a/binaries/data/mods/public/gui/loadgame/SavegamePage.js +++ b/binaries/data/mods/public/gui/loadgame/SavegamePage.js @@ -38,7 +38,8 @@ var g_SavegamePage; function init(data) { - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { g_SavegamePage = new SavegamePage(data, closePageCallback); }); } diff --git a/binaries/data/mods/public/gui/loadgame/SavegameWriter.js b/binaries/data/mods/public/gui/loadgame/SavegameWriter.js index 156ccb5bec..3198690fcc 100644 --- a/binaries/data/mods/public/gui/loadgame/SavegameWriter.js +++ b/binaries/data/mods/public/gui/loadgame/SavegameWriter.js @@ -9,7 +9,8 @@ class SavegameWriter this.closePageCallback = closePageCallback; this.savedGameData = savedGameData; - const saveNew = () => { + const saveNew = () => + { this.saveGame(); }; @@ -21,7 +22,8 @@ class SavegameWriter this.saveGameDesc.hidden = false; this.saveGameDesc.onPress = saveNew; this.descriptionChanged = false; - this.saveGameDesc.onTextEdit = () => { + this.saveGameDesc.onTextEdit = () => + { this.descriptionChanged = true; }; } @@ -30,7 +32,8 @@ class SavegameWriter { if (!this.descriptionChanged && metadata && typeof metadata.description === "string") this.saveGameDesc.caption = metadata.description; - this.confirmButton.onPress = () => { + this.confirmButton.onPress = () => + { this.saveGame(gameID, label); }; } diff --git a/binaries/data/mods/public/gui/lobby/AccountSettingsPage/AccountSettingsPage.js b/binaries/data/mods/public/gui/lobby/AccountSettingsPage/AccountSettingsPage.js index 78ced36bd9..4fe8061abe 100644 --- a/binaries/data/mods/public/gui/lobby/AccountSettingsPage/AccountSettingsPage.js +++ b/binaries/data/mods/public/gui/lobby/AccountSettingsPage/AccountSettingsPage.js @@ -12,7 +12,8 @@ var AccountSettingsPage = { pageElement.hidden = false; pageElement.onTick = updateTimers; await Promise.race([ - new Promise(resolve => { + new Promise(resolve => + { Engine.SetGlobalHotkey("cancel", "Press", resolve); Engine.GetGUIObjectByName("as_Close").onPress = resolve; }), @@ -31,7 +32,8 @@ var AccountSettingsPage = { const changePasswordButton = Engine.GetGUIObjectByName("as_ChangePasswordBtn"); while (true) { - await new Promise(resolve => { + await new Promise(resolve => + { changePasswordButton.onPress = resolve; }); try @@ -56,9 +58,11 @@ var AccountSettingsPage = { requestResult.caption = translate("Changing password…"); const encryptedPassword = AccountSettingsPage._readAndValidatePassword(SetPasswordError); Engine.LobbyChangePassword(encryptedPassword); - await new Promise((resolve, reject) => { + await new Promise((resolve, reject) => + { xmppMessages.registerXmppMessageHandler("system", "registered", resolve); - xmppMessages.registerXmppMessageHandler("system", "error", message => { + xmppMessages.registerXmppMessageHandler("system", "error", message => + { reject(new SetPasswordError(message.text)); }); timeout = setTimeout(reject.bind(null, @@ -70,7 +74,7 @@ var AccountSettingsPage = { Engine["ConfigDB_" + functionSufix]("user", "lobby.password", encryptedPassword); Engine.ConfigDB_SaveChanges("user"); } - catch (e) + catch(e) { if (e instanceof SetPasswordError) { diff --git a/binaries/data/mods/public/gui/lobby/LeaderboardPage/LeaderboardList.js b/binaries/data/mods/public/gui/lobby/LeaderboardPage/LeaderboardList.js index fc66557815..01f6123ce5 100644 --- a/binaries/data/mods/public/gui/lobby/LeaderboardPage/LeaderboardList.js +++ b/binaries/data/mods/public/gui/lobby/LeaderboardPage/LeaderboardList.js @@ -47,7 +47,8 @@ class LeaderboardList const list_rank = []; const list_rating = []; - boardList.forEach((entry, i) => { + boardList.forEach((entry, i) => + { list_name.push(escapeText(entry.name)); list_rating.push(entry.rating); list_rank.push(i + 1); diff --git a/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/ChatCommandHandler.js b/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/ChatCommandHandler.js index 0936b77c79..f6adba1049 100644 --- a/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/ChatCommandHandler.js +++ b/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/ChatCommandHandler.js @@ -86,21 +86,24 @@ ChatCommandHandler.prototype.ChatCommandTags = { ChatCommandHandler.prototype.ChatCommands = { "away": { "description": translate("Set your state to 'Away'."), - "handler": function(args) { + "handler": function(args) + { Engine.LobbySetPlayerPresence("away"); return true; } }, "back": { "description": translate("Set your state to 'Online'."), - "handler": function(args) { + "handler": function(args) + { Engine.LobbySetPlayerPresence("available"); return true; } }, "kick": { "description": translate("Kick a specified user from the lobby. Usage: /kick nick reason"), - "handler": function(args) { + "handler": function(args) + { const index = args.indexOf(" "); if (index == -1) Engine.LobbyKick(args, ""); @@ -112,7 +115,8 @@ ChatCommandHandler.prototype.ChatCommands = { }, "ban": { "description": translate("Ban a specified user from the lobby. Usage: /ban nick reason"), - "handler": function(args) { + "handler": function(args) + { const index = args.indexOf(" "); if (index == -1) Engine.LobbyBan(args, ""); @@ -124,7 +128,8 @@ ChatCommandHandler.prototype.ChatCommands = { }, "help": { "description": translate("Show this help."), - "handler": function(args) { + "handler": function(args) + { const isModerator = Engine.LobbyGetPlayerRole(g_Nickname) == "moderator"; let txt = translate("Chat commands:"); for (const command in this.ChatCommands) @@ -145,21 +150,24 @@ ChatCommandHandler.prototype.ChatCommands = { }, "me": { "description": translate("Send a chat message about yourself. Example: /me goes swimming."), - "handler": function(args) { + "handler": function(args) + { // Translation: Chat command return this.argumentCount(translate("/me"), args); } }, "say": { "description": translate("Send text as a chat message (even if it starts with slash). Example: /say /help is a great command."), - "handler": function(args) { + "handler": function(args) + { // Translation: Chat command return this.argumentCount(translate("/say"), args); } }, "clear": { "description": translate("Clear all chat scrollback."), - "handler": function(args) { + "handler": function(args) + { this.chatMessagesPanel.clearChatMessages(); return true; } diff --git a/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/StatusMessages/StatusMessageEvents.js b/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/StatusMessages/StatusMessageEvents.js index 8f59581fd6..57a85149e2 100644 --- a/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/StatusMessages/StatusMessageEvents.js +++ b/binaries/data/mods/public/gui/lobby/LobbyPage/Chat/StatusMessages/StatusMessageEvents.js @@ -104,30 +104,30 @@ ChatMessageEvents.Role = class }; ChatMessageEvents.Role.prototype.RoleStrings = -[ - { - "newrole": "visitor", - "you": translate("You have been muted."), - "nick": translate("%(nick)s has been muted.") - }, - { - "newrole": "moderator", - "you": translate("You are now a moderator."), - "nick": translate("%(nick)s is now a moderator.") - }, - { - "newrole": "participant", - "oldrole": "visitor", - "you": translate("You have been unmuted."), - "nick": translate("%(nick)s has been unmuted.") - }, - { - "newrole": "participant", - "oldrole": "moderator", - "you": translate("You are not a moderator anymore."), - "nick": translate("%(nick)s is not a moderator anymore.") - } -]; + [ + { + "newrole": "visitor", + "you": translate("You have been muted."), + "nick": translate("%(nick)s has been muted.") + }, + { + "newrole": "moderator", + "you": translate("You are now a moderator."), + "nick": translate("%(nick)s is now a moderator.") + }, + { + "newrole": "participant", + "oldrole": "visitor", + "you": translate("You have been unmuted."), + "nick": translate("%(nick)s has been unmuted.") + }, + { + "newrole": "participant", + "oldrole": "moderator", + "you": translate("You are not a moderator anymore."), + "nick": translate("%(nick)s is not a moderator anymore.") + } + ]; ChatMessageEvents.Subject = class { diff --git a/binaries/data/mods/public/gui/lobby/LobbyPage/Game.js b/binaries/data/mods/public/gui/lobby/LobbyPage/Game.js index d6ed7e6971..8105bbbfaf 100644 --- a/binaries/data/mods/public/gui/lobby/LobbyPage/Game.js +++ b/binaries/data/mods/public/gui/lobby/LobbyPage/Game.js @@ -219,7 +219,7 @@ class Game { this.mods = JSON.parse(newStanza.mods); } - catch (e) + catch(e) { this.mods = []; } diff --git a/binaries/data/mods/public/gui/lobby/LobbyPage/GameList.js b/binaries/data/mods/public/gui/lobby/LobbyPage/GameList.js index 3876e0066a..985c96bdd2 100644 --- a/binaries/data/mods/public/gui/lobby/LobbyPage/GameList.js +++ b/binaries/data/mods/public/gui/lobby/LobbyPage/GameList.js @@ -125,7 +125,8 @@ class GameList { Engine.ProfileStart("sortGameList"); const sortOrder = this.gamesBox.selected_column_order; - this.gameList.sort((game1, game2) => { + this.gameList.sort((game1, game2) => + { if (game1.sortValue < game2.sortValue) return -sortOrder; if (game1.sortValue > game2.sortValue) return +sortOrder; return 0; @@ -148,7 +149,8 @@ class GameList this.list_gameRating.length = length; this.list.length = length; - this.gameList.forEach((game, i) => { + this.gameList.forEach((game, i) => + { const displayData = game.displayData; this.list_buddy[i] = displayData.buddy || ""; diff --git a/binaries/data/mods/public/gui/lobby/LobbyPage/PlayerList.js b/binaries/data/mods/public/gui/lobby/LobbyPage/PlayerList.js index f809d0cf53..755a0a4a1c 100644 --- a/binaries/data/mods/public/gui/lobby/LobbyPage/PlayerList.js +++ b/binaries/data/mods/public/gui/lobby/LobbyPage/PlayerList.js @@ -145,7 +145,8 @@ class PlayerList this.nickList.length = length; this.ratingList.length = length; - playerList.forEach((player, i) => { + playerList.forEach((player, i) => + { // TODO: COList.cpp columns should support horizontal center align const rating = player.rating ? (" " + player.rating).substr(-5) : " -"; diff --git a/binaries/data/mods/public/gui/lobby/lobby.js b/binaries/data/mods/public/gui/lobby/lobby.js index 472b07521c..ec565ef3b8 100644 --- a/binaries/data/mods/public/gui/lobby/lobby.js +++ b/binaries/data/mods/public/gui/lobby/lobby.js @@ -34,7 +34,8 @@ var g_LobbyHandler; async function init(attribs) { if (g_Settings) - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { g_LobbyHandler = new LobbyHandler(closePageCallback, attribs && attribs.dialog); }); diff --git a/binaries/data/mods/public/gui/locale/locale.js b/binaries/data/mods/public/gui/locale/locale.js index 4108f53fa2..446c27f765 100644 --- a/binaries/data/mods/public/gui/locale/locale.js +++ b/binaries/data/mods/public/gui/locale/locale.js @@ -3,7 +3,8 @@ function init() var languageList = Engine.GetGUIObjectByName("languageList"); const displayLanguages = Engine.GetSupportedLocaleDisplayNames(); const displayLanguagesData = Engine.GetSupportedLocaleBaseNames(); - languageList.list = displayLanguages.map((name, index) => { + languageList.list = displayLanguages.map((name, index) => + { return `[locale="${displayLanguagesData[index]}"]${name}[/locale]`; }); languageList.list_data = displayLanguagesData; @@ -18,7 +19,8 @@ function init() var localeText = Engine.GetGUIObjectByName("localeText"); localeText.caption = currentLocale; - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("cancelButton").onPress = closePageCallback; }); } diff --git a/binaries/data/mods/public/gui/locale_advanced/locale_advanced.js b/binaries/data/mods/public/gui/locale_advanced/locale_advanced.js index 7ee49a8a25..8fafa21035 100644 --- a/binaries/data/mods/public/gui/locale_advanced/locale_advanced.js +++ b/binaries/data/mods/public/gui/locale_advanced/locale_advanced.js @@ -47,9 +47,11 @@ function init(initData) // fill the script scriptInput.caption = Engine.GetLocaleScript(initData.locale); - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("cancelButton").onPress = closePageCallback; - Engine.GetGUIObjectByName("acceptButton").onPress = () => { + Engine.GetGUIObjectByName("acceptButton").onPress = () => + { closePageCallback(applySelectedLocale()); }; }); diff --git a/binaries/data/mods/public/gui/manual/manual.js b/binaries/data/mods/public/gui/manual/manual.js index 56424e6778..4592f0c44a 100644 --- a/binaries/data/mods/public/gui/manual/manual.js +++ b/binaries/data/mods/public/gui/manual/manual.js @@ -8,7 +8,8 @@ function init() // Replace anything starting with 'hotkey.' with its hotkey. mainText.caption = text.replace(/hotkey.([a-z0-9_.]+)/g, (_, k) => formatHotkeyCombinations(hotkeys[k])); - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("closeButton").onPress = closePageCallback; }); } diff --git a/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapBrowserControls.js b/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapBrowserControls.js index 6bea1c1ece..9aa03ce4c5 100644 --- a/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapBrowserControls.js +++ b/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapBrowserControls.js @@ -29,7 +29,8 @@ class MapBrowserPageControls setupButtons() { this.pickRandom = Engine.GetGUIObjectByName("mapBrowserPagePickRandom"); - this.pickRandom.onPress = () => { + this.pickRandom.onPress = () => + { const index = randIntInclusive(0, this.gridBrowser.itemCount - 1); this.gridBrowser.setSelectedIndex(index); this.gridBrowser.goToPageOfSelected(); diff --git a/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapFiltering.js b/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapFiltering.js index 0b6e7a550a..7862f5582b 100644 --- a/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapFiltering.js +++ b/binaries/data/mods/public/gui/maps/mapbrowser/controls/MapFiltering.js @@ -22,7 +22,8 @@ MapBrowserPageControls.prototype.MapFiltering = class onOpenPage() { // setTimeout avoids having the hotkey key inserted into the input text. - setTimeout(() => { + setTimeout(() => + { this.searchBox.control.caption = ""; this.searchBox.focus(); }, 0); diff --git a/binaries/data/mods/public/gui/maps/mapbrowser/utils/MatchSort.js b/binaries/data/mods/public/gui/maps/mapbrowser/utils/MatchSort.js index f7bf9c4295..56a2b29bfb 100644 --- a/binaries/data/mods/public/gui/maps/mapbrowser/utils/MatchSort.js +++ b/binaries/data/mods/public/gui/maps/mapbrowser/utils/MatchSort.js @@ -1,4 +1,5 @@ -const MatchSort = (function() { +const MatchSort = (function() +{ const Highscore = -10E7; return class diff --git a/binaries/data/mods/public/gui/options/options.js b/binaries/data/mods/public/gui/options/options.js index 4c732e0c8b..23bc5e714c 100644 --- a/binaries/data/mods/public/gui/options/options.js +++ b/binaries/data/mods/public/gui/options/options.js @@ -58,7 +58,8 @@ var g_OptionType = { "boolean": { "configToValue": config => config == "true", - "valueToGui": (value, control) => { + "valueToGui": (value, control) => + { control.checked = value; }, "guiToValue": control => control.checked, @@ -67,7 +68,8 @@ var g_OptionType = { "string": { "configToValue": value => value, - "valueToGui": (value, control) => { + "valueToGui": (value, control) => + { control.caption = value; }, "guiToValue": control => control.caption, @@ -76,11 +78,14 @@ var g_OptionType = { "color": { "configToValue": value => value, - "valueToGui": (value, control) => { + "valueToGui": (value, control) => + { control.caption = value; }, - "initGUI": (option, control) => { - control.children[2].onPress = async() => { + "initGUI": (option, control) => + { + control.children[2].onPress = async() => + { const color = await Engine.OpenChildPage("page_colormixer.xml", control.caption); if (color != control.caption) @@ -92,7 +97,8 @@ var g_OptionType = { }, "guiToValue": control => control.caption, "guiSetter": "onTextEdit", - "sanitizeValue": (value, control, option) => { + "sanitizeValue": (value, control, option) => + { const color = guiToRgbColor(value); const sanitized = rgbToGuiColor(color); if (control) @@ -110,12 +116,14 @@ var g_OptionType = { "number": { "configToValue": value => value, - "valueToGui": (value, control) => { + "valueToGui": (value, control) => + { control.caption = value; }, "guiToValue": control => control.caption, "guiSetter": "onTextEdit", - "sanitizeValue": (value, control, option) => { + "sanitizeValue": (value, control, option) => + { const sanitized = Math.min(option.max !== undefined ? option.max : +Infinity, Math.max(option.min !== undefined ? option.min : -Infinity, @@ -143,15 +151,18 @@ var g_OptionType = { "dropdown": { "configToValue": value => value, - "valueToGui": (value, control) => { + "valueToGui": (value, control) => + { control.selected = control.list_data.indexOf(value); }, "guiToValue": control => control.list_data[control.selected], "guiSetter": "onSelectionChange", - "initGUI": (option, control) => { + "initGUI": (option, control) => + { control.list = option.list.map(e => e.label); control.list_data = option.list.map(e => e.value); - control.onHoverChange = () => { + control.onHoverChange = () => + { const item = option.list[control.hovered]; control.tooltip = item && item.tooltip || option.tooltip; }; @@ -160,20 +171,24 @@ var g_OptionType = { "dropdownNumber": { "configToValue": value => +value, - "valueToGui": (value, control) => { + "valueToGui": (value, control) => + { control.selected = control.list_data.indexOf("" + value); }, "guiToValue": control => +control.list_data[control.selected], "guiSetter": "onSelectionChange", - "initGUI": (option, control) => { + "initGUI": (option, control) => + { control.list = option.list.map(e => e.label); control.list_data = option.list.map(e => e.value); - control.onHoverChange = () => { + control.onHoverChange = () => + { const item = option.list[control.hovered]; control.tooltip = item && item.tooltip || option.tooltip; }; }, - "timeout": async(option, oldValue, hasChanges, newValue) => { + "timeout": async(option, oldValue, hasChanges, newValue) => + { if (!option.timeout) return; const buttonIndex = await timedConfirmation( @@ -191,12 +206,14 @@ var g_OptionType = { "slider": { "configToValue": value => +value, - "valueToGui": (value, control) => { + "valueToGui": (value, control) => + { control.value = +value; }, "guiToValue": control => control.value, "guiSetter": "onValueChange", - "initGUI": (option, control) => { + "initGUI": (option, control) => + { control.max_value = option.max; control.min_value = option.min; }, @@ -282,7 +299,8 @@ function displayOptions() if (optionType.sanitizeValue) optionType.sanitizeValue(value, control, option); - control[optionType.guiSetter] = function() { + control[optionType.guiSetter] = function() + { const newValue = optionType.guiToValue(control); @@ -326,8 +344,10 @@ function displayOptions() */ function enableButtons() { - g_Options[g_TabCategorySelected].options.forEach((option, i) => { - const isDependencyMet = dependency => { + g_Options[g_TabCategorySelected].options.forEach((option, i) => + { + const isDependencyMet = dependency => + { if (typeof dependency === "string") return Engine.ConfigDB_GetValue("user", dependency) == "true"; else if (typeof dependency === "object") @@ -409,8 +429,10 @@ function revertChanges() async function saveChanges() { - const category = Object.keys(g_Options).find(key => { - return g_Options[key].options.some(option => { + const category = Object.keys(g_Options).find(key => + { + return g_Options[key].options.some(option => + { const optionType = g_OptionType[option.type]; if (!optionType.sanitizeValue) return false; diff --git a/binaries/data/mods/public/gui/pregame/MainMenuItemHandler.js b/binaries/data/mods/public/gui/pregame/MainMenuItemHandler.js index ed8ff98928..9219123e49 100644 --- a/binaries/data/mods/public/gui/pregame/MainMenuItemHandler.js +++ b/binaries/data/mods/public/gui/pregame/MainMenuItemHandler.js @@ -27,7 +27,8 @@ export class MainMenuItemHandler setupMenuButtons(buttons, menuItems) { - buttons.forEach((button, i) => { + buttons.forEach((button, i) => + { const item = menuItems[i]; button.hidden = !item; if (button.hidden) @@ -87,7 +88,8 @@ export class MainMenuItemHandler { const item = menuItems[i]; if (item.onPress && item.hotkey) - Engine.SetGlobalHotkey(item.hotkey, "Press", () => { + Engine.SetGlobalHotkey(item.hotkey, "Press", () => + { this.closeSubmenu(); item.onPress(); }); diff --git a/binaries/data/mods/public/gui/pregame/MainMenuItems.js b/binaries/data/mods/public/gui/pregame/MainMenuItems.js index 84c5280161..688da56df1 100644 --- a/binaries/data/mods/public/gui/pregame/MainMenuItems.js +++ b/binaries/data/mods/public/gui/pregame/MainMenuItems.js @@ -6,14 +6,16 @@ export const mainMenuItems = [ { "caption": translate("Manual"), "tooltip": translate("Open the 0 A.D. Game Manual."), - "onPress": () => { + "onPress": () => + { Engine.OpenChildPage("page_manual.xml"); } }, { "caption": translate("Tutorial"), "tooltip": translate("Start the introductory tutorial."), - "onPress": () => { + "onPress": () => + { Engine.SwitchGuiPage("page_autostart.xml", { "attribs": { "mapType": "scenario", @@ -43,7 +45,8 @@ export const mainMenuItems = [ "caption": translate("Structure Tree"), "tooltip": colorizeHotkey(translate("%(hotkey)s: View the structure tree of civilizations featured in 0 A.D."), "structree"), "hotkey": "structree", - "onPress": () => { + "onPress": () => + { pageLoop("page_structree.xml"); } }, @@ -51,21 +54,24 @@ export const mainMenuItems = [ "caption": translate("Civilization Overview"), "tooltip": colorizeHotkey(translate("%(hotkey)s: Learn about the civilizations featured in 0 A.D."), "civinfo"), "hotkey": "civinfo", - "onPress": () => { + "onPress": () => + { pageLoop("page_civinfo.xml"); } }, { "caption": translate("Catafalque Overview"), "tooltip": translate("Compare the bonuses of catafalques featured in 0 A.D."), - "onPress": () => { + "onPress": () => + { Engine.OpenChildPage("page_catafalque.xml"); } }, { "caption": translate("Map Overview"), "tooltip": translate("View the different maps featured in 0 A.D."), - "onPress": () => { + "onPress": () => + { Engine.OpenChildPage("page_mapbrowser.xml"); } } @@ -74,12 +80,13 @@ export const mainMenuItems = [ { "caption": translate("Continue Campaign"), "tooltip": translate("Relive history through historical military campaigns."), - "onPress": () => { + "onPress": () => + { try { Engine.SwitchGuiPage(CampaignRun.getCurrentRun().getMenuPath()); } - catch (err) + catch(err) { error("Error opening campaign run:"); error(err.toString()); @@ -94,14 +101,16 @@ export const mainMenuItems = [ { "caption": translate("Matches"), "tooltip": translate("Start a new single-player game."), - "onPress": () => { + "onPress": () => + { Engine.SwitchGuiPage("page_gamesetup.xml"); } }, { "caption": translate("Load Game"), "tooltip": translate("Load a saved game."), - "onPress": async() => { + "onPress": async() => + { const gameId = await Engine.OpenChildPage("page_loadgame.xml"); if (!gameId) @@ -131,12 +140,13 @@ export const mainMenuItems = [ { "caption": translate("Continue Campaign"), "tooltip": translate("Relive history through historical military campaigns."), - "onPress": () => { + "onPress": () => + { try { Engine.SwitchGuiPage(CampaignRun.getCurrentRun().getMenuPath()); } - catch (err) + catch(err) { error("Error opening campaign run:"); error(err.toString()); @@ -147,14 +157,16 @@ export const mainMenuItems = [ { "caption": translate("New Campaign"), "tooltip": translate("Relive history through historical military campaigns."), - "onPress": () => { + "onPress": () => + { Engine.SwitchGuiPage("campaigns/setup/page.xml"); } }, { "caption": translate("Load Campaign"), "tooltip": translate("Relive history through historical military campaigns."), - "onPress": () => { + "onPress": () => + { // Switch instead of push, otherwise the 'continue' // button might remain enabled. // TODO: find a better solution. @@ -164,7 +176,8 @@ export const mainMenuItems = [ { "caption": translate("Replays"), "tooltip": translate("Playback previous games."), - "onPress": () => { + "onPress": () => + { Engine.SwitchGuiPage("page_replaymenu.xml", { "replaySelectionData": { "filters": { @@ -187,7 +200,8 @@ export const mainMenuItems = [ (Engine.StartXmppClient ? "" : translate("Launch the multiplayer lobby. \\[DISABLED BY BUILD]")), "enabled": () => !!Engine.StartXmppClient, "hotkey": "lobby", - "onPress": () => { + "onPress": () => + { if (Engine.StartXmppClient) Engine.OpenChildPage("page_prelobby_entrance.xml"); } @@ -219,7 +233,8 @@ export const mainMenuItems = [ { "caption": translate("Replays"), "tooltip": translate("Playback previous games."), - "onPress": () => { + "onPress": () => + { Engine.SwitchGuiPage("page_replaymenu.xml", { "replaySelectionData": { "filters": { @@ -238,35 +253,40 @@ export const mainMenuItems = [ { "caption": translate("Options"), "tooltip": translate("Adjust game settings."), - "onPress": async() => { + "onPress": async() => + { fireConfigChangeHandlers(await Engine.OpenChildPage("page_options.xml")); } }, { "caption": translate("Hotkeys"), "tooltip": translate("Adjust hotkeys."), - "onPress": () => { + "onPress": () => + { Engine.OpenChildPage("hotkeys/page_hotkeys.xml"); } }, { "caption": translate("Language"), "tooltip": translate("Choose the language of the game."), - "onPress": () => { + "onPress": () => + { Engine.OpenChildPage("page_locale.xml"); } }, { "caption": translate("Mod Selection"), "tooltip": translate("Select and download mods for the game."), - "onPress": () => { + "onPress": () => + { Engine.SwitchGuiPage("page_modmod.xml"); } }, { "caption": translate("Welcome Screen"), "tooltip": translate("Show the Welcome Screen again. Useful if you hid it by mistake."), - "onPress": () => { + "onPress": () => + { Engine.OpenChildPage("page_splashscreen.xml"); } } @@ -275,7 +295,8 @@ export const mainMenuItems = [ { "caption": translate("Scenario Editor"), "tooltip": translate('Open the Atlas Scenario Editor in a new window. You can run this more reliably by starting the game with the command-line argument "-editor".'), - "onPress": async(closePageCallback) => { + "onPress": async(closePageCallback) => + { if (!Engine.AtlasIsAvailable()) { messageBox( @@ -298,14 +319,16 @@ export const mainMenuItems = [ { "caption": translate("Credits"), "tooltip": translate("Show the 0 A.D. credits."), - "onPress": () => { + "onPress": () => + { Engine.OpenChildPage("page_credits.xml"); } }, { "caption": translate("Exit"), "tooltip": translate("Exit the game."), - "onPress": async(closePageCallback) => { + "onPress": async(closePageCallback) => + { const buttonIndex = await messageBox( 400, 200, translate("Are you sure you want to quit 0 A.D.?"), diff --git a/binaries/data/mods/public/gui/pregame/MainMenuPage.js b/binaries/data/mods/public/gui/pregame/MainMenuPage.js index ed18b5ad5b..c2f9093be6 100644 --- a/binaries/data/mods/public/gui/pregame/MainMenuPage.js +++ b/binaries/data/mods/public/gui/pregame/MainMenuPage.js @@ -19,7 +19,8 @@ function initCommunityButton(communityButtons) { const buttons = Engine.GetGUIObjectByName("communityButtons").children; - communityButtons.forEach((buttonInfo, i) => { + communityButtons.forEach((buttonInfo, i) => + { const button = buttons[i]; button.hidden = false; for (const propertyName in buttonInfo) diff --git a/binaries/data/mods/public/gui/pregame/ProjectInformation.js b/binaries/data/mods/public/gui/pregame/ProjectInformation.js index 53b71a076e..151197c034 100644 --- a/binaries/data/mods/public/gui/pregame/ProjectInformation.js +++ b/binaries/data/mods/public/gui/pregame/ProjectInformation.js @@ -25,7 +25,8 @@ export const communityButtons = [ "caption": translate("Website"), "tooltip": translate("Click to open play0ad.com in your web browser."), "size": "8 100%-148 50%-4 100%-116", - "onPress": () => { + "onPress": () => + { openURL("https://play0ad.com/"); } }, @@ -33,7 +34,8 @@ export const communityButtons = [ "caption": translate("Chat"), "tooltip": translate("Click to open the 0 A.D. IRC chat in your browser (#0ad on webchat.quakenet.org). It is run by volunteers who do all sorts of tasks, it may take a while to get your question answered. Alternatively, you can use the forum (see Website)."), "size": "50%+4 100%-148 100%-8 100%-116", - "onPress": () => { + "onPress": () => + { openURL("https://webchat.quakenet.org/?channels=0ad"); } }, @@ -41,7 +43,8 @@ export const communityButtons = [ "caption": translate("Report a Bug"), "tooltip": translate("Click to visit the 0 A.D. issue tracker to report a bug, crash, or error."), "size": "8 100%-112 50%-4 100%-80", - "onPress": () => { + "onPress": () => + { openURL("https://gitea.wildfiregames.com/0ad/0ad/issues"); } }, @@ -49,7 +52,8 @@ export const communityButtons = [ "caption": translateWithContext("Frequently Asked Questions", "FAQ"), "tooltip": translate("Click to visit the Frequently Asked Questions page in your browser."), "size": "50%+4 100%-112 100%-8 100%-80", - "onPress": () => { + "onPress": () => + { openURL("https://gitea.wildfiregames.com/0ad/0ad/wiki/FAQ"); } }, @@ -57,7 +61,8 @@ export const communityButtons = [ "caption": translate("Translate the Game"), "tooltip": translate("Click to open the 0 A.D. translate page in your browser."), "size": "8 100%-76 100%-8 100%-44", - "onPress": () => { + "onPress": () => + { openURL("https://gitea.wildfiregames.com/0ad/0ad/wiki/Localization"); } }, @@ -65,7 +70,8 @@ export const communityButtons = [ "caption": translate("Donate"), "tooltip": translate("Help with the project expenses by donating."), "size": "8 100%-40 100%-8 100%-8", - "onPress": () => { + "onPress": () => + { openURL("https://play0ad.com/community/donate/"); } } diff --git a/binaries/data/mods/public/gui/pregame/mainmenu.js b/binaries/data/mods/public/gui/pregame/mainmenu.js index edc42be7aa..c0f0039f6c 100644 --- a/binaries/data/mods/public/gui/pregame/mainmenu.js +++ b/binaries/data/mods/public/gui/pregame/mainmenu.js @@ -11,7 +11,8 @@ export function init(data, hotloadData) initUserReport(); Engine.GetGUIObjectByName("userReport").onTick = updateUserReportStatus; - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { const mainMenuPage = new MainMenuPage( closePageCallback, data, diff --git a/binaries/data/mods/public/gui/pregame/userreport/userreport.js b/binaries/data/mods/public/gui/pregame/userreport/userreport.js index 5a2dee3cdf..10bdb221ce 100644 --- a/binaries/data/mods/public/gui/pregame/userreport/userreport.js +++ b/binaries/data/mods/public/gui/pregame/userreport/userreport.js @@ -9,7 +9,8 @@ var g_TermsUserReport = { "configPath": setStringTags(escapeText(Engine.GetUserReportConfigPath()), { "font": "sans-bold-12" }) }, "config": "userreport.terms", - "callback": data => { + "callback": data => + { setUserReportEnabled(data.accepted); }, "accepted": false, @@ -61,13 +62,15 @@ function updateUserReportButtons() userReportEnableButton.caption = Engine.IsUserReportEnabled() ? translate("Disable Feedback") : translate("Enable Feedback"); userReportEnableButton.enabled = !termsFeedback; userReportEnableButton.tooltip = termsFeedback; - userReportEnableButton.onPress = () => { + userReportEnableButton.onPress = () => + { setUserReportEnabled(!Engine.IsUserReportEnabled()); }; const userReportTermsButton = Engine.GetGUIObjectByName("userReportTermsButton"); userReportTermsButton.caption = g_TermsUserReport.TermsAndConditions.title; - userReportTermsButton.onPress = () => { + userReportTermsButton.onPress = () => + { openTerms("TermsAndConditions"); }; } diff --git a/binaries/data/mods/public/gui/prelobby/common/feedback/feedback.js b/binaries/data/mods/public/gui/prelobby/common/feedback/feedback.js index 1f140cbaad..c52112984c 100644 --- a/binaries/data/mods/public/gui/prelobby/common/feedback/feedback.js +++ b/binaries/data/mods/public/gui/prelobby/common/feedback/feedback.js @@ -1,10 +1,12 @@ var g_LobbyMessages = { - "error": message => { + "error": message => + { setFeedback(message.text || translate("Unknown error. This usually occurs because the same IP address is not allowed to register more than one account within one hour.")); Engine.StopXmppClient(); }, - "disconnected": message => { + "disconnected": message => + { setFeedback(message.reason + message.certificate_status); Engine.StopXmppClient(); } diff --git a/binaries/data/mods/public/gui/prelobby/common/terms/termslobby.js b/binaries/data/mods/public/gui/prelobby/common/terms/termslobby.js index 5fca0241f8..84485f9fa9 100644 --- a/binaries/data/mods/public/gui/prelobby/common/terms/termslobby.js +++ b/binaries/data/mods/public/gui/prelobby/common/terms/termslobby.js @@ -37,13 +37,15 @@ function initLobbyTerms() } }; - Object.keys(terms).forEach((page, i) => { + Object.keys(terms).forEach((page, i) => + { const button = Engine.GetGUIObjectByName("termsButton[" + i + "]"); button.caption = terms[page].title; - button.onPress = () => { + button.onPress = () => + { openTerms(page); }; diff --git a/binaries/data/mods/public/gui/prelobby/entrance/entrance.js b/binaries/data/mods/public/gui/prelobby/entrance/entrance.js index 40e7b53e7e..19508023d8 100644 --- a/binaries/data/mods/public/gui/prelobby/entrance/entrance.js +++ b/binaries/data/mods/public/gui/prelobby/entrance/entrance.js @@ -3,7 +3,8 @@ function init() if (Engine.ConfigDB_GetValue("user", "lobby.login")) loginButton(); - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { Engine.GetGUIObjectByName("cancel").onPress = closePageCallback; }); } diff --git a/binaries/data/mods/public/gui/reference/common/TemplateLoader.js b/binaries/data/mods/public/gui/reference/common/TemplateLoader.js index e9d27dc986..217d2444b2 100644 --- a/binaries/data/mods/public/gui/reference/common/TemplateLoader.js +++ b/binaries/data/mods/public/gui/reference/common/TemplateLoader.js @@ -155,7 +155,8 @@ class TemplateLoader production.units.push(templateName); } - const appendTechnology = (technologyName) => { + const appendTechnology = (technologyName) => + { const technology = this.loadTechnologyTemplate(technologyName, civCode); if (DeriveTechnologyRequirements(technology, civCode)) production.techs.push(technologyName); diff --git a/binaries/data/mods/public/gui/reference/tips/sections/TipDisplay.js b/binaries/data/mods/public/gui/reference/tips/sections/TipDisplay.js index 46579f14d1..ed1d1171d5 100644 --- a/binaries/data/mods/public/gui/reference/tips/sections/TipDisplay.js +++ b/binaries/data/mods/public/gui/reference/tips/sections/TipDisplay.js @@ -37,7 +37,8 @@ class TipDisplay else this.tipFilesData = hotloadData?.tipFilesData || - shuffleArray(Engine.ReadJSONFile(this.TipFilesDataFile).map(category => category.files).flat().map(tip => { + shuffleArray(Engine.ReadJSONFile(this.TipFilesDataFile).map(category => category.files).flat().map(tip => + { tip.imageFiles = shuffleArray(tip.imageFiles); return tip; })); diff --git a/binaries/data/mods/public/gui/reference/tips/tips.js b/binaries/data/mods/public/gui/reference/tips/tips.js index acc8cb0f60..299c328cf6 100644 --- a/binaries/data/mods/public/gui/reference/tips/tips.js +++ b/binaries/data/mods/public/gui/reference/tips/tips.js @@ -2,7 +2,8 @@ var g_TipsPage; function init(initData, hotloadData) { - return new Promise(closePageCallback => { + return new Promise(closePageCallback => + { g_TipsPage = new TipsPage(initData, hotloadData, closePageCallback); }); } diff --git a/binaries/data/mods/public/gui/replaymenu/replay_filters.js b/binaries/data/mods/public/gui/replaymenu/replay_filters.js index 4019adf7e3..62c0b9c865 100644 --- a/binaries/data/mods/public/gui/replaymenu/replay_filters.js +++ b/binaries/data/mods/public/gui/replaymenu/replay_filters.js @@ -101,7 +101,8 @@ function initPopCapFilter(filters) const popCapOptions = g_PopulationCapacities.Options .map(item => item.List) .flat() - .reduce((list, cap) => { + .reduce((list, cap) => + { if (!list.includes(cap)) list.push(cap); return list; @@ -124,7 +125,8 @@ function initPopCapFilter(filters) function initDurationFilter(filters) { var durationFilter = Engine.GetGUIObjectByName("durationFilter"); - durationFilter.list = g_DurationFilterIntervals.map((interval, index) => { + durationFilter.list = g_DurationFilterIntervals.map((interval, index) => + { if (index == 0) return translateWithContext("duration", "Any"); @@ -201,7 +203,8 @@ function filterReplays() const sortKey = Engine.GetGUIObjectByName("replaySelection").selected_column; const sortOrder = Engine.GetGUIObjectByName("replaySelection").selected_column_order; - g_ReplaysFiltered = g_Replays.filter(replay => filterReplay(replay)).sort((a, b) => { + g_ReplaysFiltered = g_Replays.filter(replay => filterReplay(replay)).sort((a, b) => + { let cmpA, cmpB, cmpA_secondary, cmpB_secondary; switch (sortKey) { diff --git a/binaries/data/mods/public/gui/replaymenu/replay_menu.js b/binaries/data/mods/public/gui/replaymenu/replay_menu.js index ad14071eb4..98cd5f558d 100644 --- a/binaries/data/mods/public/gui/replaymenu/replay_menu.js +++ b/binaries/data/mods/public/gui/replaymenu/replay_menu.js @@ -190,7 +190,8 @@ function sanitizeInitAttributes(attribs) if (attribs.settings.PlayerData.length && attribs.settings.PlayerData[0] == null) attribs.settings.PlayerData.shift(); - attribs.settings.PlayerData.forEach((pData, index) => { + attribs.settings.PlayerData.forEach((pData, index) => + { if (!pData.Name) pData.Name = ""; }); @@ -229,7 +230,8 @@ function displayReplayList() filterReplays(); - var list = g_ReplaysFiltered.map(replay => { + var list = g_ReplaysFiltered.map(replay => + { const works = replay.isCompatible; return { "directories": replay.directory, diff --git a/binaries/data/mods/public/gui/session/AutoFormation.js b/binaries/data/mods/public/gui/session/AutoFormation.js index 566de8c031..d5d6c4d23d 100644 --- a/binaries/data/mods/public/gui/session/AutoFormation.js +++ b/binaries/data/mods/public/gui/session/AutoFormation.js @@ -20,7 +20,8 @@ class AutoFormation this.setDefault(NULL_FORMATION); this.lastDefault = this.defaultFormation === NULL_FORMATION ? "special/formations/box" : this.defaultFormation; - Engine.SetGlobalHotkey("session.toggledefaultformation", "Press", () => { + Engine.SetGlobalHotkey("session.toggledefaultformation", "Press", () => + { if (this.defaultFormation === NULL_FORMATION) this.setDefault(this.lastDefault); else diff --git a/binaries/data/mods/public/gui/session/Menu.js b/binaries/data/mods/public/gui/session/Menu.js index 61beb430c1..628fcc6a60 100644 --- a/binaries/data/mods/public/gui/session/Menu.js +++ b/binaries/data/mods/public/gui/session/Menu.js @@ -23,7 +23,8 @@ class Menu "There are " + handlerNames.length + " menu buttons defined, " + "but only " + menuButtons.length + " objects!"); - this.buttons = handlerNames.map((handlerName, i) => { + this.buttons = handlerNames.map((handlerName, i) => + { const handler = new MenuButtons.prototype[handlerName](menuButtons[i], pauseControl, playerViewControl, chat); this.initButton(handler, menuButtons[i], i); return handler; @@ -63,7 +64,8 @@ class Menu initButton(handler, button, i) { - button.onPress = () => { + button.onPress = () => + { this.close(); handler.onPress(); }; diff --git a/binaries/data/mods/public/gui/session/PanelEntity.js b/binaries/data/mods/public/gui/session/PanelEntity.js index 832e2ac356..a76770b4bd 100644 --- a/binaries/data/mods/public/gui/session/PanelEntity.js +++ b/binaries/data/mods/public/gui/session/PanelEntity.js @@ -88,7 +88,8 @@ class PanelEntity return; const playerParts = this.panelEntityCaptureBar.children; - const setCaptureBarPart = function(player, startSize) { + const setCaptureBarPart = function(player, startSize) + { const captureBar = playerParts[player]; captureBar.size.rleft = startSize; captureBar.size.rright = startSize + 100 * Math.max(0, Math.min(1, entityState.capturePoints[player] / entityState.maxCapturePoints)); diff --git a/binaries/data/mods/public/gui/session/PanelEntityManager.js b/binaries/data/mods/public/gui/session/PanelEntityManager.js index 18b310c985..0b2baedf24 100644 --- a/binaries/data/mods/public/gui/session/PanelEntityManager.js +++ b/binaries/data/mods/public/gui/session/PanelEntityManager.js @@ -60,7 +60,8 @@ class PanelEntityManager // Sort depending on given order const insertPos = this.handlers.reduce( - (pos, handler) => { + (pos, handler) => + { if (handler.orderKey <= orderKey) ++pos; return pos; diff --git a/binaries/data/mods/public/gui/session/chat/Chat.js b/binaries/data/mods/public/gui/session/chat/Chat.js index 7f27bcbcd1..31246694e4 100644 --- a/binaries/data/mods/public/gui/session/chat/Chat.js +++ b/binaries/data/mods/public/gui/session/chat/Chat.js @@ -32,7 +32,8 @@ class Chat this.ChatMessageHandler.registerMessageFormat("message", this.ChatMessageFormatPlayer); this.ChatMessageHandler.registerMessageHandler(this.ChatOverlay.onChatMessage.bind(this.ChatOverlay)); this.ChatMessageHandler.registerMessageHandler(this.ChatHistory.onChatMessage.bind(this.ChatHistory)); - this.ChatMessageHandler.registerMessageHandler(() => { + this.ChatMessageHandler.registerMessageHandler(() => + { if (this.ChatWindow.isOpen() && this.ChatWindow.isExtended()) this.ChatHistory.displayChatHistory(); }); @@ -126,7 +127,8 @@ class Chat } const senderID = Engine.GetPlayerID(); - return Object.keys(g_PlayerAssignments).filter(potentialReceiverGUID => { + return Object.keys(g_PlayerAssignments).filter(potentialReceiverGUID => + { return potentialReceiverGUID === senderGUID || isAddressee(senderID, g_PlayerAssignments[potentialReceiverGUID].player); }); diff --git a/binaries/data/mods/public/gui/session/chat/ChatMessageFormatSimulation.js b/binaries/data/mods/public/gui/session/chat/ChatMessageFormatSimulation.js index 6b51bac9db..5088e8e36d 100644 --- a/binaries/data/mods/public/gui/session/chat/ChatMessageFormatSimulation.js +++ b/binaries/data/mods/public/gui/session/chat/ChatMessageFormatSimulation.js @@ -21,7 +21,8 @@ ChatMessageFormatSimulation.attack = class "icon": '[icon="icon_focusattacked"]', "attacker": colorizePlayernameByID(msg.attacker) }), - "callback": ((target, position) => function() { + "callback": ((target, position) => function() + { focusAttack({ "target": target, "position": position }); })(msg.target, msg.position), "tooltip": translate("Click to focus on the attacked unit.") @@ -198,7 +199,8 @@ ChatMessageFormatSimulation.flare = class "icon": "[icon=\"icon_focusflare\" displace=\"0 1\"]", "player": colorizePlayernameByGUID(msg.guid) }), - "callback": ((position) => function() { + "callback": ((position) => function() + { Engine.CameraMoveTo(position.x, position.z); })(msg.position), "tooltip": translate("Click to focus on the flare's location.") diff --git a/binaries/data/mods/public/gui/session/chat/ChatWindow.js b/binaries/data/mods/public/gui/session/chat/ChatWindow.js index f04d16bc1c..a2e9dd1f69 100644 --- a/binaries/data/mods/public/gui/session/chat/ChatWindow.js +++ b/binaries/data/mods/public/gui/session/chat/ChatWindow.js @@ -27,7 +27,8 @@ class ChatWindow { this.closeChat.onPress = this.closePage.bind(this); - this.extendedChat.onPress = () => { + this.extendedChat.onPress = () => + { Engine.ConfigDB_CreateAndSaveValue("user", "chat.session.extended", String(this.isExtended())); this.resizeChatWindow(); this.chatInput.focus(); diff --git a/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlay.js b/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlay.js index fbe2614998..d88a5aac74 100644 --- a/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlay.js +++ b/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlay.js @@ -41,10 +41,12 @@ class DeveloperOverlay this.devCommandsOverlay.hidden = !this.devCommandsOverlay.hidden; this.sendNotification(); - this.checkBoxes.forEach(checkbox => { + this.checkBoxes.forEach(checkbox => + { checkbox.setHidden(this.devCommandsOverlay.hidden); }); - this.dropDowns.forEach(dropDown => { + this.dropDowns.forEach(dropDown => + { dropDown.setHidden(this.devCommandsOverlay.hidden); }); } diff --git a/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlayControlCheckboxes.js b/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlayControlCheckboxes.js index 8574b62db2..705f09d3eb 100644 --- a/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlayControlCheckboxes.js +++ b/binaries/data/mods/public/gui/session/developer_overlay/DeveloperOverlayControlCheckboxes.js @@ -221,7 +221,8 @@ DeveloperOverlayControlCheckboxes.prototype.ActivateRejoinTest = class box.Caption = "Warning: the rejoin test can't be de-activated and is quite slow. Its only purpose is to check for OOS."; const self = this; box.Buttons = [ - { "caption": "Cancel" }, { "caption": "OK", "onPress": () => { + { "caption": "Cancel" }, { "caption": "OK", "onPress": () => + { Engine.ActivateRejoinTest(); this.disabled = true; this.update(); diff --git a/binaries/data/mods/public/gui/session/input.js b/binaries/data/mods/public/gui/session/input.js index ec167df5d3..f4e6e371fd 100644 --- a/binaries/data/mods/public/gui/session/input.js +++ b/binaries/data/mods/public/gui/session/input.js @@ -426,26 +426,31 @@ function updateBandbox(bandbox, ev, hidden) // Define some useful unit filters for getPreferredEntities. var unitFilters = { - "isUnit": entity => { + "isUnit": entity => + { const entState = GetEntityState(entity); return entState && hasClass(entState, "Unit"); }, - "isDefensive": entity => { + "isDefensive": entity => + { const entState = GetEntityState(entity); return entState && hasClass(entState, "Defensive"); }, - "isMilitary": entity => { + "isMilitary": entity => + { const entState = GetEntityState(entity); return entState && g_MilitaryTypes.some(c => hasClass(entState, c)); }, - "isNonMilitary": entity => { + "isNonMilitary": entity => + { const entState = GetEntityState(entity); return entState && hasClass(entState, "Unit") && !g_MilitaryTypes.some(c => hasClass(entState, c)); }, - "isIdle": entity => { + "isIdle": entity => + { const entState = GetEntityState(entity); return entState && hasClass(entState, "Unit") && @@ -453,14 +458,16 @@ var unitFilters = { entState.unitAI.isIdle && !hasClass(entState, "Domestic"); }, - "isWounded": entity => { + "isWounded": entity => + { const entState = GetEntityState(entity); return entState && hasClass(entState, "Unit") && entState.maxHitpoints && 100 * entState.hitpoints <= entState.maxHitpoints * Engine.ConfigDB_GetValue("user", "gui.session.woundedunithotkeythreshold"); }, - "isAnything": entity => { + "isAnything": entity => + { return true; } }; @@ -1425,7 +1432,8 @@ function OnTrainMouseWheel(dir) function getBuildingsWhichCanTrainEntity(entitiesToCheck, trainEntType) { - return entitiesToCheck.filter(entity => { + return entitiesToCheck.filter(entity => + { const state = GetEntityState(entity); return state?.trainer?.entities?.includes(trainEntType) && (!state.upgrade || !state.upgrade.isUpgrading); @@ -1434,7 +1442,8 @@ function getBuildingsWhichCanTrainEntity(entitiesToCheck, trainEntType) function initBatchTrain() { - registerConfigChangeHandler(changes => { + registerConfigChangeHandler(changes => + { if (changes.has("gui.session.batchtrainingsize")) updateDefaultBatchSize(); }); diff --git a/binaries/data/mods/public/gui/session/message_box/QuitConfirmation.js b/binaries/data/mods/public/gui/session/message_box/QuitConfirmation.js index f7753b8e38..0879b175f5 100644 --- a/binaries/data/mods/public/gui/session/message_box/QuitConfirmation.js +++ b/binaries/data/mods/public/gui/session/message_box/QuitConfirmation.js @@ -9,23 +9,23 @@ QuitConfirmation.prototype.Caption = translate("The game has finished, what do you want to do?"); QuitConfirmation.prototype.Buttons = -[ - { + [ + { // Translation: Shown in the Dialog that shows up when the game finishes - "caption": translate("Stay"), - "onPress": resumeGame - }, - { + "caption": translate("Stay"), + "onPress": resumeGame + }, + { // Translation: Shown in the Dialog that shows up when the game finishes - "caption": translate("Quit and View Summary"), - "onPress": () => { endGame(true); } - }, - { + "caption": translate("Quit and View Summary"), + "onPress": () => { endGame(true); } + }, + { // Translation: Shown in the Dialog that shows up when the game finishes - "caption": translate("Quit"), - "onPress": () => { endGame(false); } - } -]; + "caption": translate("Quit"), + "onPress": () => { endGame(false); } + } + ]; QuitConfirmation.prototype.Width = 600; QuitConfirmation.prototype.Height = 200; diff --git a/binaries/data/mods/public/gui/session/message_box/QuitConfirmationMenu.js b/binaries/data/mods/public/gui/session/message_box/QuitConfirmationMenu.js index d0390cfa02..9be8307cc1 100644 --- a/binaries/data/mods/public/gui/session/message_box/QuitConfirmationMenu.js +++ b/binaries/data/mods/public/gui/session/message_box/QuitConfirmationMenu.js @@ -10,7 +10,8 @@ ReturnQuestion.prototype.Buttons = [ }, { "caption": translate("I resign"), - "onPress": () => { + "onPress": () => + { Engine.PostNetworkCommand({ "type": "resign" }); @@ -67,14 +68,15 @@ QuitConfirmationMenu.prototype.MultiplayerClient.prototype.Caption = translate("Are you sure you want to quit?"); QuitConfirmationMenu.prototype.MultiplayerClient.prototype.Buttons = -[ - { - "caption": translate("No") - }, - { - "caption": translate("Yes"), - "onPress": () => { - (new ReturnQuestion()).display(); + [ + { + "caption": translate("No") + }, + { + "caption": translate("Yes"), + "onPress": () => + { + (new ReturnQuestion()).display(); + } } - } -]; + ]; diff --git a/binaries/data/mods/public/gui/session/message_box/QuitConfirmationReplay.js b/binaries/data/mods/public/gui/session/message_box/QuitConfirmationReplay.js index b3c6fec379..189555539d 100644 --- a/binaries/data/mods/public/gui/session/message_box/QuitConfirmationReplay.js +++ b/binaries/data/mods/public/gui/session/message_box/QuitConfirmationReplay.js @@ -17,20 +17,20 @@ QuitConfirmationReplay.prototype.Caption = translateWithContext("replayFinished", "The replay has finished. What do you want to do?"); QuitConfirmationReplay.prototype.Buttons = -[ - { + [ + { // Translation: Shown in the Dialog that shows up when a replay finishes - "caption": translate("Stay"), - "onPress": resumeGame - }, - { + "caption": translate("Stay"), + "onPress": resumeGame + }, + { // Translation: Shown in the Dialog that shows up when a replay finishes - "caption": translate("Quit and View Summary"), - "onPress": () => { endGame(true); } - }, - { + "caption": translate("Quit and View Summary"), + "onPress": () => { endGame(true); } + }, + { // Translation: Shown in the Dialog that shows up when a replay finishes - "caption": translate("Quit"), - "onPress": () => { endGame(false); } - } -]; + "caption": translate("Quit"), + "onPress": () => { endGame(false); } + } + ]; diff --git a/binaries/data/mods/public/gui/session/message_box/ResignConfirmation.js b/binaries/data/mods/public/gui/session/message_box/ResignConfirmation.js index 157c8094dd..0378f022c5 100644 --- a/binaries/data/mods/public/gui/session/message_box/ResignConfirmation.js +++ b/binaries/data/mods/public/gui/session/message_box/ResignConfirmation.js @@ -10,7 +10,8 @@ ResignConfirmation.prototype.Buttons = [ }, { "caption": translate("Yes"), - "onPress": () => { + "onPress": () => + { Engine.PostNetworkCommand({ "type": "resign" }); diff --git a/binaries/data/mods/public/gui/session/messages.js b/binaries/data/mods/public/gui/session/messages.js index de287260de..34952dda32 100644 --- a/binaries/data/mods/public/gui/session/messages.js +++ b/binaries/data/mods/public/gui/session/messages.js @@ -56,47 +56,57 @@ var g_NetworkOutOfSyncHandlers = new Set(); * Handle all netmessage types that can occur. */ var g_NetMessageTypes = { - "netstatus": msg => { + "netstatus": msg => + { handleNetStatusMessage(msg); }, - "netwarn": msg => { + "netwarn": msg => + { addNetworkWarning(msg); }, - "out-of-sync": msg => { + "out-of-sync": msg => + { for (const handler of g_NetworkOutOfSyncHandlers) handler(msg); }, - "players": msg => { + "players": msg => + { handlePlayerAssignmentsMessage(msg); }, - "paused": msg => { + "paused": msg => + { g_PauseControl.setClientPauseState(msg.guid, msg.pause); }, - "clients-loading": msg => { + "clients-loading": msg => + { for (const handler of g_ClientsLoadingHandlers) handler(msg.guids); }, - "rejoined": msg => { + "rejoined": msg => + { addChatMessage({ "type": "rejoined", "guid": msg.guid }); }, - "kicked": msg => { + "kicked": msg => + { addChatMessage({ "type": "kicked", "username": msg.username, "banned": msg.banned }); }, - "chat": msg => { + "chat": msg => + { addChatMessage({ "type": "message", "guid": msg.guid, "text": msg.text }); }, - "flare": msg => { + "flare": msg => + { handleFlare(msg); }, "gamesetup": msg => {}, // Needed for autostart @@ -116,182 +126,182 @@ var g_LastAttack; * handled in the same turn can't access the GUI objects anymore. */ var g_NotificationsTypes = -{ - "aichat": function(notification, player) { - const message = { - "type": "message", - "text": notification.message, - "guid": findGuidForPlayerID(player) || -1, - "player": player, - "translate": true - }; - - if (notification.translateParameters) + "aichat": function(notification, player) { - message.translateParameters = notification.translateParameters; - message.parameters = notification.parameters; - colorizePlayernameParameters(notification.parameters); - } + const message = { + "type": "message", + "text": notification.message, + "guid": findGuidForPlayerID(player) || -1, + "player": player, + "translate": true + }; - addChatMessage(message); - }, - "defeat": function(notification, player) - { - playersFinished(notification.allies, notification.message, false); - }, - "won": function(notification, player) - { - playersFinished(notification.allies, notification.message, true); - }, - "diplomacy": function(notification, player) - { - updatePlayerData(); - g_DiplomacyColors.onDiplomacyChange(); + if (notification.translateParameters) + { + message.translateParameters = notification.translateParameters; + message.parameters = notification.parameters; + colorizePlayernameParameters(notification.parameters); + } - addChatMessage({ - "type": "diplomacy", - "sourcePlayer": player, - "targetPlayer": notification.targetPlayer, - "status": notification.status - }); - }, - "ceasefire-ended": function(notification, player) - { - updatePlayerData(); - for (const handler of g_CeasefireEndedHandlers) - handler(); - }, - "tutorial": function(notification, player) - { - updateTutorial(notification); - }, - "tribute": function(notification, player) - { - addChatMessage({ - "type": "tribute", - "sourcePlayer": notification.donator, - "targetPlayer": player, - "amounts": notification.amounts - }); - }, - "barter": function(notification, player) - { - addChatMessage({ - "type": "barter", - "player": player, - "amountGiven": notification.amountGiven, - "amountGained": notification.amountGained, - "resourceGiven": notification.resourceGiven, - "resourceGained": notification.resourceGained - }); - }, - "spy-response": function(notification, player) - { - g_DiplomacyDialog.onSpyResponse(notification, player); - - if (notification.entity && g_ViewedPlayer == player && (!g_IsObserver || g_FollowPlayer)) + addChatMessage(message); + }, + "defeat": function(notification, player) { - g_DiplomacyDialog.close(); - setCameraFollow(notification.entity); - } - }, - "attack": function(notification, player) - { - if (player != g_ViewedPlayer) - return; - - // Focus camera on attacks - if (g_FollowPlayer) + playersFinished(notification.allies, notification.message, false); + }, + "won": function(notification, player) { - setCameraFollow(notification.target); + playersFinished(notification.allies, notification.message, true); + }, + "diplomacy": function(notification, player) + { + updatePlayerData(); + g_DiplomacyColors.onDiplomacyChange(); - g_Selection.reset(); - if (notification.target) - g_Selection.addList([notification.target]); - } + addChatMessage({ + "type": "diplomacy", + "sourcePlayer": player, + "targetPlayer": notification.targetPlayer, + "status": notification.status + }); + }, + "ceasefire-ended": function(notification, player) + { + updatePlayerData(); + for (const handler of g_CeasefireEndedHandlers) + handler(); + }, + "tutorial": function(notification, player) + { + updateTutorial(notification); + }, + "tribute": function(notification, player) + { + addChatMessage({ + "type": "tribute", + "sourcePlayer": notification.donator, + "targetPlayer": player, + "amounts": notification.amounts + }); + }, + "barter": function(notification, player) + { + addChatMessage({ + "type": "barter", + "player": player, + "amountGiven": notification.amountGiven, + "amountGained": notification.amountGained, + "resourceGiven": notification.resourceGiven, + "resourceGained": notification.resourceGained + }); + }, + "spy-response": function(notification, player) + { + g_DiplomacyDialog.onSpyResponse(notification, player); - g_LastAttack = { "target": notification.target, "position": notification.position }; + if (notification.entity && g_ViewedPlayer == player && (!g_IsObserver || g_FollowPlayer)) + { + g_DiplomacyDialog.close(); + setCameraFollow(notification.entity); + } + }, + "attack": function(notification, player) + { + if (player != g_ViewedPlayer) + return; - if (Engine.ConfigDB_GetValue("user", "gui.session.notifications.attack") !== "true") - return; + // Focus camera on attacks + if (g_FollowPlayer) + { + setCameraFollow(notification.target); - addChatMessage({ - "type": "attack", - "player": player, - "attacker": notification.attacker, - "target": notification.target, - "position": notification.position, - "targetIsDomesticAnimal": notification.targetIsDomesticAnimal - }); - }, - "phase": function(notification, player) - { - addChatMessage({ - "type": "phase", - "player": player, - "phaseName": notification.phaseName, - "phaseState": notification.phaseState - }); - }, - "dialog": function(notification, player) - { - if (player == Engine.GetPlayerID()) - openDialog(notification.dialogName, notification.data, player); - }, - "playercommand": function(notification, player) - { + g_Selection.reset(); + if (notification.target) + g_Selection.addList([notification.target]); + } + + g_LastAttack = { "target": notification.target, "position": notification.position }; + + if (Engine.ConfigDB_GetValue("user", "gui.session.notifications.attack") !== "true") + return; + + addChatMessage({ + "type": "attack", + "player": player, + "attacker": notification.attacker, + "target": notification.target, + "position": notification.position, + "targetIsDomesticAnimal": notification.targetIsDomesticAnimal + }); + }, + "phase": function(notification, player) + { + addChatMessage({ + "type": "phase", + "player": player, + "phaseName": notification.phaseName, + "phaseState": notification.phaseState + }); + }, + "dialog": function(notification, player) + { + if (player == Engine.GetPlayerID()) + openDialog(notification.dialogName, notification.data, player); + }, + "playercommand": function(notification, player) + { // For observers, focus the camera on units commanded by the selected player - if (!g_FollowPlayer || player != g_ViewedPlayer) - return; + if (!g_FollowPlayer || player != g_ViewedPlayer) + return; - const cmd = notification.cmd; + const cmd = notification.cmd; - // Ignore rallypoint commands of trained animals - const entState = cmd.entities && cmd.entities[0] && GetEntityState(cmd.entities[0]); - if (g_ViewedPlayer != 0 && + // Ignore rallypoint commands of trained animals + const entState = cmd.entities && cmd.entities[0] && GetEntityState(cmd.entities[0]); + if (g_ViewedPlayer != 0 && entState && entState.identity && entState.identity.classes && entState.identity.classes.indexOf("Animal") != -1) - return; + return; - // Focus the structure to build. - if (cmd.type == "repair") + // Focus the structure to build. + if (cmd.type == "repair") + { + const targetState = GetEntityState(cmd.target); + if (targetState) + Engine.CameraMoveTo(targetState.position.x, targetState.position.z); + } + else if (cmd.type == "delete-entities" && notification.position) + Engine.CameraMoveTo(notification.position.x, notification.position.y); + // Focus commanded entities, but don't lose previous focus when training units + else if (cmd.type != "train" && cmd.type != "research" && entState) + setCameraFollow(cmd.entities[0]); + + if (["walk", "attack-walk", "patrol"].indexOf(cmd.type) != -1) + DrawTargetMarker(cmd); + + // Select units affected by that command + let selection = []; + if (cmd.entities) + selection = cmd.entities; + if (cmd.target) + selection.push(cmd.target); + + // Allow gaia in selection when gathering + g_Selection.reset(); + g_Selection.addList(selection, false, cmd.type == "gather"); + }, + "play-tracks": function(notification, player) { - const targetState = GetEntityState(cmd.target); - if (targetState) - Engine.CameraMoveTo(targetState.position.x, targetState.position.z); + if (notification.lock) + { + global.music.storeTracks(notification.tracks.map(track => ({ "Type": "custom", "File": track }))); + global.music.setState(global.music.states.CUSTOM); + } + + global.music.setLocked(notification.lock); } - else if (cmd.type == "delete-entities" && notification.position) - Engine.CameraMoveTo(notification.position.x, notification.position.y); - // Focus commanded entities, but don't lose previous focus when training units - else if (cmd.type != "train" && cmd.type != "research" && entState) - setCameraFollow(cmd.entities[0]); - - if (["walk", "attack-walk", "patrol"].indexOf(cmd.type) != -1) - DrawTargetMarker(cmd); - - // Select units affected by that command - let selection = []; - if (cmd.entities) - selection = cmd.entities; - if (cmd.target) - selection.push(cmd.target); - - // Allow gaia in selection when gathering - g_Selection.reset(); - g_Selection.addList(selection, false, cmd.type == "gather"); - }, - "play-tracks": function(notification, player) - { - if (notification.lock) - { - global.music.storeTracks(notification.tracks.map(track => ({ "Type": "custom", "File": track }))); - global.music.setState(global.music.states.CUSTOM); - } - - global.music.setLocked(notification.lock); - } -}; + }; function registerPlayerAssignmentsChangeHandler(handler) { @@ -452,7 +462,8 @@ function handlePlayerAssignmentsMessage(message) g_PlayerAssignments = message.newAssignments; - joins.forEach(guid => { + joins.forEach(guid => + { onClientJoin(guid); }); diff --git a/binaries/data/mods/public/gui/session/minimap/MiniMap.js b/binaries/data/mods/public/gui/session/minimap/MiniMap.js index 5685806182..6735f3b4ec 100644 --- a/binaries/data/mods/public/gui/session/minimap/MiniMap.js +++ b/binaries/data/mods/public/gui/session/minimap/MiniMap.js @@ -12,7 +12,8 @@ class MiniMap this.miniMap.onMouseLeave = this.onMouseLeave.bind(this); this.mouseIsOverMiniMap = false; this.updateFlareLifetime(); - registerConfigChangeHandler(changes => { + registerConfigChangeHandler(changes => + { if (changes.has("gui.session.flarelifetime")) this.updateFlareLifetime(); }); diff --git a/binaries/data/mods/public/gui/session/selection.js b/binaries/data/mods/public/gui/session/selection.js index db04df594a..855a84956c 100644 --- a/binaries/data/mods/public/gui/session/selection.js +++ b/binaries/data/mods/public/gui/session/selection.js @@ -195,7 +195,8 @@ function EntitySelection() this.groups = new EntityGroups(); this.UpdateFormationSelectionBehaviour(); - registerConfigChangeHandler(changes => { + registerConfigChangeHandler(changes => + { if (changes.has("gui.session.selectformationasone")) this.UpdateFormationSelectionBehaviour(); }); diff --git a/binaries/data/mods/public/gui/session/selection_details.js b/binaries/data/mods/public/gui/session/selection_details.js index abed5da624..156ccc559b 100644 --- a/binaries/data/mods/public/gui/session/selection_details.js +++ b/binaries/data/mods/public/gui/session/selection_details.js @@ -151,7 +151,8 @@ function displaySingle(entState) captureSection.hidden = !entState.capturePoints; if (entState.capturePoints) { - const setCaptureBarPart = function(playerID, startSize) { + const setCaptureBarPart = function(playerID, startSize) + { const unitCaptureBar = Engine.GetGUIObjectByName("captureBar[" + playerID + "]"); const width = 100 * Math.max(0, Math.min(1, entState.capturePoints[playerID] / entState.maxCapturePoints)); @@ -331,11 +332,13 @@ function displaySingle(entState) { const iconBorder = Engine.GetGUIObjectByName("iconBorder"); - iconBorder.onPress = () => { + iconBorder.onPress = () => + { setCameraFollow(entState.id); }; - iconBorder.onPressRight = () => { + iconBorder.onPressRight = () => + { showTemplateDetails(entState.template, playerState.civ); }; } diff --git a/binaries/data/mods/public/gui/session/selection_panels.js b/binaries/data/mods/public/gui/session/selection_panels.js index dd3964d326..4ff9444444 100644 --- a/binaries/data/mods/public/gui/session/selection_panels.js +++ b/binaries/data/mods/public/gui/session/selection_panels.js @@ -46,7 +46,8 @@ g_SelectionPanels.Alert = { }, "setupButton": function(data) { - data.button.onPress = function() { + data.button.onPress = function() + { switch (data.item) { case "raise": @@ -142,7 +143,8 @@ g_SelectionPanels.Command = { { data.button.tooltip = data.item.tooltip; - data.button.onPress = function() { + data.button.onPress = function() + { if (data.item.callback) data.item.callback(data.item); else @@ -281,7 +283,8 @@ g_SelectionPanels.Formation = { "formationTemplate": data.item }); - data.button.onPress = function() { + data.button.onPress = function() + { performFormation(unitIds, data.item); }; @@ -345,7 +348,8 @@ g_SelectionPanels.Garrison = { if (!template) return false; - data.button.onPress = function() { + data.button.onPress = function() + { unloadTemplate(template.selectionGroupName || entState.template, entState.player); }; @@ -813,11 +817,13 @@ g_SelectionPanels.Research = { tooltips.push(getNeededResourcesTooltip(neededResources)); button.tooltip = tooltips.filter(tip => tip).join("\n"); - button.onPress = (t => function() { + button.onPress = (t => function() + { addResearchToQueue(data.item.researchFacilityId, t); })(tech); - const showTemplateFunc = (t => function() { + const showTemplateFunc = (t => function() + { showTemplateDetails( t, GetTemplateData(data.unitEntStates.find(state => state.id == data.item.researchFacilityId).template).nativeCiv); @@ -830,10 +836,12 @@ g_SelectionPanels.Research = { { // On mouse enter, show a cross over the other icon const unchosenIcon = Engine.GetGUIObjectByName("unitResearchUnchosenIcon[" + (position + data.rowLength) % (2 * data.rowLength) + "]"); - button.onMouseEnter = function() { + button.onMouseEnter = function() + { unchosenIcon.hidden = false; }; - button.onMouseLeave = function() { + button.onMouseLeave = function() + { unchosenIcon.hidden = true; }; } @@ -943,7 +951,8 @@ g_SelectionPanels.Selection = { data.countDisplay.caption = data.item.ents.length > 1 ? data.item.ents.length : ""; - data.button.onPress = function() { + data.button.onPress = function() + { if (Engine.HotkeyIsPressed("session.deselectgroup")) removeFromSelectionGroup(data.item.key); else @@ -1024,7 +1033,8 @@ g_SelectionPanels.Training = { "player": data.player }); - data.button.onPress = function() { + data.button.onPress = function() + { if (!neededResources) addTrainingToQueue(unitIds, data.item, data.playerState); }; @@ -1188,7 +1198,8 @@ g_SelectionPanels.Upgrade = { tooltip = tooltips.filter(tip => tip).join("\n"); - data.button.onPress = function() { + data.button.onPress = function() + { upgradeEntity( data.item.entity, upgradableEntStates.map(state => state.id)); diff --git a/binaries/data/mods/public/gui/session/selection_panels_helpers.js b/binaries/data/mods/public/gui/session/selection_panels_helpers.js index da424d2e85..99b055e54a 100644 --- a/binaries/data/mods/public/gui/session/selection_panels_helpers.js +++ b/binaries/data/mods/public/gui/session/selection_panels_helpers.js @@ -417,7 +417,8 @@ function unloadTemplate(template, owner) "template": template, "owner": owner, // Filter out all entities that aren't garrisonable. - "garrisonHolders": g_Selection.filter(ent => { + "garrisonHolders": g_Selection.filter(ent => + { const state = GetEntityState(ent); return state && !!state.garrisonHolder; }) @@ -426,7 +427,8 @@ function unloadTemplate(template, owner) function unloadAll() { - const garrisonHolders = g_Selection.filter(e => { + const garrisonHolders = g_Selection.filter(e => + { const state = GetEntityState(e); return state && !!state.garrisonHolder; }); @@ -460,7 +462,8 @@ function unloadAll() function unloadAllTurrets() { - const turretHolders = g_Selection.filter(e => { + const turretHolders = g_Selection.filter(e => + { const state = GetEntityState(e); return state && !!state.turretHolder; }); @@ -498,7 +501,8 @@ function unloadAllTurrets() function leaveTurretPoints() { - const entities = g_Selection.filter(entity => { + const entities = g_Selection.filter(entity => + { const entState = GetEntityState(entity); return entState && entState.turretable && entState.turretable.holder != INVALID_ENTITY; @@ -515,7 +519,8 @@ function backToWork() Engine.PostNetworkCommand({ "type": "back-to-work", // Filter out all entities that can't go back to work. - "entities": g_Selection.filter(ent => { + "entities": g_Selection.filter(ent => + { const state = GetEntityState(ent); return state && state.unitAI && state.unitAI.hasWorkOrders; }) @@ -527,7 +532,8 @@ function removeGuard() Engine.PostNetworkCommand({ "type": "remove-guard", // Filter out all entities that are currently guarding/escorting. - "entities": g_Selection.filter(ent => { + "entities": g_Selection.filter(ent => + { const state = GetEntityState(ent); return state && state.unitAI && state.unitAI.isGuarding; }) @@ -538,7 +544,8 @@ function raiseAlert() { Engine.PostNetworkCommand({ "type": "alert-raise", - "entities": g_Selection.filter(ent => { + "entities": g_Selection.filter(ent => + { const state = GetEntityState(ent); return state && !!state.alertRaiser; }) @@ -549,7 +556,8 @@ function endOfAlert() { Engine.PostNetworkCommand({ "type": "alert-end", - "entities": g_Selection.filter(ent => { + "entities": g_Selection.filter(ent => + { const state = GetEntityState(ent); return state && !!state.alertRaiser; }) @@ -560,7 +568,8 @@ function turnAutoQueueOn() { Engine.PostNetworkCommand({ "type": "autoqueue-on", - "entities": g_Selection.filter(ent => { + "entities": g_Selection.filter(ent => + { const state = GetEntityState(ent); return !!state?.trainer?.entities?.length && !state.production.autoqueue; @@ -572,7 +581,8 @@ function turnAutoQueueOff() { Engine.PostNetworkCommand({ "type": "autoqueue-off", - "entities": g_Selection.filter(ent => { + "entities": g_Selection.filter(ent => + { const state = GetEntityState(ent); return !!state?.trainer?.entities?.length && state.production.autoqueue; diff --git a/binaries/data/mods/public/gui/session/session.js b/binaries/data/mods/public/gui/session/session.js index 4b50ded935..72ab91cfae 100644 --- a/binaries/data/mods/public/gui/session/session.js +++ b/binaries/data/mods/public/gui/session/session.js @@ -276,7 +276,8 @@ function init(initData, hotloadData) restoreSavedGameData(initData.savedGUIData); } - const promise = new Promise(closePageCallback => { + const promise = new Promise(closePageCallback => + { if (g_InitAttributes.campaignData) g_CampaignSession = new CampaignSession(g_InitAttributes.campaignData, closePageCallback); }); @@ -759,7 +760,8 @@ function updateGroups() g_Groups.update(); // Determine the sum of the costs of a given template - const getCostSum = (ent) => { + const getCostSum = (ent) => + { const cost = GetTemplateData(GetEntityState(ent).template).cost; return cost ? Object.keys(cost).map(key => cost[key]).reduce((sum, cur) => sum + cur) : 0; }; @@ -777,7 +779,8 @@ function updateGroups() // Choose the icon of the most common template (or the most costly if it's not unique) if (g_Groups.groups[i].getTotalCount() > 0) { - const icon = GetTemplateData(GetEntityState(g_Groups.groups[i].getEntsGrouped().reduce((pre, cur) => { + const icon = GetTemplateData(GetEntityState(g_Groups.groups[i].getEntsGrouped().reduce((pre, cur) => + { if (pre.ents.length == cur.ents.length) return getCostSum(pre.ents[0]) > getCostSum(cur.ents[0]) ? pre : cur; return pre.ents.length > cur.ents.length ? pre : cur; diff --git a/binaries/data/mods/public/gui/session/trade/TradeButton.js b/binaries/data/mods/public/gui/session/trade/TradeButton.js index 85e61e8d30..8ed38e40ff 100644 --- a/binaries/data/mods/public/gui/session/trade/TradeButton.js +++ b/binaries/data/mods/public/gui/session/trade/TradeButton.js @@ -23,11 +23,13 @@ class TradeButton this.tradeResourceButton.onPress = () => { tradeButtonManager.selectResource(resourceCode); }; - this.tradeArrowUp.onPress = () => { + this.tradeArrowUp.onPress = () => + { tradeButtonManager.changeResourceAmount(resourceCode, +Math.min(this.AmountStep, tradeButtonManager.tradingGoods[tradeButtonManager.selectedResource])); }; - this.tradeArrowDn.onPress = () => { + this.tradeArrowDn.onPress = () => + { tradeButtonManager.changeResourceAmount(resourceCode, -Math.min(this.AmountStep, tradeButtonManager.tradingGoods[resourceCode])); }; diff --git a/binaries/data/mods/public/gui/session/trade/TraderStatusText.js b/binaries/data/mods/public/gui/session/trade/TraderStatusText.js index bb03840340..f896506fe5 100644 --- a/binaries/data/mods/public/gui/session/trade/TraderStatusText.js +++ b/binaries/data/mods/public/gui/session/trade/TraderStatusText.js @@ -14,7 +14,8 @@ class TraderStatusText update() { const traderNumber = Engine.GuiInterfaceCall("GetTraderNumber", g_ViewedPlayer); - this.traderCountText.caption = this.components.reduce((caption, component) => { + this.traderCountText.caption = this.components.reduce((caption, component) => + { caption += component.getText(traderNumber, this.IdleTraderTextTags) + "\n\n"; return caption; }, "").trim(); } diff --git a/binaries/data/mods/public/gui/session/unit_actions.js b/binaries/data/mods/public/gui/session/unit_actions.js index 597dd37187..e25932e7ad 100644 --- a/binaries/data/mods/public/gui/session/unit_actions.js +++ b/binaries/data/mods/public/gui/session/unit_actions.js @@ -48,1115 +48,55 @@ const g_DisabledTags = { "color": "255 140 0" }; * the chance of selecting that action when multiple actions are possible */ var g_UnitActions = -{ - "move": { - "execute": function(position, action, selection, queued, pushFront) + "move": { - Engine.PostNetworkCommand({ - "type": "walk", - "entities": selection, - "x": position.x, - "z": position.z, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getDefault() - }); - - DrawTargetMarker(position); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_walk", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.unitAI) - return false; - return { "possible": true }; - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.move") && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("move", target, selection); - return actionInfo.possible && { - "type": "move", - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 12, - }, - - "attack-move": - { - "execute": function(position, action, selection, queued, pushFront) - { - let targetClasses; - if (Engine.HotkeyIsPressed("session.attackmoveUnit")) - targetClasses = { "attack": ["Unit"] }; - else - targetClasses = { "attack": ["Unit", "Structure"] }; - - Engine.PostNetworkCommand({ - "type": "attack-walk", - "entities": selection, - "x": position.x, - "z": position.z, - "targetClasses": targetClasses, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - DrawTargetMarker(position); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_attack_move", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.unitAI) - return false; - return { "possible": true }; - }, - "hotkeyActionCheck": function(target, selection) - { - return isAttackMovePressed() && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("attack-move", target, selection); - return actionInfo.possible && { - "type": "attack-move", - "cursor": "action-attack-move", - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 30, - }, - - "capture": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "attack", - "entities": selection, - "target": action.target, - "allowCapture": true, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_attack", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.attack || !targetState || !targetState.capturePoints) - return false; - - return { - "possible": Engine.GuiInterfaceCall("CanAttack", { - "entity": entState.id, - "target": targetState.id, - "types": ["Capture"] - }) - }; - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.capture") && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("capture", target, selection); - return actionInfo.possible && { - "type": "capture", - "cursor": "action-capture", - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 10, - }, - - "attack": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "attack", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront, - "allowCapture": false, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_attack", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.attack || !targetState || !targetState.hitpoints) - return false; - - return { - "possible": Engine.GuiInterfaceCall("CanAttack", { - "entity": entState.id, - "target": targetState.id, - "types": ["!Capture"] - }) - }; - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.attack") && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("attack", target, selection); - return actionInfo.possible && { - "type": "attack", - "cursor": "action-attack", - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 9, - }, - - "call-to-arms": { - "execute": function(position, action, selection, queued, pushFront) - { - let targetClasses; - if (Engine.HotkeyIsPressed("session.attackmoveUnit")) - targetClasses = { "attack": ["Unit"] }; - else - targetClasses = { "attack": ["Unit", "Structure"] }; - Engine.PostNetworkCommand({ - "type": "call-to-arms", - "entities": selection, - "position": position, - "targetClasses": targetClasses, - "queued": queued, - "pushFront": pushFront, - "allowCapture": Engine.HotkeyIsPressed("session.capture"), - "formation": g_AutoFormation.getNull() - }); - return true; - }, - "getActionInfo": function(entState, targetState) - { - return { "possible": !!entState.unitAI }; - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("call-to-arms", target, selection); - return actionInfo.possible && { - "type": "call-to-arms", - "cursor": "action-attack", - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.calltoarms") && - this.actionCheck(target, selection); - }, - "preSelectedActionCheck": function(target, selection) - { - return preSelectedAction == ACTION_CALLTOARMS && - this.actionCheck(target, selection); - }, - "specificness": 50, - }, - - "patrol": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "patrol", - "entities": selection, - "x": position.x, - "z": position.z, - "target": action.target, - "targetClasses": { "attack": g_PatrolTargets }, - "queued": queued, - "allowCapture": Engine.HotkeyIsPressed("session.capture"), - "formation": g_AutoFormation.getDefault() - }); - - DrawTargetMarker(position); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_patrol", - "entity": action.firstAbleEntity - }); - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.unitAI || !entState.unitAI.canPatrol) - return false; - - return { "possible": true }; - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.patrol") && - this.actionCheck(target, selection); - }, - "preSelectedActionCheck": function(target, selection) - { - return preSelectedAction == ACTION_PATROL && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("patrol", target, selection); - return actionInfo.possible && { - "type": "patrol", - "cursor": "action-patrol", - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 37, - }, - - "heal": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "heal", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_heal", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.heal || !targetState || - !hasClass(targetState, "Unit") || !targetState.needsHeal || - !playerCheck(entState, targetState, ["Player", "Ally"]) || - entState.id == targetState.id) // Healers can't heal themselves. - return false; - - const unhealableClasses = entState.heal.unhealableClasses; - if (MatchesClassList(targetState.identity.classes, unhealableClasses)) - return false; - - const healableClasses = entState.heal.healableClasses; - if (!MatchesClassList(targetState.identity.classes, healableClasses)) - return false; - - return { "possible": true }; - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("heal", target, selection); - return actionInfo.possible && { - "type": "heal", - "cursor": "action-heal", - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 7, - }, - - // "Fake" action to check if an entity can be ordered to "construct" - // which is handled differently from repair as the target does not exist. - "construct": - { - "preSelectedActionCheck": function(target, selection) - { - const state = GetEntityState(selection[0]); - if (state && state.builder && - target && target.constructor && target.constructor.name == "PlacementSupport") - return { "type": "construct" }; - return false; - }, - "specificness": 0, - }, - - "repair": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "repair", - "entities": selection, - "target": action.target, - "autocontinue": true, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": action.foundation ? "order_build" : "order_repair", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.builder || !targetState || - !targetState.needsRepair && !targetState.foundation || - !playerCheck(entState, targetState, ["Player", "Ally"])) - return false; - - return { - "possible": true, - "foundation": targetState.foundation - }; - }, - "preSelectedActionCheck": function(target, selection) - { - return preSelectedAction == ACTION_REPAIR && (this.actionCheck(target, selection) || { - "type": "none", - "cursor": "action-repair-disabled", - "target": null - }); - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.repair") && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("repair", target, selection); - return actionInfo.possible && { - "type": "repair", - "cursor": "action-repair", - "target": target, - "foundation": actionInfo.foundation, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 11, - }, - - "gather": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "gather", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_gather", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.resourceGatherRates || - !targetState || !targetState.resourceSupply) - return false; - - let resource; - if (entState.resourceGatherRates[targetState.resourceSupply.type.generic + "." + targetState.resourceSupply.type.specific]) - resource = targetState.resourceSupply.type.specific; - else if (entState.resourceGatherRates[targetState.resourceSupply.type.generic]) - resource = targetState.resourceSupply.type.generic; - if (!resource) - return false; - - return { - "possible": true, - "cursor": "action-gather-" + resource - }; - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("gather", target, selection); - return actionInfo.possible && { - "type": "gather", - "cursor": actionInfo.cursor, - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 1, - }, - - "returnresource": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "returnresource", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_gather", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!targetState || !targetState.resourceDropsite) - return false; - - const playerState = GetSimState().players[entState.player]; - if (playerState.hasSharedDropsites && targetState.resourceDropsite.shared) + "execute": function(position, action, selection, queued, pushFront) { - if (!playerCheck(entState, targetState, ["Player", "MutualAlly"])) - return false; - } - else if (!playerCheck(entState, targetState, ["Player"])) - return false; + Engine.PostNetworkCommand({ + "type": "walk", + "entities": selection, + "x": position.x, + "z": position.z, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getDefault() + }); - if (!entState.resourceCarrying || !entState.resourceCarrying.length) - return false; + DrawTargetMarker(position); - const carriedType = entState.resourceCarrying[0].type; - if (targetState.resourceDropsite.types.indexOf(carriedType) == -1) - return false; - - return { - "possible": true, - "cursor": "action-return-" + carriedType - }; - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("returnresource", target, selection); - return actionInfo.possible && { - "type": "returnresource", - "cursor": actionInfo.cursor, - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 2, - }, - - "cancel-setup-trade-route": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "cancel-setup-trade-route", - "entities": selection, - "target": action.target, - "queued": queued - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!targetState || targetState.foundation || !entState.trader || !targetState.market || - playerCheck(entState, targetState, ["Enemy"]) || - !(targetState.market.land && hasClass(entState, "Organic") || - targetState.market.naval && hasClass(entState, "Ship"))) - return false; - - const tradingDetails = Engine.GuiInterfaceCall("GetTradingDetails", { - "trader": entState.id, - "target": targetState.id - }); - - if (!tradingDetails || !tradingDetails.type) - return false; - - if (tradingDetails.type == "is first" && !tradingDetails.hasBothMarkets) - return { - "possible": true, - "tooltip": translate("This is the origin trade market.\nRight-click to cancel trade route.") - }; - return false; - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("cancel-setup-trade-route", target, selection); - return actionInfo.possible && { - "type": "cancel-setup-trade-route", - "cursor": "action-cancel-setup-trade-route", - "tooltip": actionInfo.tooltip, - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 2, - }, - - "setup-trade-route": - { - "execute": function(position, action, selection, queued) - { - Engine.PostNetworkCommand({ - "type": "setup-trade-route", - "entities": selection, - "target": action.target, - "source": null, - "route": null, - "queued": queued, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_trade", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!targetState || targetState.foundation || !entState.trader || !targetState.market || - playerCheck(entState, targetState, ["Enemy"]) || - !(targetState.market.land && hasClass(entState, "Organic") || - targetState.market.naval && hasClass(entState, "Ship"))) - return false; - - const tradingDetails = Engine.GuiInterfaceCall("GetTradingDetails", { - "trader": entState.id, - "target": targetState.id - }); - - if (!tradingDetails) - return false; - - let tooltip; - switch (tradingDetails.type) - { - case "is first": - tooltip = translate("Origin trade market.") + "\n"; - if (tradingDetails.hasBothMarkets) - tooltip += sprintf(translate("Gain: %(gain)s"), { - "gain": getTradingTooltip(tradingDetails.gain) - }); - else - return false; - break; - - case "is second": - tooltip = translate("Destination trade market.") + "\n" + - sprintf(translate("Gain: %(gain)s"), { - "gain": getTradingTooltip(tradingDetails.gain) - }); - break; - - case "set first": - tooltip = translate("Right-click to set as origin trade market"); - break; - - case "set second": - if (tradingDetails.gain.traderGain == 0) - return { - "possible": true, - "tooltip": setStringTags(translate("This market is too close to the origin market."), g_DisabledTags), - "disabled": true - }; - - tooltip = translate("Right-click to set as destination trade market.") + "\n" + - sprintf(translate("Gain: %(gain)s"), { - "gain": getTradingTooltip(tradingDetails.gain) - }); - break; - default: - error("Unknown type for tradingDetails: " + tradingDetails.type); - } - - return { - "possible": true, - "tooltip": tooltip - }; - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("setup-trade-route", target, selection); - if (actionInfo.disabled) - return { - "type": "none", - "cursor": "action-setup-trade-route-disabled", - "target": null, - "tooltip": actionInfo.tooltip - }; - - return actionInfo.possible && { - "type": "setup-trade-route", - "cursor": "action-setup-trade-route", - "tooltip": actionInfo.tooltip, - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 0, - }, - - "occupy-turret": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "occupy-turret", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_garrison", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.turretable || !targetState || !targetState.turretHolder || - !playerCheck(entState, targetState, ["Player", "MutualAlly"])) - return false; - - if (!targetState.turretHolder.turretPoints.find(point => - !point.allowedClasses || MatchesClassList(entState.identity.classes, point.allowedClasses))) - return false; - - const occupiedTurrets = targetState.turretHolder.turretPoints.filter(point => point.entity != null); - let tooltip = sprintf(translate("Current turrets: %(occupied)s/%(capacity)s"), { - "occupied": occupiedTurrets.length, - "capacity": targetState.turretHolder.turretPoints.length - }); - - if (occupiedTurrets.length == targetState.turretHolder.turretPoints.length) - tooltip = coloredText(tooltip, "orange"); - - return { - "possible": true, - "tooltip": tooltip - }; - }, - "preSelectedActionCheck": function(target, selection) - { - return preSelectedAction == ACTION_OCCUPY_TURRET && (this.actionCheck(target, selection) || { - "type": "none", - "cursor": "action-occupy-turret-disabled", - "target": null - }); - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.occupyturret") && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("occupy-turret", target, selection); - return actionInfo.possible && { - "type": "occupy-turret", - "cursor": "action-occupy-turret", - "tooltip": actionInfo.tooltip, - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 21, - }, - - "garrison": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "garrison", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_garrison", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.garrisonable || !targetState || !targetState.garrisonHolder || - !playerCheck(entState, targetState, ["Player", "MutualAlly"])) - return false; - - let tooltip = sprintf(translate("Current garrison: %(garrisoned)s/%(capacity)s"), { - "garrisoned": targetState.garrisonHolder.occupiedSlots, - "capacity": targetState.garrisonHolder.capacity - }); - - let extraCount = entState.garrisonable.size; - if (entState.garrisonHolder) - extraCount += entState.garrisonHolder.occupiedSlots; - - if (targetState.garrisonHolder.occupiedSlots + extraCount > targetState.garrisonHolder.capacity) - tooltip = coloredText(tooltip, "orange"); - - if (!MatchesClassList(entState.identity.classes, targetState.garrisonHolder.allowedClasses)) - return false; - - return { - "possible": true, - "tooltip": tooltip - }; - }, - "preSelectedActionCheck": function(target, selection) - { - return preSelectedAction == ACTION_GARRISON && (this.actionCheck(target, selection) || { - "type": "none", - "cursor": "action-garrison-disabled", - "target": null - }); - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.garrison") && - this.actionCheck(target, selection); - - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("garrison", target, selection); - return actionInfo.possible && { - "type": "garrison", - "cursor": "action-garrison", - "tooltip": actionInfo.tooltip, - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 20, - }, - - "guard": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "guard", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_guard", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!targetState || !targetState.guard || entState.id == targetState.id || - !playerCheck(entState, targetState, ["Player", "Ally"]) || - !entState.unitAI || !entState.unitAI.canGuard) - return false; - - return { "possible": true }; - }, - "preSelectedActionCheck": function(target, selection) - { - return preSelectedAction == ACTION_GUARD && (this.actionCheck(target, selection) || { - "type": "none", - "cursor": "action-guard-disabled", - "target": null - }); - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.guard") && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("guard", target, selection); - return actionInfo.possible && { - "type": "guard", - "cursor": "action-guard", - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 40, - }, - - "collect-treasure": - { - "execute": function(position, action, selection, queued) - { - Engine.PostNetworkCommand({ - "type": "collect-treasure", - "entities": selection, - "target": action.target, - "queued": queued, - "formation": g_AutoFormation.getNull() - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_collect_treasure", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.treasureCollector || - !targetState || !targetState.treasure) - return false; - - return { - "possible": true, - "cursor": "action-collect-treasure" - }; - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("collect-treasure", target, selection); - return actionInfo.possible && { - "type": "collect-treasure", - "cursor": actionInfo.cursor, - "target": target, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 1, - }, - - "remove-guard": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "remove-guard", - "entities": selection, - "target": action.target, - "queued": queued, - "pushFront": pushFront - }); - - Engine.GuiInterfaceCall("PlaySound", { - "name": "order_guard", - "entity": action.firstAbleEntity - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.unitAI || !entState.unitAI.isGuarding) - return false; - return { "possible": true }; - }, - "hotkeyActionCheck": function(target, selection) - { - return Engine.HotkeyIsPressed("session.guard") && - this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("remove-guard", target, selection); - return actionInfo.possible && { - "type": "remove-guard", - "cursor": "action-remove-guard", - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 41, - }, - - "focus-fire": - { - "execute": function(position, action, selection, queued, pushFront) - { - Engine.PostNetworkCommand({ - "type": "focus-fire", - "entities": selection, - "x": position.x, - "z": position.z, - "target": action.target, - "data": action.data, - "queued": queued, - "pushFront": pushFront - }); - - if (action.data.sound) Engine.GuiInterfaceCall("PlaySound", { - "name": "focus_fire", + "name": "order_walk", "entity": action.firstAbleEntity }); - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.rallyPoint) - return undefined; - - let tooltip; - const data = { "command": "walk" }; - data.sound = false; - - if (entState.attack && Engine.HotkeyIsPressed("session.focusfire")) + return true; + }, + "getActionInfo": function(entState, targetState) { - data.command = "attack-only"; - if (targetState && playerCheck(entState, targetState, ["Enemy"]) && !targetState.resourceSupply) - { - data.target = targetState.id; - data.sound = true; - } - return { - "possible": true, - "data": data, - "position": targetState && targetState.position, - "cursor": "action-target", - "tooltip": tooltip + if (!entState.unitAI) + return false; + return { "possible": true }; + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.move") && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("move", target, selection); + return actionInfo.possible && { + "type": "move", + "firstAbleEntity": actionInfo.entity }; - } - return undefined; + }, + "specificness": 12, }, - "hotkeyActionCheck": function(target, selection) + + "attack-move": { - // Hotkeys are checked in the actionInfo. - return this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - // We want commands to units take precedence. - if (selection.some(ent => { - const entState = GetEntityState(ent); - return entState && !!entState.unitAI; - })) - return false; - - const actionInfo = getActionInfo("focus-fire", target, selection); - - return actionInfo.possible && { - "type": "focus-fire", - "cursor": actionInfo.cursor, - "data": actionInfo.data, - "target": target, - "tooltip": actionInfo.tooltip, - "position": actionInfo.position, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 6, - }, - - "set-rallypoint": - { - "execute": function(position, action, selection, queued, pushFront) - { - // if there is a position set in the action then use this so that when setting a - // rally point on an entity it is centered on that entity - if (action.position) - position = action.position; - - Engine.PostNetworkCommand({ - "type": "set-rallypoint", - "entities": selection, - "x": position.x, - "z": position.z, - "data": action.data, - "queued": queued - }); - - // Display rally point at the new coordinates, to avoid display lag - Engine.GuiInterfaceCall("DisplayRallyPoint", { - "entities": selection, - "x": position.x, - "z": position.z, - "queued": queued - }); - - return true; - }, - "getActionInfo": function(entState, targetState) - { - if (!entState.rallyPoint) - return false; - - // Don't allow the rally point to be set on any of the currently selected entities (used for unset) - // except if the autorallypoint hotkey is pressed and the target can produce entities. - if (targetState && (!Engine.HotkeyIsPressed("session.autorallypoint") || - !targetState.trainer || - !targetState.trainer.entities.length)) - for (const ent of g_Selection.toList()) - if (targetState.id == ent) - return false; - - let tooltip; - let disabled = false; - // default to walking there (or attack-walking if hotkey pressed) - const data = { "command": "walk" }; - let cursor = ""; - - if (isAttackMovePressed()) + "execute": function(position, action, selection, queued, pushFront) { let targetClasses; if (Engine.HotkeyIsPressed("session.attackmoveUnit")) @@ -1164,255 +104,1318 @@ var g_UnitActions = else targetClasses = { "attack": ["Unit", "Structure"] }; - data.command = "attack-walk"; - data.targetClasses = targetClasses; - cursor = "action-attack-move"; - } - - if (Engine.HotkeyIsPressed("session.repair") && targetState && - (targetState.needsRepair || targetState.foundation) && - playerCheck(entState, targetState, ["Player", "Ally"])) - { - data.command = "repair"; - data.target = targetState.id; - cursor = "action-repair"; - } - else if (targetState && targetState.garrisonHolder && - playerCheck(entState, targetState, ["Player", "MutualAlly"])) - { - data.command = "garrison"; - data.target = targetState.id; - cursor = "action-garrison"; - - tooltip = sprintf(translate("Current garrison: %(garrisoned)s/%(capacity)s"), { - "garrisoned": targetState.garrisonHolder.occupiedSlots, - "capacity": targetState.garrisonHolder.capacity + Engine.PostNetworkCommand({ + "type": "attack-walk", + "entities": selection, + "x": position.x, + "z": position.z, + "targetClasses": targetClasses, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() }); - if (targetState.garrisonHolder.occupiedSlots >= - targetState.garrisonHolder.capacity) - tooltip = coloredText(tooltip, "orange"); - } - else if (targetState && targetState.turretHolder && - playerCheck(entState, targetState, ["Player", "MutualAlly"])) + DrawTargetMarker(position); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_attack_move", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) { - data.command = "occupy-turret"; - data.target = targetState.id; - cursor = "action-garrison"; + if (!entState.unitAI) + return false; + return { "possible": true }; + }, + "hotkeyActionCheck": function(target, selection) + { + return isAttackMovePressed() && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("attack-move", target, selection); + return actionInfo.possible && { + "type": "attack-move", + "cursor": "action-attack-move", + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 30, + }, + + "capture": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "attack", + "entities": selection, + "target": action.target, + "allowCapture": true, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_attack", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.attack || !targetState || !targetState.capturePoints) + return false; + + return { + "possible": Engine.GuiInterfaceCall("CanAttack", { + "entity": entState.id, + "target": targetState.id, + "types": ["Capture"] + }) + }; + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.capture") && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("capture", target, selection); + return actionInfo.possible && { + "type": "capture", + "cursor": "action-capture", + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 10, + }, + + "attack": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "attack", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront, + "allowCapture": false, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_attack", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.attack || !targetState || !targetState.hitpoints) + return false; + + return { + "possible": Engine.GuiInterfaceCall("CanAttack", { + "entity": entState.id, + "target": targetState.id, + "types": ["!Capture"] + }) + }; + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.attack") && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("attack", target, selection); + return actionInfo.possible && { + "type": "attack", + "cursor": "action-attack", + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 9, + }, + + "call-to-arms": { + "execute": function(position, action, selection, queued, pushFront) + { + let targetClasses; + if (Engine.HotkeyIsPressed("session.attackmoveUnit")) + targetClasses = { "attack": ["Unit"] }; + else + targetClasses = { "attack": ["Unit", "Structure"] }; + Engine.PostNetworkCommand({ + "type": "call-to-arms", + "entities": selection, + "position": position, + "targetClasses": targetClasses, + "queued": queued, + "pushFront": pushFront, + "allowCapture": Engine.HotkeyIsPressed("session.capture"), + "formation": g_AutoFormation.getNull() + }); + return true; + }, + "getActionInfo": function(entState, targetState) + { + return { "possible": !!entState.unitAI }; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("call-to-arms", target, selection); + return actionInfo.possible && { + "type": "call-to-arms", + "cursor": "action-attack", + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.calltoarms") && + this.actionCheck(target, selection); + }, + "preSelectedActionCheck": function(target, selection) + { + return preSelectedAction == ACTION_CALLTOARMS && + this.actionCheck(target, selection); + }, + "specificness": 50, + }, + + "patrol": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "patrol", + "entities": selection, + "x": position.x, + "z": position.z, + "target": action.target, + "targetClasses": { "attack": g_PatrolTargets }, + "queued": queued, + "allowCapture": Engine.HotkeyIsPressed("session.capture"), + "formation": g_AutoFormation.getDefault() + }); + + DrawTargetMarker(position); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_patrol", + "entity": action.firstAbleEntity + }); + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.unitAI || !entState.unitAI.canPatrol) + return false; + + return { "possible": true }; + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.patrol") && + this.actionCheck(target, selection); + }, + "preSelectedActionCheck": function(target, selection) + { + return preSelectedAction == ACTION_PATROL && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("patrol", target, selection); + return actionInfo.possible && { + "type": "patrol", + "cursor": "action-patrol", + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 37, + }, + + "heal": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "heal", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_heal", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.heal || !targetState || + !hasClass(targetState, "Unit") || !targetState.needsHeal || + !playerCheck(entState, targetState, ["Player", "Ally"]) || + entState.id == targetState.id) // Healers can't heal themselves. + return false; + + const unhealableClasses = entState.heal.unhealableClasses; + if (MatchesClassList(targetState.identity.classes, unhealableClasses)) + return false; + + const healableClasses = entState.heal.healableClasses; + if (!MatchesClassList(targetState.identity.classes, healableClasses)) + return false; + + return { "possible": true }; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("heal", target, selection); + return actionInfo.possible && { + "type": "heal", + "cursor": "action-heal", + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 7, + }, + + // "Fake" action to check if an entity can be ordered to "construct" + // which is handled differently from repair as the target does not exist. + "construct": + { + "preSelectedActionCheck": function(target, selection) + { + const state = GetEntityState(selection[0]); + if (state && state.builder && + target && target.constructor && target.constructor.name == "PlacementSupport") + return { "type": "construct" }; + return false; + }, + "specificness": 0, + }, + + "repair": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "repair", + "entities": selection, + "target": action.target, + "autocontinue": true, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": action.foundation ? "order_build" : "order_repair", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.builder || !targetState || + !targetState.needsRepair && !targetState.foundation || + !playerCheck(entState, targetState, ["Player", "Ally"])) + return false; + + return { + "possible": true, + "foundation": targetState.foundation + }; + }, + "preSelectedActionCheck": function(target, selection) + { + return preSelectedAction == ACTION_REPAIR && (this.actionCheck(target, selection) || { + "type": "none", + "cursor": "action-repair-disabled", + "target": null + }); + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.repair") && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("repair", target, selection); + return actionInfo.possible && { + "type": "repair", + "cursor": "action-repair", + "target": target, + "foundation": actionInfo.foundation, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 11, + }, + + "gather": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "gather", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_gather", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.resourceGatherRates || + !targetState || !targetState.resourceSupply) + return false; + + let resource; + if (entState.resourceGatherRates[targetState.resourceSupply.type.generic + "." + targetState.resourceSupply.type.specific]) + resource = targetState.resourceSupply.type.specific; + else if (entState.resourceGatherRates[targetState.resourceSupply.type.generic]) + resource = targetState.resourceSupply.type.generic; + if (!resource) + return false; + + return { + "possible": true, + "cursor": "action-gather-" + resource + }; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("gather", target, selection); + return actionInfo.possible && { + "type": "gather", + "cursor": actionInfo.cursor, + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 1, + }, + + "returnresource": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "returnresource", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_gather", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!targetState || !targetState.resourceDropsite) + return false; + + const playerState = GetSimState().players[entState.player]; + if (playerState.hasSharedDropsites && targetState.resourceDropsite.shared) + { + if (!playerCheck(entState, targetState, ["Player", "MutualAlly"])) + return false; + } + else if (!playerCheck(entState, targetState, ["Player"])) + return false; + + if (!entState.resourceCarrying || !entState.resourceCarrying.length) + return false; + + const carriedType = entState.resourceCarrying[0].type; + if (targetState.resourceDropsite.types.indexOf(carriedType) == -1) + return false; + + return { + "possible": true, + "cursor": "action-return-" + carriedType + }; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("returnresource", target, selection); + return actionInfo.possible && { + "type": "returnresource", + "cursor": actionInfo.cursor, + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 2, + }, + + "cancel-setup-trade-route": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "cancel-setup-trade-route", + "entities": selection, + "target": action.target, + "queued": queued + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!targetState || targetState.foundation || !entState.trader || !targetState.market || + playerCheck(entState, targetState, ["Enemy"]) || + !(targetState.market.land && hasClass(entState, "Organic") || + targetState.market.naval && hasClass(entState, "Ship"))) + return false; + + const tradingDetails = Engine.GuiInterfaceCall("GetTradingDetails", { + "trader": entState.id, + "target": targetState.id + }); + + if (!tradingDetails || !tradingDetails.type) + return false; + + if (tradingDetails.type == "is first" && !tradingDetails.hasBothMarkets) + return { + "possible": true, + "tooltip": translate("This is the origin trade market.\nRight-click to cancel trade route.") + }; + return false; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("cancel-setup-trade-route", target, selection); + return actionInfo.possible && { + "type": "cancel-setup-trade-route", + "cursor": "action-cancel-setup-trade-route", + "tooltip": actionInfo.tooltip, + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 2, + }, + + "setup-trade-route": + { + "execute": function(position, action, selection, queued) + { + Engine.PostNetworkCommand({ + "type": "setup-trade-route", + "entities": selection, + "target": action.target, + "source": null, + "route": null, + "queued": queued, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_trade", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!targetState || targetState.foundation || !entState.trader || !targetState.market || + playerCheck(entState, targetState, ["Enemy"]) || + !(targetState.market.land && hasClass(entState, "Organic") || + targetState.market.naval && hasClass(entState, "Ship"))) + return false; + + const tradingDetails = Engine.GuiInterfaceCall("GetTradingDetails", { + "trader": entState.id, + "target": targetState.id + }); + + if (!tradingDetails) + return false; + + let tooltip; + switch (tradingDetails.type) + { + case "is first": + tooltip = translate("Origin trade market.") + "\n"; + if (tradingDetails.hasBothMarkets) + tooltip += sprintf(translate("Gain: %(gain)s"), { + "gain": getTradingTooltip(tradingDetails.gain) + }); + else + return false; + break; + + case "is second": + tooltip = translate("Destination trade market.") + "\n" + + sprintf(translate("Gain: %(gain)s"), { + "gain": getTradingTooltip(tradingDetails.gain) + }); + break; + + case "set first": + tooltip = translate("Right-click to set as origin trade market"); + break; + + case "set second": + if (tradingDetails.gain.traderGain == 0) + return { + "possible": true, + "tooltip": setStringTags(translate("This market is too close to the origin market."), g_DisabledTags), + "disabled": true + }; + + tooltip = translate("Right-click to set as destination trade market.") + "\n" + + sprintf(translate("Gain: %(gain)s"), { + "gain": getTradingTooltip(tradingDetails.gain) + }); + break; + default: + error("Unknown type for tradingDetails: " + tradingDetails.type); + } + + return { + "possible": true, + "tooltip": tooltip + }; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("setup-trade-route", target, selection); + if (actionInfo.disabled) + return { + "type": "none", + "cursor": "action-setup-trade-route-disabled", + "target": null, + "tooltip": actionInfo.tooltip + }; + + return actionInfo.possible && { + "type": "setup-trade-route", + "cursor": "action-setup-trade-route", + "tooltip": actionInfo.tooltip, + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 0, + }, + + "occupy-turret": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "occupy-turret", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_garrison", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.turretable || !targetState || !targetState.turretHolder || + !playerCheck(entState, targetState, ["Player", "MutualAlly"])) + return false; + + if (!targetState.turretHolder.turretPoints.find(point => + !point.allowedClasses || MatchesClassList(entState.identity.classes, point.allowedClasses))) + return false; const occupiedTurrets = targetState.turretHolder.turretPoints.filter(point => point.entity != null); - tooltip = sprintf(translate("Current turrets: %(occupied)s/%(capacity)s"), { + let tooltip = sprintf(translate("Current turrets: %(occupied)s/%(capacity)s"), { "occupied": occupiedTurrets.length, "capacity": targetState.turretHolder.turretPoints.length }); - if (occupiedTurrets.length >= targetState.turretHolder.turretPoints.length) + if (occupiedTurrets.length == targetState.turretHolder.turretPoints.length) tooltip = coloredText(tooltip, "orange"); - } - else if (targetState && targetState.resourceSupply) - { - const resourceType = targetState.resourceSupply.type; - cursor = "action-gather-" + resourceType.specific; - data.command = "gather-near-position"; - data.resourceType = resourceType; - data.resourceTemplate = targetState.template; - if (!targetState.speed) - { - data.command = "gather"; - data.target = targetState.id; - } - } - else if (targetState && targetState.treasure) - { - cursor = "action-collect-treasure"; - data.command = "collect-treasure-near-position"; - if (!targetState.speed) - { - data.command = "collect-treasure"; - data.target = targetState.id; - } - } - else if (entState.market && targetState && targetState.market && - entState.id != targetState.id && - (!entState.market.naval || targetState.market.naval) && - !playerCheck(entState, targetState, ["Enemy"])) - { - // Find a trader (if any) that this structure can train. - let trader; - if (entState.trainer?.entities?.length) - for (let i = 0; i < entState.trainer.entities.length; ++i) - if ((trader = GetTemplateData(entState.trainer.entities[i]).trader)) - break; - - const traderData = { - "firstMarket": entState.id, - "secondMarket": targetState.id, - "template": trader + return { + "possible": true, + "tooltip": tooltip }; + }, + "preSelectedActionCheck": function(target, selection) + { + return preSelectedAction == ACTION_OCCUPY_TURRET && (this.actionCheck(target, selection) || { + "type": "none", + "cursor": "action-occupy-turret-disabled", + "target": null + }); + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.occupyturret") && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("occupy-turret", target, selection); + return actionInfo.possible && { + "type": "occupy-turret", + "cursor": "action-occupy-turret", + "tooltip": actionInfo.tooltip, + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 21, + }, - const gain = Engine.GuiInterfaceCall("GetTradingRouteGain", traderData); - if (gain) + "garrison": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "garrison", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_garrison", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.garrisonable || !targetState || !targetState.garrisonHolder || + !playerCheck(entState, targetState, ["Player", "MutualAlly"])) + return false; + + let tooltip = sprintf(translate("Current garrison: %(garrisoned)s/%(capacity)s"), { + "garrisoned": targetState.garrisonHolder.occupiedSlots, + "capacity": targetState.garrisonHolder.capacity + }); + + let extraCount = entState.garrisonable.size; + if (entState.garrisonHolder) + extraCount += entState.garrisonHolder.occupiedSlots; + + if (targetState.garrisonHolder.occupiedSlots + extraCount > targetState.garrisonHolder.capacity) + tooltip = coloredText(tooltip, "orange"); + + if (!MatchesClassList(entState.identity.classes, targetState.garrisonHolder.allowedClasses)) + return false; + + return { + "possible": true, + "tooltip": tooltip + }; + }, + "preSelectedActionCheck": function(target, selection) + { + return preSelectedAction == ACTION_GARRISON && (this.actionCheck(target, selection) || { + "type": "none", + "cursor": "action-garrison-disabled", + "target": null + }); + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.garrison") && + this.actionCheck(target, selection); + + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("garrison", target, selection); + return actionInfo.possible && { + "type": "garrison", + "cursor": "action-garrison", + "tooltip": actionInfo.tooltip, + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 20, + }, + + "guard": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "guard", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_guard", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!targetState || !targetState.guard || entState.id == targetState.id || + !playerCheck(entState, targetState, ["Player", "Ally"]) || + !entState.unitAI || !entState.unitAI.canGuard) + return false; + + return { "possible": true }; + }, + "preSelectedActionCheck": function(target, selection) + { + return preSelectedAction == ACTION_GUARD && (this.actionCheck(target, selection) || { + "type": "none", + "cursor": "action-guard-disabled", + "target": null + }); + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.guard") && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("guard", target, selection); + return actionInfo.possible && { + "type": "guard", + "cursor": "action-guard", + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 40, + }, + + "collect-treasure": + { + "execute": function(position, action, selection, queued) + { + Engine.PostNetworkCommand({ + "type": "collect-treasure", + "entities": selection, + "target": action.target, + "queued": queued, + "formation": g_AutoFormation.getNull() + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_collect_treasure", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.treasureCollector || + !targetState || !targetState.treasure) + return false; + + return { + "possible": true, + "cursor": "action-collect-treasure" + }; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("collect-treasure", target, selection); + return actionInfo.possible && { + "type": "collect-treasure", + "cursor": actionInfo.cursor, + "target": target, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 1, + }, + + "remove-guard": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "remove-guard", + "entities": selection, + "target": action.target, + "queued": queued, + "pushFront": pushFront + }); + + Engine.GuiInterfaceCall("PlaySound", { + "name": "order_guard", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.unitAI || !entState.unitAI.isGuarding) + return false; + return { "possible": true }; + }, + "hotkeyActionCheck": function(target, selection) + { + return Engine.HotkeyIsPressed("session.guard") && + this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("remove-guard", target, selection); + return actionInfo.possible && { + "type": "remove-guard", + "cursor": "action-remove-guard", + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 41, + }, + + "focus-fire": + { + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "focus-fire", + "entities": selection, + "x": position.x, + "z": position.z, + "target": action.target, + "data": action.data, + "queued": queued, + "pushFront": pushFront + }); + + if (action.data.sound) + Engine.GuiInterfaceCall("PlaySound", { + "name": "focus_fire", + "entity": action.firstAbleEntity + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.rallyPoint) + return undefined; + + let tooltip; + const data = { "command": "walk" }; + data.sound = false; + + if (entState.attack && Engine.HotkeyIsPressed("session.focusfire")) { - data.command = "trade"; - data.target = traderData.secondMarket; - data.source = traderData.firstMarket; - cursor = "action-setup-trade-route"; - - if (gain.traderGain) - tooltip = translate("Right-click to establish a default route for new traders.") + "\n" + - sprintf( - trader ? - translate("Gain: %(gain)s") : - translate("Expected gain: %(gain)s"), - { "gain": getTradingTooltip(gain) }); - else + data.command = "attack-only"; + if (targetState && playerCheck(entState, targetState, ["Enemy"]) && !targetState.resourceSupply) { - disabled = true; - tooltip = setStringTags(translate("This market is too close to the origin market."), g_DisabledTags); - cursor = "action-setup-trade-route-disabled"; + data.target = targetState.id; + data.sound = true; + } + return { + "possible": true, + "data": data, + "position": targetState && targetState.position, + "cursor": "action-target", + "tooltip": tooltip + }; + } + return undefined; + }, + "hotkeyActionCheck": function(target, selection) + { + // Hotkeys are checked in the actionInfo. + return this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + // We want commands to units take precedence. + if (selection.some(ent => + { + const entState = GetEntityState(ent); + return entState && !!entState.unitAI; + })) + return false; + + const actionInfo = getActionInfo("focus-fire", target, selection); + + return actionInfo.possible && { + "type": "focus-fire", + "cursor": actionInfo.cursor, + "data": actionInfo.data, + "target": target, + "tooltip": actionInfo.tooltip, + "position": actionInfo.position, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 6, + }, + + "set-rallypoint": + { + "execute": function(position, action, selection, queued, pushFront) + { + // if there is a position set in the action then use this so that when setting a + // rally point on an entity it is centered on that entity + if (action.position) + position = action.position; + + Engine.PostNetworkCommand({ + "type": "set-rallypoint", + "entities": selection, + "x": position.x, + "z": position.z, + "data": action.data, + "queued": queued + }); + + // Display rally point at the new coordinates, to avoid display lag + Engine.GuiInterfaceCall("DisplayRallyPoint", { + "entities": selection, + "x": position.x, + "z": position.z, + "queued": queued + }); + + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!entState.rallyPoint) + return false; + + // Don't allow the rally point to be set on any of the currently selected entities (used for unset) + // except if the autorallypoint hotkey is pressed and the target can produce entities. + if (targetState && (!Engine.HotkeyIsPressed("session.autorallypoint") || + !targetState.trainer || + !targetState.trainer.entities.length)) + for (const ent of g_Selection.toList()) + if (targetState.id == ent) + return false; + + let tooltip; + let disabled = false; + // default to walking there (or attack-walking if hotkey pressed) + const data = { "command": "walk" }; + let cursor = ""; + + if (isAttackMovePressed()) + { + let targetClasses; + if (Engine.HotkeyIsPressed("session.attackmoveUnit")) + targetClasses = { "attack": ["Unit"] }; + else + targetClasses = { "attack": ["Unit", "Structure"] }; + + data.command = "attack-walk"; + data.targetClasses = targetClasses; + cursor = "action-attack-move"; + } + + if (Engine.HotkeyIsPressed("session.repair") && targetState && + (targetState.needsRepair || targetState.foundation) && + playerCheck(entState, targetState, ["Player", "Ally"])) + { + data.command = "repair"; + data.target = targetState.id; + cursor = "action-repair"; + } + else if (targetState && targetState.garrisonHolder && + playerCheck(entState, targetState, ["Player", "MutualAlly"])) + { + data.command = "garrison"; + data.target = targetState.id; + cursor = "action-garrison"; + + tooltip = sprintf(translate("Current garrison: %(garrisoned)s/%(capacity)s"), { + "garrisoned": targetState.garrisonHolder.occupiedSlots, + "capacity": targetState.garrisonHolder.capacity + }); + + if (targetState.garrisonHolder.occupiedSlots >= + targetState.garrisonHolder.capacity) + tooltip = coloredText(tooltip, "orange"); + } + else if (targetState && targetState.turretHolder && + playerCheck(entState, targetState, ["Player", "MutualAlly"])) + { + data.command = "occupy-turret"; + data.target = targetState.id; + cursor = "action-garrison"; + + const occupiedTurrets = targetState.turretHolder.turretPoints.filter(point => point.entity != null); + tooltip = sprintf(translate("Current turrets: %(occupied)s/%(capacity)s"), { + "occupied": occupiedTurrets.length, + "capacity": targetState.turretHolder.turretPoints.length + }); + + if (occupiedTurrets.length >= targetState.turretHolder.turretPoints.length) + tooltip = coloredText(tooltip, "orange"); + } + else if (targetState && targetState.resourceSupply) + { + const resourceType = targetState.resourceSupply.type; + cursor = "action-gather-" + resourceType.specific; + + data.command = "gather-near-position"; + data.resourceType = resourceType; + data.resourceTemplate = targetState.template; + if (!targetState.speed) + { + data.command = "gather"; + data.target = targetState.id; } } - } - else if (targetState && (targetState.needsRepair || targetState.foundation) && playerCheck(entState, targetState, ["Ally"])) - { - data.command = "repair"; - data.target = targetState.id; - cursor = "action-repair"; - } - else if (targetState && playerCheck(entState, targetState, ["Enemy"])) - { - data.target = targetState.id; - data.command = "attack"; - if (targetState.hitpoints) - cursor = "action-attack"; - else if (targetState.capturePoints) + else if (targetState && targetState.treasure) { - cursor = "action-capture"; - data.allowCapture = true; + cursor = "action-collect-treasure"; + data.command = "collect-treasure-near-position"; + if (!targetState.speed) + { + data.command = "collect-treasure"; + data.target = targetState.id; + } } - else - return false; - } + else if (entState.market && targetState && targetState.market && + entState.id != targetState.id && + (!entState.market.naval || targetState.market.naval) && + !playerCheck(entState, targetState, ["Enemy"])) + { + // Find a trader (if any) that this structure can train. + let trader; + if (entState.trainer?.entities?.length) + for (let i = 0; i < entState.trainer.entities.length; ++i) + if ((trader = GetTemplateData(entState.trainer.entities[i]).trader)) + break; - return { - "possible": true, - "data": data, - "position": targetState && targetState.position, - "cursor": cursor, - "disabled": disabled, - "tooltip": tooltip - }; + const traderData = { + "firstMarket": entState.id, + "secondMarket": targetState.id, + "template": trader + }; - }, - "hotkeyActionCheck": function(target, selection) - { - // Hotkeys are checked in the actionInfo. - return this.actionCheck(target, selection); - }, - "actionCheck": function(target, selection) - { - // We want commands to units take precedence. - if (selection.some(ent => { - const entState = GetEntityState(ent); - return entState && !!entState.unitAI; - })) - return false; + const gain = Engine.GuiInterfaceCall("GetTradingRouteGain", traderData); + if (gain) + { + data.command = "trade"; + data.target = traderData.secondMarket; + data.source = traderData.firstMarket; + cursor = "action-setup-trade-route"; + + if (gain.traderGain) + tooltip = translate("Right-click to establish a default route for new traders.") + "\n" + + sprintf( + trader ? + translate("Gain: %(gain)s") : + translate("Expected gain: %(gain)s"), + { "gain": getTradingTooltip(gain) }); + else + { + disabled = true; + tooltip = setStringTags(translate("This market is too close to the origin market."), g_DisabledTags); + cursor = "action-setup-trade-route-disabled"; + } + } + } + else if (targetState && (targetState.needsRepair || targetState.foundation) && playerCheck(entState, targetState, ["Ally"])) + { + data.command = "repair"; + data.target = targetState.id; + cursor = "action-repair"; + } + else if (targetState && playerCheck(entState, targetState, ["Enemy"])) + { + data.target = targetState.id; + data.command = "attack"; + if (targetState.hitpoints) + cursor = "action-attack"; + else if (targetState.capturePoints) + { + cursor = "action-capture"; + data.allowCapture = true; + } + else + return false; + } - const actionInfo = getActionInfo("set-rallypoint", target, selection); - if (actionInfo.disabled) return { - "type": "none", - "cursor": actionInfo.cursor, - "target": null, - "tooltip": actionInfo.tooltip + "possible": true, + "data": data, + "position": targetState && targetState.position, + "cursor": cursor, + "disabled": disabled, + "tooltip": tooltip }; - return actionInfo.possible && { - "type": "set-rallypoint", - "cursor": actionInfo.cursor, - "data": actionInfo.data, - "tooltip": actionInfo.tooltip, - "position": actionInfo.position, - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 6, - }, + }, + "hotkeyActionCheck": function(target, selection) + { + // Hotkeys are checked in the actionInfo. + return this.actionCheck(target, selection); + }, + "actionCheck": function(target, selection) + { + // We want commands to units take precedence. + if (selection.some(ent => + { + const entState = GetEntityState(ent); + return entState && !!entState.unitAI; + })) + return false; - "unset-rallypoint": - { - "execute": function(position, action, selection, queued, pushFront) + const actionInfo = getActionInfo("set-rallypoint", target, selection); + if (actionInfo.disabled) + return { + "type": "none", + "cursor": actionInfo.cursor, + "target": null, + "tooltip": actionInfo.tooltip + }; + + return actionInfo.possible && { + "type": "set-rallypoint", + "cursor": actionInfo.cursor, + "data": actionInfo.data, + "tooltip": actionInfo.tooltip, + "position": actionInfo.position, + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 6, + }, + + "unset-rallypoint": { - Engine.PostNetworkCommand({ - "type": "unset-rallypoint", - "entities": selection - }); + "execute": function(position, action, selection, queued, pushFront) + { + Engine.PostNetworkCommand({ + "type": "unset-rallypoint", + "entities": selection + }); - // Remove displayed rally point - Engine.GuiInterfaceCall("DisplayRallyPoint", { - "entities": [] - }); + // Remove displayed rally point + Engine.GuiInterfaceCall("DisplayRallyPoint", { + "entities": [] + }); - return true; + return true; + }, + "getActionInfo": function(entState, targetState) + { + if (!targetState || + entState.id != targetState.id || entState.unitAI || + !entState.rallyPoint || !entState.rallyPoint.position) + return false; + + return { "possible": true }; + }, + "actionCheck": function(target, selection) + { + const actionInfo = getActionInfo("unset-rallypoint", target, selection); + return actionInfo.possible && { + "type": "unset-rallypoint", + "cursor": "action-unset-rally", + "firstAbleEntity": actionInfo.entity + }; + }, + "specificness": 11, }, - "getActionInfo": function(entState, targetState) + + // This is a "fake" action to show a failure cursor + // when only uncontrollable entities are selected. + "uncontrollable": { - if (!targetState || - entState.id != targetState.id || entState.unitAI || - !entState.rallyPoint || !entState.rallyPoint.position) - return false; + "execute": function(position, action, selection, queued) + { + return true; + }, + "actionCheck": function(target, selection) + { + // Only show this action if all entities are marked uncontrollable. + const playerState = g_SimState.players[g_ViewedPlayer]; + if (playerState && playerState.controlsAll || selection.some(ent => + { + const entState = GetEntityState(ent); + return entState && entState.identity && entState.identity.controllable; + })) + return false; - return { "possible": true }; + return { + "type": "none", + "cursor": "cursor-no", + "tooltip": translatePlural("This entity cannot be controlled.", "These entities cannot be controlled.", selection.length) + }; + }, + "specificness": 100, }, - "actionCheck": function(target, selection) - { - const actionInfo = getActionInfo("unset-rallypoint", target, selection); - return actionInfo.possible && { - "type": "unset-rallypoint", - "cursor": "action-unset-rally", - "firstAbleEntity": actionInfo.entity - }; - }, - "specificness": 11, - }, - // This is a "fake" action to show a failure cursor - // when only uncontrollable entities are selected. - "uncontrollable": - { - "execute": function(position, action, selection, queued) + "none": { - return true; + "execute": function(position, action, selection, queued) + { + return true; + }, + "specificness": 100, }, - "actionCheck": function(target, selection) - { - // Only show this action if all entities are marked uncontrollable. - const playerState = g_SimState.players[g_ViewedPlayer]; - if (playerState && playerState.controlsAll || selection.some(ent => { - const entState = GetEntityState(ent); - return entState && entState.identity && entState.identity.controllable; - })) - return false; - - return { - "type": "none", - "cursor": "cursor-no", - "tooltip": translatePlural("This entity cannot be controlled.", "These entities cannot be controlled.", selection.length) - }; - }, - "specificness": 100, - }, - - "none": - { - "execute": function(position, action, selection, queued) - { - return true; - }, - "specificness": 100, - }, -}; + }; var g_UnitActionsSortedKeys = Object.keys(g_UnitActions).sort((a, b) => g_UnitActions[a].specificness - g_UnitActions[b].specificness); @@ -1421,85 +1424,85 @@ var g_UnitActionsSortedKeys = Object.keys(g_UnitActions).sort((a, b) => g_UnitAc * Currently displayed in the bottom of the central panel */ var g_EntityCommands = -{ - "unload-all": { - "getInfo": function(entStates) - { - let count = 0; - for (const entState of entStates) + { + "unload-all": { + "getInfo": function(entStates) { - if (!entState.garrisonHolder) - continue; + let count = 0; + for (const entState of entStates) + { + if (!entState.garrisonHolder) + continue; - if (allowedPlayersCheck([entState], ["Player"])) - count += entState.garrisonHolder.entities.length; - else - for (const entity of entState.garrisonHolder.entities) - if (allowedPlayersCheck([GetEntityState(entity)], ["Player"])) - ++count; - } + if (allowedPlayersCheck([entState], ["Player"])) + count += entState.garrisonHolder.entities.length; + else + for (const entity of entState.garrisonHolder.entities) + if (allowedPlayersCheck([GetEntityState(entity)], ["Player"])) + ++count; + } - if (!count) - return false; + if (!count) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.unload") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.unload") + translate("Unload All") + "\n" + bodyFont(translate("Order all units to leave the selected entities.")), - "icon": "garrison-out.png", - "count": count, - "enabled": true - }; - }, - "execute": function() - { - unloadAll(); - }, - "allowedPlayers": ["Player", "Ally"] - }, - - "unload-all-turrets": { - "getInfo": function(entStates) - { - let count = 0; - for (const entState of entStates) + "icon": "garrison-out.png", + "count": count, + "enabled": true + }; + }, + "execute": function() { - if (!entState.turretHolder) - continue; + unloadAll(); + }, + "allowedPlayers": ["Player", "Ally"] + }, - if (allowedPlayersCheck([entState], ["Player"])) - count += entState.turretHolder.turretPoints.filter(turretPoint => turretPoint.entity && turretPoint.ejectable).length; - else - for (const turretPoint of entState.turretHolder.turretPoints) - if (turretPoint.entity && allowedPlayersCheck([GetEntityState(turretPoint.entity)], ["Player"])) - ++count; - } + "unload-all-turrets": { + "getInfo": function(entStates) + { + let count = 0; + for (const entState of entStates) + { + if (!entState.turretHolder) + continue; - if (!count) - return false; + if (allowedPlayersCheck([entState], ["Player"])) + count += entState.turretHolder.turretPoints.filter(turretPoint => turretPoint.entity && turretPoint.ejectable).length; + else + for (const turretPoint of entState.turretHolder.turretPoints) + if (turretPoint.entity && allowedPlayersCheck([GetEntityState(turretPoint.entity)], ["Player"])) + ++count; + } - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.unloadturrets") + + if (!count) + return false; + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.unloadturrets") + translate("Unload Turrets") + "\n" + bodyFont(translate("Order all units to leave the selected turret points.")), - "icon": "garrison-out.png", - "count": count, - "enabled": true - }; + "icon": "garrison-out.png", + "count": count, + "enabled": true + }; + }, + "execute": function() + { + unloadAllTurrets(); + }, + "allowedPlayers": ["Player", "Ally"] }, - "execute": function() - { - unloadAllTurrets(); - }, - "allowedPlayers": ["Player", "Ally"] - }, - "delete": { - "getInfo": function(entStates) - { - return entStates.some(entState => !isUndeletable(entState)) ? - { - "tooltip": + "delete": { + "getInfo": function(entStates) + { + return entStates.some(entState => !isUndeletable(entState)) ? + { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.kill") + translate("Self-Destruct") + "\n" + bodyFont(translate("Destroy the selected entities.") + "\n" + @@ -1508,445 +1511,446 @@ var g_EntityCommands = "session.noconfirmation" ) ), - "icon": "kill_small.png", - "enabled": true - } : - { + "icon": "kill_small.png", + "enabled": true + } : + { // Get all delete reasons and remove duplications - "tooltip": entStates.map(entState => isUndeletable(entState)) - .filter((reason, pos, self) => - self.indexOf(reason) == pos && reason - ).join("\n"), - "icon": "kill_small_disabled.png", - "enabled": false - }; + "tooltip": entStates.map(entState => isUndeletable(entState)) + .filter((reason, pos, self) => + self.indexOf(reason) == pos && reason + ).join("\n"), + "icon": "kill_small_disabled.png", + "enabled": false + }; + }, + "execute": function(entStates) + { + const entityIDs = entStates.reduce( + (ids, entState) => + { + if (!isUndeletable(entState)) + ids.push(entState.id); + return ids; + }, + []); + + if (!entityIDs.length) + return; + + const deleteSelection = () => Engine.PostNetworkCommand({ + "type": "delete-entities", + "entities": entityIDs + }); + + if (Engine.HotkeyIsPressed("session.noconfirmation")) + deleteSelection(); + else + (new DeleteSelectionConfirmation(deleteSelection)).display(); + }, + "allowedPlayers": ["Player"] }, - "execute": function(entStates) - { - const entityIDs = entStates.reduce( - (ids, entState) => { - if (!isUndeletable(entState)) - ids.push(entState.id); - return ids; - }, - []); - if (!entityIDs.length) - return; - - const deleteSelection = () => Engine.PostNetworkCommand({ - "type": "delete-entities", - "entities": entityIDs - }); - - if (Engine.HotkeyIsPressed("session.noconfirmation")) - deleteSelection(); - else - (new DeleteSelectionConfirmation(deleteSelection)).display(); - }, - "allowedPlayers": ["Player"] - }, - - "stop": { - "getInfo": function(entStates) - { + "stop": { + "getInfo": function(entStates) + { // Don't show generic option to abort if not applicable or in case of guard, which has its own abort action - if (entStates.every(entState => !entState.unitAI || entState.unitAI.isIdle || entState.unitAI.isGuarding)) - return false; + if (entStates.every(entState => !entState.unitAI || entState.unitAI.isIdle || entState.unitAI.isGuarding)) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.stop") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.stop") + translate("Abort") + "\n" + bodyFont(translate("Cancel the current orders for the selected units.")), - "icon": "stop.png", - "enabled": true - }; + "icon": "stop.png", + "enabled": true + }; + }, + "execute": function(entStates) + { + if (entStates.length) + stopUnits(entStates.map(entState => entState.id)); + }, + "allowedPlayers": ["Player"] }, - "execute": function(entStates) - { - if (entStates.length) - stopUnits(entStates.map(entState => entState.id)); - }, - "allowedPlayers": ["Player"] - }, - "call-to-arms": { - "getInfo": function(entStates) - { - const classes = ["Soldier", "Warship", "Siege", "Healer"]; - if (entStates.every(entState => !MatchesClassList(entState.identity.classes, classes))) - return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.calltoarms") + + "call-to-arms": { + "getInfo": function(entStates) + { + const classes = ["Soldier", "Warship", "Siege", "Healer"]; + if (entStates.every(entState => !MatchesClassList(entState.identity.classes, classes))) + return false; + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.calltoarms") + translate("Attack") + "\n" + bodyFont(translate("Send the selected units on attack move to the specified location after dropping resources.")), - "icon": "call-to-arms.png", - "enabled": true - }; + "icon": "call-to-arms.png", + "enabled": true + }; + }, + "execute": function(entStates) + { + inputState = INPUT_PRESELECTEDACTION; + preSelectedAction = ACTION_CALLTOARMS; + }, + "allowedPlayers": ["Player"] }, - "execute": function(entStates) - { - inputState = INPUT_PRESELECTEDACTION; - preSelectedAction = ACTION_CALLTOARMS; - }, - "allowedPlayers": ["Player"] - }, - "garrison": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.garrisonable || + "garrison": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.garrisonable || entState.garrisonable.holder != INVALID_ENTITY)) - return false; + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.garrison") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.garrison") + translate("Garrison") + "\n" + bodyFont(translate("Order the selected units to garrison in a structure or another unit.")), - "icon": "garrison.png", - "enabled": true - }; + "icon": "garrison.png", + "enabled": true + }; + }, + "execute": function() + { + inputState = INPUT_PRESELECTEDACTION; + preSelectedAction = ACTION_GARRISON; + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - inputState = INPUT_PRESELECTEDACTION; - preSelectedAction = ACTION_GARRISON; - }, - "allowedPlayers": ["Player"] - }, - "occupy-turret": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.turretable || + "occupy-turret": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.turretable || entState.turretable.holder != INVALID_ENTITY)) - return false; + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.occupyturret") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.occupyturret") + translate("Occupy Turret") + "\n" + bodyFont(translate("Order the selected units to occupy a turret point.")), - "icon": "occupy-turret.png", - "enabled": true - }; + "icon": "occupy-turret.png", + "enabled": true + }; + }, + "execute": function() + { + inputState = INPUT_PRESELECTEDACTION; + preSelectedAction = ACTION_OCCUPY_TURRET; + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - inputState = INPUT_PRESELECTEDACTION; - preSelectedAction = ACTION_OCCUPY_TURRET; - }, - "allowedPlayers": ["Player"] - }, - "leave-turret": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.turretable || + "leave-turret": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.turretable || entState.turretable.holder == INVALID_ENTITY || !entState.turretable.ejectable)) - return false; + return false; - return { - "tooltip": translate("Unload") + "\n" + + return { + "tooltip": translate("Unload") + "\n" + bodyFont(translate("Order the selected units to leave their turret points.")), - "icon": "leave-turret.png", - "enabled": true - }; + "icon": "leave-turret.png", + "enabled": true + }; + }, + "execute": function(entStates) + { + leaveTurretPoints(); + }, + "allowedPlayers": ["Player"] }, - "execute": function(entStates) - { - leaveTurretPoints(); - }, - "allowedPlayers": ["Player"] - }, - "repair": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.builder)) - return false; + "repair": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.builder)) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.repair") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.repair") + translate("Repair") + "\n" + bodyFont(translate("Order the selected units to repair a structure, ship, or siege engine.")), - "icon": "repair.png", - "enabled": true - }; + "icon": "repair.png", + "enabled": true + }; + }, + "execute": function() + { + inputState = INPUT_PRESELECTEDACTION; + preSelectedAction = ACTION_REPAIR; + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - inputState = INPUT_PRESELECTEDACTION; - preSelectedAction = ACTION_REPAIR; - }, - "allowedPlayers": ["Player"] - }, - "focus-rally": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.rallyPoint)) - return false; + "focus-rally": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.rallyPoint)) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "camera.rallypointfocus") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "camera.rallypointfocus") + translate("Focus on Rally Point") + "\n" + bodyFont(translate("Center the view on the selected rally point.")), - "icon": "focus-rally.png", - "enabled": true - }; - }, - "execute": function(entStates) - { + "icon": "focus-rally.png", + "enabled": true + }; + }, + "execute": function(entStates) + { // TODO: Would be nicer to cycle between the rallypoints of multiple entities instead of just using the first - let focusTarget; - for (const entState of entStates) - if (entState.rallyPoint && entState.rallyPoint.position) - { - focusTarget = entState.rallyPoint.position; - break; - } - if (!focusTarget) + let focusTarget; for (const entState of entStates) - if (entState.position) + if (entState.rallyPoint && entState.rallyPoint.position) { - focusTarget = entState.position; + focusTarget = entState.rallyPoint.position; break; } + if (!focusTarget) + for (const entState of entStates) + if (entState.position) + { + focusTarget = entState.position; + break; + } - if (focusTarget) - Engine.CameraMoveTo(focusTarget.x, focusTarget.z); + if (focusTarget) + Engine.CameraMoveTo(focusTarget.x, focusTarget.z); + }, + "allowedPlayers": ["Player", "Observer"] }, - "allowedPlayers": ["Player", "Observer"] - }, - "back-to-work": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.unitAI || !entState.unitAI.hasWorkOrders)) - return false; + "back-to-work": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.unitAI || !entState.unitAI.hasWorkOrders)) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.backtowork") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.backtowork") + translate("Back to Work") + "\n" + bodyFont(translate("Order the selected units to resume their work.")), - "icon": "back-to-work.png", - "enabled": true - }; + "icon": "back-to-work.png", + "enabled": true + }; + }, + "execute": function() + { + backToWork(); + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - backToWork(); - }, - "allowedPlayers": ["Player"] - }, - "add-guard": { - "getInfo": function(entStates) - { - if (entStates.every(entState => - !entState.unitAI || !entState.unitAI.canGuard || entState.unitAI.isGuarding)) - return false; + "add-guard": { + "getInfo": function(entStates) + { + if (entStates.every(entState => + !entState.unitAI || !entState.unitAI.canGuard || entState.unitAI.isGuarding)) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.guard") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.guard") + translate("Guard") + "\n" + bodyFont(translate("Order the selected units to guard a structure or unit.")), - "icon": "add-guard.png", - "enabled": true - }; + "icon": "add-guard.png", + "enabled": true + }; + }, + "execute": function() + { + inputState = INPUT_PRESELECTEDACTION; + preSelectedAction = ACTION_GUARD; + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - inputState = INPUT_PRESELECTEDACTION; - preSelectedAction = ACTION_GUARD; - }, - "allowedPlayers": ["Player"] - }, - "remove-guard": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.unitAI || !entState.unitAI.isGuarding)) - return false; + "remove-guard": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.unitAI || !entState.unitAI.isGuarding)) + return false; - return { - "tooltip": translate("Abort Guard") + "\n" + + return { + "tooltip": translate("Abort Guard") + "\n" + bodyFont(translate("Order the selected units to stop guarding.")), - "icon": "remove-guard.png", - "enabled": true - }; + "icon": "remove-guard.png", + "enabled": true + }; + }, + "execute": function() + { + removeGuard(); + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - removeGuard(); - }, - "allowedPlayers": ["Player"] - }, - "select-trading-goods": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.market)) - return false; + "select-trading-goods": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.market)) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.gui.barter.toggle") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.gui.barter.toggle") + translate("Barter & Trade") + "\n" + bodyFont(translate("Open the dialog for managing resource trading and bartering.")), - "icon": "economics.png", - "enabled": true - }; + "icon": "economics.png", + "enabled": true + }; + }, + "execute": function() + { + g_TradeDialog.toggle(); + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - g_TradeDialog.toggle(); - }, - "allowedPlayers": ["Player"] - }, - "patrol": { - "getInfo": function(entStates) - { - if (!entStates.some(entState => entState.unitAI && entState.unitAI.canPatrol)) - return false; + "patrol": { + "getInfo": function(entStates) + { + if (!entStates.some(entState => entState.unitAI && entState.unitAI.canPatrol)) + return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.patrol") + + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.patrol") + translate("Patrol") + "\n" + bodyFont(translate("Order to repeatedly go to a point and come back, attacking all enemies along the way.")), - "icon": "patrol.png", - "enabled": true - }; + "icon": "patrol.png", + "enabled": true + }; + }, + "execute": function() + { + inputState = INPUT_PRESELECTEDACTION; + preSelectedAction = ACTION_PATROL; + }, + "allowedPlayers": ["Player"] }, - "execute": function() - { - inputState = INPUT_PRESELECTEDACTION; - preSelectedAction = ACTION_PATROL; - }, - "allowedPlayers": ["Player"] - }, - "share-dropsite": { - "getInfo": function(entStates) - { - const sharableEntities = entStates.filter( - entState => entState.resourceDropsite && entState.resourceDropsite.sharable); - if (!sharableEntities.length) - return false; + "share-dropsite": { + "getInfo": function(entStates) + { + const sharableEntities = entStates.filter( + entState => entState.resourceDropsite && entState.resourceDropsite.sharable); + if (!sharableEntities.length) + return false; - // Returns if none of the entities belong to a player with a mutual ally. - if (entStates.every(entState => !GetSimState().players[entState.player].isMutualAlly.some( - (isAlly, playerId) => isAlly && playerId != entState.player))) - return false; + // Returns if none of the entities belong to a player with a mutual ally. + if (entStates.every(entState => !GetSimState().players[entState.player].isMutualAlly.some( + (isAlly, playerId) => isAlly && playerId != entState.player))) + return false; - return sharableEntities.some(entState => !entState.resourceDropsite.shared) ? - { - "tooltip": translate("Share Dropsite") + "\n" + + return sharableEntities.some(entState => !entState.resourceDropsite.shared) ? + { + "tooltip": translate("Share Dropsite") + "\n" + bodyFont(translate("Allow allies to use this dropsite, now locked.")), - "icon": "locked_small.png", - "enabled": true - } : - { - "tooltip": translate("Lock Dropsite") + "\n" + + "icon": "locked_small.png", + "enabled": true + } : + { + "tooltip": translate("Lock Dropsite") + "\n" + bodyFont(translate("Prevent allies from using this dropsite, now shared.")), - "icon": "unlocked_small.png", - "enabled": true - }; + "icon": "unlocked_small.png", + "enabled": true + }; + }, + "execute": function(entStates) + { + const sharableEntities = entStates.filter( + entState => entState.resourceDropsite && entState.resourceDropsite.sharable); + if (sharableEntities) + Engine.PostNetworkCommand({ + "type": "set-dropsite-sharing", + "entities": sharableEntities.map(entState => entState.id), + "shared": sharableEntities.some(entState => !entState.resourceDropsite.shared) + }); + }, + "allowedPlayers": ["Player"] }, - "execute": function(entStates) - { - const sharableEntities = entStates.filter( - entState => entState.resourceDropsite && entState.resourceDropsite.sharable); - if (sharableEntities) - Engine.PostNetworkCommand({ - "type": "set-dropsite-sharing", - "entities": sharableEntities.map(entState => entState.id), - "shared": sharableEntities.some(entState => !entState.resourceDropsite.shared) - }); - }, - "allowedPlayers": ["Player"] - }, - "is-dropsite-shared": { - "getInfo": function(entStates) - { - const shareableEntities = entStates.filter( - entState => entState.resourceDropsite && entState.resourceDropsite.sharable); - if (!shareableEntities.length) - return false; + "is-dropsite-shared": { + "getInfo": function(entStates) + { + const shareableEntities = entStates.filter( + entState => entState.resourceDropsite && entState.resourceDropsite.sharable); + if (!shareableEntities.length) + return false; - const player = Engine.GetPlayerID(); - const simState = GetSimState(); - if (!g_IsObserver && !simState.players[player].hasSharedDropsites || + const player = Engine.GetPlayerID(); + const simState = GetSimState(); + if (!g_IsObserver && !simState.players[player].hasSharedDropsites || shareableEntities.every(entState => controlsPlayer(entState.player))) - return false; + return false; - if (!shareableEntities.every(entState => entState.resourceDropsite.shared)) - return { - "tooltip": translate("Locked Dropsite") + "\n" + + if (!shareableEntities.every(entState => entState.resourceDropsite.shared)) + return { + "tooltip": translate("Locked Dropsite") + "\n" + bodyFont(translate("The use of this dropsite is prohibited.")), - "icon": "locked_small.png", - "enabled": false - }; + "icon": "locked_small.png", + "enabled": false + }; - return { - "tooltip": translate("Shared Dropsite") + "\n" + + return { + "tooltip": translate("Shared Dropsite") + "\n" + bodyFont(g_IsObserver ? translate("Allies are allowed to use this dropsite.") : translate("You are allowed to use this dropsite.")), - "icon": "unlocked_small.png", - "enabled": false - }; - }, - "execute": function(entState) - { + "icon": "unlocked_small.png", + "enabled": false + }; + }, + "execute": function(entState) + { // This command button is always disabled. + }, + "allowedPlayers": ["Ally", "Observer"] }, - "allowedPlayers": ["Ally", "Observer"] - }, - "autoqueue-on": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.trainer?.entities?.length || !entState.production || entState.production.autoqueue)) - return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.queueunit.autoqueueon") + + "autoqueue-on": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.trainer?.entities?.length || !entState.production || entState.production.autoqueue)) + return false; + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.queueunit.autoqueueon") + translate("Activate Auto-Queue") + "\n" + bodyFont(translate("Activate the production auto-queue for the selected structures.")), - "icon": "autoqueue-on.png", - "enabled": true - }; + "icon": "autoqueue-on.png", + "enabled": true + }; + }, + "execute": function(entStates) + { + if (entStates.length) + turnAutoQueueOn(); + }, + "allowedPlayers": ["Player"] }, - "execute": function(entStates) - { - if (entStates.length) - turnAutoQueueOn(); - }, - "allowedPlayers": ["Player"] - }, - "autoqueue-off": { - "getInfo": function(entStates) - { - if (entStates.every(entState => !entState.production?.autoqueue)) - return false; - return { - "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.queueunit.autoqueueoff") + + "autoqueue-off": { + "getInfo": function(entStates) + { + if (entStates.every(entState => !entState.production?.autoqueue)) + return false; + return { + "tooltip": colorizeHotkey("%(hotkey)s" + " ", "session.queueunit.autoqueueoff") + translate("Deactivate Auto-Queue") + "\n" + bodyFont(translate("Deactivate the production auto-queue for the selected structures.")), - "icon": "autoqueue-off.png", - "enabled": true - }; + "icon": "autoqueue-off.png", + "enabled": true + }; + }, + "execute": function(entStates) + { + if (entStates.length) + turnAutoQueueOff(); + }, + "allowedPlayers": ["Player"] }, - "execute": function(entStates) - { - if (entStates.length) - turnAutoQueueOff(); - }, - "allowedPlayers": ["Player"] - }, -}; + }; function playerCheck(entState, targetState, validPlayers) { diff --git a/binaries/data/mods/public/gui/splashscreen/splashscreen.js b/binaries/data/mods/public/gui/splashscreen/splashscreen.js index b42d7ba059..e265dd2a5d 100644 --- a/binaries/data/mods/public/gui/splashscreen/splashscreen.js +++ b/binaries/data/mods/public/gui/splashscreen/splashscreen.js @@ -36,7 +36,8 @@ export async function init(data) Engine.GetGUIObjectByName("displaySplashScreen").checked = Engine.ConfigDB_GetValue("user", "gui.splashscreen.enable") === "true"; - await new Promise(resolve => { + await new Promise(resolve => + { Engine.GetGUIObjectByName("btnOK").onPress = resolve; }); diff --git a/binaries/data/mods/public/gui/summary/counters.js b/binaries/data/mods/public/gui/summary/counters.js index 8652f86059..f9b5aaf276 100644 --- a/binaries/data/mods/public/gui/summary/counters.js +++ b/binaries/data/mods/public/gui/summary/counters.js @@ -80,7 +80,8 @@ function summaryAddObject(obj1, obj2) */ function summaryArraySum(array) { - return array.reduce((sum, val) => { + return array.reduce((sum, val) => + { if (typeof sum !== "object") return sum + val; summaryAddObject(sum, val); diff --git a/binaries/data/mods/public/gui/summary/layout.js b/binaries/data/mods/public/gui/summary/layout.js index 4216d70f1e..e67440032e 100644 --- a/binaries/data/mods/public/gui/summary/layout.js +++ b/binaries/data/mods/public/gui/summary/layout.js @@ -160,7 +160,8 @@ var getScorePanelsData = () => [ { "identifier": "playername", "caption": translate("Player name"), "yStart": 26, "width": 200 }, { "identifier": "tradeIncome", "caption": translate("Trade income"), "yStart": 0, "width": 120 }, { "identifier": "barterEfficency", "caption": translate("Barter efficiency"), "yStart": 0, "width": 120, "format": "PERCENTAGE" }, - ...g_ResourceData.GetResources().map(res => { + ...g_ResourceData.GetResources().map(res => + { return { "identifier": res.code, "caption": diff --git a/binaries/data/mods/public/gui/summary/summary.js b/binaries/data/mods/public/gui/summary/summary.js index 8869cfb4ed..45200a6960 100644 --- a/binaries/data/mods/public/gui/summary/summary.js +++ b/binaries/data/mods/public/gui/summary/summary.js @@ -142,7 +142,8 @@ async function init(data) while (true) { - const branchless = await new Promise(resolve => { + const branchless = await new Promise(resolve => + { Engine.GetGUIObjectByName("continueButton").onPress = resolve.bind(null, true); Engine.GetGUIObjectByName("summaryHotkey").onPress = resolve.bind(null, true); Engine.GetGUIObjectByName("cancelHotkey").onPress = resolve.bind(null, false); @@ -275,7 +276,8 @@ function updateCategoryDropdown(number) const chartCategory = Engine.GetGUIObjectByName("chart[" + number + "]CategorySelection"); chartCategory.list_data = g_ScorePanelsData.map((panel, idx) => idx); chartCategory.list = g_ScorePanelsData.map(panel => panel.label); - chartCategory.onSelectionChange = function() { + chartCategory.onSelectionChange = function() + { if (!this.list_data[this.selected]) return; if (g_SelectedChart.category[number] != this.selected) @@ -300,7 +302,8 @@ function updateValueDropdown(number, category) const list_data = g_ScorePanelsData[category].headings.map(heading => heading.identifier); list_data.shift(); chartValue.list_data = list_data; - chartValue.onSelectionChange = function() { + chartValue.onSelectionChange = function() + { if (!this.list_data[this.selected]) return; if (g_SelectedChart.value[number] != this.selected) @@ -331,7 +334,8 @@ function updateTypeDropdown(number, category, item, itemNumber) chartType.list = Object.keys(testValue).map(type => g_SummaryTypes[type].caption); chartType.list_data = Object.keys(testValue); - chartType.onSelectionChange = function() { + chartType.onSelectionChange = function() + { if (!this.list_data[this.selected]) return; g_SelectedChart.type[number] = this.selected; diff --git a/binaries/data/mods/public/maps/random/belgian_uplands.js b/binaries/data/mods/public/maps/random/belgian_uplands.js index 7da4e76601..c35cdea365 100644 --- a/binaries/data/mods/public/maps/random/belgian_uplands.js +++ b/binaries/data/mods/public/maps/random/belgian_uplands.js @@ -200,7 +200,8 @@ export function* generateMap(mapSettings) const lowerHeightLimit = terrainTypes[3].upperHeightLimit; const upperHeightLimit = terrainTypes[6].upperHeightLimit; - const { playerIDs, playerPosition } = (() => { + const { playerIDs, playerPosition } = (() => + { while (true) { g_Map.log("Randomizing heightmap"); @@ -272,7 +273,8 @@ export function* generateMap(mapSettings) const resourceSpacing = 1; const resourceCount = 4; - playerPosition.forEach((position, i) => { + playerPosition.forEach((position, i) => + { placeCivDefaultStartingEntities(position, playerIDs[i], false); for (let j = 1; j <= 4; ++j) diff --git a/binaries/data/mods/public/maps/random/caledonian_meadows.js b/binaries/data/mods/public/maps/random/caledonian_meadows.js index 2653a74c07..2f0318b6d8 100644 --- a/binaries/data/mods/public/maps/random/caledonian_meadows.js +++ b/binaries/data/mods/public/maps/random/caledonian_meadows.js @@ -293,7 +293,8 @@ export function* generateMap(mapSettings) [false, 7 / 8], // 10 Hilltop [false, 8 / 8] - ].map(([underWater, ratio]) => { + ].map(([underWater, ratio]) => + { const base = underWater ? heightRange.min : heightSeaGroundAdjusted; const factor = underWater ? heightSeaGroundAdjusted - heightRange.min : heightRange.max - heightSeaGroundAdjusted; @@ -593,7 +594,8 @@ export function* generateMap(mapSettings) * Get midpoint slope of each area */ const slopeMap = getSlopeMap(); - const slopeMidpoints = areas.map(area => { + const slopeMidpoints = areas.map(area => + { const slopesInThisArea = area.map(({ x, y }) => slopeMap[x][y]); return Math.min(...slopesInThisArea) + Math.max(...slopesInThisArea); }); diff --git a/binaries/data/mods/public/maps/random/danubius.js b/binaries/data/mods/public/maps/random/danubius.js index 577ff07e37..5b94b00005 100644 --- a/binaries/data/mods/public/maps/random/danubius.js +++ b/binaries/data/mods/public/maps/random/danubius.js @@ -457,14 +457,16 @@ export function* generateMap(mapSettings) "heightLand": heightLand, "meanderShort": 30, "meanderLong": 0, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { const origPos = position.clone().rotateAround(-startAngle, mapCenter); // Distinguish left and right shoreline if (height > 0 && height < 1 && origPos.y > ShorelineDistance && origPos.y < mapSize - ShorelineDistance) clShore[origPos.x < mapCenter.x ? 0 : 1].add(position); }, - "landFunc": (position, shoreDist1, shoreDist2) => { + "landFunc": (position, shoreDist1, shoreDist2) => + { if (shoreDist1 > 0) clLand[0].add(position); diff --git a/binaries/data/mods/public/maps/random/english_channel.js b/binaries/data/mods/public/maps/random/english_channel.js index 11dd89fb9e..539e17588f 100644 --- a/binaries/data/mods/public/maps/random/english_channel.js +++ b/binaries/data/mods/public/maps/random/english_channel.js @@ -105,10 +105,12 @@ export function* generateMap() "heightLand": heightLand, "meanderShort": 20, "meanderLong": 0, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { createTerrain(height < -1.5 ? tWater : tShore).place(position); }, - "landFunc": (position, shoreDist1, shoreDist2) => { + "landFunc": (position, shoreDist1, shoreDist2) => + { g_Map.setHeight(position, heightLand + 0.1); } }); diff --git a/binaries/data/mods/public/maps/random/fields_of_meroe.js b/binaries/data/mods/public/maps/random/fields_of_meroe.js index 7cdb4d841a..27e1419290 100644 --- a/binaries/data/mods/public/maps/random/fields_of_meroe.js +++ b/binaries/data/mods/public/maps/random/fields_of_meroe.js @@ -119,11 +119,13 @@ export function* generateMap(mapSettings) "heightLand": heightShore, "meanderShort": 14, "meanderLong": 18, - "waterFunc": (position, height, z) => { + "waterFunc": (position, height, z) => + { clRiver.add(position); createTerrain(tRiverBank).place(position); }, - "landFunc": (position, shoreDist1, shoreDist2) => { + "landFunc": (position, shoreDist1, shoreDist2) => + { for (const riv of riverTextures) if (riv.left < +shoreDist1 && +shoreDist1 < riv.right || riv.left < -shoreDist2 && -shoreDist2 < riv.right) diff --git a/binaries/data/mods/public/maps/random/flood_triggers.js b/binaries/data/mods/public/maps/random/flood_triggers.js index e034445402..a88740dbc9 100644 --- a/binaries/data/mods/public/maps/random/flood_triggers.js +++ b/binaries/data/mods/public/maps/random/flood_triggers.js @@ -102,7 +102,8 @@ Trigger.prototype.OnGlobalInitGame = function(msg) return; } - const schedule = (targetWaterLevel, riseStartTime) => { + const schedule = (targetWaterLevel, riseStartTime) => + { this.DoAfterDelay(riseStartTime * 1000, "RaiseWaterLevelStep", targetWaterLevel); this.DoAfterDelay((riseStartTime - this.warningDuration) * 1000, "DisplayWarning"); }; diff --git a/binaries/data/mods/public/maps/random/guadalquivir_river.js b/binaries/data/mods/public/maps/random/guadalquivir_river.js index b11be9ce10..3c205e2544 100644 --- a/binaries/data/mods/public/maps/random/guadalquivir_river.js +++ b/binaries/data/mods/public/maps/random/guadalquivir_river.js @@ -132,7 +132,8 @@ export function* generateMap() "heightLand": heightShore, "meanderShort": 12, "meanderLong": 0, - "waterFunc": (position, height, z) => { + "waterFunc": (position, height, z) => + { clRiver.add(position); createTerrain(tWater).place(position); diff --git a/binaries/data/mods/public/maps/random/hyrcanian_shores.js b/binaries/data/mods/public/maps/random/hyrcanian_shores.js index 4529f66c42..f32d555388 100644 --- a/binaries/data/mods/public/maps/random/hyrcanian_shores.js +++ b/binaries/data/mods/public/maps/random/hyrcanian_shores.js @@ -116,7 +116,8 @@ export function* generateMap(mapSettings) "heightLand": heightLand, "meanderShort": 20, "meanderLong": 0, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { if (height < heightShore2) clWater.add(position); diff --git a/binaries/data/mods/public/maps/random/jebel_barkal.js b/binaries/data/mods/public/maps/random/jebel_barkal.js index 60f8e89125..42d163cac3 100644 --- a/binaries/data/mods/public/maps/random/jebel_barkal.js +++ b/binaries/data/mods/public/maps/random/jebel_barkal.js @@ -392,11 +392,13 @@ export function* generateMap(mapSettings) "heightRiverbed": heightFertileLand, "meanderShort": 40, "meanderLong": 0, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { createTerrain(tGrass).place(position); clFertileLand.add(position); }, - "landFunc": (position, shoreDist1, shoreDist2) => { + "landFunc": (position, shoreDist1, shoreDist2) => + { for (const riv of layoutFertileLandTextures) if (riv.left < +shoreDist1 && +shoreDist1 < riv.right || diff --git a/binaries/data/mods/public/maps/random/jebel_barkal_triggers.js b/binaries/data/mods/public/maps/random/jebel_barkal_triggers.js index 249045700b..cf5ae3b38f 100644 --- a/binaries/data/mods/public/maps/random/jebel_barkal_triggers.js +++ b/binaries/data/mods/public/maps/random/jebel_barkal_triggers.js @@ -46,7 +46,8 @@ var jebelBarkal_templateClasses = deepfreeze({ "civilians": "Civilian" }); -var jebelBarkal_templates = deepfreeze(Object.keys(jebelBarkal_templateClasses).reduce((templates, name) => { +var jebelBarkal_templates = deepfreeze(Object.keys(jebelBarkal_templateClasses).reduce((templates, name) => +{ templates[name] = TriggerHelper.GetTemplateNamesByClasses(jebelBarkal_templateClasses[name], "kush", undefined, jebelBarkal_rank, true); return templates; }, {})); diff --git a/binaries/data/mods/public/maps/random/kerala.js b/binaries/data/mods/public/maps/random/kerala.js index 752bd0bf56..2de6207a00 100644 --- a/binaries/data/mods/public/maps/random/kerala.js +++ b/binaries/data/mods/public/maps/random/kerala.js @@ -117,7 +117,8 @@ export function* generateMap() "heightLand": heightLand, "meanderShort": 20, "meanderLong": 0, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { clWater.add(position); } }); diff --git a/binaries/data/mods/public/maps/random/latium.js b/binaries/data/mods/public/maps/random/latium.js index c513c417b1..68dfc66019 100644 --- a/binaries/data/mods/public/maps/random/latium.js +++ b/binaries/data/mods/public/maps/random/latium.js @@ -122,7 +122,8 @@ export function* generateMap() "heightLand": heightLand, "meanderShort": 0, "meanderLong": 0, - "waterFunc": (position, height, z) => { + "waterFunc": (position, height, z) => + { clWater.add(position); } }); diff --git a/binaries/data/mods/public/maps/random/lions_den.js b/binaries/data/mods/public/maps/random/lions_den.js index 334ed6e928..0ca415749a 100644 --- a/binaries/data/mods/public/maps/random/lions_den.js +++ b/binaries/data/mods/public/maps/random/lions_den.js @@ -512,7 +512,8 @@ export function* generateMap(mapSettings) new TileClassPainter(g_TileClasses.mountain) ]); - const getCoords = (distance, playerID, playerIDOffset) => { + const getCoords = (distance, playerID, playerIDOffset) => + { const angle = startAngle + (playerID + playerIDOffset) * 2 * Math.PI / numPlayers; return Vector2D.add(mapCenter, new Vector2D(fractionToTiles(distance), 0).rotate(-angle)) .round(); diff --git a/binaries/data/mods/public/maps/random/polar_sea_triggers.js b/binaries/data/mods/public/maps/random/polar_sea_triggers.js index 7fd7d41383..2ede850681 100644 --- a/binaries/data/mods/public/maps/random/polar_sea_triggers.js +++ b/binaries/data/mods/public/maps/random/polar_sea_triggers.js @@ -51,7 +51,8 @@ Trigger.prototype.SpawnWolvesAndAttack = function() // The returned entities are sorted by RangeManager already // Only consider units implementing Health since wolves deal damage. - const targets = PositionHelper.EntitiesNearPoint(attackerPos, 200, players, IID_Health).filter(ent => { + const targets = PositionHelper.EntitiesNearPoint(attackerPos, 200, players, IID_Health).filter(ent => + { const cmpIdentity = Engine.QueryInterface(ent, IID_Identity); return cmpIdentity && MatchesClassList(cmpIdentity.GetClassesList(), targetClasses); }); @@ -62,12 +63,14 @@ Trigger.prototype.SpawnWolvesAndAttack = function() if (goodTargets.length < targetCount) { if (!allTargets) - allTargets = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager).GetNonGaiaEntities().filter(ent => { + allTargets = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager).GetNonGaiaEntities().filter(ent => + { const cmpIdentity = Engine.QueryInterface(ent, IID_Identity); return cmpIdentity && MatchesClassList(cmpIdentity.GetClassesList(), targetClasses); }); - const getDistance = target => { + const getDistance = target => + { const targetPos = TriggerHelper.GetEntityPosition2D(target); return targetPos ? attackerPos.distanceToSquared(targetPos) : Infinity; }; diff --git a/binaries/data/mods/public/maps/random/rivers.js b/binaries/data/mods/public/maps/random/rivers.js index f362738385..357e1fa347 100644 --- a/binaries/data/mods/public/maps/random/rivers.js +++ b/binaries/data/mods/public/maps/random/rivers.js @@ -143,7 +143,8 @@ export function* generateMap(mapSettings) "minHeight": heightSeaGround, "meanderShort": 10, "meanderLong": 0, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { clWater.add(position); diff --git a/binaries/data/mods/public/maps/random/rmbiome/randombiome.js b/binaries/data/mods/public/maps/random/rmbiome/randombiome.js index 0f43f802eb..39de548f15 100644 --- a/binaries/data/mods/public/maps/random/rmbiome/randombiome.js +++ b/binaries/data/mods/public/maps/random/rmbiome/randombiome.js @@ -46,7 +46,8 @@ function loadBiomeFile(file) const biome = Engine.ReadJSONFile(path); - const copyProperties = (from, to) => { + const copyProperties = (from, to) => + { for (const prop in from) { if (from[prop] !== null && typeof from[prop] === "object" && !Array.isArray(from[prop])) diff --git a/binaries/data/mods/public/maps/random/rmgen-common/player.js b/binaries/data/mods/public/maps/random/rmgen-common/player.js index 931bf711d8..4638c44804 100644 --- a/binaries/data/mods/public/maps/random/rmgen-common/player.js +++ b/binaries/data/mods/public/maps/random/rmgen-common/player.js @@ -784,7 +784,8 @@ function placeStronghold(teamsArray, distance, groupedDistance, startAngle) const playerIDs = []; const playerPosition = []; const teamPositions = []; - const strongholdRadius = teamsArray.map(team => { + const strongholdRadius = teamsArray.map(team => + { // If we have a solo player, place them on the center of the team's location if (team.length == 1) return 0; @@ -795,11 +796,13 @@ function placeStronghold(teamsArray, distance, groupedDistance, startAngle) const distanceBetweenStrongholds = (distance * 2 * Math.PI - 2 * strongholdRadius.reduce((a, b) => a + b)) / strongholdRadius.length; - const relativeTeamAngles = strongholdRadius.map((r1, i) => { + const relativeTeamAngles = strongholdRadius.map((r1, i) => + { return (distanceBetweenStrongholds + strongholdRadius.at(i - 1) + r1) / distance; }); - const teamAngles = relativeTeamAngles.reduce((acc, angle, i) => { + const teamAngles = relativeTeamAngles.reduce((acc, angle, i) => + { acc.push((i === 0 ? startAngle : acc.at(-1)) + angle); return acc; }, []); @@ -896,7 +899,8 @@ function groupPlayersByArea(playerIDs, locations) // Of all permutations of starting locations, find the one where // the sum of the distances between allies is minimal, weighted by teamsize. - heapsPermute(shuffleArray(locations).slice(0, playerIDs.length), v => v.clone(), permutation => { + heapsPermute(shuffleArray(locations).slice(0, playerIDs.length), v => v.clone(), permutation => + { let dist = 0; let teamDist = 0; let teamSize = 0; diff --git a/binaries/data/mods/public/maps/random/rmgen/TileClass.js b/binaries/data/mods/public/maps/random/rmgen/TileClass.js index 06f7db7cd3..5cce919169 100644 --- a/binaries/data/mods/public/maps/random/rmgen/TileClass.js +++ b/binaries/data/mods/public/maps/random/rmgen/TileClass.js @@ -1,7 +1,8 @@ /** * Class that can be tagged to any tile. Can be used to constrain placers and entity placement to given areas. */ -class TileClass { +class TileClass +{ constructor(size) { diff --git a/binaries/data/mods/public/maps/random/rmgen/library.js b/binaries/data/mods/public/maps/random/rmgen/library.js index bffd5b0a9e..70523c9730 100644 --- a/binaries/data/mods/public/maps/random/rmgen/library.js +++ b/binaries/data/mods/public/maps/random/rmgen/library.js @@ -146,7 +146,8 @@ function createObjectGroupsByAreasDeprecated(group, player, constraints, amount, */ function createAreas(centeredPlacer, painter, constraints, amount, retryFactor = 10) { - const placeFunc = function() { + const placeFunc = function() + { centeredPlacer.setCenterPosition(g_Map.randomCoordinate(false)); return createArea(centeredPlacer, painter, constraints); }; @@ -167,7 +168,8 @@ function createAreasInAreas(centeredPlacer, painter, constraints, amount, retryF return []; } - const placeFunc = function() { + const placeFunc = function() + { centeredPlacer.setCenterPosition(pickRandom(pickRandom(areas).getPoints())); return createArea(centeredPlacer, painter, constraints); }; @@ -181,7 +183,8 @@ function createAreasInAreas(centeredPlacer, painter, constraints, amount, retryF */ function createObjectGroups(group, player, constraints, amount, retryFactor = 10, behaveDeprecated = false) { - const placeFunc = function() { + const placeFunc = function() + { group.setCenterPosition(g_Map.randomCoordinate(true)); return createObjectGroup(group, player, constraints); }; @@ -202,7 +205,8 @@ function createObjectGroupsByAreas(group, player, constraints, amount, retryFact return []; } - const placeFunc = function() { + const placeFunc = function() + { group.setCenterPosition(pickRandom(pickRandom(areas).getPoints())); return createObjectGroup(group, player, constraints); }; diff --git a/binaries/data/mods/public/maps/random/rmgen/painter/CityPainter.js b/binaries/data/mods/public/maps/random/rmgen/painter/CityPainter.js index b523fd1850..56da017b0c 100644 --- a/binaries/data/mods/public/maps/random/rmgen/painter/CityPainter.js +++ b/binaries/data/mods/public/maps/random/rmgen/painter/CityPainter.js @@ -5,7 +5,8 @@ function CityPainter(templates, angle, playerID) { this.angle = angle; this.playerID = playerID; - this.templates = templates.map(template => { + this.templates = templates.map(template => + { const obstructionSize = getObstructionSize(template.templateName, template.margin || 0); return { diff --git a/binaries/data/mods/public/maps/random/rmgen/painter/LayeredPainter.js b/binaries/data/mods/public/maps/random/rmgen/painter/LayeredPainter.js index 2812aac909..3a9a415fa6 100644 --- a/binaries/data/mods/public/maps/random/rmgen/painter/LayeredPainter.js +++ b/binaries/data/mods/public/maps/random/rmgen/painter/LayeredPainter.js @@ -23,7 +23,8 @@ LayeredPainter.prototype.paint = function(area) "brushSize": 1, "gridSize": g_Map.getSize(), "withinArea": (bounds, position) => bounds.contains(position), - "paintTile": (point, distance) => { + "paintTile": (point, distance) => + { let width = 0; let i = 0; diff --git a/binaries/data/mods/public/maps/random/rmgen/painter/SmoothElevationPainter.js b/binaries/data/mods/public/maps/random/rmgen/painter/SmoothElevationPainter.js index 5bee53d316..7dcf508c81 100644 --- a/binaries/data/mods/public/maps/random/rmgen/painter/SmoothElevationPainter.js +++ b/binaries/data/mods/public/maps/random/rmgen/painter/SmoothElevationPainter.js @@ -71,7 +71,8 @@ SmoothElevationPainter.prototype.paint = function(area) "brushSize": brushSize, "gridSize": heightmapSize, "withinArea": withinArea, - "paintTile": (point, distance) => { + "paintTile": (point, distance) => + { let a = 1; if (distance <= this.blendRadius) a = (distance - 1) / this.blendRadius; diff --git a/binaries/data/mods/public/maps/random/tests/test_Constraint.js b/binaries/data/mods/public/maps/random/tests/test_Constraint.js index 3e2cdde659..987b2504b2 100644 --- a/binaries/data/mods/public/maps/random/tests/test_Constraint.js +++ b/binaries/data/mods/public/maps/random/tests/test_Constraint.js @@ -1,4 +1,5 @@ -Engine.GetTemplate = (path) => { +Engine.GetTemplate = (path) => +{ return { "Identity": { "GenericName": null, diff --git a/binaries/data/mods/public/maps/random/tests/test_DiskPlacer.js b/binaries/data/mods/public/maps/random/tests/test_DiskPlacer.js index 7ab065c041..4f832c851b 100644 --- a/binaries/data/mods/public/maps/random/tests/test_DiskPlacer.js +++ b/binaries/data/mods/public/maps/random/tests/test_DiskPlacer.js @@ -1,4 +1,5 @@ -Engine.GetTemplate = (path) => { +Engine.GetTemplate = (path) => +{ return { "Identity": { "GenericName": null, diff --git a/binaries/data/mods/public/maps/random/tests/test_LayeredPainter.js b/binaries/data/mods/public/maps/random/tests/test_LayeredPainter.js index b40aad995c..05a0d76de7 100644 --- a/binaries/data/mods/public/maps/random/tests/test_LayeredPainter.js +++ b/binaries/data/mods/public/maps/random/tests/test_LayeredPainter.js @@ -1,4 +1,5 @@ -Engine.GetTemplate = (path) => { +Engine.GetTemplate = (path) => +{ return { "Identity": { "GenericName": null, diff --git a/binaries/data/mods/public/maps/random/tests/test_RecoverableError.js b/binaries/data/mods/public/maps/random/tests/test_RecoverableError.js index 624f122760..c55c33c7a4 100644 --- a/binaries/data/mods/public/maps/random/tests/test_RecoverableError.js +++ b/binaries/data/mods/public/maps/random/tests/test_RecoverableError.js @@ -5,7 +5,7 @@ export function* generateMap() yield; TS_FAIL("The yield statement didn't throw."); } - catch (error) + catch(error) { TS_ASSERT(error instanceof Error); TS_ASSERT_EQUALS(error.message, "Failed to convert the yielded value to an integer."); diff --git a/binaries/data/mods/public/maps/random/tests/test_RectPlacer.js b/binaries/data/mods/public/maps/random/tests/test_RectPlacer.js index 00000a3bdc..933bb793ef 100644 --- a/binaries/data/mods/public/maps/random/tests/test_RectPlacer.js +++ b/binaries/data/mods/public/maps/random/tests/test_RectPlacer.js @@ -1,4 +1,5 @@ -Engine.GetTemplate = (path) => { +Engine.GetTemplate = (path) => +{ return { "Identity": { "GenericName": null, diff --git a/binaries/data/mods/public/maps/random/tests/test_SmoothingPainter.js b/binaries/data/mods/public/maps/random/tests/test_SmoothingPainter.js index 25de852fc5..ebc55a0fb7 100644 --- a/binaries/data/mods/public/maps/random/tests/test_SmoothingPainter.js +++ b/binaries/data/mods/public/maps/random/tests/test_SmoothingPainter.js @@ -1,4 +1,5 @@ -Engine.GetTemplate = (path) => { +Engine.GetTemplate = (path) => +{ return { "Identity": { "GenericName": null, diff --git a/binaries/data/mods/public/maps/random/tests/test_TileClass.js b/binaries/data/mods/public/maps/random/tests/test_TileClass.js index 07c52243bc..7238ee12cf 100644 --- a/binaries/data/mods/public/maps/random/tests/test_TileClass.js +++ b/binaries/data/mods/public/maps/random/tests/test_TileClass.js @@ -1,4 +1,5 @@ -Engine.GetTemplate = (path) => { +Engine.GetTemplate = (path) => +{ return { "Identity": { "GenericName": null, diff --git a/binaries/data/mods/public/maps/random/the_nile.js b/binaries/data/mods/public/maps/random/the_nile.js index 7da309ee63..0cda1fcac2 100644 --- a/binaries/data/mods/public/maps/random/the_nile.js +++ b/binaries/data/mods/public/maps/random/the_nile.js @@ -151,7 +151,8 @@ export function* generateMap() "heightLand": heightShore, "meanderShort": 12, "meanderLong": 50, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { clWater.add(position); createTerrain(tShore).place(position); @@ -167,7 +168,8 @@ export function* generateMap() } ++plantID; }, - "landFunc": (position, shoreDist1, shoreDist2) => { + "landFunc": (position, shoreDist1, shoreDist2) => + { for (const riv of riverTextures) if (riv.left < +shoreDist1 && +shoreDist1 < riv.right || diff --git a/binaries/data/mods/public/maps/random/unknown.js b/binaries/data/mods/public/maps/random/unknown.js index 07361edfb7..88c3ded1f4 100644 --- a/binaries/data/mods/public/maps/random/unknown.js +++ b/binaries/data/mods/public/maps/random/unknown.js @@ -121,11 +121,13 @@ export function* generateMap(mapSettings) "heightLand": heightLand, "meanderShort": 20, "meanderLong": 0, - "waterFunc": (position, height, riverFraction) => { + "waterFunc": (position, height, riverFraction) => + { if (height < 0) clWater.add(position); }, - "landFunc": (position, shoreDist1, shoreDist2) => { + "landFunc": (position, shoreDist1, shoreDist2) => + { g_Map.setHeight(position, 3.1); clLand.add(position); } @@ -237,7 +239,8 @@ export function* generateMap(mapSettings) const unknownMapFunctions = { // Chain of islands or many disconnected islands. - "Archipelago": () => { + "Archipelago": () => + { g_StartingWalls = "towers"; g_StartingTreasures = true; @@ -317,7 +320,8 @@ export function* generateMap(mapSettings) }, // Disk shaped mainland with water on the edge. - "Continent": () => { + "Continent": () => + { const waterHeight = -5; if (!mapSettings.Nomad) @@ -386,7 +390,8 @@ export function* generateMap(mapSettings) // Creates a circular lake in the middle and possibly a river // between each player ("pizza slices"). - "RiversAndLake": () => { + "RiversAndLake": () => + { const waterHeight = -4; createArea( new MapBoundsPlacer(), @@ -467,7 +472,8 @@ export function* generateMap(mapSettings) // Align players on a land strip with seas bordering on one or both // sides that can hold islands. - "EdgeSeas": () => { + "EdgeSeas": () => + { const waterHeight = -4; createArea( @@ -508,7 +514,8 @@ export function* generateMap(mapSettings) }, // Land shaped like a concrescent moon around a central lake. - "Gulf": () => { + "Gulf": () => + { const waterHeight = -3; createArea( @@ -550,7 +557,8 @@ export function* generateMap(mapSettings) }, // Mainland style with some small random lakes. - "Lakes": () => { + "Lakes": () => + { const waterHeight = -5; createArea( @@ -579,7 +587,8 @@ export function* generateMap(mapSettings) // A large hill leaving players only a small passage to each of the // the two neighboring players. - "Passes": () => { + "Passes": () => + { const heightMountain = 24; const waterHeight = -4; @@ -626,7 +635,8 @@ export function* generateMap(mapSettings) g_Map.log("Creating passages between neighboring players"); if (numPlayers > 1) { - const getEndpoints = (() => { + const getEndpoints = (() => + { if (numPlayers !== 2) return i => [i, (i + 1) % numPlayers] .map(index => playerPosition[index]); @@ -677,7 +687,8 @@ export function* generateMap(mapSettings) // Land enclosed by a hill that leaves small areas for civic centers // and large central place. - "Lowlands": () => { + "Lowlands": () => + { const heightMountain = 30; g_Map.log("Creating mountain that is going to separate players"); @@ -738,7 +749,8 @@ export function* generateMap(mapSettings) }, // No water, no hills. - "Mainland": () => { + "Mainland": () => + { createArea( new MapBoundsPlacer(), new ElevationPainter(3)); diff --git a/binaries/data/mods/public/maps/scenarios/pickup_test_map_triggers.js b/binaries/data/mods/public/maps/scenarios/pickup_test_map_triggers.js index 551d6fadaf..9d111841dd 100644 --- a/binaries/data/mods/public/maps/scenarios/pickup_test_map_triggers.js +++ b/binaries/data/mods/public/maps/scenarios/pickup_test_map_triggers.js @@ -168,7 +168,8 @@ Trigger.prototype.UnitsIntoShipThenAnotherCloseBy = function() // Don't do this at home const holder = Engine.QueryInterface(ship, IID_GarrisonHolder); const og = Object.getPrototypeOf(holder).PerformGarrison; - holder.PerformGarrison = (...args) => { + holder.PerformGarrison = (...args) => + { const res = og.apply(holder, args); delete holder.PerformGarrison; pos = TriggerHelper.GetEntityPosition2D(point_coast_2); diff --git a/binaries/data/mods/public/maps/scenarios/unit_chasing_test_triggers.js b/binaries/data/mods/public/maps/scenarios/unit_chasing_test_triggers.js index c72c5a587a..664a4d027b 100644 --- a/binaries/data/mods/public/maps/scenarios/unit_chasing_test_triggers.js +++ b/binaries/data/mods/public/maps/scenarios/unit_chasing_test_triggers.js @@ -64,7 +64,8 @@ var gy; var straight_line = function(attacker_first, attacker, target, walk = true) { - return () => { + return () => + { let chaser; let chasee; if (attacker_first) @@ -86,7 +87,8 @@ var straight_line = function(attacker_first, attacker, target, walk = true) var straight_line_garrison = function(garrison_first, attacker, target) { - return () => { + return () => + { let chaser; let chasee; if (garrison_first) diff --git a/binaries/data/mods/public/maps/scenarios/unit_dancing_test_triggers.js b/binaries/data/mods/public/maps/scenarios/unit_dancing_test_triggers.js index ef9876dd57..30555755a9 100644 --- a/binaries/data/mods/public/maps/scenarios/unit_dancing_test_triggers.js +++ b/binaries/data/mods/public/maps/scenarios/unit_dancing_test_triggers.js @@ -87,7 +87,8 @@ var experiments = {}; var manual_dance = function(attacker, target, dance_distance, att_distance = 50, n_attackers = 1) { - return () => { + return () => + { const dancer = QuickSpawn(gx, gy, target); for (let i = 0; i < 100; ++i) WalkTo(gx, gy + dance_distance * (i % 2), true, dancer); @@ -102,7 +103,8 @@ var manual_dance = function(attacker, target, dance_distance, att_distance = 50, var manual_square_dance = function(attacker, target, dance_distance, att_distance = 50, n_attackers = 1) { - return () => { + return () => + { const dancer = QuickSpawn(gx, gy, target); for (let i = 0; i < 25; ++i) { @@ -122,7 +124,8 @@ var manual_square_dance = function(attacker, target, dance_distance, att_distanc var manual_zigzag_dance = function(attacker, target, dance_distance, att_distance = 50, n_attackers = 1) { - return () => { + return () => + { const dancer = QuickSpawn(gx, gy, target); for (let i = 0; i < 12; ++i) { @@ -150,7 +153,8 @@ var manual_zigzag_dance = function(attacker, target, dance_distance, att_distanc var patrol_dance = function(attacker, target, dance_distance, att_distance = 50, n_attackers = 1) { - return () => { + return () => + { const dancer = QuickSpawn(gx, gy, target); Patrol(gx, gy + dance_distance, true, dancer); @@ -164,7 +168,8 @@ var patrol_dance = function(attacker, target, dance_distance, att_distance = 50, var manual_formation_dance = function(attacker, target, dance_distance, att_distance = 50, n_attackers = 1) { - return () => { + return () => + { const dancers = []; for (let x = 0; x < 4; x++) for (let z = 0; z < 4; z++) @@ -186,7 +191,8 @@ var manual_formation_dance = function(attacker, target, dance_distance, att_dist */ var avoidance = function(attacker, target, att_distance = 10) { - return () => { + return () => + { const dancer = QuickSpawn(200, 300, target); for (let i = 0; i < 5; ++i) { @@ -317,7 +323,8 @@ Trigger.prototype.SetupUnits = function() for (const key in experiments) { const [dancers, attackers] = experiments[key].spawn(); - const ReportResults = (killed) => { + const ReportResults = (killed) => + { warn(`Exp ${key} finished in ${Engine.QueryInterface(SYSTEM_ENTITY, IID_Timer).GetTime() - start}, ` + `target was ${killed ? "killed" : "not killed (failure)"}`); ProcessCommand(1, { @@ -335,7 +342,8 @@ Trigger.prototype.SetupUnits = function() const uai = Engine.QueryInterface(dancers[0], IID_UnitAI); const odes = uai.OnDestroy; uai.OnDestroy = () => ReportResults(true) && odes(); - uai.FindNewTargets = () => { + uai.FindNewTargets = () => + { ReportResults(false); uai.OnDestroy = odes; }; diff --git a/binaries/data/mods/public/maps/scenarios/unit_motion_integration_test.js b/binaries/data/mods/public/maps/scenarios/unit_motion_integration_test.js index 22375c8e29..cda4c87759 100644 --- a/binaries/data/mods/public/maps/scenarios/unit_motion_integration_test.js +++ b/binaries/data/mods/public/maps/scenarios/unit_motion_integration_test.js @@ -63,13 +63,15 @@ var gy = 100; var experiments = {}; experiments.single_unit = { - "spawn": () => { + "spawn": () => + { WalkTo(gx, gy + 100, QuickSpawn(gx, gy, UNIT_TEMPLATE)); } }; experiments.two_followers = { - "spawn": () => { + "spawn": () => + { WalkTo(gx, gy + 100, QuickSpawn(gx, gy, UNIT_TEMPLATE)); const follow = WalkTo(gx, gy + 102, QuickSpawn(gx, gy + 2, UNIT_TEMPLATE)); Guard(follow, QuickSpawn(gx, gy - 2, UNIT_TEMPLATE)); @@ -77,14 +79,16 @@ experiments.two_followers = { }; experiments.follow_faster = { - "spawn": () => { + "spawn": () => + { WalkTo(gx, gy + 100, QuickSpawn(gx, gy, FAST_UNIT_TEMPLATE)); WalkTo(gx, gy + 104, QuickSpawn(gx, gy + 4, UNIT_TEMPLATE)); } }; experiments.group = { - "spawn": () => { + "spawn": () => + { for (let i = -3; i <= 3; ++i) for (let j = -3; j <= 3; ++j) WalkTo(gx, gy + 100, QuickSpawn(gx + i * 2, gy + j * 2, UNIT_TEMPLATE)); @@ -92,14 +96,16 @@ experiments.group = { }; experiments.single_unit_building = { - "spawn": () => { + "spawn": () => + { QuickSpawn(gx, gy + 40, SMALL_STRUCTURE_TEMPLATE); WalkTo(gx, gy + 100, QuickSpawn(gx, gy, UNIT_TEMPLATE)); } }; experiments.single_unit_pass_nopass = { - "spawn": () => { + "spawn": () => + { WalkTo(gx, gy + 100, QuickSpawn(gx, gy, UNIT_TEMPLATE)); QuickSpawn(gx - 10, gy + 40, SMALL_STRUCTURE_TEMPLATE); QuickSpawn(gx + 10, gy + 40, SMALL_STRUCTURE_TEMPLATE); @@ -111,7 +117,8 @@ experiments.single_unit_pass_nopass = { experiments.units_dense_forest = { - "spawn": () => { + "spawn": () => + { WalkTo(gx, gy + 100, QuickSpawn(gx, gy, UNIT_TEMPLATE)); WalkTo(gx, gy + 100, QuickSpawn(gx - 2, gy, UNIT_TEMPLATE)); WalkTo(gx, gy + 100, QuickSpawn(gx + 2, gy + 2, UNIT_TEMPLATE)); @@ -129,7 +136,8 @@ experiments.units_dense_forest = { }; experiments.units_sparse_forest = { - "spawn": () => { + "spawn": () => + { gx += 10; for (let i = -4; i <= 4; i += 2) for (let j = -4; j <= 4; j += 2) @@ -146,7 +154,8 @@ experiments.units_sparse_forest = { }; experiments.units_running_into_eachother = { - "spawn": () => { + "spawn": () => + { for (let i = -4; i <= 4; i += 2) for (let j = -4; j <= 4; j += 2) WalkTo(gx, gy + 100, QuickSpawn(gx + i, gy + j, UNIT_TEMPLATE)); @@ -157,7 +166,8 @@ experiments.units_running_into_eachother = { }; experiments.enclosed = { - "spawn": () => { + "spawn": () => + { QuickSpawn(gx, gy - 8, "structures/palisades_long"); QuickSpawn(gx, gy + 8, "structures/palisades_long"); Rotate(Math.PI / 2, QuickSpawn(gx - 8, gy, "structures/palisades_long")); @@ -175,13 +185,15 @@ experiments.enclosed = { WalkTo(gx, gy + 100, QuickSpawn(gx, gy + 28, UNIT_TEMPLATE)); }, - "timeout": () => { + "timeout": () => + { Engine.DestroyEntity(experiments.enclosed.remove); } }; experiments.line_of_rams = { - "spawn": () => { + "spawn": () => + { for (let i = -20; i <= 20; i+=4) WalkTo(gx + i, gy + 50, QuickSpawn(gx + i, gy, LARGE_UNIT_TEMPLATE)); WalkTo(gx, gy + 100, QuickSpawn(gx, gy - 10, UNIT_TEMPLATE)); @@ -190,7 +202,8 @@ experiments.line_of_rams = { experiments.units_sparse_forest_of_units = { - "spawn": () => { + "spawn": () => + { for (let i = -16; i <= 16; i += 8) for (let j = -16; j <= 16; j += 8) Do("stance", { "name": "standground" }, QuickSpawn(gx + i, gy + 50 + j, UNIT_TEMPLATE)); @@ -200,7 +213,8 @@ experiments.units_sparse_forest_of_units = { }; experiments.units_dense_forest_of_units = { - "spawn": () => { + "spawn": () => + { for (let i = -16; i <= 16; i += 4) for (let j = -16; j <= 16; j += 4) Do("stance", { "name": "standground" }, QuickSpawn(gx + i, gy + 50 + j, UNIT_TEMPLATE)); @@ -210,7 +224,8 @@ experiments.units_dense_forest_of_units = { }; experiments.units_superdense_forest_of_units = { - "spawn": () => { + "spawn": () => + { for (let i = -6; i <= 6; i += 2) for (let j = -6; j <= 6; j += 2) Do("stance", { "name": "standground" }, QuickSpawn(gx + i, gy + 50 + j, UNIT_TEMPLATE)); @@ -220,7 +235,8 @@ experiments.units_superdense_forest_of_units = { }; experiments.u_shape_tight_exit = { - "spawn": () => { + "spawn": () => + { Rotate(Math.PI / 2, QuickSpawn(gx + 8, gy, "structures/palisades_long")); Rotate(Math.PI / 2, QuickSpawn(gx + 8, gy + 12, "structures/palisades_long")); QuickSpawn(gx, gy + 16, "structures/palisades_long"); @@ -246,7 +262,8 @@ experiments.u_shape_tight_exit = { }; experiments.cluttered_around_tree = { - "spawn": () => { + "spawn": () => + { const tree = QuickSpawn(gx, gy + 50, "gaia/tree/acacia"); for (let i = -3; i <= 3; i += 1) @@ -259,7 +276,8 @@ experiments.cluttered_around_tree = { }; experiments.formation_move = { - "spawn": () => { + "spawn": () => + { const ents = []; for (let i = -3; i <= 3; ++i) for (let j = -3; j <= 3; ++j) @@ -270,7 +288,8 @@ experiments.formation_move = { }; experiments.formation_attack = { - "spawn": () => { + "spawn": () => + { const ents = []; for (let i = -3; i <= 3; ++i) for (let j = -3; j <= 3; ++j) @@ -281,7 +300,8 @@ experiments.formation_attack = { }; experiments.multiple_resources = { - "spawn": () => { + "spawn": () => + { QuickSpawn(gx, gy + 80, "structures/athen/civil_centre"); const chicken = QuickSpawn(gx, gy + 50, "gaia/fauna_chicken"); @@ -299,7 +319,8 @@ experiments.multiple_resources = { * However, the vertex pathfinder should be able to find a way out, then a way in. */ experiments.locked_within = { - "spawn": () => { + "spawn": () => + { QuickSpawn(gx + 10, gy + 7, SMALL_STRUCTURE_TEMPLATE); QuickSpawn(gx - 10, gy + 7, SMALL_STRUCTURE_TEMPLATE); QuickSpawn(gx, gy, SMALL_STRUCTURE_TEMPLATE); @@ -327,7 +348,8 @@ experiments.locked_within = { * so the short-pathfinder has to backtrack. */ experiments.need_to_backtrack = { - "spawn": () => { + "spawn": () => + { gx += 50; QuickSpawn(gx + 10, gy + 60, SMALL_STRUCTURE_TEMPLATE); QuickSpawn(gx - 10, gy + 60, SMALL_STRUCTURE_TEMPLATE); @@ -351,7 +373,8 @@ experiments.need_to_backtrack = { * (note that it's not an entirely perfect fix, but it should just be a few units, not half) */ experiments.small_exit_of_hill = { - "spawn": () => { + "spawn": () => + { const x = 350; const y = 615; for (let i = -5; i <= 5; i += 1) diff --git a/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js b/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js index ccf034cb6c..d54259b71c 100644 --- a/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js +++ b/binaries/data/mods/public/maps/scenarios/unit_pushing_test.js @@ -81,7 +81,8 @@ var Do = function(name, data, ent, owner = 1) var experiments = {}; experiments.units_sparse_forest_of_units = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = -16; i <= 16; i += 8) for (let j = -16; j <= 16; j += 8) QuickSpawn(gx + i, gy + 50 + j, REG_UNIT_TEMPLATE); @@ -91,7 +92,8 @@ experiments.units_sparse_forest_of_units = { }; experiments.units_dense_forest_of_units = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = -16; i <= 16; i += 4) for (let j = -16; j <= 16; j += 4) QuickSpawn(gx + i, gy + 50 + j, REG_UNIT_TEMPLATE); @@ -101,7 +103,8 @@ experiments.units_dense_forest_of_units = { }; experiments.units_superdense_forest_of_units = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = -6; i <= 6; i += 2) for (let j = -6; j <= 6; j += 2) QuickSpawn(gx + i, gy + 50 + j, REG_UNIT_TEMPLATE); @@ -111,7 +114,8 @@ experiments.units_superdense_forest_of_units = { }; experiments.units_superdense_forest_of_fast_units = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = -12; i <= 12; i += 2) for (let j = -12; j <= 12; j += 2) QuickSpawn(gx + i, gy + 50 + j, FAST_UNIT_TEMPLATE); @@ -121,7 +125,8 @@ experiments.units_superdense_forest_of_fast_units = { }; experiments.building = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { const target = QuickSpawn(gx + 20, gy + 20, "foundation|structures/athen/storehouse"); for (let i = 0; i < 8; ++i) Do("repair", { "target": target }, QuickSpawn(gx + i, gy, REG_UNIT_TEMPLATE)); @@ -132,7 +137,8 @@ experiments.building = { }; experiments.collecting_tree = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { const target = QuickSpawn(gx + 10, gy + 10, "gaia/tree/acacia"); const storehouse = QuickSpawn(gx - 10, gy - 10, "structures/athen/storehouse"); for (let i = 0; i < 8; ++i) @@ -157,7 +163,8 @@ experiments.collecting_tree = { }; experiments.multicrossing = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = 0; i < 20; i += 2) for (let j = 0; j < 20; j += 2) WalkTo(gx+10, gy+70, false, QuickSpawn(gx + i, gy + j, REG_UNIT_TEMPLATE)); @@ -169,7 +176,8 @@ experiments.multicrossing = { // Same as above but not as aligned. experiments.multicrossing_spaced = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = 0; i < 20; i += 2) for (let j = 0; j < 20; j += 2) WalkTo(gx+10, gy+70, false, QuickSpawn(gx + i, gy + j, REG_UNIT_TEMPLATE)); @@ -181,7 +189,8 @@ experiments.multicrossing_spaced = { // Same as above but not as aligned. experiments.multicrossing_spaced_2 = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = 0; i < 20; i += 2) for (let j = 0; j < 20; j += 2) WalkTo(gx+10, gy+70, false, QuickSpawn(gx + i, gy + j, REG_UNIT_TEMPLATE)); @@ -192,7 +201,8 @@ experiments.multicrossing_spaced_2 = { }; experiments.crossing_perpendicular = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = 0; i < 20; i += 4) for (let j = 0; j < 20; j += 4) WalkTo(gx+10, gy+70, false, QuickSpawn(gx + i, gy + j, REG_UNIT_TEMPLATE)); @@ -203,7 +213,8 @@ experiments.crossing_perpendicular = { }; experiments.elephant_formation = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { const ents = []; for (let i = 0; i < 20; i += 4) for (let j = 0; j < 20; j += 4) @@ -218,7 +229,8 @@ experiments.sep1 = { }; experiments.battle = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = 0; i < 4; ++i) for (let j = 0; j < 8; ++j) { @@ -234,7 +246,8 @@ experiments.sep2 = { experiments.overlapping = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = 0; i < 20; ++i) QuickSpawn(gx, gy, REG_UNIT_TEMPLATE); for (let i = 0; i < 20; ++i) @@ -243,7 +256,8 @@ experiments.overlapping = { }; experiments.large_against_units = { - "spawn": (gx, gy) => { + "spawn": (gx, gy) => + { for (let i = -18; i < 20; i += 2) for (let j = 0; j < 40; j += 3) WalkTo(gx, gy - 50, false, QuickSpawn(gx + i, gy + 10 + j, REG_UNIT_TEMPLATE)); @@ -256,7 +270,8 @@ var perf_experiments = {}; // Perf check: put units everywhere, not moving. perf_experiments.Idle = { - "spawn": () => { + "spawn": () => + { const spacing = 12; for (let x = 0; x < 20*4*4 - 20; x += spacing) for (let z = 0; z < 20*4*4 - 20; z += spacing) @@ -266,7 +281,8 @@ perf_experiments.Idle = { // Perf check: put units everywhere, moving. perf_experiments.MovingAround = { - "spawn": () => { + "spawn": () => + { const spacing = 24; for (let x = 0; x < 20*16*4 - 20; x += spacing) for (let z = 0; z < 20*16*4 - 20; z += spacing) @@ -284,7 +300,8 @@ perf_experiments.MovingAround = { }; // Perf check: fewer units moving more. perf_experiments.LighterMovingAround = { - "spawn": () => { + "spawn": () => + { const spacing = 48; for (let x = 0; x < 20*16*4 - 20; x += spacing) for (let z = 0; z < 20*16*4 - 20; z += spacing) @@ -303,7 +320,8 @@ perf_experiments.LighterMovingAround = { // Perf check: rows of units crossing each other. perf_experiments.BunchaCollisions = { - "spawn": () => { + "spawn": () => + { const spacing = 64; for (let x = 0; x < 20*16*4 - 20; x += spacing) for (let z = 0; z < 20*16*4 - 20; z += spacing) @@ -324,7 +342,8 @@ perf_experiments.BunchaCollisions = { // Massive moshpit of pushing. perf_experiments.LotsaLocalCollisions = { - "spawn": () => { + "spawn": () => + { const spacing = 3; for (let x = 100; x < 200; x += spacing) for (let z = 100; z < 200; z += spacing) @@ -337,7 +356,8 @@ perf_experiments.LotsaLocalCollisions = { }; -var woodcutting = (gx, gy) => { +var woodcutting = (gx, gy) => +{ const dropsite = QuickSpawn(gx + 50, gy, "structures/athen/storehouse"); const cmpModifiersManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_ModifiersManager); cmpModifiersManager.AddModifiers("root", { @@ -356,7 +376,8 @@ var woodcutting = (gx, gy) => { }; perf_experiments.WoodCutting = { - "spawn": () => { + "spawn": () => + { for (let i = 0; i < 8; i++) for (let j = 0; j < 8; j++) { diff --git a/binaries/data/mods/public/maps/scripts/Regicide.js b/binaries/data/mods/public/maps/scripts/Regicide.js index c7996e29d7..6ecf0d4406 100644 --- a/binaries/data/mods/public/maps/scripts/Regicide.js +++ b/binaries/data/mods/public/maps/scripts/Regicide.js @@ -34,7 +34,8 @@ Trigger.prototype.InitRegicideGame = function(msg) // Sort available spawn points by preference const spawnPreferences = ["CivilCentre", "Structure", "Ship"]; - const getSpawnPreference = entity => { + const getSpawnPreference = entity => + { const cmpIdentity = Engine.QueryInterface(entity, IID_Identity); if (!cmpIdentity) diff --git a/binaries/data/mods/public/maps/scripts/TriggerHelper.js b/binaries/data/mods/public/maps/scripts/TriggerHelper.js index b5516d7396..2e01c129e0 100644 --- a/binaries/data/mods/public/maps/scripts/TriggerHelper.js +++ b/binaries/data/mods/public/maps/scripts/TriggerHelper.js @@ -512,7 +512,8 @@ TriggerHelper.BalancedTemplateComposition = function(templateBalancing, totalCou // Helper function to add randomized templates to the result let remainder = totalCount; const results = {}; - const addTemplates = (templateNames, count) => { + const addTemplates = (templateNames, count) => + { const templateCounts = TriggerHelper.RandomTemplateComposition(templateNames, count); for (const templateName in templateCounts) { diff --git a/binaries/data/mods/public/maps/tutorials/introductory_tutorial.js b/binaries/data/mods/public/maps/tutorials/introductory_tutorial.js index 91b794018e..fb6f282de3 100644 --- a/binaries/data/mods/public/maps/tutorials/introductory_tutorial.js +++ b/binaries/data/mods/public/maps/tutorials/introductory_tutorial.js @@ -390,18 +390,21 @@ Trigger.prototype.LaunchAttack = function() const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); const entities = cmpRangeManager.GetEntitiesByPlayer(this.playerID); const target = - entities.find(e => { + entities.find(e => + { const cmpIdentity = Engine.QueryInterface(e, IID_Identity); return cmpIdentity && cmpIdentity.HasClass("Tower") && Engine.QueryInterface(e, IID_Position); }) || - entities.find(e => { + entities.find(e => + { const cmpIdentity = Engine.QueryInterface(e, IID_Identity); return cmpIdentity && cmpIdentity.HasClass("CivilCentre") && Engine.QueryInterface(e, IID_Position); }); const position = Engine.QueryInterface(target, IID_Position).GetPosition2D(); - this.attackers = cmpRangeManager.GetEntitiesByPlayer(this.enemyID).filter(e => { + this.attackers = cmpRangeManager.GetEntitiesByPlayer(this.enemyID).filter(e => + { const cmpIdentity = Engine.QueryInterface(e, IID_Identity); return Engine.QueryInterface(e, IID_UnitAI) && cmpIdentity && cmpIdentity.HasClass("CitizenSoldier"); }); diff --git a/binaries/data/mods/public/simulation/ai/common-api/entity.js b/binaries/data/mods/public/simulation/ai/common-api/entity.js index b86cf490e5..e3186ee272 100644 --- a/binaries/data/mods/public/simulation/ai/common-api/entity.js +++ b/binaries/data/mods/public/simulation/ai/common-api/entity.js @@ -48,41 +48,48 @@ export const Template = Class({ "civ": function() { return this.get("Identity/Civ"); }, - "matchLimit": function() { + "matchLimit": function() + { if (!this.get("TrainingRestrictions")) return undefined; return this.get("TrainingRestrictions/MatchLimit"); }, - "classes": function() { + "classes": function() + { const template = this.get("Identity"); if (!template) return undefined; return GetIdentityClasses(template); }, - "hasClass": function(name) { + "hasClass": function(name) + { if (!this._classes) this._classes = this.classes(); return this._classes && this._classes.indexOf(name) != -1; }, - "hasClasses": function(array) { + "hasClasses": function(array) + { if (!this._classes) this._classes = this.classes(); return this._classes && MatchesClassList(this._classes, array); }, - "requirements": function() { + "requirements": function() + { return this.get("Identity/Requirements"); }, - "available": function(gameState) { + "available": function(gameState) + { const requirements = this.requirements(); return !requirements || Sim.RequirementsHelper.AreRequirementsMet(requirements, PlayerID); }, - "cost": function(productionQueue) { + "cost": function(productionQueue) + { if (!this.get("Cost")) return {}; @@ -92,7 +99,8 @@ export const Template = Class({ return ret; }, - "costSum": function(productionQueue) { + "costSum": function(productionQueue) + { const cost = this.cost(productionQueue); if (!cost) return 0; @@ -102,7 +110,8 @@ export const Template = Class({ return ret; }, - "techCostMultiplier": function(type) { + "techCostMultiplier": function(type) + { return +(this.get("Researcher/TechCostMultiplier/"+type) || 1); }, @@ -111,7 +120,8 @@ export const Template = Class({ * max: radius of the outer circle surrounding this entity's obstruction shape * min: radius of the inner circle */ - "obstructionRadius": function() { + "obstructionRadius": function() + { if (!this.get("Obstruction")) return undefined; @@ -144,7 +154,8 @@ export const Template = Class({ /** * Returns the radius of a circle surrounding this entity's footprint. */ - "footprintRadius": function() { + "footprintRadius": function() + { if (!this.get("Footprint")) return undefined; @@ -172,14 +183,16 @@ export const Template = Class({ "isRepairable": function() { return this.get("Repairable") !== undefined; }, - "getPopulationBonus": function() { + "getPopulationBonus": function() + { if (!this.get("Population")) return 0; return +this.get("Population/Bonus"); }, - "resistanceStrengths": function() { + "resistanceStrengths": function() + { const resistanceTypes = this.get("Resistance"); if (!resistanceTypes || !resistanceTypes.Entity) return undefined; @@ -200,7 +213,8 @@ export const Template = Class({ return resistance; }, - "attackTypes": function() { + "attackTypes": function() + { const attack = this.get("Attack"); if (!attack) return undefined; @@ -211,7 +225,8 @@ export const Template = Class({ return ret; }, - "attackRange": function(type) { + "attackRange": function(type) + { if (!this.get("Attack/" + type)) return undefined; @@ -221,7 +236,8 @@ export const Template = Class({ }; }, - "attackStrengths": function(type) { + "attackStrengths": function(type) + { const attackDamageTypes = this.get("Attack/" + type + "/Damage"); if (!attackDamageTypes) return undefined; @@ -233,14 +249,16 @@ export const Template = Class({ return damage; }, - "captureStrength": function() { + "captureStrength": function() + { if (!this.get("Attack/Capture")) return undefined; return +this.get("Attack/Capture/Capture") || 0; }, - "attackTimes": function(type) { + "attackTimes": function(type) + { if (!this.get("Attack/" + type)) return undefined; @@ -252,7 +270,8 @@ export const Template = Class({ // returns the classes this templates counters: // Return type is [ [-neededClasses- , multiplier], … ]. - "getCounteredClasses": function() { + "getCounteredClasses": function() + { const attack = this.get("Attack"); if (!attack) return undefined; @@ -275,7 +294,8 @@ export const Template = Class({ // returns true if the entity counters the target entity. // TODO: refine using the multiplier - "counters": function(target) { + "counters": function(target) + { const attack = this.get("Attack"); if (!attack) return false; @@ -296,7 +316,8 @@ export const Template = Class({ }, // returns, if it exists, the multiplier from each attack against a given class - "getMultiplierAgainst": function(type, againstClass) { + "getMultiplierAgainst": function(type, againstClass) + { if (!this.get("Attack/" + type +"")) return undefined; @@ -316,21 +337,24 @@ export const Template = Class({ return 1; }, - "buildableEntities": function(civ) { + "buildableEntities": function(civ) + { const templates = this.get("Builder/Entities/_string"); if (!templates) return []; return templates.replace(/\{native\}/g, this.civ()).replace(/\{civ\}/g, civ).split(/\s+/); }, - "trainableEntities": function(civ) { + "trainableEntities": function(civ) + { const templates = this.get("Trainer/Entities/_string"); if (!templates) return undefined; return templates.replace(/\{native\}/g, this.civ()).replace(/\{civ\}/g, civ).split(/\s+/); }, - "researchableTechs": function(gameState, civ) { + "researchableTechs": function(gameState, civ) + { const templates = this.get("Researcher/Technologies/_string"); if (!templates) return undefined; @@ -347,14 +371,16 @@ export const Template = Class({ return techs; }, - "resourceSupplyType": function() { + "resourceSupplyType": function() + { if (!this.get("ResourceSupply")) return undefined; const [type, subtype] = this.get("ResourceSupply/Type").split('.'); return { "generic": type, "specific": subtype }; }, - "getResourceType": function() { + "getResourceType": function() + { if (!this.get("ResourceSupply")) return undefined; return this.get("ResourceSupply/Type").split('.')[0]; @@ -366,7 +392,8 @@ export const Template = Class({ "maxGatherers": function() { return +(this.get("ResourceSupply/MaxGatherers") || 0); }, - "resourceGatherRates": function() { + "resourceGatherRates": function() + { if (!this.get("ResourceGatherer")) return undefined; const ret = {}; @@ -376,7 +403,8 @@ export const Template = Class({ return ret; }, - "resourceDropsiteTypes": function() { + "resourceDropsiteTypes": function() + { if (!this.get("ResourceDropsite")) return undefined; @@ -384,14 +412,16 @@ export const Template = Class({ return types ? types.split(/\s+/) : []; }, - "isResourceDropsite": function(resourceType) { + "isResourceDropsite": function(resourceType) + { const types = this.resourceDropsiteTypes(); return types && (!resourceType || types.indexOf(resourceType) !== -1); }, "isTreasure": function() { return this.get("Treasure") !== undefined; }, - "treasureResources": function() { + "treasureResources": function() + { if (!this.get("Treasure")) return undefined; const ret = {}; @@ -413,7 +443,8 @@ export const Template = Class({ "getArrowMultiplier": function() { return +this.get("BuildingAI/GarrisonArrowMultiplier"); }, - "getGarrisonArrowClasses": function() { + "getGarrisonArrowClasses": function() + { if (!this.get("BuildingAI")) return undefined; return this.get("BuildingAI/GarrisonArrowClasses").split(/\s+/); @@ -425,7 +456,8 @@ export const Template = Class({ "isPackable": function() { return this.get("Pack") != undefined; }, - "isHuntable": function() { + "isHuntable": function() + { // Do not hunt retaliating animals (dead animals can be used). // Assume entities which can attack, will attack. return this.get("ResourceSupply/KillBeforeGather") && @@ -436,7 +468,8 @@ export const Template = Class({ "trainingCategory": function() { return this.get("TrainingRestrictions/Category"); }, - "buildTime": function(researcher) { + "buildTime": function(researcher) + { let time = +this.get("Cost/BuildTime"); if (researcher) time *= researcher.techCostMultiplier("time"); @@ -445,7 +478,8 @@ export const Template = Class({ "buildCategory": function() { return this.get("BuildRestrictions/Category"); }, - "buildDistance": function() { + "buildDistance": function() + { const distance = this.get("BuildRestrictions/Distance"); if (!distance) return undefined; @@ -457,49 +491,58 @@ export const Template = Class({ "buildPlacementType": function() { return this.get("BuildRestrictions/PlacementType"); }, - "buildTerritories": function() { + "buildTerritories": function() + { if (!this.get("BuildRestrictions")) return undefined; const territory = this.get("BuildRestrictions/Territory"); return !territory ? undefined : territory.split(/\s+/); }, - "hasBuildTerritory": function(territory) { + "hasBuildTerritory": function(territory) + { const territories = this.buildTerritories(); return territories && territories.indexOf(territory) != -1; }, - "hasTerritoryInfluence": function() { + "hasTerritoryInfluence": function() + { return this.get("TerritoryInfluence") !== undefined; }, - "hasDefensiveFire": function() { + "hasDefensiveFire": function() + { if (!this.get("Attack/Ranged")) return false; return this.getDefaultArrow() || this.getArrowMultiplier(); }, - "territoryInfluenceRadius": function() { + "territoryInfluenceRadius": function() + { if (this.get("TerritoryInfluence") !== undefined) return +this.get("TerritoryInfluence/Radius"); return -1; }, - "territoryInfluenceWeight": function() { + "territoryInfluenceWeight": function() + { if (this.get("TerritoryInfluence") !== undefined) return +this.get("TerritoryInfluence/Weight"); return -1; }, - "territoryDecayRate": function() { + "territoryDecayRate": function() + { return +(this.get("TerritoryDecay/DecayRate") || 0); }, - "defaultRegenRate": function() { + "defaultRegenRate": function() + { return +(this.get("Capturable/RegenRate") || 0); }, - "garrisonRegenRate": function() { + "garrisonRegenRate": function() + { return +(this.get("Capturable/GarrisonRegenRate") || 0); }, @@ -511,7 +554,8 @@ export const Template = Class({ "isGatherer": function() { return this.get("ResourceGatherer") !== undefined; }, - "canGather": function(type) { + "canGather": function(type) + { const gatherRates = this.get("ResourceGatherer/Rates"); if (!gatherRates) return false; @@ -622,11 +666,13 @@ export const Entity = Class({ * Returns the current training queue state, of the form * [ { "id": 0, "template": "...", "count": 1, "progress": 0.5, "metadata": ... }, ... ] */ - "trainingQueue": function() { + "trainingQueue": function() + { return this._entity.trainingQueue; }, - "trainingQueueTime": function() { + "trainingQueueTime": function() + { const queue = this._entity.trainingQueue; if (!queue) return undefined; @@ -636,11 +682,13 @@ export const Entity = Class({ return time / 1000; }, - "foundationProgress": function() { + "foundationProgress": function() + { return this._entity.foundationProgress; }, - "getBuilders": function() { + "getBuilders": function() + { if (this._entity.foundationProgress === undefined) return undefined; if (this._entity.foundationBuilders === undefined) @@ -648,7 +696,8 @@ export const Entity = Class({ return this._entity.foundationBuilders; }, - "getBuildersNb": function() { + "getBuildersNb": function() + { if (this._entity.foundationProgress === undefined) return undefined; if (this._entity.foundationBuilders === undefined) @@ -656,17 +705,20 @@ export const Entity = Class({ return this._entity.foundationBuilders.length; }, - "owner": function() { + "owner": function() + { return this._entity.owner; }, - "isOwn": function(player) { + "isOwn": function(player) + { if (typeof this._entity.owner === "undefined") return false; return this._entity.owner === player; }, - "resourceSupplyAmount": function() { + "resourceSupplyAmount": function() + { return this.queryInterface(Sim.IID_ResourceSupply)?.GetCurrentAmount(); }, @@ -684,11 +736,13 @@ export const Entity = Class({ return undefined; }, - "resourceCarrying": function() { + "resourceCarrying": function() + { return this.queryInterface(Sim.IID_ResourceGatherer)?.GetCarryingStatus(); }, - "currentGatherRate": function() { + "currentGatherRate": function() + { // returns the gather rate for the current target if applicable. if (!this.get("ResourceGatherer")) return undefined; @@ -718,13 +772,15 @@ export const Entity = Class({ return undefined; }, - "garrisonHolderID": function() { + "garrisonHolderID": function() + { return this._entity.garrisonHolderID; }, "garrisoned": function() { return this._entity.garrisoned; }, - "garrisonedSlots": function() { + "garrisonedSlots": function() + { let count = 0; if (this._entity.garrisoned) @@ -787,34 +843,40 @@ export const Entity = Class({ return false; }, - "move": function(x, z, queued = false, pushFront = false) { + "move": function(x, z, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "walk", "entities": [this.id()], "x": x, "z": z, "queued": queued, "pushFront": pushFront }); return this; }, - "moveToRange": function(x, z, min, max, queued = false, pushFront = false) { + "moveToRange": function(x, z, min, max, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "walk-to-range", "entities": [this.id()], "x": x, "z": z, "min": min, "max": max, "queued": queued, "pushFront": pushFront }); return this; }, - "attackMove": function(x, z, targetClasses, allowCapture = true, queued = false, pushFront = false) { + "attackMove": function(x, z, targetClasses, allowCapture = true, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "attack-walk", "entities": [this.id()], "x": x, "z": z, "targetClasses": targetClasses, "allowCapture": allowCapture, "queued": queued, "pushFront": pushFront }); return this; }, // violent, aggressive, defensive, passive, standground - "setStance": function(stance) { + "setStance": function(stance) + { if (this.getStance() === undefined) return undefined; Engine.PostCommand(PlayerID, { "type": "stance", "entities": [this.id()], "name": stance }); return this; }, - "stopMoving": function() { + "stopMoving": function() + { Engine.PostCommand(PlayerID, { "type": "stop", "entities": [this.id()], "queued": false, "pushFront": false }); }, - "unload": function(id) { + "unload": function(id) + { if (!this.get("GarrisonHolder")) return undefined; Engine.PostCommand(PlayerID, { "type": "unload", "garrisonHolder": this.id(), "entities": [id] }); @@ -822,29 +884,34 @@ export const Entity = Class({ }, // Unloads all owned units, don't unload allies - "unloadAll": function() { + "unloadAll": function() + { if (!this.get("GarrisonHolder")) return undefined; Engine.PostCommand(PlayerID, { "type": "unload-all-by-owner", "garrisonHolders": [this.id()] }); return this; }, - "garrison": function(target, queued = false, pushFront = false) { + "garrison": function(target, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "garrison", "entities": [this.id()], "target": target.id(), "queued": queued, "pushFront": pushFront }); return this; }, - "occupy-turret": function(target, queued = false, pushFront = false) { + "occupy-turret": function(target, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "occupy-turret", "entities": [this.id()], "target": target.id(), "queued": queued, "pushFront": pushFront }); return this; }, - "attack": function(unitId, allowCapture = true, queued = false, pushFront = false) { + "attack": function(unitId, allowCapture = true, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "attack", "entities": [this.id()], "target": unitId, "allowCapture": allowCapture, "queued": queued, "pushFront": pushFront }); return this; }, - "collectTreasure": function(target, queued = false, pushFront = false) { + "collectTreasure": function(target, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "collect-treasure", "entities": [this.id()], @@ -856,7 +923,8 @@ export const Entity = Class({ }, // moveApart from a point in the opposite direction with a distance dist - "moveApart": function(point, dist) { + "moveApart": function(point, dist) + { if (this.position() !== undefined) { let direction = [this.position()[0] - point[0], this.position()[1] - point[1]]; @@ -874,7 +942,8 @@ export const Entity = Class({ }, // Flees from a unit in the opposite direction. - "flee": function(unitToFleeFrom) { + "flee": function(unitToFleeFrom) + { if (this.position() !== undefined && unitToFleeFrom.position() !== undefined) { const FleeDirection = [this.position()[0] - unitToFleeFrom.position()[0], @@ -888,43 +957,51 @@ export const Entity = Class({ return this; }, - "gather": function(target, queued = false, pushFront = false) { + "gather": function(target, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "gather", "entities": [this.id()], "target": target.id(), "queued": queued, "pushFront": pushFront }); return this; }, - "repair": function(target, autocontinue = false, queued = false, pushFront = false) { + "repair": function(target, autocontinue = false, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "repair", "entities": [this.id()], "target": target.id(), "autocontinue": autocontinue, "queued": queued, "pushFront": pushFront }); return this; }, - "returnResources": function(target, queued = false, pushFront = false) { + "returnResources": function(target, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "returnresource", "entities": [this.id()], "target": target.id(), "queued": queued, "pushFront": pushFront }); return this; }, - "destroy": function() { + "destroy": function() + { Engine.PostCommand(PlayerID, { "type": "delete-entities", "entities": [this.id()] }); return this; }, - "barter": function(buyType, sellType, amount) { + "barter": function(buyType, sellType, amount) + { Engine.PostCommand(PlayerID, { "type": "barter", "sell": sellType, "buy": buyType, "amount": amount }); return this; }, - "tradeRoute": function(target, source) { + "tradeRoute": function(target, source) + { Engine.PostCommand(PlayerID, { "type": "setup-trade-route", "entities": [this.id()], "target": target.id(), "source": source.id(), "route": undefined, "queued": false, "pushFront": false }); return this; }, - "setRallyPoint": function(target, command) { + "setRallyPoint": function(target, command) + { const data = { "command": command, "target": target.id() }; Engine.PostCommand(PlayerID, { "type": "set-rallypoint", "entities": [this.id()], "x": target.position()[0], "z": target.position()[1], "data": data }); return this; }, - "unsetRallyPoint": function() { + "unsetRallyPoint": function() + { Engine.PostCommand(PlayerID, { "type": "unset-rallypoint", "entities": [this.id()] }); return this; }, @@ -954,7 +1031,8 @@ export const Entity = Class({ return this; }, - "construct": function(template, x, z, angle, metadata) { + "construct": function(template, x, z, angle, metadata) + { // TODO: verify this unit can construct this, just for internal // sanity-checking and error reporting @@ -974,7 +1052,8 @@ export const Entity = Class({ return this; }, - "research": function(template, pushFront = false) { + "research": function(template, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "research", "entity": this.id(), @@ -984,12 +1063,14 @@ export const Entity = Class({ return this; }, - "stopProduction": function(id) { + "stopProduction": function(id) + { Engine.PostCommand(PlayerID, { "type": "stop-production", "entity": this.id(), "id": id }); return this; }, - "stopAllProduction": function(percentToStopAt) { + "stopAllProduction": function(percentToStopAt) + { const queue = this._entity.trainingQueue; if (!queue) return true; // no queue, so technically we stopped all production. @@ -999,12 +1080,14 @@ export const Entity = Class({ return this; }, - "guard": function(target, queued = false, pushFront = false) { + "guard": function(target, queued = false, pushFront = false) + { Engine.PostCommand(PlayerID, { "type": "guard", "entities": [this.id()], "target": target.id(), "queued": queued, "pushFront": pushFront }); return this; }, - "removeGuard": function() { + "removeGuard": function() + { Engine.PostCommand(PlayerID, { "type": "remove-guard", "entities": [this.id()] }); return this; } diff --git a/binaries/data/mods/public/simulation/ai/common-api/filters.js b/binaries/data/mods/public/simulation/ai/common-api/filters.js index 615abee977..c68f5e6344 100644 --- a/binaries/data/mods/public/simulation/ai/common-api/filters.js +++ b/binaries/data/mods/public/simulation/ai/common-api/filters.js @@ -177,7 +177,8 @@ export function isDropsite(resourceType) export function isTreasure() { return { - "func": ent => { + "func": ent => + { if (!ent.isTreasure()) return false; @@ -194,7 +195,8 @@ export function isTreasure() export function byResource(resourceType) { return { - "func": ent => { + "func": ent => + { if (!ent.resourceSupplyMax()) return false; diff --git a/binaries/data/mods/public/simulation/ai/common-api/gamestate.js b/binaries/data/mods/public/simulation/ai/common-api/gamestate.js index 0fb60945ec..d4fd5b9dde 100644 --- a/binaries/data/mods/public/simulation/ai/common-api/gamestate.js +++ b/binaries/data/mods/public/simulation/ai/common-api/gamestate.js @@ -262,7 +262,8 @@ GameState.prototype.checkTechRequirements = function(reqs) if (!reqs.length) return true; - const doesEntitySpecPass = entity => { + const doesEntitySpecPass = entity => + { switch (entity.check) { case "count": @@ -278,8 +279,10 @@ GameState.prototype.checkTechRequirements = function(reqs) } }; - return reqs.some(req => { - return Object.keys(req).every(type => { + return reqs.some(req => + { + return Object.keys(req).every(type => + { switch (type) { case "techs": @@ -316,11 +319,13 @@ GameState.prototype.getPopulation = function() return this.playerData.popCount; }; -GameState.prototype.getPopulationLimit = function() { +GameState.prototype.getPopulationLimit = function() +{ return this.playerData.popLimit; }; -GameState.prototype.getPopulationMax = function() { +GameState.prototype.getPopulationMax = function() +{ return this.playerData.popMax; }; @@ -625,7 +630,8 @@ GameState.prototype.countEntitiesAndQueuedByType = function(type, maintain) { // Count entities in building production queues // TODO: maybe this fails for corrals. - this.getOwnTrainingFacilities().forEach(function(ent) { + this.getOwnTrainingFacilities().forEach(function(ent) + { for (const item of ent.trainingQueue()) if (item.unitTemplate == type) count += item.count; @@ -646,7 +652,8 @@ GameState.prototype.countFoundationsByType = function(type, maintain) } let count = 0; - this.getOwnStructures().forEach(function(ent) { + this.getOwnStructures().forEach(function(ent) + { if (ent.templateName() == foundationType) ++count; }); @@ -663,7 +670,8 @@ GameState.prototype.countOwnEntitiesAndQueuedWithRole = function(role) let count = this.countOwnEntitiesByRole(role); // Count entities in building production queues - this.getOwnTrainingFacilities().forEach(function(ent) { + this.getOwnTrainingFacilities().forEach(function(ent) + { for (const item of ent.trainingQueue()) if (item.metadata && item.metadata.role && item.metadata.role == role) count += item.count; @@ -675,7 +683,8 @@ GameState.prototype.countOwnQueuedEntitiesWithMetadata = function(data, value) { // Count entities in building production queues let count = 0; - this.getOwnTrainingFacilities().forEach(function(ent) { + this.getOwnTrainingFacilities().forEach(function(ent) + { for (const item of ent.trainingQueue()) if (item.metadata && item.metadata[data] && item.metadata[data] == value) count += item.count; @@ -727,7 +736,8 @@ GameState.prototype.findTrainableUnits = function(classes, anticlasses) { const allTrainable = []; const civ = this.playerData.civ; - this.getOwnTrainingFacilities().forEach(function(ent) { + this.getOwnTrainingFacilities().forEach(function(ent) + { const trainable = ent.trainableEntities(civ); if (!trainable) return; @@ -822,7 +832,8 @@ GameState.prototype.hasTrainer = function(template) GameState.prototype.findTrainers = function(template) { const civ = this.playerData.civ; - return this.getOwnTrainingFacilities().filter(function(ent) { + return this.getOwnTrainingFacilities().filter(function(ent) + { const trainable = ent.trainableEntities(civ); return trainable && trainable.indexOf(template) !== -1; }); @@ -886,7 +897,8 @@ GameState.prototype.findResearchers = function(templateName, noRequirementCheck) const self = this; const civ = this.playerData.civ; - return this.getOwnResearchFacilities().filter(function(ent) { + return this.getOwnResearchFacilities().filter(function(ent) + { const techs = ent.researchableTechs(self, civ); for (const tech of techs) { diff --git a/binaries/data/mods/public/simulation/ai/petra/attackPlan.js b/binaries/data/mods/public/simulation/ai/petra/attackPlan.js index 23c026f8ff..5eae5fbf69 100644 --- a/binaries/data/mods/public/simulation/ai/petra/attackPlan.js +++ b/binaries/data/mods/public/simulation/ai/petra/attackPlan.js @@ -629,7 +629,8 @@ AttackPlan.prototype.trainMoreUnits = function(gameState) aQueued += this.queueSiege.countQueuedUnitsWithMetadata("special", special); order[0] = order[2].length + aQueued; } - this.buildOrders.sort((a, b) => { + this.buildOrders.sort((a, b) => + { let va = a[0]/a[3].targetSize - a[3].priority; if (a[0] >= a[3].targetSize) va += 1000; @@ -1353,7 +1354,8 @@ AttackPlan.prototype.update = function(gameState, events) // let's proceed on with whatever happens now. this.state = ""; this.startingAttack = true; - this.unitCollection.forEach(ent => { + this.unitCollection.forEach(ent => + { ent.stopMoving(); ent.setMetadata(PlayerID, "subrole", Worker.SUBROLE_ATTACKING); }); @@ -1628,7 +1630,8 @@ AttackPlan.prototype.update = function(gameState, events) // Checking for gates if we're a siege unit. if (siegeUnit) { - const mStruct = enemyStructures.filter(enemy => { + const mStruct = enemyStructures.filter(enemy => + { if (!enemy.position() || !ent.canAttackTarget(enemy, allowCapture(gameState, ent, enemy))) return false; if (SquareVectorDistance(enemy.position(), ent.position()) > range) @@ -1641,7 +1644,8 @@ AttackPlan.prototype.update = function(gameState, events) }).toEntityArray(); if (mStruct.length) { - mStruct.sort((structa, structb) => { + mStruct.sort((structa, structb) => + { let vala = structa.costSum(); if (structa.hasClass("Gate") && ent.canAttackClass("Wall")) vala += 10000; @@ -1680,7 +1684,8 @@ AttackPlan.prototype.update = function(gameState, events) else { const nearby = !ent.hasClasses(["FastMoving", "Ranged"]); - const mUnit = enemyUnits.filter(enemy => { + const mUnit = enemyUnits.filter(enemy => + { if (!enemy.position() || !ent.canAttackTarget(enemy, allowCapture(gameState, ent, enemy))) return false; if (enemy.hasClass("Animal")) @@ -1703,7 +1708,8 @@ AttackPlan.prototype.update = function(gameState, events) }, this).toEntityArray(); if (mUnit.length) { - mUnit.sort((unitA, unitB) => { + mUnit.sort((unitA, unitB) => + { let vala = unitA.hasClass("Support") ? 50 : 0; if (ent.counters(unitA)) vala += 100; @@ -1746,7 +1752,8 @@ AttackPlan.prototype.update = function(gameState, events) } else { - const mStruct = enemyStructures.filter(enemy => { + const mStruct = enemyStructures.filter(enemy => + { if (this.isBlocked && enemy.id() != this.target.id()) return false; if (!enemy.position() || !ent.canAttackTarget(enemy, allowCapture(gameState, ent, enemy))) @@ -1759,7 +1766,8 @@ AttackPlan.prototype.update = function(gameState, events) }, this).toEntityArray(); if (mStruct.length) { - mStruct.sort((structa, structb) => { + mStruct.sort((structa, structb) => + { let vala = structa.costSum(); if (structa.hasClass("Gate") && ent.canAttackClass("Wall")) vala += 10000; @@ -1784,7 +1792,8 @@ AttackPlan.prototype.update = function(gameState, events) { let distmin = Math.min(); let attacker; - this.unitCollection.forEach(unit => { + this.unitCollection.forEach(unit => + { if (!unit.position()) return; if (unit.unitAIState().split(".")[1] != "COMBAT" || !unit.unitAIOrderData().length || diff --git a/binaries/data/mods/public/simulation/ai/petra/baseManager.js b/binaries/data/mods/public/simulation/ai/petra/baseManager.js index 4e208a096d..b1150d0d38 100644 --- a/binaries/data/mods/public/simulation/ai/petra/baseManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/baseManager.js @@ -270,7 +270,8 @@ BaseManager.prototype.removeDropsite = function(gameState, ent) if (!ent.id()) return; - const removeSupply = function(entId, supply){ + const removeSupply = function(entId, supply) + { for (let i = 0; i < supply.length; ++i) { // exhausted resource, remove it from this list @@ -553,7 +554,8 @@ BaseManager.prototype.addGatherRates = function(gameState, currentRates) // I use some logarithms. // TODO: this should take into account for unit speed and/or distance to target - this.gatherersByType(gameState, res).forEach(ent => { + this.gatherersByType(gameState, res).forEach(ent => + { if (ent.isIdle() || !ent.position()) return; const gRate = ent.currentGatherRate(); @@ -562,14 +564,16 @@ BaseManager.prototype.addGatherRates = function(gameState, currentRates) }); if (res == "food") { - this.workersBySubrole(gameState, Worker.SUBROLE_HUNTER).forEach(ent => { + this.workersBySubrole(gameState, Worker.SUBROLE_HUNTER).forEach(ent => + { if (ent.isIdle() || !ent.position()) return; const gRate = ent.currentGatherRate(); if (gRate) currentRates[res] += Math.log(1+gRate)/1.1; }); - this.workersBySubrole(gameState, Worker.SUBROLE_FISHER).forEach(ent => { + this.workersBySubrole(gameState, Worker.SUBROLE_FISHER).forEach(ent => + { if (ent.isIdle() || !ent.position()) return; const gRate = ent.currentGatherRate(); @@ -753,7 +757,8 @@ BaseManager.prototype.gatherersByType = function(gameState, type) */ BaseManager.prototype.pickBuilders = function(gameState, workers, number) { - const availableWorkers = this.workers.filter(ent => { + const availableWorkers = this.workers.filter(ent => + { if (!ent.position() || !ent.isBuilder()) return false; if (ent.getMetadata(PlayerID, "plan") == -2 || ent.getMetadata(PlayerID, "plan") == -3) @@ -762,7 +767,8 @@ BaseManager.prototype.pickBuilders = function(gameState, workers, number) return false; return true; }).toEntityArray(); - availableWorkers.sort((a, b) => { + availableWorkers.sort((a, b) => + { let vala = 0; let valb = 0; if (a.getMetadata(PlayerID, "subrole") === Worker.SUBROLE_BUILDER) @@ -815,7 +821,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) { foundations = foundations.filter(filters.byMetadata(PlayerID, "baseAnchor", true)); const tID = foundations.toEntityArray()[0].id(); - workers.forEach(ent => { + workers.forEach(ent => + { const target = ent.getMetadata(PlayerID, "target-foundation"); if (target && target != tID) { @@ -831,7 +838,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) if (fromOtherBase) { const baseID = this.ID; - fromOtherBase.forEach(worker => { + fromOtherBase.forEach(worker => + { worker.setMetadata(PlayerID, "base", baseID); worker.setMetadata(PlayerID, "subrole", Worker.SUBROLE_BUILDER); workers.updateEnt(worker); @@ -902,7 +910,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) if (assigned >= targetNB) continue; - idleBuilderWorkers.forEach(function(ent) { + idleBuilderWorkers.forEach(function(ent) + { if (ent.getMetadata(PlayerID, "target-foundation") !== undefined) return; if (assigned >= targetNB || !ent.position() || @@ -916,7 +925,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) }); if (assigned >= targetNB || builderTot >= maxTotalBuilders) continue; - const nonBuilderWorkers = workers.filter(function(ent) { + const nonBuilderWorkers = workers.filter(function(ent) + { if (ent.getMetadata(PlayerID, "subrole") === Worker.SUBROLE_BUILDER) return false; if (!ent.position()) @@ -928,7 +938,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) return true; }).toEntityArray(); const time = target.buildTime(); - nonBuilderWorkers.sort((workerA, workerB) => { + nonBuilderWorkers.sort((workerA, workerB) => + { let coeffA = SquareVectorDistance(target.position(), workerA.position()); // elephant moves slowly, so when far away they are only useful if build time is long if (workerA.hasClass("Elephant")) @@ -992,7 +1003,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) if (assigned >= targetNB) continue; - idleBuilderWorkers.forEach(function(ent) { + idleBuilderWorkers.forEach(function(ent) + { if (ent.getMetadata(PlayerID, "target-foundation") !== undefined) return; if (assigned >= targetNB || !ent.position() || @@ -1004,7 +1016,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) }); if (assigned >= targetNB || builderTot >= maxTotalBuilders) continue; - const nonBuilderWorkers = workers.filter(function(ent) { + const nonBuilderWorkers = workers.filter(function(ent) + { if (ent.getMetadata(PlayerID, "subrole") === Worker.SUBROLE_BUILDER) return false; if (!ent.position()) @@ -1018,7 +1031,8 @@ BaseManager.prototype.assignToFoundations = function(gameState, noRepair) const num = Math.min(nonBuilderWorkers.length, targetNB-assigned); const nearestNonBuilders = nonBuilderWorkers.filterNearest(target.position(), num); - nearestNonBuilders.forEach(function(ent) { + nearestNonBuilders.forEach(function(ent) + { ++assigned; ++builderTot; ent.stopMoving(); diff --git a/binaries/data/mods/public/simulation/ai/petra/basesManager.js b/binaries/data/mods/public/simulation/ai/petra/basesManager.js index dfd0c044c4..e4a6f32b4a 100644 --- a/binaries/data/mods/public/simulation/ai/petra/basesManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/basesManager.js @@ -202,7 +202,8 @@ BasesManager.prototype.checkEvents = function(gameState, events) const builders = this.bulkPickWorkers(gameState, newbase, 10); if (builders !== false) { - builders.forEach(worker => { + builders.forEach(worker => + { worker.setMetadata(PlayerID, "base", newbase.ID); worker.setMetadata(PlayerID, "subrole", Worker.SUBROLE_BUILDER); worker.setMetadata(PlayerID, "target-foundation", ent.id()); @@ -216,7 +217,8 @@ BasesManager.prototype.checkEvents = function(gameState, events) const builders = this.bulkPickWorkers(gameState, newbase, 4); if (builders != false) { - builders.forEach(worker => { + builders.forEach(worker => + { worker.setMetadata(PlayerID, "base", newbase.ID); worker.setMetadata(PlayerID, "subrole", Worker.SUBROLE_BUILDER); worker.setMetadata(PlayerID, "target-foundation", ent.id()); @@ -359,7 +361,8 @@ BasesManager.prototype.bulkPickWorkers = function(gameState, baseRef, number) const baseBest = this.baseManagers.slice(); // We can also use workers without a base. baseBest.push(this.noBase); - baseBest.sort((a, b) => { + baseBest.sort((a, b) => + { if (a.accessIndex == accessIndex && b.accessIndex != accessIndex) return -1; else if (b.accessIndex == accessIndex && a.accessIndex != accessIndex) diff --git a/binaries/data/mods/public/simulation/ai/petra/config.js b/binaries/data/mods/public/simulation/ai/petra/config.js index cef0eb992c..d5229c80f2 100644 --- a/binaries/data/mods/public/simulation/ai/petra/config.js +++ b/binaries/data/mods/public/simulation/ai/petra/config.js @@ -46,122 +46,122 @@ export function Config(difficulty = difficultyLevel.MEDIUM, behavior) // Note: attack settings are set directly in attack_plan.js // defense this.Defense = - { - "defenseRatio": { "ally": 1.4, "neutral": 1.8, "own": 2 }, // ratio of defenders/attackers. - "armyCompactSize": 2000, // squared. Half-diameter of an army. - "armyBreakawaySize": 3500, // squared. - "armyMergeSize": 1400 // squared. - }; + { + "defenseRatio": { "ally": 1.4, "neutral": 1.8, "own": 2 }, // ratio of defenders/attackers. + "armyCompactSize": 2000, // squared. Half-diameter of an army. + "armyBreakawaySize": 3500, // squared. + "armyMergeSize": 1400 // squared. + }; // Additional buildings that the AI does not yet know when to build // and that it will try to build on phase 3 when enough resources. this.buildings = - { - "default": [], - "athen": [ - "structures/{civ}/gymnasium", - "structures/{civ}/prytaneion", - "structures/{civ}/theater" - ], - "brit": [], - "cart": [ - "structures/{civ}/embassy_celtic", - "structures/{civ}/embassy_iberian", - "structures/{civ}/embassy_italic" - ], - "gaul": [ - "structures/{civ}/assembly" - ], - "han": [ - "structures/{civ}/academy" - ], - "iber": [ - "structures/{civ}/monument" - ], - "kush": [ - "structures/{civ}/camp_blemmye", - "structures/{civ}/camp_noba", - "structures/{civ}/pyramid_large", - "structures/{civ}/pyramid_small", - "structures/{civ}/temple_amun" - ], - "mace": [ - "structures/{civ}/theater" - ], - "maur": [ - "structures/{civ}/palace", - "structures/{civ}/pillar_ashoka" - ], - "pers": [ - "structures/{civ}/tachara" - ], - "ptol": [ - "structures/{civ}/library", - "structures/{civ}/theater" - ], - "rome": [ - "structures/{civ}/army_camp", - "structures/{civ}/temple_vesta" - ], - "sele": [ - "structures/{civ}/theater" - ], - "spart": [ - "structures/{civ}/syssiton", - "structures/{civ}/theater" - ] - }; + { + "default": [], + "athen": [ + "structures/{civ}/gymnasium", + "structures/{civ}/prytaneion", + "structures/{civ}/theater" + ], + "brit": [], + "cart": [ + "structures/{civ}/embassy_celtic", + "structures/{civ}/embassy_iberian", + "structures/{civ}/embassy_italic" + ], + "gaul": [ + "structures/{civ}/assembly" + ], + "han": [ + "structures/{civ}/academy" + ], + "iber": [ + "structures/{civ}/monument" + ], + "kush": [ + "structures/{civ}/camp_blemmye", + "structures/{civ}/camp_noba", + "structures/{civ}/pyramid_large", + "structures/{civ}/pyramid_small", + "structures/{civ}/temple_amun" + ], + "mace": [ + "structures/{civ}/theater" + ], + "maur": [ + "structures/{civ}/palace", + "structures/{civ}/pillar_ashoka" + ], + "pers": [ + "structures/{civ}/tachara" + ], + "ptol": [ + "structures/{civ}/library", + "structures/{civ}/theater" + ], + "rome": [ + "structures/{civ}/army_camp", + "structures/{civ}/temple_vesta" + ], + "sele": [ + "structures/{civ}/theater" + ], + "spart": [ + "structures/{civ}/syssiton", + "structures/{civ}/theater" + ] + }; this.priorities = - { - "villager": 300, // should be slightly lower than the citizen soldier one to not get all the food - "citizenSoldier": 600, - "trader": 1, - "healer": 20, - "ships": 1, - "house": 250, - "dropsites": 950, - "field": 480, - "dock": 90, - "corral": 1, - "economicBuilding": 700, - "militaryBuilding": 330, - "defenseBuilding": 70, - "civilCentre": 1, - "majorTech": 700, - "minorTech": 250, - "wonder": 1, - "emergency": 1000 // used only in emergency situations, should be the highest one - }; + { + "villager": 300, // should be slightly lower than the citizen soldier one to not get all the food + "citizenSoldier": 600, + "trader": 1, + "healer": 20, + "ships": 1, + "house": 250, + "dropsites": 950, + "field": 480, + "dock": 90, + "corral": 1, + "economicBuilding": 700, + "militaryBuilding": 330, + "defenseBuilding": 70, + "civilCentre": 1, + "majorTech": 700, + "minorTech": 250, + "wonder": 1, + "emergency": 1000 // used only in emergency situations, should be the highest one + }; // Default personality (will be updated in setConfig) this.personality = - { - "aggressive": 0.5, - "cooperative": 0.5, - "defensive": 0.5 - }; + { + "aggressive": 0.5, + "cooperative": 0.5, + "defensive": 0.5 + }; // See QueueManager.prototype.wantedGatherRates() this.queues = - { - "firstTurn": { - "food": 10, - "wood": 10, - "default": 0 - }, - "short": { - "food": 200, - "wood": 200, - "default": 100 - }, - "medium": { - "default": 0 - }, - "long": { - "default": 0 - } - }; + { + "firstTurn": { + "food": 10, + "wood": 10, + "default": 0 + }, + "short": { + "food": 200, + "wood": 200, + "default": 100 + }, + "medium": { + "default": 0 + }, + "long": { + "default": 0 + } + }; this.garrisonHealthLevel = { "low": 0.4, "medium": 0.55, "high": 0.7 }; diff --git a/binaries/data/mods/public/simulation/ai/petra/defenseManager.js b/binaries/data/mods/public/simulation/ai/petra/defenseManager.js index 299862e8ed..5d0e444a45 100644 --- a/binaries/data/mods/public/simulation/ai/petra/defenseManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/defenseManager.js @@ -427,7 +427,8 @@ DefenseManager.prototype.assignDefenders = function(gameState) // Let's get our potential units. const potentialDefenders = []; - gameState.getOwnUnits().forEach(function(ent) { + gameState.getOwnUnits().forEach(function(ent) + { if (!ent.position()) return; if (ent.getMetadata(PlayerID, "plan") == -2 || ent.getMetadata(PlayerID, "plan") == -3) @@ -474,7 +475,8 @@ DefenseManager.prototype.assignDefenders = function(gameState) continue; // Do not assign defender if it cannot attack at least part of the attacking army. - if (!armiesNeeding[a].army.foeEntities.some(eEnt => { + if (!armiesNeeding[a].army.foeEntities.some(eEnt => + { const eEntID = gameState.getEntityById(eEnt); return ent.canAttackTarget(eEntID, allowCapture(gameState, ent, eEntID)); })) @@ -789,7 +791,8 @@ DefenseManager.prototype.garrisonUnitsInside = function(gameState, target, data) else allowMelee = true; } - const units = gameState.getOwnUnits().filter(ent => { + const units = gameState.getOwnUnits().filter(ent => + { if (!ent.position()) return false; if (!ent.hasClasses(garrisonArrowClasses)) diff --git a/binaries/data/mods/public/simulation/ai/petra/emergencyManager.js b/binaries/data/mods/public/simulation/ai/petra/emergencyManager.js index 8f9c144ea7..636b45a78d 100644 --- a/binaries/data/mods/public/simulation/ai/petra/emergencyManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/emergencyManager.js @@ -65,7 +65,8 @@ EmergencyManager.prototype.emergencyUpdate = function(gameState) EmergencyManager.prototype.rootCount = function(gameState) { let roots = 0; - gameState.getOwnStructures().toEntityArray().forEach(ent => { + gameState.getOwnStructures().toEntityArray().forEach(ent => + { if (ent?.get("TerritoryInfluence")?.Root === "true") roots++; }); diff --git a/binaries/data/mods/public/simulation/ai/petra/headquarters.js b/binaries/data/mods/public/simulation/ai/petra/headquarters.js index fc34397221..88d19b62ba 100644 --- a/binaries/data/mods/public/simulation/ai/petra/headquarters.js +++ b/binaries/data/mods/public/simulation/ai/petra/headquarters.js @@ -407,7 +407,8 @@ Headquarters.prototype.trainMoreWorkers = function(gameState, queues) // counting the workers that aren't part of a plan let numberOfWorkers = 0; // all workers let numberOfSupports = 0; // only support workers (i.e. non fighting) - gameState.getOwnUnits().forEach(ent => { + gameState.getOwnUnits().forEach(ent => + { if (ent.getMetadata(PlayerID, "role") === Worker.ROLE_WORKER && ent.getMetadata(PlayerID, "plan") === undefined) { ++numberOfWorkers; @@ -416,7 +417,8 @@ Headquarters.prototype.trainMoreWorkers = function(gameState, queues) } }); let numberInTraining = 0; - gameState.getOwnTrainingFacilities().forEach(function(ent) { + gameState.getOwnTrainingFacilities().forEach(function(ent) + { for (const item of ent.trainingQueue()) { numberInTraining += item.count; @@ -541,7 +543,8 @@ Headquarters.prototype.findBestTrainableUnit = function(gameState, classes, requ parameters.push(["costsResource", costsResource, type]); } - units.sort((a, b) => { + units.sort((a, b) => + { const aCost = 1 + a[1].costSum(); const bCost = 1 + b[1].costSum(); let aValue = 0.1; @@ -640,7 +643,8 @@ Headquarters.prototype.pickMostNeededResources = function(gameState, allowedReso for (const res of allowedResources) needed.push({ "type": res, "wanted": wantedRates[res], "current": currentRates[res] }); - needed.sort((a, b) => { + needed.sort((a, b) => + { if (a.current < a.wanted && b.current < b.wanted) { if (a.current && b.current) diff --git a/binaries/data/mods/public/simulation/ai/petra/mapModule.js b/binaries/data/mods/public/simulation/ai/petra/mapModule.js index 16fed63777..d85de11e01 100644 --- a/binaries/data/mods/public/simulation/ai/petra/mapModule.js +++ b/binaries/data/mods/public/simulation/ai/petra/mapModule.js @@ -198,7 +198,8 @@ function debugMap(gameState, map) { const width = map.width; const cell = map.cellSize; - gameState.getEntities().forEach(ent => { + gameState.getEntities().forEach(ent => + { const pos = ent.position(); if (!pos) return; diff --git a/binaries/data/mods/public/simulation/ai/petra/navalManager.js b/binaries/data/mods/public/simulation/ai/petra/navalManager.js index 956ac8b5f7..b5d093da61 100644 --- a/binaries/data/mods/public/simulation/ai/petra/navalManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/navalManager.js @@ -196,7 +196,8 @@ NavalManager.prototype.getFishSea = function(gameState, fish) sea = gameState.ai.accessibility.navalPassMap[k]; fish.setMetadata(PlayerID, "sea", sea); const radius = 120 / gameState.ai.accessibility.cellSize / ntry; - if (around.every(a => { + if (around.every(a => + { for (let t = 0; t < ntry; ++t) { const i = pos[0] + Math.round(a[0]*radius*(ntry-t)); @@ -230,7 +231,8 @@ NavalManager.prototype.canFishSafely = function(gameState, fish) const width = territoryMap.width; const radius = 120 / territoryMap.cellSize / ntry; const pos = territoryMap.gamePosToMapPos(fish.position()); - return around.every(a => { + return around.every(a => + { for (let t = 0; t < ntry; ++t) { const i = pos[0] + Math.round(a[0]*radius*(ntry-t)); @@ -249,7 +251,8 @@ NavalManager.prototype.canFishSafely = function(gameState, fish) NavalManager.prototype.getUnconnectedSeas = function(gameState, region) { const seas = gameState.ai.accessibility.regionLinks[region].slice(); - this.docks.forEach(dock => { + this.docks.forEach(dock => + { if (!dock.hasClass("Dock") || getLandAccess(gameState, dock) != region) return; const i = seas.indexOf(getSeaAccess(gameState, dock)); @@ -302,7 +305,8 @@ NavalManager.prototype.checkEvents = function(gameState, queues, events) if (plan.state === TransportPlan.BOARDING) { // just reset the units onBoard metadata and wait for a new ship to be assigned to this plan - plan.units.forEach(ent => { + plan.units.forEach(ent => + { if (ent.getMetadata(PlayerID, "onBoard") == "onBoard" && ent.position() || ent.getMetadata(PlayerID, "onBoard") == shipId) ent.setMetadata(PlayerID, "onBoard", undefined); @@ -798,7 +802,8 @@ NavalManager.prototype.getBestShip = function(gameState, sea, goal) const civ = gameState.getPlayerCiv(); const trainableShips = []; gameState.getOwnTrainingFacilities().filter(filters.byMetadata(PlayerID, "sea", sea)).forEach( - function(ent) { + function(ent) + { const trainables = ent.trainableEntities(civ); for (const trainable of trainables) { diff --git a/binaries/data/mods/public/simulation/ai/petra/queueManager.js b/binaries/data/mods/public/simulation/ai/petra/queueManager.js index 63f3ffa195..d7f9295212 100644 --- a/binaries/data/mods/public/simulation/ai/petra/queueManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/queueManager.js @@ -163,7 +163,8 @@ QueueManager.prototype.wantedGatherRates = function(gameState) QueueManager.prototype.printQueues = function(gameState) { let numWorkers = 0; - gameState.getOwnUnits().forEach(ent => { + gameState.getOwnUnits().forEach(ent => + { if (ent.getMetadata(PlayerID, "role") === Worker.ROLE_WORKER && ent.getMetadata(PlayerID, "plan") === undefined) { diff --git a/binaries/data/mods/public/simulation/ai/petra/queueplanBuilding.js b/binaries/data/mods/public/simulation/ai/petra/queueplanBuilding.js index 0700ac96a8..f49812779c 100644 --- a/binaries/data/mods/public/simulation/ai/petra/queueplanBuilding.js +++ b/binaries/data/mods/public/simulation/ai/petra/queueplanBuilding.js @@ -221,7 +221,8 @@ ConstructionPlan.prototype.findGoodPosition = function(gameState) if (!HQ.requireHouses || !template.hasClass("House")) { - gameState.getOwnStructures().forEach(function(ent) { + gameState.getOwnStructures().forEach(function(ent) + { const pos = ent.position(); const x = Math.round(pos[0] / cellSize); const z = Math.round(pos[1] / cellSize); diff --git a/binaries/data/mods/public/simulation/ai/petra/queueplanTraining.js b/binaries/data/mods/public/simulation/ai/petra/queueplanTraining.js index 947d5c00d8..0c556288e5 100644 --- a/binaries/data/mods/public/simulation/ai/petra/queueplanTraining.js +++ b/binaries/data/mods/public/simulation/ai/petra/queueplanTraining.js @@ -88,7 +88,8 @@ TrainingPlan.prototype.start = function(gameState) const workerUnit = this.metadata && this.metadata.role && this.metadata.role === Worker.ROLE_WORKER; const supportUnit = this.template.hasClass("Support"); - this.trainers.sort(function(a, b) { + this.trainers.sort(function(a, b) + { // Prefer training buildings with short queues let aa = a.trainingQueueTime(); let bb = b.trainingQueueTime(); diff --git a/binaries/data/mods/public/simulation/ai/petra/startingStrategy.js b/binaries/data/mods/public/simulation/ai/petra/startingStrategy.js index 8e359f7b60..fba247325d 100644 --- a/binaries/data/mods/public/simulation/ai/petra/startingStrategy.js +++ b/binaries/data/mods/public/simulation/ai/petra/startingStrategy.js @@ -355,7 +355,8 @@ Headquarters.prototype.dispatchUnits = function(gameState) let num1 = Math.floor(num / 2); let num2 = num1; // first pass to affect ranged infantry - units.filter(filters.byClasses(["Infantry+Ranged"])).forEach(ent => { + units.filter(filters.byClasses(["Infantry+Ranged"])).forEach(ent => + { if (!num || !num1) return; if (ent.getMetadata(PlayerID, "allied")) @@ -374,7 +375,8 @@ Headquarters.prototype.dispatchUnits = function(gameState) } }); // second pass to affect melee infantry - units.filter(filters.byClasses(["Infantry+Melee"])).forEach(ent => { + units.filter(filters.byClasses(["Infantry+Melee"])).forEach(ent => + { if (!num || !num2) return; if (ent.getMetadata(PlayerID, "allied")) @@ -393,7 +395,8 @@ Headquarters.prototype.dispatchUnits = function(gameState) } }); // and now complete the affectation, including all support units - units.forEach(ent => { + units.forEach(ent => + { if (!num && !ent.hasClass("Support")) return; if (ent.getMetadata(PlayerID, "allied")) diff --git a/binaries/data/mods/public/simulation/ai/petra/tradeManager.js b/binaries/data/mods/public/simulation/ai/petra/tradeManager.js index 2245612951..d6772179cc 100644 --- a/binaries/data/mods/public/simulation/ai/petra/tradeManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/tradeManager.js @@ -50,7 +50,8 @@ TradeManager.prototype.trainMoreTraders = function(gameState, queues) let numSeaTraders = this.traders.filter(filters.byClass("Ship")).length; let numLandTraders = numTraders - numSeaTraders; // add traders already in training - gameState.getOwnTrainingFacilities().forEach(function(ent) { + gameState.getOwnTrainingFacilities().forEach(function(ent) + { for (const item of ent.trainingQueue()) { if (!item.metadata || !item.metadata.role || item.metadata.role !== Worker.ROLE_TRADER) @@ -76,7 +77,8 @@ TradeManager.prototype.trainMoreTraders = function(gameState, queues) // and the naval manager will train now more appropriate ships. let already = false; let shipToSwitch; - gameState.ai.HQ.navalManager.seaTransportShips[this.tradeRoute.sea].forEach(function(ship) { + gameState.ai.HQ.navalManager.seaTransportShips[this.tradeRoute.sea].forEach(function(ship) + { if (already || !ship.hasClass("Trader")) return; if (ship.getMetadata(PlayerID, "role") === Worker.ROLE_SWITCH_TO_TRADER) diff --git a/binaries/data/mods/public/simulation/ai/petra/transportPlan.js b/binaries/data/mods/public/simulation/ai/petra/transportPlan.js index a208db9bf1..39a4e52ffd 100644 --- a/binaries/data/mods/public/simulation/ai/petra/transportPlan.js +++ b/binaries/data/mods/public/simulation/ai/petra/transportPlan.js @@ -172,7 +172,8 @@ TransportPlan.prototype.assignShip = function(gameState) // and choose the nearest available ship from this unit let distmin = Math.min(); let nearest; - gameState.ai.HQ.navalManager.seaTransportShips[this.sea].forEach(ship => { + gameState.ai.HQ.navalManager.seaTransportShips[this.sea].forEach(ship => + { if (ship.getMetadata(PlayerID, "transporter")) return; if (pos) diff --git a/binaries/data/mods/public/simulation/ai/petra/victoryManager.js b/binaries/data/mods/public/simulation/ai/petra/victoryManager.js index 0896d59128..9492c21678 100644 --- a/binaries/data/mods/public/simulation/ai/petra/victoryManager.js +++ b/binaries/data/mods/public/simulation/ai/petra/victoryManager.js @@ -678,7 +678,8 @@ VictoryManager.prototype.captureGaiaRelic = function(gameState, relic) return; const relicPosition = relic.position(); const access = getLandAccess(gameState, relic); - const units = gameState.getOwnUnits().filter(ent => { + const units = gameState.getOwnUnits().filter(ent => + { if (!ent.position() || !ent.canCapture(relic)) return false; if (ent.getMetadata(PlayerID, "transport") !== undefined) diff --git a/binaries/data/mods/public/simulation/ai/petra/worker.js b/binaries/data/mods/public/simulation/ai/petra/worker.js index 5a3d0dec23..00a7ee7cb6 100644 --- a/binaries/data/mods/public/simulation/ai/petra/worker.js +++ b/binaries/data/mods/public/simulation/ai/petra/worker.js @@ -481,7 +481,8 @@ Worker.prototype.startGathering = function(gameState) if (resource == "food" && this.startHunting(gameState)) return true; - const findSupply = function(worker, supplies) { + const findSupply = function(worker, supplies) + { const ent = worker.ent; let ret = false; const gatherRates = ent.resourceGatherRates(); @@ -611,7 +612,8 @@ Worker.prototype.startGathering = function(gameState) // Okay may-be we haven't found any appropriate dropsite anywhere. // Try to help building one if any accessible foundation available const foundations = gameState.getOwnFoundations().toEntityArray(); - let shouldBuild = this.ent.isBuilder() && foundations.some(function(foundation) { + let shouldBuild = this.ent.isBuilder() && foundations.some(function(foundation) + { if (!foundation || getLandAccess(gameState, foundation) != this.entAccess) return false; const structure = gameState.getBuiltTemplate(foundation.templateName()); @@ -678,7 +680,8 @@ Worker.prototype.startGathering = function(gameState) } // Okay so we haven't found any appropriate dropsite anywhere. // Try to help building one if any non-accessible foundation available - shouldBuild = this.ent.isBuilder() && foundations.some(function(foundation) { + shouldBuild = this.ent.isBuilder() && foundations.some(function(foundation) + { if (!foundation || getLandAccess(gameState, foundation) == this.entAccess) return false; const structure = gameState.getBuiltTemplate(foundation.templateName()); @@ -889,7 +892,8 @@ Worker.prototype.startFishing = function(gameState) const fishDropsites = (gameState.playerData.hasSharedDropsites ? gameState.getAnyDropsites("food") : gameState.getOwnDropsites("food")).filter(filters.byClass("Dock")).toEntityArray(); - const nearestDropsiteDist = function(supply) { + const nearestDropsiteDist = function(supply) + { let distMin = 1000000; const pos = supply.position(); for (const dropsite of fishDropsites) @@ -909,7 +913,8 @@ Worker.prototype.startFishing = function(gameState) let exhausted = true; const gatherRates = this.ent.resourceGatherRates(); - resources.forEach((supply) => { + resources.forEach((supply) => + { if (!supply.position()) return; diff --git a/binaries/data/mods/public/simulation/components/AlertRaiser.js b/binaries/data/mods/public/simulation/components/AlertRaiser.js index bde802ad34..904c068f4a 100644 --- a/binaries/data/mods/public/simulation/components/AlertRaiser.js +++ b/binaries/data/mods/public/simulation/components/AlertRaiser.js @@ -59,7 +59,8 @@ AlertRaiser.prototype.RaiseAlert = function() const size = cmpGarrisonable.TotalSize(); const cmpUnitAI = Engine.QueryInterface(unit, IID_UnitAI); - const holder = cmpRangeManager.ExecuteQuery(unit, 0, +this.template.SearchRange, mutualAllies, IID_GarrisonHolder, true).find(ent => { + const holder = cmpRangeManager.ExecuteQuery(unit, 0, +this.template.SearchRange, mutualAllies, IID_GarrisonHolder, true).find(ent => + { // Ignore moving garrison holders if (Engine.QueryInterface(ent, IID_UnitAI)) return false; @@ -130,7 +131,8 @@ AlertRaiser.prototype.EndOfAlert = function() continue; const cmpGarrisonHolder = Engine.QueryInterface(holder, IID_GarrisonHolder); - const garrisonedUnits = cmpGarrisonHolder.GetEntities().filter(ent => { + const garrisonedUnits = cmpGarrisonHolder.GetEntities().filter(ent => + { const cmpOwner = Engine.QueryInterface(ent, IID_Ownership); return cmpOwner && cmpOwner.GetOwner() == owner && this.UnitFilter(ent); }); diff --git a/binaries/data/mods/public/simulation/components/Attack.js b/binaries/data/mods/public/simulation/components/Attack.js index 774c22ce62..9f9ae91909 100644 --- a/binaries/data/mods/public/simulation/components/Attack.js +++ b/binaries/data/mods/public/simulation/components/Attack.js @@ -380,7 +380,8 @@ Attack.prototype.GetBestAttackAgainst = function(target, allowCapture) return "Slaughter"; const targetClasses = cmpIdentity.GetClassesList(); - const getPreferrence = attackType => { + const getPreferrence = attackType => + { let pref = 0; if (MatchesClassList(targetClasses, this.GetPreferredClasses(attackType))) pref += 2; @@ -389,7 +390,8 @@ Attack.prototype.GetBestAttackAgainst = function(target, allowCapture) return pref; }; - return types.filter(type => this.CanAttack(target, [type])).sort((a, b) => { + return types.filter(type => this.CanAttack(target, [type])).sort((a, b) => + { const prefA = getPreferrence(a); const prefB = getPreferrence(b); return (types.indexOf(a) + (prefA > 0 ? prefA + types.length : 0)) - @@ -468,7 +470,8 @@ Attack.prototype.GetAttackYOrigin = function(type) return ApplyValueModificationsToEntity("Attack/" + type + "/Origin/Y", +this.template[type].Origin.Y, this.entity); }; -Attack.prototype.RepeatRangeCheck = function(type) { +Attack.prototype.RepeatRangeCheck = function(type) +{ if (!this.IsTargetInRange(this.target, type)) this.StopAttacking("OutOfRange"); }; diff --git a/binaries/data/mods/public/simulation/components/Auras.js b/binaries/data/mods/public/simulation/components/Auras.js index ad5369e142..f3bac47091 100644 --- a/binaries/data/mods/public/simulation/components/Auras.js +++ b/binaries/data/mods/public/simulation/components/Auras.js @@ -308,7 +308,8 @@ Auras.prototype.Clean = function() Auras.prototype.GiveMembersWithValidClass = function(auraName, entityList) { var match = this.GetClasses(auraName); - return entityList.filter(ent => { + return entityList.filter(ent => + { const cmpIdentity = Engine.QueryInterface(ent, IID_Identity); return cmpIdentity && MatchesClassList(cmpIdentity.GetClassesList(), match); }); diff --git a/binaries/data/mods/public/simulation/components/BuildingAI.js b/binaries/data/mods/public/simulation/components/BuildingAI.js index e0fab70a8b..929bb83feb 100644 --- a/binaries/data/mods/public/simulation/components/BuildingAI.js +++ b/binaries/data/mods/public/simulation/components/BuildingAI.js @@ -178,7 +178,8 @@ BuildingAI.prototype.OnRangeUpdate = function(msg) // Target enemy units except non-dangerous animals. if (msg.tag == this.gaiaUnitsQuery) { - msg.added = msg.added.filter(e => { + msg.added = msg.added.filter(e => + { const cmpUnitAI = Engine.QueryInterface(e, IID_UnitAI); return cmpUnitAI && (!cmpUnitAI.IsAnimal() || cmpUnitAI.IsDangerousAnimal()); }); @@ -347,7 +348,8 @@ BuildingAI.prototype.FireArrows = function() for (const target of this.targetUnits) addTarget(target); // Sort targets by preference and then by proximity. - targets.sort((a, b) => { + targets.sort((a, b) => + { if (a.preference > b.preference) return 1; else if (a.preference < b.preference) diff --git a/binaries/data/mods/public/simulation/components/Formation.js b/binaries/data/mods/public/simulation/components/Formation.js index 1ea70dae04..519259eef8 100644 --- a/binaries/data/mods/public/simulation/components/Formation.js +++ b/binaries/data/mods/public/simulation/components/Formation.js @@ -565,13 +565,13 @@ Formation.prototype.ArrangeFormation = function(moveCenter, force, variant) } const data = - { - "target": this.entity, - "x": offset.x, - "z": offset.y, - "offsetsChanged": offsetsChanged, - "variant": variant - }; + { + "target": this.entity, + "x": offset.x, + "z": offset.y, + "offsetsChanged": offsetsChanged, + "variant": variant + }; cmpUnitAI.AddOrder("FormationWalk", data, !force); xMax = Math.max(xMax, offset.x); yMax = Math.max(yMax, offset.y); @@ -789,7 +789,8 @@ Formation.prototype.ComputeFormationOffsets = function(active, positions) if (this.sortingOrder == "fillFromTheSides") offsets.sort(function(o1, o2) { return Math.abs(o1.x) < Math.abs(o2.x);}); else if (this.sortingOrder == "fillToTheCenter") - offsets.sort(function(o1, o2) { + offsets.sort(function(o1, o2) + { return Math.max(Math.abs(o1.x), Math.abs(o1.y)) < Math.max(Math.abs(o2.x), Math.abs(o2.y)); }); @@ -1035,7 +1036,8 @@ Formation.prototype.LoadFormation = function(newTemplate) * @param {boolean} force - Force rearrangement regardless of state * @param {string} formationType - Formation variant to be passed as order parameter. */ -Formation.prototype.UpdateFormation = function(moveCenter = false, force = false, formationType = "default") { +Formation.prototype.UpdateFormation = function(moveCenter = false, force = false, formationType = "default") +{ // Move members into appropriate formation type if (this.IsRearrangementAllowed() || force) this.ArrangeFormation(moveCenter, force, formationType); diff --git a/binaries/data/mods/public/simulation/components/GarrisonHolder.js b/binaries/data/mods/public/simulation/components/GarrisonHolder.js index 5a8c820011..be266ee459 100644 --- a/binaries/data/mods/public/simulation/components/GarrisonHolder.js +++ b/binaries/data/mods/public/simulation/components/GarrisonHolder.js @@ -289,7 +289,8 @@ GarrisonHolder.prototype.UnloadTemplate = function(template, owner, all) */ GarrisonHolder.prototype.UnloadAllByOwner = function(owner) { - const entities = this.entities.filter(ent => { + const entities = this.entities.filter(ent => + { const cmpOwnership = Engine.QueryInterface(ent, IID_Ownership); return cmpOwnership && cmpOwnership.GetOwner() == owner; }); diff --git a/binaries/data/mods/public/simulation/components/GuiInterface.js b/binaries/data/mods/public/simulation/components/GuiInterface.js index 1098ce8abb..c3b375f445 100644 --- a/binaries/data/mods/public/simulation/components/GuiInterface.js +++ b/binaries/data/mods/public/simulation/components/GuiInterface.js @@ -868,7 +868,8 @@ GuiInterface.prototype.GetFormationInfoFromTemplate = function(player, data) GuiInterface.prototype.IsFormationSelected = function(player, data) { - return data.ents.some(ent => { + return data.ents.some(ent => + { const cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI); return cmpUnitAI && cmpUnitAI.GetFormationTemplate() == data.formationTemplate; }); @@ -903,7 +904,8 @@ GuiInterface.prototype.GetAllBuildableEntities = function(player, cmd) GuiInterface.prototype.UpdateDisplayedPlayerColors = function(player, data) { - const updateEntityColor = (iids, entities) => { + const updateEntityColor = (iids, entities) => + { for (const ent of entities) for (const iid of iids) { @@ -1986,7 +1988,8 @@ GuiInterface.prototype.SetObstructionDebugOverlay = function(player, enabled) GuiInterface.prototype.SetMotionDebugOverlay = function(player, data) { - data.entities.forEach(ent => { + data.entities.forEach(ent => + { Engine.QueryInterface(ent, IID_UnitMotion)?.SetDebugOverlay(data.enabled); }); }; diff --git a/binaries/data/mods/public/simulation/components/ModifiersManager.js b/binaries/data/mods/public/simulation/components/ModifiersManager.js index a2a3b3abcc..fe58c301a7 100644 --- a/binaries/data/mods/public/simulation/components/ModifiersManager.js +++ b/binaries/data/mods/public/simulation/components/ModifiersManager.js @@ -228,7 +228,8 @@ ModifiersManager.prototype.OnGlobalOwnershipChanged = function(msg) // Warn entities that our values have changed. // Local modifiers will be added by the relevant components, so no need to check for them here. const modifiedComponents = {}; - const fetchPlayerModifiedValueNames = (owner) => { + const fetchPlayerModifiedValueNames = (owner) => + { if (!owner) return; const playerModifs = this.modifiersStorage.GetAllItems(owner); @@ -238,7 +239,8 @@ ModifiersManager.prototype.OnGlobalOwnershipChanged = function(msg) const component = propertyName.split("/")[0]; // Only inform if the modifier actually applies to the entity as an optimisation. // TODO: would it be better to call FetchModifiedProperty here and compare values? - playerModifs[propertyName].forEach(item => item.value.forEach(modif => { + playerModifs[propertyName].forEach(item => item.value.forEach(modif => + { if (!DoesModificationApply(modif, classes)) return; if (!modifiedComponents[component]) @@ -259,35 +261,43 @@ ModifiersManager.prototype.OnGlobalOwnershipChanged = function(msg) /** * The following functions simply proxy MultiKeyMap's interface. */ -ModifiersManager.prototype.AddModifier = function(propName, ModifID, Modif, entity, stackable = false) { +ModifiersManager.prototype.AddModifier = function(propName, ModifID, Modif, entity, stackable = false) +{ return this.modifiersStorage.AddItem(propName, ModifID, Modif, entity, stackable); }; -ModifiersManager.prototype.AddModifiers = function(ModifID, Modifs, entity, stackable = false) { +ModifiersManager.prototype.AddModifiers = function(ModifID, Modifs, entity, stackable = false) +{ return this.modifiersStorage.AddItems(ModifID, Modifs, entity, stackable); }; -ModifiersManager.prototype.RemoveModifier = function(propName, ModifID, entity, stackable = false) { +ModifiersManager.prototype.RemoveModifier = function(propName, ModifID, entity, stackable = false) +{ return this.modifiersStorage.RemoveItem(propName, ModifID, entity, stackable); }; -ModifiersManager.prototype.RemoveAllModifiers = function(ModifID, entity, stackable = false) { +ModifiersManager.prototype.RemoveAllModifiers = function(ModifID, entity, stackable = false) +{ return this.modifiersStorage.RemoveAllItems(ModifID, entity, stackable); }; -ModifiersManager.prototype.HasModifier = function(propName, ModifID, entity) { +ModifiersManager.prototype.HasModifier = function(propName, ModifID, entity) +{ return this.modifiersStorage.HasItem(propName, ModifID, entity); }; -ModifiersManager.prototype.HasAnyModifier = function(ModifID, entity) { +ModifiersManager.prototype.HasAnyModifier = function(ModifID, entity) +{ return this.modifiersStorage.HasAnyItem(ModifID, entity); }; -ModifiersManager.prototype.GetModifiers = function(propName, entity, stackable = false) { +ModifiersManager.prototype.GetModifiers = function(propName, entity, stackable = false) +{ return this.modifiersStorage.GetItems(propName, entity, stackable); }; -ModifiersManager.prototype.GetAllModifiers = function(entity, stackable = false) { +ModifiersManager.prototype.GetAllModifiers = function(entity, stackable = false) +{ return this.modifiersStorage.GetAllItems(entity, stackable); }; diff --git a/binaries/data/mods/public/simulation/components/MotionBall.js b/binaries/data/mods/public/simulation/components/MotionBall.js index 4eed7ae2ac..2425e3cdcd 100644 --- a/binaries/data/mods/public/simulation/components/MotionBall.js +++ b/binaries/data/mods/public/simulation/components/MotionBall.js @@ -3,12 +3,14 @@ function MotionBallScripted() {} MotionBallScripted.prototype.Schema = ""; -MotionBallScripted.prototype.Init = function() { +MotionBallScripted.prototype.Init = function() +{ this.speedX = 0; this.speedZ = 0; }; -MotionBallScripted.prototype.OnUpdate = function(msg) { +MotionBallScripted.prototype.OnUpdate = function(msg) +{ var dt = msg.turnLength; var cmpPos = Engine.QueryInterface(this.entity, IID_Position); diff --git a/binaries/data/mods/public/simulation/components/PopulationCapManager.js b/binaries/data/mods/public/simulation/components/PopulationCapManager.js index 1726cc5b72..68e860efcc 100644 --- a/binaries/data/mods/public/simulation/components/PopulationCapManager.js +++ b/binaries/data/mods/public/simulation/components/PopulationCapManager.js @@ -121,7 +121,8 @@ PopulationCapManager.prototype.InitializeTeamPopCaps = function() PopulationCapManager.prototype.RedistributeTeamPopCap = function(team) { const activePlayers = Engine.QueryInterface(SYSTEM_ENTITY, IID_PlayerManager).GetActivePlayers(); - const teamMembers = activePlayers.reduce((list, player) => { + const teamMembers = activePlayers.reduce((list, player) => + { if (QueryPlayerIDInterface(player, IID_Diplomacy).GetTeam() === team) list.push(player); return list; diff --git a/binaries/data/mods/public/simulation/components/SkirmishReplacer.js b/binaries/data/mods/public/simulation/components/SkirmishReplacer.js index 166222fb8f..d481437421 100644 --- a/binaries/data/mods/public/simulation/components/SkirmishReplacer.js +++ b/binaries/data/mods/public/simulation/components/SkirmishReplacer.js @@ -1,13 +1,13 @@ function SkirmishReplacer() {} SkirmishReplacer.prototype.Schema = - "" + - "" + - "" + - "" + - "" + - "" + - ""; + "" + + "" + + "" + + "" + + "" + + "" + + ""; SkirmishReplacer.prototype.Init = function() { diff --git a/binaries/data/mods/public/simulation/components/TechnologyManager.js b/binaries/data/mods/public/simulation/components/TechnologyManager.js index cf06f0d181..dadd550900 100644 --- a/binaries/data/mods/public/simulation/components/TechnologyManager.js +++ b/binaries/data/mods/public/simulation/components/TechnologyManager.js @@ -339,8 +339,10 @@ TechnologyManager.prototype.CheckTechnologyRequirements = function(reqs, civonly if (civonly || !reqs.length) return true; - return reqs.some(req => { - return Object.keys(req).every(type => { + return reqs.some(req => + { + return Object.keys(req).every(type => + { switch (type) { case "techs": diff --git a/binaries/data/mods/public/simulation/components/TerritoryDecayManager.js b/binaries/data/mods/public/simulation/components/TerritoryDecayManager.js index 49fa8b0e64..4f3953cb6a 100644 --- a/binaries/data/mods/public/simulation/components/TerritoryDecayManager.js +++ b/binaries/data/mods/public/simulation/components/TerritoryDecayManager.js @@ -1,7 +1,7 @@ function TerritoryDecayManager() {} TerritoryDecayManager.prototype.Schema = - ""; + ""; TerritoryDecayManager.prototype.Init = function() { diff --git a/binaries/data/mods/public/simulation/components/Timer.js b/binaries/data/mods/public/simulation/components/Timer.js index 13ff24e9be..27ec937cb6 100644 --- a/binaries/data/mods/public/simulation/components/Timer.js +++ b/binaries/data/mods/public/simulation/components/Timer.js @@ -114,7 +114,8 @@ Timer.prototype.OnUpdate = function(msg) // (We do this in two stages to avoid deleting from the timer list while // we're in the middle of iterating through it) const run = []; - this.timers.forEach((timer, id) => { + this.timers.forEach((timer, id) => + { if (timer.time <= this.time) run.push(id); }); @@ -139,7 +140,7 @@ Timer.prototype.OnUpdate = function(msg) { timerTargetComponent[timer.functionName](timer.data, this.time - timer.time); } - catch (e) + catch(e) { error( "Error in timer on entity " + timer.entity + ", " + diff --git a/binaries/data/mods/public/simulation/components/Trainer.js b/binaries/data/mods/public/simulation/components/Trainer.js index dd625651e1..f85467e948 100644 --- a/binaries/data/mods/public/simulation/components/Trainer.js +++ b/binaries/data/mods/public/simulation/components/Trainer.js @@ -502,7 +502,8 @@ Trainer.prototype.CalculateEntitiesMap = function() * This also updates currently queued production (it's more convenient to do it here). */ - const removeAllQueuedTemplate = (token) => { + const removeAllQueuedTemplate = (token) => + { const queue = clone(this.queue); const template = this.entitiesMap.get(token); for (const [id, item] of queue) @@ -511,7 +512,8 @@ Trainer.prototype.CalculateEntitiesMap = function() }; // ToDo: Notice this doesn't account for entity limits changing due to the template change. - const updateAllQueuedTemplate = (token, updateTo) => { + const updateAllQueuedTemplate = (token, updateTo) => + { const template = this.entitiesMap.get(token); for (const [id, item] of this.queue) if (item.templateName === template) @@ -526,7 +528,8 @@ Trainer.prototype.CalculateEntitiesMap = function() const playerCiv = QueryOwnerInterface(this.entity, IID_Identity)?.GetCiv(); const addedDict = addedTokens.reduce((out, token) => { out[token] = true; return out; }, {}); - this.entitiesMap = toks.reduce((entMap, token) => { + this.entitiesMap = toks.reduce((entMap, token) => + { const rawToken = token; if (!(token in addedDict)) { diff --git a/binaries/data/mods/public/simulation/components/Trigger.js b/binaries/data/mods/public/simulation/components/Trigger.js index bedac796c0..3d8b4c8e34 100644 --- a/binaries/data/mods/public/simulation/components/Trigger.js +++ b/binaries/data/mods/public/simulation/components/Trigger.js @@ -7,28 +7,28 @@ Trigger.prototype.Schema = * Events we're able to receive and call handlers for. */ Trigger.prototype.eventNames = -[ - "OnAttackDetected", - "OnCinemaPathEnded", - "OnCinemaQueueEnded", - "OnConstructionStarted", - "OnDiplomacyChanged", - "OnDeserialized", - "OnInitGame", - "OnInterval", - "OnEntityRenamed", - "OnOwnershipChanged", - "OnPlayerCommand", - "OnPlayerDefeated", - "OnPlayerWon", - "OnRange", - "OnResearchFinished", - "OnResearchQueued", - "OnStructureBuilt", - "OnTrainingFinished", - "OnTrainingQueued", - "OnTreasureCollected" -]; + [ + "OnAttackDetected", + "OnCinemaPathEnded", + "OnCinemaQueueEnded", + "OnConstructionStarted", + "OnDiplomacyChanged", + "OnDeserialized", + "OnInitGame", + "OnInterval", + "OnEntityRenamed", + "OnOwnershipChanged", + "OnPlayerCommand", + "OnPlayerDefeated", + "OnPlayerWon", + "OnRange", + "OnResearchFinished", + "OnResearchQueued", + "OnStructureBuilt", + "OnTrainingFinished", + "OnTrainingQueued", + "OnTreasureCollected" + ]; Trigger.prototype.Init = function() { diff --git a/binaries/data/mods/public/simulation/components/UnitAI.js b/binaries/data/mods/public/simulation/components/UnitAI.js index 2e011362bd..5014a6e76d 100644 --- a/binaries/data/mods/public/simulation/components/UnitAI.js +++ b/binaries/data/mods/public/simulation/components/UnitAI.js @@ -195,49 +195,60 @@ UnitAI.prototype.UnitFsmSpec = { // Default event handlers: - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { // ignore spurious movement messages // (these can happen when stopping moving at the same time // as switching states) }, - "ConstructionFinished": function(msg) { + "ConstructionFinished": function(msg) + { // ignore uninteresting construction messages }, - "LosRangeUpdate": function(msg) { + "LosRangeUpdate": function(msg) + { // Ignore newly-seen units by default. }, - "LosHealRangeUpdate": function(msg) { + "LosHealRangeUpdate": function(msg) + { // Ignore newly-seen injured units by default. }, - "LosAttackRangeUpdate": function(msg) { + "LosAttackRangeUpdate": function(msg) + { // Ignore newly-seen enemy units by default. }, - "Attacked": function(msg) { + "Attacked": function(msg) + { // ignore attacker }, - "PackFinished": function(msg) { + "PackFinished": function(msg) + { // ignore }, - "PickupCanceled": function(msg) { + "PickupCanceled": function(msg) + { // ignore }, - "TradingCanceled": function(msg) { + "TradingCanceled": function(msg) + { // ignore }, - "GuardedAttacked": function(msg) { + "GuardedAttacked": function(msg) + { // ignore }, - "OrderTargetRenamed": function() { + "OrderTargetRenamed": function() + { // By default, trigger an exit-reenter // so that state preconditions are checked against the new entity // (there is no reason to assume the target is still valid). @@ -246,7 +257,8 @@ UnitAI.prototype.UnitFsmSpec = { // Formation handlers: - "FormationLeave": function(msg) { + "FormationLeave": function(msg) + { // Overloaded by FORMATIONMEMBER // We end up here if LeaveFormation was called when the entity // was executing an order in an individual state, so we must @@ -256,7 +268,8 @@ UnitAI.prototype.UnitFsmSpec = { }, // Called when being told to walk as part of a formation - "Order.FormationWalk": function(msg) { + "Order.FormationWalk": function(msg) + { if (!this.IsFormationMember() || !this.AbleToMove()) return this.FinishOrder(); @@ -277,7 +290,8 @@ UnitAI.prototype.UnitFsmSpec = { // Special orders: // (these will be overridden by various states) - "Order.LeaveFoundation": function(msg) { + "Order.LeaveFoundation": function(msg) + { if (!this.WillMoveFromFoundation(msg.data.target)) return this.FinishOrder(); msg.data.min = g_LeaveFoundationRange; @@ -287,7 +301,8 @@ UnitAI.prototype.UnitFsmSpec = { // Individual orders: - "Order.LeaveFormation": function() { + "Order.LeaveFormation": function() + { if (!this.IsFormationMember()) return this.FinishOrder(); @@ -297,12 +312,14 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Stop": function(msg) { + "Order.Stop": function(msg) + { this.FinishOrder(); return ACCEPT_ORDER; }, - "Order.Walk": function(msg) { + "Order.Walk": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); @@ -318,7 +335,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.WalkAndFight": function(msg) { + "Order.WalkAndFight": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); @@ -335,7 +353,8 @@ UnitAI.prototype.UnitFsmSpec = { }, - "Order.WalkToTarget": function(msg) { + "Order.WalkToTarget": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); @@ -354,7 +373,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.PickupUnit": function(msg) { + "Order.PickupUnit": function(msg) + { const cmpHolder = Engine.QueryInterface(this.entity, msg.data.iid); if (!cmpHolder || cmpHolder.IsFull()) return this.FinishOrder(); @@ -380,7 +400,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Guard": function(msg) { + "Order.Guard": function(msg) + { if (!this.AddGuard(msg.data.target)) return this.FinishOrder(); @@ -393,14 +414,16 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Flee": function(msg) { + "Order.Flee": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); this.SetNextState("INDIVIDUAL.FLEEING"); return ACCEPT_ORDER; }, - "Order.Attack": function(msg) { + "Order.Attack": function(msg) + { const type = this.GetBestAttackAgainst(msg.data.target, msg.data.allowCapture); if (!type) return this.FinishOrder(); @@ -442,7 +465,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Patrol": function(msg) { + "Order.Patrol": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); @@ -458,7 +482,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Heal": function(msg) { + "Order.Heal": function(msg) + { if (!this.TargetIsAlive(msg.data.target)) return this.FinishOrder(); @@ -481,7 +506,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Gather": function(msg) { + "Order.Gather": function(msg) + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (!cmpResourceGatherer) return this.FinishOrder(); @@ -555,7 +581,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.GatherNearPosition": function(msg) { + "Order.GatherNearPosition": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); this.SetNextState("INDIVIDUAL.GATHER.WALKING"); @@ -564,7 +591,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.DropAtNearestDropSite": function(msg) { + "Order.DropAtNearestDropSite": function(msg) + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (!cmpResourceGatherer) return this.FinishOrder(); @@ -575,7 +603,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.ReturnResource": function(msg) { + "Order.ReturnResource": function(msg) + { if (this.CheckTargetRange(msg.data.target, IID_ResourceGatherer)) this.SetNextState("INDIVIDUAL.RETURNRESOURCE.DROPPINGRESOURCES"); else if (this.AbleToMove()) @@ -585,7 +614,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Trade": function(msg) { + "Order.Trade": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); // We must check if this trader has both markets in case it was a back-to-work order. @@ -598,7 +628,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Repair": function(msg) { + "Order.Repair": function(msg) + { if (this.CheckTargetRange(msg.data.target, IID_Builder)) this.SetNextState("INDIVIDUAL.REPAIR.REPAIRING"); else if (this.AbleToMove()) @@ -608,7 +639,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Garrison": function(msg) { + "Order.Garrison": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); @@ -626,7 +658,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Ungarrison": function(msg) { + "Order.Ungarrison": function(msg) + { // Note that this order MUST succeed, or we break // the assumptions done in garrisonable/garrisonHolder, // especially in Unloading in the latter. (For user feedback.) @@ -635,32 +668,37 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Cheer": function(msg) { + "Order.Cheer": function(msg) + { return this.FinishOrder(); }, - "Order.Pack": function(msg) { + "Order.Pack": function(msg) + { if (!this.CanPack()) return this.FinishOrder(); this.SetNextState("INDIVIDUAL.PACKING"); return ACCEPT_ORDER; }, - "Order.Unpack": function(msg) { + "Order.Unpack": function(msg) + { if (!this.CanUnpack()) return this.FinishOrder(); this.SetNextState("INDIVIDUAL.UNPACKING"); return ACCEPT_ORDER; }, - "Order.MoveToChasingPoint": function(msg) { + "Order.MoveToChasingPoint": function(msg) + { // Overriden by the CHASING state. // Can however happen outside of it when renaming... // TODO: don't use an order for that behaviour. return this.FinishOrder(); }, - "Order.CollectTreasure": function(msg) { + "Order.CollectTreasure": function(msg) + { if (this.CheckTargetRange(msg.data.target, IID_TreasureCollector)) this.SetNextState("INDIVIDUAL.COLLECTTREASURE.COLLECTING"); else if (this.AbleToMove()) @@ -671,7 +709,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.CollectTreasureNearPosition": function(msg) { + "Order.CollectTreasureNearPosition": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); this.SetNextState("INDIVIDUAL.COLLECTTREASURE.WALKING"); @@ -683,7 +722,8 @@ UnitAI.prototype.UnitFsmSpec = { // States for the special entity representing a group of units moving in formation: "FORMATIONCONTROLLER": { - "Order.Walk": function(msg) { + "Order.Walk": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); this.CallMemberFunction("SetHeldPosition", [msg.data.x, msg.data.z]); @@ -691,7 +731,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.WalkAndFight": function(msg) { + "Order.WalkAndFight": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); this.CallMemberFunction("SetHeldPosition", [msg.data.x, msg.data.z]); @@ -699,7 +740,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.MoveIntoFormation": function(msg) { + "Order.MoveIntoFormation": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); this.CallMemberFunction("SetHeldPosition", [msg.data.x, msg.data.z]); @@ -708,7 +750,8 @@ UnitAI.prototype.UnitFsmSpec = { }, // Only used by other orders to walk there in formation. - "Order.WalkToTargetRange": function(msg) { + "Order.WalkToTargetRange": function(msg) + { if (this.CheckRange(msg.data)) return this.FinishOrder(); if (!this.AbleToMove()) @@ -717,7 +760,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.WalkToTarget": function(msg) { + "Order.WalkToTarget": function(msg) + { if (this.CheckRange(msg.data)) return this.FinishOrder(); if (!this.AbleToMove()) @@ -726,7 +770,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.WalkToPointRange": function(msg) { + "Order.WalkToPointRange": function(msg) + { if (this.CheckRange(msg.data)) return this.FinishOrder(); if (!this.AbleToMove()) @@ -735,7 +780,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Patrol": function(msg) { + "Order.Patrol": function(msg) + { if (!this.AbleToMove()) return this.FinishOrder(); this.CallMemberFunction("SetHeldPosition", [msg.data.x, msg.data.z]); @@ -743,13 +789,15 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Guard": function(msg) { + "Order.Guard": function(msg) + { this.CallMemberFunction("Guard", [msg.data.target, false]); Engine.QueryInterface(this.entity, IID_Formation).Disband(); return ACCEPT_ORDER; }, - "Order.Stop": function(msg) { + "Order.Stop": function(msg) + { const cmpFormation = Engine.QueryInterface(this.entity, IID_Formation); cmpFormation.ResetOrderVariant(); if (!this.IsAttackingAsFormation()) @@ -761,7 +809,8 @@ UnitAI.prototype.UnitFsmSpec = { // TODO: this should be improved in the formation reshaping code. }, - "Order.Attack": function(msg) { + "Order.Attack": function(msg) + { const target = msg.data.target; let formationTarget; const cmpTargetUnitAI = Engine.QueryInterface(target, IID_UnitAI); @@ -787,7 +836,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Garrison": function(msg) { + "Order.Garrison": function(msg) + { if (!Engine.QueryInterface(msg.data.target, msg.data.garrison ? IID_GarrisonHolder : IID_TurretHolder)) return this.FinishOrder(); @@ -803,7 +853,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Gather": function(msg) { + "Order.Gather": function(msg) + { if (this.MustKillGatherTarget(msg.data.target)) { // The target was visible when this order was given, @@ -855,7 +906,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.GatherNearPosition": function(msg) { + "Order.GatherNearPosition": function(msg) + { // TODO: on what should we base this range? if (!this.CheckPointRangeExplicit(msg.data.x, msg.data.z, 0, 20)) { @@ -870,7 +922,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Heal": function(msg) { + "Order.Heal": function(msg) + { // TODO: on what should we base this range? if (!this.CheckTargetRangeExplicit(msg.data.target, 0, 10)) { @@ -892,7 +945,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.CollectTreasure": function(msg) { + "Order.CollectTreasure": function(msg) + { // TODO: on what should we base this range? if (this.CheckTargetRangeExplicit(msg.data.target, 0, 20)) { @@ -909,7 +963,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.CollectTreasureNearPosition": function(msg) { + "Order.CollectTreasureNearPosition": function(msg) + { // TODO: on what should we base this range? if (!this.CheckPointRangeExplicit(msg.data.x, msg.data.z, 0, 20)) { @@ -922,7 +977,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Repair": function(msg) { + "Order.Repair": function(msg) + { // TODO: on what should we base this range? if (!this.CheckTargetRangeExplicit(msg.data.target, 0, 10)) { @@ -944,7 +1000,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.ReturnResource": function(msg) { + "Order.ReturnResource": function(msg) + { // TODO: on what should we base this range? if (!this.CheckTargetRangeExplicit(msg.data.target, 0, 10)) { @@ -966,21 +1023,24 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "Order.Pack": function(msg) { + "Order.Pack": function(msg) + { this.CallMemberFunction("Pack", [false]); this.SetNextState("MEMBER"); return ACCEPT_ORDER; }, - "Order.Unpack": function(msg) { + "Order.Unpack": function(msg) + { this.CallMemberFunction("Unpack", [false]); this.SetNextState("MEMBER"); return ACCEPT_ORDER; }, - "Order.DropAtNearestDropSite": function(msg) { + "Order.DropAtNearestDropSite": function(msg) + { this.CallMemberFunction("DropAtNearestDropSite", [false, false]); this.SetNextState("MEMBER"); @@ -988,19 +1048,22 @@ UnitAI.prototype.UnitFsmSpec = { }, "IDLE": { - "enter": function(msg) { + "enter": function(msg) + { // Start the timer on the next turn to catch up with potential stragglers. this.StartTimer(100, 2000); this.isIdle = true; return false; }, - "leave": function() { + "leave": function() + { this.isIdle = false; this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { const cmpFormation = Engine.QueryInterface(this.entity, IID_Formation); if (!cmpFormation) return; @@ -1011,7 +1074,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "WALKING": { - "enter": function() { + "enter": function() + { this.RequestFormationUpdate(true, true); this.StartTimer(100, 2000); @@ -1023,25 +1087,29 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopTimer(); this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.veryObstructed && !this.obstructionMitigationAttempted) this.AttemptObstructionMitigation(); else if (msg.likelyFailure || this.CheckRange(this.order.data)) this.FinishOrder(); }, - "Timer": function() { + "Timer": function() + { // Update Formation in case some members left. this.RequestFormationUpdate(false, true); } }, "WALKINGANDFIGHTING": { - "enter": function(msg) { + "enter": function(msg) + { this.RequestFormationUpdate(true, true, "combat"); if (!this.MoveTo(this.order.data)) { @@ -1053,12 +1121,14 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { Engine.ProfileStart("FindWalkAndFightTargets"); if (this.FindWalkAndFightTargets()) this.SetNextState("MEMBER"); @@ -1066,7 +1136,8 @@ UnitAI.prototype.UnitFsmSpec = { Engine.ProfileStop(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.veryObstructed && !this.obstructionMitigationAttempted) this.AttemptObstructionMitigation(); else if (msg.likelyFailure || this.CheckRange(this.order.data)) @@ -1075,7 +1146,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "PATROL": { - "enter": function() { + "enter": function() + { const cmpPosition = Engine.QueryInterface(this.entity, IID_Position); if (!cmpPosition || !cmpPosition.IsInWorld()) { @@ -1095,13 +1167,15 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { delete this.patrolStartPosOrder; this.SetDefaultAnimationVariant(); }, "PATROLLING": { - "enter": function() { + "enter": function() + { const cmpPosition = Engine.QueryInterface(this.entity, IID_Position); if (!cmpPosition || !cmpPosition.IsInWorld() || !this.MoveTo(this.order.data)) @@ -1115,12 +1189,14 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { // Force the units to stick together // TODO : better handling of formation patrolling // See https://gitea.wildfiregames.com/0ad/0ad/issues/8558 @@ -1130,7 +1206,8 @@ UnitAI.prototype.UnitFsmSpec = { this.SetNextState("MEMBER"); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.veryObstructed && !this.obstructionMitigationAttempted) { this.AttemptObstructionMitigation(); @@ -1149,19 +1226,22 @@ UnitAI.prototype.UnitFsmSpec = { }, "CHECKINGWAYPOINT": { - "enter": function() { + "enter": function() + { this.StartTimer(0, 1000); this.stopSurveying = 0; // TODO: pick a proper animation return false; }, - "leave": function() { + "leave": function() + { this.StopTimer(); delete this.stopSurveying; }, - "Timer": function(msg) { + "Timer": function(msg) + { if (this.stopSurveying >= +this.template.PatrolWaitTime) { this.FinishOrder(); @@ -1177,7 +1257,8 @@ UnitAI.prototype.UnitFsmSpec = { "GARRISON": { "APPROACHING": { - "enter": function() { + "enter": function() + { if (!this.MoveToTargetRange(this.order.data.target, this.order.data.garrison ? IID_Garrisonable : IID_Turretable)) { this.FinishOrder(); @@ -1195,7 +1276,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); if (this.pickup) { @@ -1204,14 +1286,16 @@ UnitAI.prototype.UnitFsmSpec = { } }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || msg.likelySuccess) this.SetNextState("GARRISONING"); }, }, "GARRISONING": { - "enter": function() { + "enter": function() + { this.CallMemberFunction(this.order.data.garrison ? "Garrison" : "OccupyTurret", [this.order.data.target, false]); // We might have been disbanded due to the lack of members. if (Engine.QueryInterface(this.entity, IID_Formation).GetMemberCount()) @@ -1222,7 +1306,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "FORMING": { - "enter": function() { + "enter": function() + { this.RequestFormationUpdate(true, true); if (!this.MoveTo(this.order.data)) @@ -1233,11 +1318,13 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (!msg.likelyFailure && !this.CheckRange(this.order.data)) return; @@ -1247,7 +1334,8 @@ UnitAI.prototype.UnitFsmSpec = { "COMBAT": { "APPROACHING": { - "enter": function() { + "enter": function() + { this.RequestFormationUpdate(true, true, "combat"); if (!this.MoveFormationToTargetAttackRange(this.order.data.target)) @@ -1258,11 +1346,13 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { let target = this.order.data.target; const cmpTargetUnitAI = Engine.QueryInterface(target, IID_UnitAI); if (cmpTargetUnitAI && cmpTargetUnitAI.IsFormationMember()) @@ -1278,7 +1368,8 @@ UnitAI.prototype.UnitFsmSpec = { "ATTACKING": { // Wait for individual members to finish - "enter": function(msg) { + "enter": function(msg) + { const target = this.order.data.target; if (!this.CheckFormationTargetAttackRange(target)) { @@ -1295,7 +1386,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "Timer": function(msg) { + "Timer": function(msg) + { const target = this.order.data.target; if (!this.CheckFormationTargetAttackRange(target)) { @@ -1309,7 +1401,8 @@ UnitAI.prototype.UnitFsmSpec = { } }, - "leave": function(msg) { + "leave": function(msg) + { this.StopTimer(); }, }, @@ -1317,7 +1410,8 @@ UnitAI.prototype.UnitFsmSpec = { // Wait for individual members to finish "MEMBER": { - "OrderTargetRenamed": function(msg) { + "OrderTargetRenamed": function(msg) + { // In general, don't react - we don't want to send spurious messages to members. // This looks odd for hunting however because we wait for all // entities to have clumped around the dead resource before proceeding @@ -1328,7 +1422,8 @@ UnitAI.prototype.UnitFsmSpec = { this.FinishOrder(); }, - "enter": function(msg) { + "enter": function(msg) + { // While waiting on members, the formation is more like // a group of unit and does not have a well-defined position, // so move the controller out of the world to enforce that. @@ -1340,7 +1435,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "Timer": function(msg) { + "Timer": function(msg) + { const cmpFormation = Engine.QueryInterface(this.entity, IID_Formation); if (cmpFormation && !cmpFormation.AreAllMembersFinished()) return; @@ -1351,7 +1447,8 @@ UnitAI.prototype.UnitFsmSpec = { this.FinishOrder(); }, - "leave": function(msg) { + "leave": function(msg) + { this.StopTimer(); // Update the held position so entities respond to orders. @@ -1368,7 +1465,8 @@ UnitAI.prototype.UnitFsmSpec = { // States for entities moving as part of a formation: "FORMATIONMEMBER": { - "FormationLeave": function(msg) { + "FormationLeave": function(msg) + { // Called when selecting units out of a formation // Stop moving as soon as the formation disbands // Keep current rotation @@ -1393,7 +1491,8 @@ UnitAI.prototype.UnitFsmSpec = { // Override the LeaveFoundation order since we're not doing // anything more important (and we might be stuck in the WALKING // state forever and need to get out of foundations in that case) - "Order.LeaveFoundation": function(msg) { + "Order.LeaveFoundation": function(msg) + { if (!this.WillMoveFromFoundation(msg.data.target)) return this.FinishOrder(); msg.data.min = g_LeaveFoundationRange; @@ -1401,7 +1500,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "enter": function() { + "enter": function() + { const cmpFormation = Engine.QueryInterface(this.formationController, IID_Formation); if (cmpFormation) { @@ -1414,7 +1514,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.SetDefaultAnimationVariant(); this.formationAnimationVariant = undefined; }, @@ -1424,7 +1525,8 @@ UnitAI.prototype.UnitFsmSpec = { "CHEERING": "INDIVIDUAL.CHEERING", "WALKING": { - "enter": function() { + "enter": function() + { const cmpUnitMotion = Engine.QueryInterface(this.entity, IID_UnitMotion); cmpUnitMotion.MoveToFormationOffset(this.order.data.target, this.order.data.x, this.order.data.z); if (this.order.data.offsetsChanged) @@ -1448,7 +1550,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { // Don't use the logic from unitMotion, as SetInPosition // has already given us a custom rotation // (or we failed to move and thus don't care.) @@ -1460,7 +1563,8 @@ UnitAI.prototype.UnitFsmSpec = { // Occurs when the unit has reached its destination and the controller // is done moving. The controller is notified. - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { // When walking in formation, we'll only get notified in case of failure // if the formation controller has stopped walking. // Formations can start lagging a lot if many entities request short path @@ -1473,7 +1577,8 @@ UnitAI.prototype.UnitFsmSpec = { // Special case used by Order.LeaveFoundation "WALKINGTOPOINT": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data)) { this.FinishOrder(); @@ -1482,11 +1587,13 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function() { + "MovementUpdate": function() + { if (!this.CheckRange(this.order.data)) return; this.FinishOrder(); @@ -1497,12 +1604,14 @@ UnitAI.prototype.UnitFsmSpec = { // States for entities not part of a formation: "INDIVIDUAL": { - "Attacked": function(msg) { + "Attacked": function(msg) + { if (this.GetStance().targetAttackersAlways || !this.order || !this.order.data || !this.order.data.force) this.RespondToTargetedEntities([msg.data.attacker]); }, - "GuardedAttacked": function(msg) { + "GuardedAttacked": function(msg) + { // do nothing if we have a forced order in queue before the guard order for (var i = 0; i < this.orderQueue.length; ++i) { @@ -1554,7 +1663,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "IDLE": { - "Order.Cheer": function() { + "Order.Cheer": function() + { // Do not cheer if there is no cheering time and we are not idle yet. if (!this.cheeringTime || !this.isIdle) return this.FinishOrder(); @@ -1563,7 +1673,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "enter": function() { + "enter": function() + { // Mark unit as idle internally, but delay idle behaviors and notifications // to prevent spurious state changes and infinite loops. this.isIdle = true; @@ -1582,7 +1693,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.isIdle = false; const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); @@ -1600,7 +1712,8 @@ UnitAI.prototype.UnitFsmSpec = { delete this.isIdleConfirmed; }, - "Attacked": function(msg) { + "Attacked": function(msg) + { if (this.isIdle && (this.GetStance().targetAttackersAlways || !this.order || !this.order.data || !this.order.data.force)) this.RespondToTargetedEntities([msg.data.attacker]); }, @@ -1610,22 +1723,26 @@ UnitAI.prototype.UnitFsmSpec = { // when receiving a Los*RangeUpdate on the same turn as the entity becomes idle // since this.FindNew*Targets is called in the timer. - "LosRangeUpdate": function(msg) { + "LosRangeUpdate": function(msg) + { if (this.isIdle && msg && msg.data && msg.data.added && msg.data.added.length) this.RespondToSightedEntities(msg.data.added); }, - "LosHealRangeUpdate": function(msg) { + "LosHealRangeUpdate": function(msg) + { if (this.isIdle && msg && msg.data && msg.data.added && msg.data.added.length) this.RespondToHealableEntities(msg.data.added); }, - "LosAttackRangeUpdate": function(msg) { + "LosAttackRangeUpdate": function(msg) + { if (this.isIdle && msg && msg.data && msg.data.added && msg.data.added.length && this.GetStance().targetVisibleEnemies) this.AttackEntitiesByPreference(msg.data.added); }, - "Timer": function(msg) { + "Timer": function(msg) + { if (this.isGuardOf) { this.Guard(this.isGuardOf, false); @@ -1667,49 +1784,57 @@ UnitAI.prototype.UnitFsmSpec = { }, "ROAMING": { - "enter": function() { + "enter": function() + { this.SetFacePointAfterMove(false); this.MoveRandomly(+this.template.RoamDistance); this.StartTimer(randIntInclusive(+this.template.RoamTimeMin, +this.template.RoamTimeMax)); return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.StopTimer(); this.SetFacePointAfterMove(true); }, - "Timer": function(msg) { + "Timer": function(msg) + { this.SetNextState("LINGERING"); }, - "MovementUpdate": function() { + "MovementUpdate": function() + { this.MoveRandomly(+this.template.RoamDistance); }, }, "LINGERING": { - "enter": function() { + "enter": function() + { // ToDo: rename animations? this.SelectAnimation("feeding"); this.StartTimer(randIntInclusive(+this.template.FeedTimeMin, +this.template.FeedTimeMax)); return false; }, - "leave": function() { + "leave": function() + { this.ResetAnimation(); this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { this.SetNextState("ROAMING"); }, }, }, "WALKING": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data)) { this.FinishOrder(); @@ -1718,11 +1843,13 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { // If it looks like the path is failing, and we are close enough stop anyways. // This avoids pathing for an unreachable goal and reduces lag considerably. if (msg.likelyFailure || msg.obstructed && this.RelaxedMaxRangeCheck(this.order.data, this.DefaultRelaxedMaxRange) || @@ -1732,7 +1859,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "WALKINGANDFIGHTING": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data)) { this.FinishOrder(); @@ -1745,17 +1873,20 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "Timer": function(msg) { + "Timer": function(msg) + { this.FindWalkAndFightTargets(); }, - "leave": function(msg) { + "leave": function(msg) + { this.StopMoving(); this.StopTimer(); this.SetDefaultAnimationVariant(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { // If it looks like the path is failing, and we are close enough stop anyways. // This avoids pathing for an unreachable goal and reduces lag considerably. if (msg.likelyFailure || msg.obstructed && this.RelaxedMaxRangeCheck(this.order.data, this.DefaultRelaxedMaxRange) || @@ -1765,7 +1896,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "PATROL": { - "enter": function() { + "enter": function() + { const cmpPosition = Engine.QueryInterface(this.entity, IID_Position); if (!cmpPosition || !cmpPosition.IsInWorld()) { @@ -1786,13 +1918,15 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { delete this.patrolStartPosOrder; this.SetDefaultAnimationVariant(); }, "PATROLLING": { - "enter": function() { + "enter": function() + { const cmpPosition = Engine.QueryInterface(this.entity, IID_Position); if (!cmpPosition || !cmpPosition.IsInWorld() || !this.MoveTo(this.order.data)) @@ -1804,16 +1938,19 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { this.FindWalkAndFightTargets(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (!msg.likelyFailure && !msg.likelySuccess && !this.RelaxedMaxRangeCheck(this.order.data, this.DefaultRelaxedMaxRange)) return; @@ -1826,19 +1963,22 @@ UnitAI.prototype.UnitFsmSpec = { }, "CHECKINGWAYPOINT": { - "enter": function() { + "enter": function() + { this.StartTimer(0, 1000); this.stopSurveying = 0; // TODO: pick a proper animation return false; }, - "leave": function() { + "leave": function() + { this.StopTimer(); delete this.stopSurveying; }, - "Timer": function(msg) { + "Timer": function(msg) + { if (this.stopSurveying >= +this.template.PatrolWaitTime) { this.FinishOrder(); @@ -1851,12 +1991,14 @@ UnitAI.prototype.UnitFsmSpec = { }, "GUARD": { - "RemoveGuard": function() { + "RemoveGuard": function() + { this.FinishOrder(); }, "ESCORTING": { - "enter": function() { + "enter": function() + { if (!this.MoveToTargetRangeExplicit(this.isGuardOf, 0, this.guardRange)) { this.FinishOrder(); @@ -1871,7 +2013,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "Timer": function(msg) { + "Timer": function(msg) + { if (!this.ShouldGuard(this.isGuardOf)) { this.FinishOrder(); @@ -1885,20 +2028,23 @@ UnitAI.prototype.UnitFsmSpec = { this.SetHeldPositionOnEntity(this.isGuardOf); }, - "leave": function(msg) { + "leave": function(msg) + { this.StopMoving(); this.StopTimer(); this.SetDefaultAnimationVariant(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || this.CheckTargetRangeExplicit(this.isGuardOf, 0, this.guardRange)) this.SetNextState("GUARDING"); }, }, "GUARDING": { - "enter": function() { + "enter": function() + { this.StartTimer(1000, 1000); this.SetHeldPositionOnEntity(this.entity); this.SetAnimationVariant("combat"); @@ -1906,12 +2052,14 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "LosAttackRangeUpdate": function(msg) { + "LosAttackRangeUpdate": function(msg) + { if (this.GetStance().targetVisibleEnemies) this.AttackEntitiesByPreference(msg.data.added); }, - "Timer": function(msg) { + "Timer": function(msg) + { if (!this.ShouldGuard(this.isGuardOf)) { this.FinishOrder(); @@ -1935,7 +2083,8 @@ UnitAI.prototype.UnitFsmSpec = { } }, - "leave": function(msg) { + "leave": function(msg) + { this.StopTimer(); this.SetDefaultAnimationVariant(); }, @@ -1943,7 +2092,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "FLEEING": { - "enter": function() { + "enter": function() + { // We use the distance between the entities to account for ranged attacks this.order.data.distanceToFlee = PositionHelper.DistanceBetweenEntities(this.entity, this.order.data.target) + (+this.template.FleeDistance); const cmpUnitMotion = Engine.QueryInterface(this.entity, IID_UnitMotion); @@ -1961,7 +2111,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "OrderTargetRenamed": function(msg) { + "OrderTargetRenamed": function(msg) + { // To avoid replaying the panic sound, handle this explicitly. const cmpUnitMotion = Engine.QueryInterface(this.entity, IID_UnitMotion); if (this.CheckTargetRangeExplicit(this.order.data.target, this.order.data.distanceToFlee, -1) || @@ -1969,7 +2120,8 @@ UnitAI.prototype.UnitFsmSpec = { this.FinishOrder(); }, - "Attacked": function(msg) { + "Attacked": function(msg) + { if (msg.data.attacker == this.order.data.target) return; @@ -1981,36 +2133,42 @@ UnitAI.prototype.UnitFsmSpec = { this.RespondToTargetedEntities([msg.data.attacker]); }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || this.CheckTargetRangeExplicit(this.order.data.target, this.order.data.distanceToFlee, -1)) this.FinishOrder(); }, }, "COMBAT": { - "Order.LeaveFoundation": function(msg) { + "Order.LeaveFoundation": function(msg) + { // Ignore the order as we're busy. return this.FinishOrder(); }, - "Attacked": function(msg) { + "Attacked": function(msg) + { // If we're already in combat mode, ignore anyone else who's attacking us // unless it's a melee attack since they may be blocking our way to the target if (msg.data.type == "Melee" && (this.GetStance().targetAttackersAlways || !this.order.data.force)) this.RespondToTargetedEntities([msg.data.attacker]); }, - "leave": function() { + "leave": function() + { if (!this.formationAnimationVariant) this.SetDefaultAnimationVariant(); }, "APPROACHING": { - "enter": function() { + "enter": function() + { // Set this.order.data.target and this.order.formationTarget. // Should only mutate these once, when receiving a order with // a formation controller as target. @@ -2029,12 +2187,14 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { if (this.ShouldAbandonChase(this.order.data.target, this.order.data.force, IID_Attack, this.order.data.attackType)) { this.FinishOrder(); @@ -2051,7 +2211,8 @@ UnitAI.prototype.UnitFsmSpec = { } }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure) { // This also handles hunting. @@ -2095,7 +2256,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "ATTACKING": { - "enter": function() { + "enter": function() + { // Set this.order.data.target and this.order.formationTarget. // Should only mutate these once, when receiving a order with // a formation controller as target. @@ -2152,7 +2314,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { const cmpBuildingAI = Engine.QueryInterface(this.entity, IID_BuildingAI); if (cmpBuildingAI) cmpBuildingAI.SetUnitAITarget(0); @@ -2161,7 +2324,8 @@ UnitAI.prototype.UnitFsmSpec = { cmpAttack.StopAttacking(); }, - "OutOfRange": function() { + "OutOfRange": function() + { if (this.ShouldChaseTargetedEntity(this.order.data.target, this.order.data.force)) { if (this.CanPack()) @@ -2175,11 +2339,13 @@ UnitAI.prototype.UnitFsmSpec = { this.SetNextState("FINDINGNEWTARGET"); }, - "TargetInvalidated": function() { + "TargetInvalidated": function() + { this.SetNextState("FINDINGNEWTARGET"); }, - "Attacked": function(msg) { + "Attacked": function(msg) + { if (this.order.data.attackType == "Capture" && (this.GetStance().targetAttackersAlways || !this.order.data.force) && this.order.data.target != msg.data.attacker && this.GetBestAttackAgainst(msg.data.attacker, true) != "Capture") this.RespondToTargetedEntities([msg.data.attacker]); @@ -2187,7 +2353,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "FINDINGNEWTARGET": { - "Order.Cheer": function() { + "Order.Cheer": function() + { if (!this.cheeringTime) return this.FinishOrder(); @@ -2195,7 +2362,8 @@ UnitAI.prototype.UnitFsmSpec = { return ACCEPT_ORDER; }, - "enter": function() { + "enter": function() + { // Check if we are attacking a formation. let cmpFormation = Engine.QueryInterface(this.order.data.target, IID_Formation); if (cmpFormation) @@ -2249,7 +2417,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "CHASING": { - "Order.MoveToChasingPoint": function(msg) { + "Order.MoveToChasingPoint": function(msg) + { if (this.CheckPointRangeExplicit(msg.data.x, msg.data.z, 0, msg.data.max) || !this.AbleToMove()) return this.FinishOrder(); msg.data.relaxed = true; @@ -2257,7 +2426,8 @@ UnitAI.prototype.UnitFsmSpec = { this.SetNextState("MOVINGTOPOINT"); return ACCEPT_ORDER; }, - "enter": function() { + "enter": function() + { if (!this.MoveToTargetAttackRange(this.order.data.target, this.order.data.attackType)) { this.FinishOrder(); @@ -2274,12 +2444,14 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { if (this.ShouldAbandonChase(this.order.data.target, this.order.data.force, IID_Attack, this.order.data.attackType)) { this.FinishOrder(); @@ -2296,7 +2468,8 @@ UnitAI.prototype.UnitFsmSpec = { } }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure) { // This also handles hunting. @@ -2339,7 +2512,8 @@ UnitAI.prototype.UnitFsmSpec = { this.FinishOrder(); }, "MOVINGTOPOINT": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data)) { this.FinishOrder(); @@ -2347,10 +2521,12 @@ UnitAI.prototype.UnitFsmSpec = { } return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { // If it looks like the path is failing, and we are close enough from wanted range // stop anyways. This avoids pathing for an unreachable goal and reduces lag considerably. if (msg.likelyFailure || @@ -2363,14 +2539,16 @@ UnitAI.prototype.UnitFsmSpec = { }, "GATHER": { - "enter": function() { + "enter": function() + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (cmpResourceGatherer) cmpResourceGatherer.AddToPlayerCounter(this.order.data.type.generic); return false; }, - "leave": function() { + "leave": function() + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (cmpResourceGatherer) cmpResourceGatherer.RemoveFromPlayerCounter(); @@ -2380,7 +2558,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "APPROACHING": { - "enter": function() { + "enter": function() + { this.gatheringTarget = this.order.data.target; // temporary, deleted in "leave". if (this.CheckRange(this.order.data, IID_ResourceGatherer)) { @@ -2421,7 +2600,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { // The GATHERING timer will handle finding a valid resource. if (msg.likelyFailure) this.SetNextState("FINDINGNEWTARGET"); @@ -2429,7 +2609,8 @@ UnitAI.prototype.UnitFsmSpec = { this.SetNextState("GATHERING"); }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.SetDefaultAnimationVariant(); @@ -2446,7 +2627,8 @@ UnitAI.prototype.UnitFsmSpec = { // Walking to a good place to gather resources near, used by GatherNearPosition "WALKING": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data)) { this.FinishOrder(); @@ -2456,12 +2638,14 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.SetDefaultAnimationVariant(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || msg.obstructed && this.RelaxedMaxRangeCheck(this.order.data, this.DefaultRelaxedMaxRange) || this.CheckRange(this.order.data)) this.SetNextState("FINDINGNEWTARGET"); @@ -2469,7 +2653,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "GATHERING": { - "enter": function() { + "enter": function() + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (!cmpResourceGatherer) { @@ -2498,17 +2683,20 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (cmpResourceGatherer) cmpResourceGatherer.StopGathering(); }, - "InventoryFilled": function(msg) { + "InventoryFilled": function(msg) + { this.SetNextState("RETURNINGRESOURCE"); }, - "OutOfRange": function(msg) { + "OutOfRange": function(msg) + { if (this.MoveToTargetRange(this.order.data.target, IID_ResourceGatherer)) this.SetNextState("APPROACHING"); // Our target is no longer visible - go to its last known position first @@ -2523,13 +2711,15 @@ UnitAI.prototype.UnitFsmSpec = { this.SetNextState("FINDINGNEWTARGET"); }, - "TargetInvalidated": function(msg) { + "TargetInvalidated": function(msg) + { this.SetNextState("FINDINGNEWTARGET"); }, }, "FINDINGNEWTARGET": { - "enter": function() { + "enter": function() + { const previousForced = this.order.data.force; const previousTarget = this.order.data.target; const resourceTemplate = this.order.data.template; @@ -2559,7 +2749,8 @@ UnitAI.prototype.UnitFsmSpec = { if (!cmpPosition || !cmpPosition.IsInWorld()) return true; - const filter = (ent, type, template) => { + const filter = (ent, type, template) => + { if (previousTarget == ent) return false; @@ -2614,7 +2805,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "RETURNINGRESOURCE": { - "enter": function() { + "enter": function() + { const nearestDropsite = this.FindNearestDropsite(this.order.data.type.generic); if (!nearestDropsite) { @@ -2635,13 +2827,15 @@ UnitAI.prototype.UnitFsmSpec = { return true; }, - "leave": function() { + "leave": function() + { }, "APPROACHING": "INDIVIDUAL.RETURNRESOURCE.APPROACHING", "DROPPINGRESOURCES": { - "enter": function() { + "enter": function() + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (this.CanReturnResource(this.order.data.target, true, cmpResourceGatherer) && cmpResourceGatherer.IsTargetInRange(this.order.data.target)) @@ -2658,7 +2852,8 @@ UnitAI.prototype.UnitFsmSpec = { return true; }, - "leave": function() { + "leave": function() + { }, }, }, @@ -2666,7 +2861,8 @@ UnitAI.prototype.UnitFsmSpec = { "HEAL": { "APPROACHING": { - "enter": function() { + "enter": function() + { if (this.CheckRange(this.order.data, IID_Heal)) { this.SetNextState("HEALING"); @@ -2683,24 +2879,28 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); this.StopTimer(); }, - "Timer": function(msg) { + "Timer": function(msg) + { if (this.ShouldAbandonChase(this.order.data.target, this.order.data.force, IID_Heal, null)) this.SetNextState("FINDINGNEWTARGET"); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || this.CheckRange(this.order.data, IID_Heal)) this.SetNextState("HEALING"); }, }, "HEALING": { - "enter": function() { + "enter": function() + { const cmpHeal = Engine.QueryInterface(this.entity, IID_Heal); if (!cmpHeal) { @@ -2724,13 +2924,15 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { const cmpHeal = Engine.QueryInterface(this.entity, IID_Heal); if (cmpHeal) cmpHeal.StopHealing(); }, - "OutOfRange": function(msg) { + "OutOfRange": function(msg) + { if (this.ShouldChaseTargetedEntity(this.order.data.target, this.order.data.force)) { if (this.CanPack()) @@ -2742,13 +2944,15 @@ UnitAI.prototype.UnitFsmSpec = { this.SetNextState("FINDINGNEWTARGET"); }, - "TargetInvalidated": function(msg) { + "TargetInvalidated": function(msg) + { this.SetNextState("FINDINGNEWTARGET"); }, }, "FINDINGNEWTARGET": { - "enter": function() { + "enter": function() + { // If we have another order, do that instead. if (this.FinishOrder()) return true; @@ -2768,7 +2972,8 @@ UnitAI.prototype.UnitFsmSpec = { // Returning to dropsite "RETURNRESOURCE": { "APPROACHING": { - "enter": function() { + "enter": function() + { if (this.CheckTargetRange(this.order.data.target, IID_ResourceGatherer)) { this.SetNextState("DROPPINGRESOURCES"); @@ -2785,18 +2990,21 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || this.CheckTargetRange(this.order.data.target, IID_ResourceGatherer)) this.SetNextState("DROPPINGRESOURCES"); }, }, "DROPPINGRESOURCES": { - "enter": function() { + "enter": function() + { const cmpResourceGatherer = Engine.QueryInterface(this.entity, IID_ResourceGatherer); if (this.CanReturnResource(this.order.data.target, true, cmpResourceGatherer) && cmpResourceGatherer.IsTargetInRange(this.order.data.target)) @@ -2817,17 +3025,20 @@ UnitAI.prototype.UnitFsmSpec = { return true; }, - "leave": function() { + "leave": function() + { }, }, }, "COLLECTTREASURE": { - "leave": function() { + "leave": function() + { }, "APPROACHING": { - "enter": function() { + "enter": function() + { // If we can't move, assume we'll fail any subsequent order // and finish the order entirely to avoid an infinite loop. if (!this.AbleToMove()) @@ -2843,11 +3054,13 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (this.CheckTargetRange(this.order.data.target, IID_TreasureCollector)) this.SetNextState("COLLECTING"); else if (msg.likelyFailure) @@ -2856,7 +3069,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "COLLECTING": { - "enter": function() { + "enter": function() + { const cmpTreasureCollector = Engine.QueryInterface(this.entity, IID_TreasureCollector); if (!cmpTreasureCollector.StartCollecting(this.order.data.target, IID_UnitAI)) { @@ -2867,23 +3081,27 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { const cmpTreasureCollector = Engine.QueryInterface(this.entity, IID_TreasureCollector); if (cmpTreasureCollector) cmpTreasureCollector.StopCollecting(); }, - "OutOfRange": function(msg) { + "OutOfRange": function(msg) + { this.SetNextState("APPROACHING"); }, - "TargetInvalidated": function(msg) { + "TargetInvalidated": function(msg) + { this.SetNextState("FINDINGNEWTARGET"); }, }, "FINDINGNEWTARGET": { - "enter": function() { + "enter": function() + { const oldTarget = this.order.data.target || INVALID_ENTITY; // Switch to the next order (if any). @@ -2900,7 +3118,8 @@ UnitAI.prototype.UnitFsmSpec = { // Walking to a good place to collect treasures near, used by CollectTreasureNearPosition. "WALKING": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data)) { this.FinishOrder(); @@ -2909,11 +3128,13 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || msg.obstructed && this.RelaxedMaxRangeCheck(this.order.data, this.DefaultRelaxedMaxRange) || this.CheckRange(this.order.data)) this.SetNextState("FINDINGNEWTARGET"); @@ -2922,16 +3143,19 @@ UnitAI.prototype.UnitFsmSpec = { }, "TRADE": { - "Attacked": function(msg) { + "Attacked": function(msg) + { // Ignore attack // TODO: Inform player }, - "leave": function() { + "leave": function() + { }, "APPROACHINGMARKET": { - "enter": function() { + "enter": function() + { if (!this.MoveToMarket(this.order.data.target)) { this.FinishOrder(); @@ -2940,11 +3164,13 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (!msg.likelyFailure && !this.CheckRange(this.order.data.nextTarget, IID_Trader)) return; if (this.waypoints && this.waypoints.length) @@ -2958,7 +3184,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "TRADING": { - "enter": function() { + "enter": function() + { if (!this.CanTrade(this.order.data.target)) { this.FinishOrder(); @@ -2993,11 +3220,13 @@ UnitAI.prototype.UnitFsmSpec = { return true; }, - "leave": function() { + "leave": function() + { }, }, - "TradingCanceled": function(msg) { + "TradingCanceled": function(msg) + { if (msg.market != this.order.data.target) return; const cmpTrader = Engine.QueryInterface(this.entity, IID_Trader); @@ -3011,7 +3240,8 @@ UnitAI.prototype.UnitFsmSpec = { "REPAIR": { "APPROACHING": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data, IID_Builder)) { this.FinishOrder(); @@ -3020,18 +3250,21 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || msg.likelySuccess) this.SetNextState("REPAIRING"); }, }, "REPAIRING": { - "enter": function() { + "enter": function() + { const cmpBuilder = Engine.QueryInterface(this.entity, IID_Builder); if (!cmpBuilder) { @@ -3071,22 +3304,26 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { const cmpBuilder = Engine.QueryInterface(this.entity, IID_Builder); if (cmpBuilder) cmpBuilder.StopRepairing(); }, - "OutOfRange": function(msg) { + "OutOfRange": function(msg) + { this.SetNextState("APPROACHING"); }, - "TargetInvalidated": function(msg) { + "TargetInvalidated": function(msg) + { this.FinishOrder(); }, }, - "ConstructionFinished": function(msg) { + "ConstructionFinished": function(msg) + { if (msg.data.entity != this.order.data.target) return; // ignore other buildings @@ -3174,7 +3411,8 @@ UnitAI.prototype.UnitFsmSpec = { "GARRISON": { "APPROACHING": { - "enter": function() { + "enter": function() + { if (this.order.data.garrison ? !this.CanGarrison(this.order.data.target) : !this.CanOccupyTurret(this.order.data.target)) { @@ -3200,7 +3438,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { if (this.pickup) { Engine.PostMessage(this.pickup, MT_PickupCanceled, { "entity": this.entity }); @@ -3209,7 +3448,8 @@ UnitAI.prototype.UnitFsmSpec = { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (!msg.likelyFailure && !msg.likelySuccess) return; @@ -3230,7 +3470,8 @@ UnitAI.prototype.UnitFsmSpec = { }, "GARRISONING": { - "enter": function() { + "enter": function() + { const target = this.order.data.target; if (this.order.data.garrison) { @@ -3269,19 +3510,22 @@ UnitAI.prototype.UnitFsmSpec = { return true; }, - "leave": function() { + "leave": function() + { }, }, }, "CHEERING": { - "enter": function() { + "enter": function() + { this.SelectAnimation("promotion"); this.StartTimer(this.cheeringTime); return false; }, - "leave": function() { + "leave": function() + { // PushOrderFront preserves the cheering order, // which can lead to very bad behaviour, so make // sure to delete any queued ones. @@ -3292,81 +3536,96 @@ UnitAI.prototype.UnitFsmSpec = { this.ResetAnimation(); }, - "LosRangeUpdate": function(msg) { + "LosRangeUpdate": function(msg) + { if (msg && msg.data && msg.data.added && msg.data.added.length) this.RespondToSightedEntities(msg.data.added); }, - "LosHealRangeUpdate": function(msg) { + "LosHealRangeUpdate": function(msg) + { if (msg && msg.data && msg.data.added && msg.data.added.length) this.RespondToHealableEntities(msg.data.added); }, - "LosAttackRangeUpdate": function(msg) { + "LosAttackRangeUpdate": function(msg) + { if (msg && msg.data && msg.data.added && msg.data.added.length && this.GetStance().targetVisibleEnemies) this.AttackEntitiesByPreference(msg.data.added); }, - "Timer": function(msg) { + "Timer": function(msg) + { this.FinishOrder(); }, }, "PACKING": { - "enter": function() { + "enter": function() + { const cmpPack = Engine.QueryInterface(this.entity, IID_Pack); cmpPack.Pack(); return false; }, - "Order.CancelPack": function(msg) { + "Order.CancelPack": function(msg) + { this.FinishOrder(); return ACCEPT_ORDER; }, - "PackFinished": function(msg) { + "PackFinished": function(msg) + { this.FinishOrder(); }, - "leave": function() { + "leave": function() + { const cmpPack = Engine.QueryInterface(this.entity, IID_Pack); cmpPack.CancelPack(); }, - "Attacked": function(msg) { + "Attacked": function(msg) + { // Ignore attacks while packing }, }, "UNPACKING": { - "enter": function() { + "enter": function() + { const cmpPack = Engine.QueryInterface(this.entity, IID_Pack); cmpPack.Unpack(); return false; }, - "Order.CancelUnpack": function(msg) { + "Order.CancelUnpack": function(msg) + { this.FinishOrder(); return ACCEPT_ORDER; }, - "PackFinished": function(msg) { + "PackFinished": function(msg) + { this.FinishOrder(); }, - "leave": function() { + "leave": function() + { const cmpPack = Engine.QueryInterface(this.entity, IID_Pack); cmpPack.CancelPack(); }, - "Attacked": function(msg) { + "Attacked": function(msg) + { // Ignore attacks while unpacking }, }, "PICKUP": { "APPROACHING": { - "enter": function() { + "enter": function() + { if (!this.MoveTo(this.order.data)) { this.FinishOrder(); @@ -3375,22 +3634,26 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "leave": function() { + "leave": function() + { this.StopMoving(); }, - "MovementUpdate": function(msg) { + "MovementUpdate": function(msg) + { if (msg.likelyFailure || msg.likelySuccess) this.SetNextState("LOADING"); }, - "PickupCanceled": function() { + "PickupCanceled": function() + { this.FinishOrder(); }, }, "LOADING": { - "enter": function() { + "enter": function() + { const cmpHolder = Engine.QueryInterface(this.entity, this.order.data.iid); if (!cmpHolder || cmpHolder.IsFull()) { @@ -3400,7 +3663,8 @@ UnitAI.prototype.UnitFsmSpec = { return false; }, - "PickupCanceled": function() { + "PickupCanceled": function() + { this.FinishOrder(); }, }, @@ -4388,7 +4652,8 @@ UnitAI.prototype.FindNearbyResource = function(position, filter) const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); // Don't account for entity size, we need to match LOS visibility. const nearby = cmpRangeManager.ExecuteQueryAroundPos(position, 0, range, players, IID_ResourceSupply, false); - return nearby.find(ent => { + return nearby.find(ent => + { if (!this.CanGather(ent) || !this.CheckTargetVisible(ent)) return false; @@ -4744,7 +5009,8 @@ UnitAI.prototype.MoveFormationToTargetAttackRange = function(target) * Requests the formation component to update member positions. * Called by formation controller when formation needs reorganization. */ -UnitAI.prototype.RequestFormationUpdate = function(moveCenter = false, force = false, formationType = "default") { +UnitAI.prototype.RequestFormationUpdate = function(moveCenter = false, force = false, formationType = "default") +{ const cmpFormation = Engine.QueryInterface(this.entity, IID_Formation); if (!cmpFormation) return; @@ -6005,7 +6271,8 @@ UnitAI.prototype.FindWalkAndFightTargets = function() entities = cmpRangeManager.ResetActiveQuery(this.losAttackRangeQuery); } - const attackfilter = e => { + const attackfilter = e => + { if (this?.order?.data?.targetClasses) { const cmpIdentity = Engine.QueryInterface(e, IID_Identity); @@ -6027,7 +6294,8 @@ UnitAI.prototype.FindWalkAndFightTargets = function() return cmpUnitAI && (!cmpUnitAI.IsAnimal() || cmpUnitAI.IsDangerousAnimal()); }; - const attack = target => { + const attack = target => + { const order = { "target": target, "force": false, @@ -6411,7 +6679,8 @@ UnitAI.prototype.AttackEntitiesByPreference = function(ents) if (!cmpAttack) return false; - const attackfilter = function(e) { + const attackfilter = function(e) + { if (!cmpAttack.CanAttack(e)) return false; @@ -6479,7 +6748,8 @@ UnitAI.prototype.CallMemberFunction = function(funcname, args, resetFinishedEnti cmpFormation.ResetFinishedEntities(); let result = false; - cmpFormation.GetMembers().forEach(ent => { + cmpFormation.GetMembers().forEach(ent => + { const cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI); if (cmpUnitAI[funcname].apply(cmpUnitAI, args)) result = true; diff --git a/binaries/data/mods/public/simulation/components/tests/setup.js b/binaries/data/mods/public/simulation/components/tests/setup.js index 72b94cc085..9998573771 100644 --- a/binaries/data/mods/public/simulation/components/tests/setup.js +++ b/binaries/data/mods/public/simulation/components/tests/setup.js @@ -127,14 +127,16 @@ global.Spy = function(obj, func) this._called = 0; this._callargs = []; const og_func = obj[func]; - const spy = (...args) => { + const spy = (...args) => + { ++this._called; this._callargs.push(args); return og_func.apply(obj, args); }; obj[func] = spy; - this._reset = () => { + this._reset = () => + { this._called = 0; this._callargs = []; }; diff --git a/binaries/data/mods/public/simulation/components/tests/test_Attack.js b/binaries/data/mods/public/simulation/components/tests/test_Attack.js index a28838efb3..3024fff1f7 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Attack.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Attack.js @@ -185,7 +185,8 @@ function attackComponentTest(defenderClass, isEnemy, test_function) } // Validate template getter functions -attackComponentTest(undefined, true, (attacker, cmpAttack, defender) => { +attackComponentTest(undefined, true, (attacker, cmpAttack, defender) => +{ TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetAttackTypes(), ["Melee", "Ranged", "Capture"]); TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetAttackTypes([]), ["Melee", "Ranged", "Capture"]); @@ -282,7 +283,8 @@ attackComponentTest(undefined, true, (attacker, cmpAttack, defender) => { }); for (const className of ["Infantry", "Cavalry"]) - attackComponentTest(className, true, (attacker, cmpAttack, defender) => { + attackComponentTest(className, true, (attacker, cmpAttack, defender) => + { TS_ASSERT_EQUALS(cmpAttack.GetAttackEffectsData("Melee").Bonuses.BonusCav.Multiplier, 2); @@ -297,17 +299,20 @@ for (const className of ["Infantry", "Cavalry"]) }); // CanAttack rejects elephant attack due to RestrictedClasses -attackComponentTest("Elephant", true, (attacker, cmpAttack, defender) => { +attackComponentTest("Elephant", true, (attacker, cmpAttack, defender) => +{ TS_ASSERT_EQUALS(cmpAttack.CanAttack(defender), false); }); function testGetBestAttackAgainst(defenderClass, bestAttack, bestAllyAttack, isBuilding = false) { - attackComponentTest(defenderClass, true, (attacker, cmpAttack, defender) => { + attackComponentTest(defenderClass, true, (attacker, cmpAttack, defender) => + { if (isBuilding) AddMock(defender, IID_Capturable, { - "CanCapture": playerID => { + "CanCapture": playerID => + { TS_ASSERT_EQUALS(playerID, 1); return true; } @@ -331,11 +336,13 @@ function testGetBestAttackAgainst(defenderClass, bestAttack, bestAllyAttack, isB TS_ASSERT_EQUALS(cmpAttack.GetBestAttackAgainst(defender, ac), bestAttack); }); - attackComponentTest(defenderClass, false, (attacker, cmpAttack, defender) => { + attackComponentTest(defenderClass, false, (attacker, cmpAttack, defender) => + { if (isBuilding) AddMock(defender, IID_Capturable, { - "CanCapture": playerID => { + "CanCapture": playerID => + { TS_ASSERT_EQUALS(playerID, 1); return true; } diff --git a/binaries/data/mods/public/simulation/components/tests/test_Auras.js b/binaries/data/mods/public/simulation/components/tests/test_Auras.js index 10ac34fb99..ec3882757f 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Auras.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Auras.js @@ -17,7 +17,8 @@ var auraRange = 40; var template = { "Identity": { "Classes": { "_string": "CorrectClass OtherClass" } } }; global.AuraTemplates = { - "Get": name => { + "Get": name => + { const auraTemplate = { "type": name, "affectedPlayers": ["Ally"], @@ -104,20 +105,23 @@ function testAuras(name, test_function) } targetEnt = playerEnt[playerID[2]]; -testAuras("player", (name, cmpAuras) => { +testAuras("player", (name, cmpAuras) => +{ TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 15); }); targetEnt = 30; // Test the case when the aura source is a player entity. sourceEnt = 11; -testAuras("global", (name, cmpAuras) => { +testAuras("global", (name, cmpAuras) => +{ TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 15); TS_ASSERT_EQUALS(ApplyValueModificationsToTemplate("Component/Value", 5, playerID[1], template), 15); }); sourceEnt = 20; -testAuras("range", (name, cmpAuras) => { +testAuras("range", (name, cmpAuras) => +{ cmpAuras.OnRangeUpdate({ "tag": 1, "added": [targetEnt], "removed": [] }); TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 15); TS_ASSERT_EQUALS(ApplyValueModificationsToTemplate("Component/Value", 5, playerID[1], template), 5); @@ -125,14 +129,16 @@ testAuras("range", (name, cmpAuras) => { TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 5); }); -testAuras("garrisonedUnits", (name, cmpAuras) => { +testAuras("garrisonedUnits", (name, cmpAuras) => +{ cmpAuras.OnGarrisonedUnitsChanged({ "added": [targetEnt], "removed": [] }); TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 15); cmpAuras.OnGarrisonedUnitsChanged({ "added": [], "removed": [targetEnt] }); TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 5); }); -testAuras("garrison", (name, cmpAuras) => { +testAuras("garrison", (name, cmpAuras) => +{ TS_ASSERT_EQUALS(cmpAuras.HasGarrisonAura(), true); cmpAuras.ApplyGarrisonAura(targetEnt); TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 15); @@ -140,7 +146,8 @@ testAuras("garrison", (name, cmpAuras) => { TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 5); }); -testAuras("formation", (name, cmpAuras) => { +testAuras("formation", (name, cmpAuras) => +{ TS_ASSERT_EQUALS(cmpAuras.HasFormationAura(), true); cmpAuras.ApplyFormationAura([targetEnt]); TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 15); @@ -148,7 +155,8 @@ testAuras("formation", (name, cmpAuras) => { TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 5); }); -testAuras("global", (name, cmpAuras) => { +testAuras("global", (name, cmpAuras) => +{ TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Component/Value", 5, targetEnt), 15); TS_ASSERT_EQUALS(ApplyValueModificationsToTemplate("Component/Value", 5, playerID[1], template), 15); TS_ASSERT_EQUALS(ApplyValueModificationsToTemplate("Component/Value", 5, playerID[2], template), 15); @@ -162,7 +170,8 @@ testAuras("global", (name, cmpAuras) => { }); playerDefeated[1] = true; -testAuras("global", (name, cmpAuras) => { +testAuras("global", (name, cmpAuras) => +{ cmpAuras.OnGlobalPlayerDefeated({ "playerId": playerID[1] }); TS_ASSERT_EQUALS(ApplyValueModificationsToTemplate("Component/Value", 5, playerID[2], template), 5); }); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Barter.js b/binaries/data/mods/public/simulation/components/tests/test_Barter.js index 0f821bd3d8..74bec17d19 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Barter.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Barter.js @@ -40,7 +40,8 @@ const cmpBarter = ConstructComponent(SYSTEM_ENTITY, "Barter"); AddMock(SYSTEM_ENTITY, IID_Timer, { "CancelTimer": id => { timerActivated = false; }, - "SetInterval": (ent, iid, funcname, time, repeattime, data) => { + "SetInterval": (ent, iid, funcname, time, repeattime, data) => + { TS_ASSERT_EQUALS(time, cmpBarter.RESTORE_TIMER_INTERVAL); TS_ASSERT_EQUALS(repeattime, cmpBarter.RESTORE_TIMER_INTERVAL); timerActivated = true; @@ -53,11 +54,13 @@ TS_ASSERT_EQUALS(cmpBarter.restoreTimer, undefined); TS_ASSERT_UNEVAL_EQUALS(cmpBarter.priceDifferences, { "wood": 0, "stone": 0, "metal": 0 }); const cmpPlayer = AddMock(playerEnt, IID_Player, { - "TrySubtractResources": amounts => { + "TrySubtractResources": amounts => + { sold = amounts[Object.keys(amounts)[0]]; return true; }, - "AddResource": (type, amount) => { + "AddResource": (type, amount) => + { bought = amount; return true; }, diff --git a/binaries/data/mods/public/simulation/components/tests/test_Builder.js b/binaries/data/mods/public/simulation/components/tests/test_Builder.js index cf0562359b..e7354ac27d 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Builder.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Builder.js @@ -121,7 +121,8 @@ function testBuildingFoundation() let increased = false; AddMock(target, IID_Foundation, { - "Build": (entity, amount) => { + "Build": (entity, amount) => + { increased = true; TS_ASSERT_EQUALS(amount, 1); }, diff --git a/binaries/data/mods/public/simulation/components/tests/test_Capturable.js b/binaries/data/mods/public/simulation/components/tests/test_Capturable.js index dc2136eb57..423ae0c1bd 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Capturable.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Capturable.js @@ -93,7 +93,8 @@ function testCapturable(data, test_function) if (testCaptureAttacks[entity] === undefined) continue; AddMock(entity, IID_Attack, { - "GetAttackEffectsData": (type) => { + "GetAttackEffectsData": (type) => + { return type === "Capture" ? { "Capture": testCaptureAttacks[entity] } : undefined; }, }); @@ -106,8 +107,10 @@ function testCapturable(data, test_function) } // Tests initialisation of the capture points when the entity is created -testCapturable(testData, cmpCapturable => { - Engine.PostMessage = function(ent, iid, message) { +testCapturable(testData, cmpCapturable => +{ + Engine.PostMessage = function(ent, iid, message) + { TS_ASSERT_UNEVAL_EQUALS(message, { "regenerating": true, "regenRate": cmpCapturable.GetRegenRate(), "territoryDecay": 0 }); }; cmpCapturable.OnOwnershipChanged({ "from": INVALID_PLAYER, "to": testData.playerID }); @@ -115,7 +118,8 @@ testCapturable(testData, cmpCapturable => { }); // Tests if the message is sent when capture points change -testCapturable(testData, cmpCapturable => { +testCapturable(testData, cmpCapturable => +{ cmpCapturable.SetCapturePoints([0, 2000, 0, 1000]); TS_ASSERT_UNEVAL_EQUALS(cmpCapturable.GetCapturePoints(), [0, 2000, 0, 1000]); Engine.PostMessage = function(ent, iid, message) @@ -126,10 +130,12 @@ testCapturable(testData, cmpCapturable => { }); // Tests reducing capture points (after a capture attack or a decay) -testCapturable(testData, cmpCapturable => { +testCapturable(testData, cmpCapturable => +{ cmpCapturable.SetCapturePoints([0, 2000, 0, 1000]); cmpCapturable.CheckTimer(); - Engine.PostMessage = function(ent, iid, message) { + Engine.PostMessage = function(ent, iid, message) + { if (iid == MT_CapturePointsChanged) TS_ASSERT_UNEVAL_EQUALS(message, { "capturePoints": [0, 2000 - 100, 0, 1000 + 100] }); if (iid == MT_CaptureRegenStateChanged) @@ -140,7 +146,8 @@ testCapturable(testData, cmpCapturable => { }); // Tests reducing capture points (after a capture attack or a decay) -testCapturable(testData, cmpCapturable => { +testCapturable(testData, cmpCapturable => +{ cmpCapturable.SetCapturePoints([0, 2000, 0, 1000]); cmpCapturable.CheckTimer(); TS_ASSERT_EQUALS(cmpCapturable.Reduce(2500, 3), 2000); @@ -149,10 +156,12 @@ testCapturable(testData, cmpCapturable => { function testRegen(data, capturePointsIn, capturePointsOut, regenerating) { - testCapturable(data, cmpCapturable => { + testCapturable(data, cmpCapturable => + { cmpCapturable.SetCapturePoints(capturePointsIn); cmpCapturable.CheckTimer(); - Engine.PostMessage = function(ent, iid, message) { + Engine.PostMessage = function(ent, iid, message) + { if (iid == MT_CaptureRegenStateChanged) TS_ASSERT_UNEVAL_EQUALS(message.regenerating, regenerating); }; @@ -174,10 +183,12 @@ testData.regenRate = 2; function testDecay(data, capturePointsIn, capturePointsOut) { - testCapturable(data, cmpCapturable => { + testCapturable(data, cmpCapturable => + { cmpCapturable.SetCapturePoints(capturePointsIn); cmpCapturable.CheckTimer(); - Engine.PostMessage = function(ent, iid, message) { + Engine.PostMessage = function(ent, iid, message) + { if (iid == MT_CaptureRegenStateChanged) TS_ASSERT_UNEVAL_EQUALS(message.territoryDecay, data.decayRate); }; @@ -195,7 +206,8 @@ testData.decay = false; // Tests Reduce function testReduce(data, amount, player, taken) { - testCapturable(data, cmpCapturable => { + testCapturable(data, cmpCapturable => + { cmpCapturable.SetCapturePoints([0, 2000, 0, 1000]); cmpCapturable.CheckTimer(); TS_ASSERT_UNEVAL_EQUALS(cmpCapturable.Reduce(amount, player), taken); @@ -213,7 +225,8 @@ testReduce(testData, 2000, 3, 2000); testReduce(testData, 3000, 3, 2000); // Test defeated player -testCapturable(testData, cmpCapturable => { +testCapturable(testData, cmpCapturable => +{ cmpCapturable.SetCapturePoints([500, 1000, 0, 250]); cmpCapturable.OnGlobalPlayerDefeated({ "playerId": 3 }); TS_ASSERT_UNEVAL_EQUALS(cmpCapturable.GetCapturePoints(), [750, 1000, 0, 0]); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Damage.js b/binaries/data/mods/public/simulation/components/tests/test_Damage.js index ff98d81631..5ccd606281 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Damage.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Damage.js @@ -101,14 +101,16 @@ function Test_Generic() }); AddMock(target, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { damageTaken = true; return { "healthChange": -amount }; }, }); AddMock(SYSTEM_ENTITY, IID_DelayedDamage, { - "Hit": () => { + "Hit": () => + { damageTaken = true; }, }); @@ -234,7 +236,8 @@ function TestLinearSplashDamage() }); AddMock(60, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(60); TS_ASSERT_EQUALS(amount, 100 * fallOff(3, -0.5)); return { "healthChange": -amount }; @@ -242,7 +245,8 @@ function TestLinearSplashDamage() }); AddMock(61, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(61); TS_ASSERT_EQUALS(amount, 100 * fallOff(0, 0)); return { "healthChange": -amount }; @@ -250,7 +254,8 @@ function TestLinearSplashDamage() }); AddMock(62, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(62); // Minor numerical precision issues make this necessary TS_ASSERT(amount < 0.00001); @@ -267,7 +272,8 @@ function TestLinearSplashDamage() data.direction = new Vector3D(0.6, 747, 0.8); AddMock(60, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(60); TS_ASSERT_EQUALS(amount, 100 * fallOff(1, 2)); return { "healthChange": -amount }; @@ -347,34 +353,39 @@ function TestCircularSplashDamage() }); AddMock(60, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, 100 * fallOff(0)); return { "healthChange": -amount }; } }); AddMock(61, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, 100 * fallOff(5)); return { "healthChange": -amount }; } }); AddMock(62, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, 100 * fallOff(1)); return { "healthChange": -amount }; } }); AddMock(63, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT(false); } }); const cmphealth64 = AddMock(64, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, 0); return { "healthChange": -amount }; } @@ -382,7 +393,8 @@ function TestCircularSplashDamage() const spy64 = new Spy(cmphealth64, "TakeDamage"); const cmpHealth65 = AddMock(65, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, 100 * fallOff(2)); return { "healthChange": -amount }; } @@ -454,7 +466,8 @@ function Test_MissileHit() }); AddMock(60, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(60); TS_ASSERT_EQUALS(amount, 100); return { "healthChange": -amount }; @@ -500,7 +513,8 @@ function Test_MissileHit() }); AddMock(61, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(61); TS_ASSERT_EQUALS(amount, 100); return { "healthChange": -amount }; @@ -530,7 +544,8 @@ function Test_MissileHit() }); AddMock(60, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(false); return { "healthChange": -amount }; } @@ -564,7 +579,8 @@ function Test_MissileHit() let dealtDamage = 0; AddMock(61, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(61); dealtDamage += amount; return { "healthChange": -amount }; @@ -579,7 +595,8 @@ function Test_MissileHit() }); AddMock(62, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(62); TS_ASSERT_EQUALS(amount, 200 * 0.75); return { "healthChange": -amount }; @@ -671,7 +688,8 @@ function Test_MissileHit() dealtDamage = 0; AddMock(61, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(61); dealtDamage += amount; return { "healthChange": -amount }; @@ -686,7 +704,8 @@ function Test_MissileHit() }); AddMock(62, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { hitEnts.add(62); TS_ASSERT_EQUALS(amount, 200 * 0.75); return { "healtChange": -amount }; diff --git a/binaries/data/mods/public/simulation/components/tests/test_EntityLimits.js b/binaries/data/mods/public/simulation/components/tests/test_EntityLimits.js index 52961b9396..61b9341f69 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_EntityLimits.js +++ b/binaries/data/mods/public/simulation/components/tests/test_EntityLimits.js @@ -149,7 +149,8 @@ TS_ASSERT_UNEVAL_EQUALS(cmpEntityLimits.GetCounts(), { "Tower": 0, "Wonder": 0, // Test AllowedToReplace AddMock(SYSTEM_ENTITY, IID_TemplateManager, { - "GetTemplate": name => { + "GetTemplate": name => + { switch (name) { case "templateA": @@ -164,7 +165,8 @@ AddMock(SYSTEM_ENTITY, IID_TemplateManager, { return null; } }, - "GetCurrentTemplateName": id => { + "GetCurrentTemplateName": id => + { switch (id) { case 100: diff --git a/binaries/data/mods/public/simulation/components/tests/test_Formation.js b/binaries/data/mods/public/simulation/components/tests/test_Formation.js index a5f0fca111..b4795634e5 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Formation.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Formation.js @@ -199,7 +199,8 @@ function TestIsRearrangementAllowed() } // Controller in COMBAT.ATTACKING should block rearrangement - (function() { + (function() + { const controllerID = cmpFormation.entity; cmpFormation.members = [201, 202]; @@ -215,7 +216,8 @@ function TestIsRearrangementAllowed() })(); // Different critical states sum should count toward threshold - (function() { + (function() + { const controllerID = cmpFormation.entity; // Mock controller in walking state diff --git a/binaries/data/mods/public/simulation/components/tests/test_Foundation.js b/binaries/data/mods/public/simulation/components/tests/test_Foundation.js index f0bcf47418..2d18e5b513 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Foundation.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Foundation.js @@ -51,14 +51,16 @@ function testFoundation(...mocks) }); AddMock(SYSTEM_ENTITY, IID_TerritoryManager, { - "GetOwner": (x, y) => { + "GetOwner": (x, y) => + { TS_ASSERT_EQUALS(x, pos.x); TS_ASSERT_EQUALS(y, pos.y); return player; }, }); - Engine.RegisterGlobal("PlaySound", (name, source) => { + Engine.RegisterGlobal("PlaySound", (name, source) => + { TS_ASSERT_EQUALS(name, "constructed"); TS_ASSERT_EQUALS(source, newEnt); }); @@ -72,7 +74,8 @@ function testFoundation(...mocks) AddMock(foundationEnt, IID_Health, { "GetHitpoints": () => foundationHP, "GetMaxHitpoints": () => maxHP, - "Increase": hp => { + "Increase": hp => + { foundationHP = Math.min(foundationHP + hp, maxHP); cmpFoundation.OnHealthChanged(); }, @@ -103,13 +106,15 @@ function testFoundation(...mocks) }); AddMock(previewEnt, IID_Position, { - "JumpTo": (x, y) => { + "JumpTo": (x, y) => + { TS_ASSERT_EQUALS(x, pos.x); TS_ASSERT_EQUALS(y, pos.y); }, "SetConstructionProgress": p => {}, "SetYRotation": r => { TS_ASSERT_EQUALS(r, rot.y); }, - "SetXZRotation": (rx, rz) => { + "SetXZRotation": (rx, rz) => + { TS_ASSERT_EQUALS(rx, rot.x); TS_ASSERT_EQUALS(rz, rot.z); }, @@ -121,12 +126,14 @@ function testFoundation(...mocks) AddMock(newEnt, IID_Position, { "GetPosition2D": () => pos, - "JumpTo": (x, y) => { + "JumpTo": (x, y) => + { TS_ASSERT_EQUALS(x, pos.x); TS_ASSERT_EQUALS(y, pos.y); }, "SetYRotation": r => { TS_ASSERT_EQUALS(r, rot.y); }, - "SetXZRotation": (rx, rz) => { + "SetXZRotation": (rx, rz) => + { TS_ASSERT_EQUALS(rx, rot.x); TS_ASSERT_EQUALS(rz, rot.z); }, @@ -137,7 +144,8 @@ function testFoundation(...mocks) AddMock(...mock); // INITIALISE - Engine.AddLocalEntity = function(template) { + Engine.AddLocalEntity = function(template) + { TS_ASSERT_EQUALS(template, "construction|" + finalTemplate); return previewEnt; }; @@ -198,7 +206,8 @@ function testFoundation(...mocks) TS_ASSERT_EQUALS(cmpFoundation.totalBuilderRate, 5); // FINISH CONSTRUCTION - Engine.AddEntity = function(template) { + Engine.AddEntity = function(template) + { TS_ASSERT_EQUALS(template, finalTemplate); return newEnt; }; @@ -210,7 +219,8 @@ function testFoundation(...mocks) testFoundation(); testFoundation([foundationEnt, IID_Visual, { - "SetVariable": (key, num) => { + "SetVariable": (key, num) => + { TS_ASSERT_EQUALS(key, "numbuilders"); TS_ASSERT(num == 1 || num == 2); }, @@ -223,7 +233,8 @@ testFoundation([newEnt, IID_TerritoryDecay, { }]); testFoundation([playerEnt, IID_StatisticsTracker, { - "IncreaseConstructedBuildingsCounter": ent => { + "IncreaseConstructedBuildingsCounter": ent => + { TS_ASSERT_EQUALS(ent, newEnt); }, }]); @@ -245,7 +256,8 @@ const cmpAutoBuildingFoundation = ConstructComponent(foundationEnt2, "Foundation AddMock(foundationEnt2, IID_Health, { "GetHitpoints": () => currentFoundationHP, "GetMaxHitpoints": () => 100, - "Increase": hp => { + "Increase": hp => + { currentFoundationHP = Math.min(currentFoundationHP + hp, 100); cmpAutoBuildingFoundation.OnHealthChanged(); }, diff --git a/binaries/data/mods/public/simulation/components/tests/test_GarrisonHolder.js b/binaries/data/mods/public/simulation/components/tests/test_GarrisonHolder.js index 30a4136fea..e577936ac6 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_GarrisonHolder.js +++ b/binaries/data/mods/public/simulation/components/tests/test_GarrisonHolder.js @@ -268,7 +268,8 @@ const oldApplyValueModificationsToEntity = ApplyValueModificationsToEntity; TS_ASSERT(cmpGarrisonHolder.Garrison(siegeEngineId)); TS_ASSERT_UNEVAL_EQUALS(cmpGarrisonHolder.GetEntities(), [siegeEngineId]); -Engine.RegisterGlobal("ApplyValueModificationsToEntity", (valueName, currentValue, entity) => { +Engine.RegisterGlobal("ApplyValueModificationsToEntity", (valueName, currentValue, entity) => +{ if (valueName !== "GarrisonHolder/List/_string") return valueName; diff --git a/binaries/data/mods/public/simulation/components/tests/test_Garrisoning.js b/binaries/data/mods/public/simulation/components/tests/test_Garrisoning.js index 1c2dbfba8a..bdd9619827 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Garrisoning.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Garrisoning.js @@ -17,7 +17,8 @@ const friendlyPlayer = 3; const garrison = 10; const holder = 11; -const createGarrisonCmp = entity => { +const createGarrisonCmp = entity => +{ AddMock(entity, IID_Identity, { "GetClassesList": () => ["Ranged"], "GetSelectionGroupName": () => "mace_infantry_archer_a" diff --git a/binaries/data/mods/public/simulation/components/tests/test_GuiInterface.js b/binaries/data/mods/public/simulation/components/tests/test_GuiInterface.js index 1eff79c930..7d11dce456 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_GuiInterface.js +++ b/binaries/data/mods/public/simulation/components/tests/test_GuiInterface.js @@ -67,7 +67,8 @@ var cmp = ConstructComponent(SYSTEM_ENTITY, "GuiInterface"); AddMock(SYSTEM_ENTITY, IID_Barter, { - "GetPrices": function() { + "GetPrices": function() + { return { "buy": { "food": 150 }, "sell": { "food": 25 } @@ -159,7 +160,8 @@ AddMock(100, IID_TechnologyManager, { }); AddMock(100, IID_StatisticsTracker, { - "GetBasicStatistics": function() { + "GetBasicStatistics": function() + { return { "resourcesGathered": { "food": 100, @@ -171,7 +173,8 @@ AddMock(100, IID_StatisticsTracker, { "percentMapExplored": 10 }; }, - "GetSequences": function() { + "GetSequences": function() + { return { "unitsTrained": [0, 10], "unitsLost": [0, 42], @@ -254,7 +257,8 @@ AddMock(101, IID_TechnologyManager, { }); AddMock(101, IID_StatisticsTracker, { - "GetBasicStatistics": function() { + "GetBasicStatistics": function() + { return { "resourcesGathered": { "food": 100, @@ -266,7 +270,8 @@ AddMock(101, IID_StatisticsTracker, { "percentMapExplored": 10 }; }, - "GetSequences": function() { + "GetSequences": function() + { return { "unitsTrained": [0, 10], "unitsLost": [0, 9], @@ -569,7 +574,8 @@ TS_ASSERT_UNEVAL_EQUALS(cmp.GetExtendedSimulationState(), { AddMock(10, IID_Builder, { - "GetEntitiesList": function() { + "GetEntitiesList": function() + { return ["test1", "test2"]; }, }); @@ -593,10 +599,12 @@ AddMock(10, IID_Identity, { AddMock(10, IID_Position, { "GetTurretParent": function() { return INVALID_ENTITY; }, - "GetPosition": function() { + "GetPosition": function() + { return { "x": 1, "y": 2, "z": 3 }; }, - "IsInWorld": function() { + "IsInWorld": function() + { return true; } }); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Heal.js b/binaries/data/mods/public/simulation/components/tests/test_Heal.js index dff17bde5c..19517cc6a0 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Heal.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Heal.js @@ -103,7 +103,8 @@ let increased; let unhealable = false; AddMock(target, IID_Health, { "GetMaxHitpoints": () => 700, - "Increase": amount => { + "Increase": amount => + { increased = true; TS_ASSERT_EQUALS(amount, 5 + 100); return { "old": 600, "new": 600 + 5 + 100 }; @@ -128,14 +129,16 @@ TS_ASSERT(!increased); // Test experience. let looted; AddMock(target, IID_Loot, { - "GetXp": () => { + "GetXp": () => + { looted = true; return 80; } }); let promoted; AddMock(entity, IID_Promotion, { - "IncreaseXp": amount => { + "IncreaseXp": amount => + { promoted = true; TS_ASSERT_EQUALS(amount, (5 + 100) * 80 / 700); } @@ -150,7 +153,8 @@ TS_ASSERT(increased && looted && promoted); let updated; AddMock(entity, IID_UnitAI, { "FaceTowardsTarget": () => {}, - "UpdateRangeQueries": () => { + "UpdateRangeQueries": () => + { updated = true; } }); @@ -199,7 +203,8 @@ TS_ASSERT(!cmpHeal.CanHeal(otherTarget)); increased = false; AddMock(target, IID_Health, { "GetMaxHitpoints": () => 700, - "Increase": amount => { + "Increase": amount => + { increased = true; TS_ASSERT_EQUALS(amount, 5 + 100); return { "old": 600, "new": 600 + 5 + 100 }; @@ -214,7 +219,8 @@ TS_ASSERT(increased); increased = false; AddMock(target, IID_Health, { "GetMaxHitpoints": () => 700, - "Increase": amount => { + "Increase": amount => + { increased = true; TS_ASSERT(false); }, diff --git a/binaries/data/mods/public/simulation/components/tests/test_Health.js b/binaries/data/mods/public/simulation/components/tests/test_Health.js index 0e22be3409..ce479a819b 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Health.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Health.js @@ -79,7 +79,8 @@ TS_ASSERT_EQUALS(cmpHealth.IsInjured(), false); TS_ASSERT_EQUALS(cmpHealth.IsUnhealable(), true); // Check death. -Engine.AddLocalEntity = function(template) { +Engine.AddLocalEntity = function(template) +{ corpse_entity = template; AddMock(corpse_id, IID_Position, { diff --git a/binaries/data/mods/public/simulation/components/tests/test_Loot.js b/binaries/data/mods/public/simulation/components/tests/test_Loot.js index 76dcee7fa8..7fe7ad38fa 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Loot.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Loot.js @@ -3,7 +3,8 @@ Resources = { "GetTradableCodes": () => ["food", "metal", "stone", "wood"], "GetBarterableCodes": () => ["food", "metal", "stone", "wood"], "GetResource": () => ({}), - "BuildSchema": (type) => { + "BuildSchema": (type) => + { let schema = ""; for (const res of Resources.GetCodes()) schema += @@ -21,12 +22,14 @@ Engine.LoadComponentScript("Loot.js"); Engine.LoadHelperScript("ValueModification.js"); Engine.LoadComponentScript("interfaces/ModifiersManager.js"); -let applyModifierOverride = (key, val, ent) => { +let applyModifierOverride = (key, val, ent) => +{ return val; }; AddMock(SYSTEM_ENTITY, IID_ModifiersManager, { - "ApplyModifiers": (key, val, ent) => { + "ApplyModifiers": (key, val, ent) => + { return applyModifierOverride(key, val, ent); } }); @@ -54,13 +57,15 @@ TS_ASSERT_EQUALS(cmpLootNoXp.GetResources().stone, 0); TS_ASSERT_UNEVAL_EQUALS(cmpLootNoXp.GetResources(), { "food": 0, "metal": 10, "stone": 0, "wood": 20 }); TS_ASSERT_EQUALS(cmpLootNoXp.GetXp(), 0); -applyModifierOverride = (key, val, ent) => { +applyModifierOverride = (key, val, ent) => +{ return key == "Loot/xp" ? 100 : val; }; TS_ASSERT_EQUALS(cmpLootNoXp.GetXp(), 100); -applyModifierOverride = (key, val, ent) => { +applyModifierOverride = (key, val, ent) => +{ return key == "Loot/wood" ? 100 : val; }; diff --git a/binaries/data/mods/public/simulation/components/tests/test_Looter.js b/binaries/data/mods/public/simulation/components/tests/test_Looter.js index b622df7d4b..1fd3066b1c 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Looter.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Looter.js @@ -3,7 +3,8 @@ Resources = { "GetTradableCodes": () => ["food", "metal", "stone", "wood"], "GetBarterableCodes": () => ["food", "metal", "stone", "wood"], "GetResource": () => ({}), - "BuildSchema": (type) => { + "BuildSchema": (type) => + { let schema = ""; for (const res of Resources.GetCodes()) schema += @@ -49,7 +50,8 @@ AddMock(SYSTEM_ENTITY, IID_PlayerManager, { const resourceCount = {}; AddMock(playerEntity, IID_Player, { - "AddResources": (amounts) => { + "AddResources": (amounts) => + { for (const type in amounts) resourceCount[type] = (resourceCount[type] ?? 0) +amounts[type]; } diff --git a/binaries/data/mods/public/simulation/components/tests/test_ModifiersManager.js b/binaries/data/mods/public/simulation/components/tests/test_ModifiersManager.js index 3891dd8af0..bfc4ef644b 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_ModifiersManager.js +++ b/binaries/data/mods/public/simulation/components/tests/test_ModifiersManager.js @@ -158,7 +158,8 @@ AddMock(5, IID_Ownership, { TS_ASSERT_EQUALS(ApplyValueModificationsToEntity("Test_D", 10, 5), 16); // Test: Entity changes owner from player 2 (HP modifier) to player 3 (Vision modifier) -(function Test_OwnerChange_ModifierSwitch() { +(function Test_OwnerChange_ModifierSwitch() +{ const PLAYER2_ID = 2; const PLAYER3_ID = 3; const PLAYER2_ENTITY = 20; diff --git a/binaries/data/mods/public/simulation/components/tests/test_Pack.js b/binaries/data/mods/public/simulation/components/tests/test_Pack.js index 44a8ff2068..f707414f85 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Pack.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Pack.js @@ -45,7 +45,8 @@ AddMock(SYSTEM_ENTITY, IID_Timer, { "SetInterval": (entity, iid, funcname, time, repeattime, data) => { timerActivated = true; return 7; } }); -Engine.AddEntity = function(template) { +Engine.AddEntity = function(template) +{ TS_ASSERT_EQUALS(template, "finalTemplate"); return true; }; diff --git a/binaries/data/mods/public/simulation/components/tests/test_Player.js b/binaries/data/mods/public/simulation/components/tests/test_Player.js index e825da5af3..6687eb3438 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Player.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Player.js @@ -3,7 +3,8 @@ Resources = { "GetTradableCodes": () => ["food", "metal", "stone", "wood"], "GetBarterableCodes": () => ["food", "metal", "stone", "wood"], "GetResource": () => ({}), - "BuildSchema": (type) => { + "BuildSchema": (type) => + { let schema = ""; for (const res of Resources.GetCodes()) schema += diff --git a/binaries/data/mods/public/simulation/components/tests/test_RallyPoint.js b/binaries/data/mods/public/simulation/components/tests/test_RallyPoint.js index 8b83ff6710..a64cf5b1bc 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_RallyPoint.js +++ b/binaries/data/mods/public/simulation/components/tests/test_RallyPoint.js @@ -44,36 +44,42 @@ function initialRallyPointTest(test_function) initialRallyPointTest((cmpRallyPoint) => {}); -initialRallyPointTest((cmpRallyPoint) => { +initialRallyPointTest((cmpRallyPoint) => +{ cmpRallyPoint.Unset(); return true; }); -initialRallyPointTest((cmpRallyPoint) => { +initialRallyPointTest((cmpRallyPoint) => +{ cmpRallyPoint.Reset(); return true; }); // Construction -initialRallyPointTest((cmpRallyPoint) => { +initialRallyPointTest((cmpRallyPoint) => +{ cmpRallyPoint.OnOwnershipChanged({ "from": INVALID_PLAYER, "to": 1 }); return false; }); // Capturing -initialRallyPointTest((cmpRallyPoint) => { +initialRallyPointTest((cmpRallyPoint) => +{ cmpRallyPoint.OnOwnershipChanged({ "from": 1, "to": 2 }); return true; }); // Destruction -initialRallyPointTest((cmpRallyPoint) => { +initialRallyPointTest((cmpRallyPoint) => +{ cmpRallyPoint.OnOwnershipChanged({ "from": 2, "to": INVALID_PLAYER }); return false; }); // Gaia -initialRallyPointTest((cmpRallyPoint) => { +initialRallyPointTest((cmpRallyPoint) => +{ cmpRallyPoint.OnOwnershipChanged({ "from": 2, "to": 0 }); return true; }); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Researcher.js b/binaries/data/mods/public/simulation/components/tests/test_Researcher.js index 5d73a3a95e..34c2ce308e 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Researcher.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Researcher.js @@ -113,18 +113,22 @@ const techManager = AddMock(playerEntityID, IID_TechnologyManager, { "CheckTechnologyRequirements": () => true, "IsInProgress": () => false, "IsTechnologyResearched": () => false, - "QueuedResearch": (templateName, researcher, techCostMultiplier) => { + "QueuedResearch": (templateName, researcher, techCostMultiplier) => + { TS_ASSERT_UNEVAL_EQUALS(templateName, queuedTech); TS_ASSERT_UNEVAL_EQUALS(researcher, entityID); return true; }, - "StoppedResearch": (templateName, _) => { + "StoppedResearch": (templateName, _) => + { TS_ASSERT_UNEVAL_EQUALS(templateName, queuedTech); }, - "StartedResearch": (templateName, _) => { + "StartedResearch": (templateName, _) => + { TS_ASSERT_UNEVAL_EQUALS(templateName, queuedTech); }, - "ResearchTechnology": (templateName, _) => { + "ResearchTechnology": (templateName, _) => + { TS_ASSERT_UNEVAL_EQUALS(templateName, queuedTech); } }); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Resistance.js b/binaries/data/mods/public/simulation/components/tests/test_Resistance.js index 8739885e64..c80ec99ac9 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Resistance.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Resistance.js @@ -67,7 +67,8 @@ class testResistance TS_ASSERT(!this.cmpResistance.IsInvulnerable()); const cmpHealth = AddMock(this.EntityID, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, damage); return { "healthChange": -amount }; } @@ -113,7 +114,8 @@ class testResistance }); const cmpHealth = AddMock(this.EntityID, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, damage * bonus); return { "healthChange": -amount }; } @@ -147,7 +149,8 @@ class testResistance }; const cmpHealth = AddMock(this.EntityID, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, damage * Math.pow(0.9, resistanceValue)); return { "healthChange": -amount }; } @@ -178,7 +181,8 @@ class testResistance }; const cmpCapturable = AddMock(this.EntityID, IID_Capturable, { - "Capture": (amount, __, ___) => { + "Capture": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, damage * Math.pow(0.9, resistanceValue)); return { "captureChange": amount }; } @@ -219,7 +223,8 @@ class testResistance }; let cmpStatusEffectsReceiver = AddMock(this.EntityID, IID_StatusEffectsReceiver, { - "ApplyStatus": (effectData, __, ___) => { + "ApplyStatus": (effectData, __, ___) => + { TS_ASSERT_EQUALS(effectData[statusName].Duration, duration * durationFactor); return { "inflictedStatuses": Object.keys(effectData) }; } @@ -246,7 +251,8 @@ class testResistance }); cmpStatusEffectsReceiver = AddMock(this.EntityID, IID_StatusEffectsReceiver, { - "ApplyStatus": (effectData, __, ___) => { + "ApplyStatus": (effectData, __, ___) => + { TS_ASSERT_UNEVAL_EQUALS(effectData, {}); return { "inflictedStatuses": Object.keys(effectData) }; } @@ -289,7 +295,8 @@ class testResistance }; cmpStatusEffectsReceiver = AddMock(this.EntityID, IID_StatusEffectsReceiver, { - "ApplyStatus": (effectData, __, ___) => { + "ApplyStatus": (effectData, __, ___) => + { TS_ASSERT_EQUALS(effectData[reducedStatusName].Duration, duration * durationFactor); TS_ASSERT_UNEVAL_EQUALS(Object.keys(effectData), [reducedStatusName]); return { "inflictedStatuses": Object.keys(effectData) }; @@ -337,7 +344,8 @@ class testResistance }); const cmpHealth = AddMock(this.EntityID, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, damage * bonus * Math.pow(0.9, resistanceValue)); return { "healthChange": -amount }; } @@ -382,13 +390,15 @@ class testResistance }); const cmpCapturable = AddMock(this.EntityID, IID_Capturable, { - "Capture": (amount, __, ___) => { + "Capture": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, damage * bonus * Math.pow(0.9, captureResistanceValue)); return { "captureChange": amount }; } }); const cmpHealth = AddMock(this.EntityID, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, damage * bonus); return { "healthChange": -amount }; }, diff --git a/binaries/data/mods/public/simulation/components/tests/test_ResourceDropsite.js b/binaries/data/mods/public/simulation/components/tests/test_ResourceDropsite.js index 58403df104..1379a8959f 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_ResourceDropsite.js +++ b/binaries/data/mods/public/simulation/components/tests/test_ResourceDropsite.js @@ -1,5 +1,6 @@ Resources = { - "BuildChoicesSchema": () => { + "BuildChoicesSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { diff --git a/binaries/data/mods/public/simulation/components/tests/test_ResourceGatherer.js b/binaries/data/mods/public/simulation/components/tests/test_ResourceGatherer.js index 737a740e5e..1fa593ff9b 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_ResourceGatherer.js +++ b/binaries/data/mods/public/simulation/components/tests/test_ResourceGatherer.js @@ -1,5 +1,6 @@ Resources = { - "BuildSchema": () => { + "BuildSchema": () => + { let schema = ""; for (const res of ["food", "metal", "wood"]) { @@ -9,7 +10,8 @@ Resources = { } return "" + schema + ""; }, - "GetResource": (type) => { + "GetResource": (type) => + { return { "subtypes": { "meat": "meat", @@ -71,7 +73,8 @@ TS_ASSERT_UNEVAL_EQUALS(cmpResourceGatherer.GetCarryingStatus(), []); // Test committing resources. AddMock(dropsiteID, IID_ResourceDropsite, { - "ReceiveResources": (resources, ent) => { + "ReceiveResources": (resources, ent) => + { return { "food": resources.food }; @@ -141,7 +144,8 @@ AddMock(supplyID, IID_ResourceSupply, { "GetCurrentAmount": () => 2, "GetType": () => ({ "generic": "food", "specific": "grain" }), "GetDiminishingReturns": () => 1, - "TakeResources": (amount) => { + "TakeResources": (amount) => + { return { "amount": amount, "exhausted": false @@ -174,7 +178,8 @@ AddMock(supplyID, IID_ResourceSupply, { "GetCurrentAmount": () => 2, "GetType": () => ({ "generic": "food", "specific": "grain" }), "GetDiminishingReturns": () => 1, - "TakeResources": (amount) => { + "TakeResources": (amount) => + { return { "amount": amount, "exhausted": false @@ -194,7 +199,8 @@ AddMock(supplyID, IID_ResourceSupply, { "GetCurrentAmount": () => 3, "GetType": () => ({ "generic": "wood", "specific": "tree" }), "GetDiminishingReturns": () => 1, - "TakeResources": (amount) => { + "TakeResources": (amount) => + { return { "amount": amount, "exhausted": false @@ -221,7 +227,8 @@ AddMock(supplyID, IID_ResourceSupply, { "GetCurrentAmount": () => 1, "GetType": () => ({ "generic": "food", "specific": "grain" }), "GetDiminishingReturns": () => 1, - "TakeResources": (amount) => { + "TakeResources": (amount) => + { return { "amount": amount, "exhausted": true @@ -246,7 +253,8 @@ AddMock(supplyID, IID_ResourceSupply, { "GetCurrentAmount": () => 11, "GetType": () => ({ "generic": "food", "specific": "grain" }), "GetDiminishingReturns": () => 1, - "TakeResources": (amount) => { + "TakeResources": (amount) => + { return { "amount": amount, "exhausted": false @@ -271,7 +279,8 @@ AddMock(supplyID, IID_ResourceSupply, { "GetCurrentAmount": () => 3, "GetType": () => ({ "generic": "food", "specific": "grain" }), "GetDiminishingReturns": () => 1, - "TakeResources": (amount) => { + "TakeResources": (amount) => + { return { "amount": amount, "exhausted": false diff --git a/binaries/data/mods/public/simulation/components/tests/test_ResourceSupply.js b/binaries/data/mods/public/simulation/components/tests/test_ResourceSupply.js index 9c765170be..9cf5ba18d2 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_ResourceSupply.js +++ b/binaries/data/mods/public/simulation/components/tests/test_ResourceSupply.js @@ -1,5 +1,6 @@ Resources = { - "BuildChoicesSchema": () => { + "BuildChoicesSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { diff --git a/binaries/data/mods/public/simulation/components/tests/test_ResourceTrickle.js b/binaries/data/mods/public/simulation/components/tests/test_ResourceTrickle.js index 6faa14dd48..0f463db183 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_ResourceTrickle.js +++ b/binaries/data/mods/public/simulation/components/tests/test_ResourceTrickle.js @@ -3,7 +3,8 @@ Resources = { "GetTradableCodes": () => ["food", "metal"], "GetBarterableCodes": () => ["food", "metal"], "GetResource": () => ({}), - "BuildSchema": (type) => { + "BuildSchema": (type) => + { let schema = ""; for (const res of Resources.GetCodes()) schema += @@ -66,7 +67,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 300, "metal": 300 }); // Test that only trickling food works. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "ResourceTrickle/Rates/food") return currentValue + 1; @@ -89,7 +91,8 @@ TS_ASSERT_EQUALS(cmpResourceTrickle.ComputeRates(), false); cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 301, "metal": 300 }); -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "ResourceTrickle/Interval") return currentValue + 200; if (valueName == "ResourceTrickle/Rates/food") @@ -106,7 +109,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 302, "metal": 300 }); // Interval becomes a normal timer, thus cancelled after the first execution. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "ResourceTrickle/Interval") return currentValue - 200; if (valueName == "ResourceTrickle/Rates/food") @@ -125,7 +129,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 303, "metal": 300 }); // Timer became invalidated, check whether it's recreated properly after that. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "ResourceTrickle/Interval") return currentValue - 100; if (valueName == "ResourceTrickle/Rates/food") @@ -144,7 +149,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 309, "metal": 300 }); // Value is now invalid, timer should be cancelled. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "ResourceTrickle/Interval") return currentValue - 201; if (valueName == "ResourceTrickle/Rates/food") @@ -161,7 +167,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 309, "metal": 300 }); // Timer became invalidated, check whether it's recreated properly after that. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "ResourceTrickle/Rates/food") return currentValue + 1; diff --git a/binaries/data/mods/public/simulation/components/tests/test_Resources.js b/binaries/data/mods/public/simulation/components/tests/test_Resources.js index 447192cda2..828e7e2471 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Resources.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Resources.js @@ -2,7 +2,8 @@ Resources = { "GetCodes": () => ["food", "metal", "stone", "wood"], "GetTradableCodes": () => ["food", "metal", "stone", "wood"], "GetBarterableCodes": () => ["food", "metal", "stone", "wood"], - "BuildSchema": () => { + "BuildSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { @@ -12,7 +13,8 @@ Resources = { } return "" + schema + ""; }, - "BuildChoicesSchema": () => { + "BuildChoicesSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { @@ -22,7 +24,8 @@ Resources = { } return "" + schema + ""; }, - "GetResource": (type) => { + "GetResource": (type) => + { return { "subtypes": { "meat": "meat", diff --git a/binaries/data/mods/public/simulation/components/tests/test_StatusEffectsReceiver.js b/binaries/data/mods/public/simulation/components/tests/test_StatusEffectsReceiver.js index 44398b7511..20a774d125 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_StatusEffectsReceiver.js +++ b/binaries/data/mods/public/simulation/components/tests/test_StatusEffectsReceiver.js @@ -18,7 +18,8 @@ const enemy = 2; let statusName; const AttackHelper = { - "HandleAttackEffects": (_, data) => { + "HandleAttackEffects": (_, data) => + { for (const type in data.attackData.Damage) dealtDamage += data.attackData.Damage[type]; } diff --git a/binaries/data/mods/public/simulation/components/tests/test_Technologies.js b/binaries/data/mods/public/simulation/components/tests/test_Technologies.js index 8976b1d016..6fd6789989 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Technologies.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Technologies.js @@ -2,7 +2,8 @@ Resources = { "GetCodes": () => ["food", "metal", "stone", "wood"], "GetTradableCodes": () => ["food", "metal", "stone", "wood"], "GetBarterableCodes": () => ["food", "metal", "stone", "wood"], - "BuildSchema": () => { + "BuildSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { @@ -12,7 +13,8 @@ Resources = { } return "" + schema + ""; }, - "BuildChoicesSchema": () => { + "BuildChoicesSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { @@ -22,7 +24,8 @@ Resources = { } return "" + schema + ""; }, - "GetResource": (type) => { + "GetResource": (type) => + { return { "subtypes": { "meat": "meat", @@ -57,7 +60,8 @@ const template = { }; Engine.RegisterGlobal("TechnologyTemplates", { "GetAll": () => [], - "Get": (tech) => { + "Get": (tech) => + { return template; } }); diff --git a/binaries/data/mods/public/simulation/components/tests/test_TechnologyManager.js b/binaries/data/mods/public/simulation/components/tests/test_TechnologyManager.js index a7db8730f8..75d9459b6f 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_TechnologyManager.js +++ b/binaries/data/mods/public/simulation/components/tests/test_TechnologyManager.js @@ -11,7 +11,8 @@ ConstructComponent(SYSTEM_ENTITY, "Trigger"); const techTemplate = {}; Engine.RegisterGlobal("TechnologyTemplates", { "GetAll": () => [], - "Get": (tech) => { + "Get": (tech) => + { return techTemplate; } }); @@ -41,12 +42,14 @@ techTemplate.cost = { }; const cmpPlayer = AddMock(playerEntityID, IID_Player, { "GetPlayerID": () => playerID, - "TrySubtractResources": (resources) => { + "TrySubtractResources": (resources) => + { TS_ASSERT_UNEVAL_EQUALS(resources, techTemplate.cost); // Just have enough resources. return true; }, - "RefundResources": (resources) => { + "RefundResources": (resources) => + { TS_ASSERT_UNEVAL_EQUALS(resources, techTemplate.cost); }, }); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Timer.js b/binaries/data/mods/public/simulation/components/tests/test_Timer.js index c2c21fbb94..c75b9dca10 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Timer.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Timer.js @@ -8,14 +8,16 @@ var cmpTimer = ConstructComponent(SYSTEM_ENTITY, "Timer"); var fired = []; AddMock(10, IID_Test, { - "Callback": function(data, lateness) { + "Callback": function(data, lateness) + { fired.push([data, lateness]); } }); var cancelId; AddMock(20, IID_Test, { - "Callback": function(data, lateness) { + "Callback": function(data, lateness) + { fired.push([data, lateness]); cmpTimer.CancelTimer(cancelId); } diff --git a/binaries/data/mods/public/simulation/components/tests/test_Trainer.js b/binaries/data/mods/public/simulation/components/tests/test_Trainer.js index d7abe08814..a75e18d5a5 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Trainer.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Trainer.js @@ -168,10 +168,12 @@ AddMock(SYSTEM_ENTITY, IID_GuiInterface, { const cmpPlayer = AddMock(playerEntityID, IID_Player, { "BlockTraining": () => {}, "GetPlayerID": () => playerID, - "RefundResources": (resources) => { + "RefundResources": (resources) => + { TS_ASSERT_UNEVAL_EQUALS(resources, cost); }, - "TrySubtractResources": (resources) => { + "TrySubtractResources": (resources) => + { TS_ASSERT_UNEVAL_EQUALS(resources, cost); // Just have enough resources. return true; @@ -231,7 +233,8 @@ TS_ASSERT_EQUALS(cmpTrainer.GetBatch(id).progress, 0.5); const spawedEntityIDs = [4, 5, 6, 7, 8]; let spawned = 0; -Engine.AddEntity = () => { +Engine.AddEntity = () => +{ const ent = spawedEntityIDs[spawned++]; ConstructComponent(ent, "TrainingRestrictions", { @@ -247,7 +250,8 @@ Engine.AddEntity = () => { }); AddMock(ent, IID_Ownership, { - "SetOwner": (pid) => { + "SetOwner": (pid) => + { QueryOwnerInterface(ent, IID_EntityLimits).OnGlobalOwnershipChanged({ "entity": ent, "from": -1, @@ -304,7 +308,8 @@ TS_ASSERT_EQUALS(cmpTrainer.GetBatch(id2).unitTemplate, queuedSecondUnit); // Add a modifier that replaces unit A with unit C, // adds a unit D and removes unit B from the roster. -Engine.RegisterGlobal("ApplyValueModificationsToEntity", (_, val) => { +Engine.RegisterGlobal("ApplyValueModificationsToEntity", (_, val) => +{ return typeof val === "string" ? HandleTokens(val, "units/{civ}/cavalry_javelineer_b>units/{civ}/c units/{civ}/d -units/{civ}/infantry_swordsman_b") : val; }); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Treasure.js b/binaries/data/mods/public/simulation/components/tests/test_Treasure.js index d1210d2ebe..df2bd14d3a 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Treasure.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Treasure.js @@ -1,5 +1,6 @@ Resources = { - "BuildSchema": () => { + "BuildSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { diff --git a/binaries/data/mods/public/simulation/components/tests/test_Treasures.js b/binaries/data/mods/public/simulation/components/tests/test_Treasures.js index 3cab69ac5a..0d16fb6511 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Treasures.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Treasures.js @@ -2,7 +2,8 @@ Resources = { "GetCodes": () => ["food", "metal", "stone", "wood"], "GetTradableCodes": () => ["food", "metal", "stone", "wood"], "GetBarterableCodes": () => ["food", "metal", "stone", "wood"], - "BuildSchema": () => { + "BuildSchema": () => + { let schema = ""; for (const res of ["food", "metal"]) { @@ -12,7 +13,8 @@ Resources = { } return "" + schema + ""; }, - "GetResource": (type) => { + "GetResource": (type) => + { return { "subtypes": { "meat": "meat", diff --git a/binaries/data/mods/public/simulation/components/tests/test_TurretHolder.js b/binaries/data/mods/public/simulation/components/tests/test_TurretHolder.js index 8ca3335a76..7ece123cc4 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_TurretHolder.js +++ b/binaries/data/mods/public/simulation/components/tests/test_TurretHolder.js @@ -137,7 +137,8 @@ cmpTurretHolder = ConstructComponent(turretHolderID, "TurretHolder", { }); let spawned = 100; -Engine.AddEntity = function() { +Engine.AddEntity = function() +{ ++spawned; if (spawned > 101) { @@ -186,7 +187,8 @@ cmpTurretHolder.OnOwnershipChanged({ TS_ASSERT(cmpTurretHolder.OccupiesTurretPoint(spawned)); // Normal turret creation. -Engine.AddEntity = function(t) { +Engine.AddEntity = function(t) +{ ++spawned; // Check that we're using the upgraded template. TS_ASSERT(t, "units/iber/cavalry_javelineer_a"); diff --git a/binaries/data/mods/public/simulation/components/tests/test_Turrets.js b/binaries/data/mods/public/simulation/components/tests/test_Turrets.js index e3c22562a2..8e465f5e3d 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Turrets.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Turrets.js @@ -15,7 +15,8 @@ const friendlyPlayer = 3; const turret = 10; const holder = 11; -const createTurretCmp = entity => { +const createTurretCmp = entity => +{ AddMock(entity, IID_Identity, { "GetClassesList": () => ["Ranged"], "GetSelectionGroupName": () => "mace_infantry_archer_a" diff --git a/binaries/data/mods/public/simulation/components/tests/test_UnitAI.js b/binaries/data/mods/public/simulation/components/tests/test_UnitAI.js index 3d1a4a4181..f6d1fa2e6e 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_UnitAI.js +++ b/binaries/data/mods/public/simulation/components/tests/test_UnitAI.js @@ -59,7 +59,8 @@ function TestTargetEntityRenaming(init_state, post_state, setup) TestTargetEntityRenaming( "INDIVIDUAL.GARRISON.APPROACHING", "INDIVIDUAL.IDLE", - (unitAI, player_ent, target_ent) => { + (unitAI, player_ent, target_ent) => + { unitAI.CanGarrison = (target) => target == target_ent; unitAI.MoveToTargetRange = (target) => target == target_ent; unitAI.AbleToMove = () => true; @@ -70,7 +71,8 @@ TestTargetEntityRenaming( TestTargetEntityRenaming( "INDIVIDUAL.REPAIR.REPAIRING", "INDIVIDUAL.REPAIR.REPAIRING", - (unitAI, player_ent, target_ent) => { + (unitAI, player_ent, target_ent) => + { AddMock(player_ent, IID_Builder, { "StartRepairing": () => true, @@ -88,7 +90,8 @@ TestTargetEntityRenaming( TestTargetEntityRenaming( "INDIVIDUAL.FLEEING", "INDIVIDUAL.FLEEING", - (unitAI, player_ent, target_ent) => { + (unitAI, player_ent, target_ent) => + { PositionHelper.DistanceBetweenEntities = () => 10; unitAI.CheckTargetRangeExplicit = () => false; @@ -127,7 +130,8 @@ function TestFormationExiting(mode) }); AddMock(SYSTEM_ENTITY, IID_RangeManager, { - "CreateActiveQuery": function(ent, minRange, maxRange, players, iid, flags, accountForSize) { + "CreateActiveQuery": function(ent, minRange, maxRange, players, iid, flags, accountForSize) + { return 1; }, "EnableActiveQuery": function(id) { }, @@ -307,7 +311,8 @@ function TestMoveIntoFormationWhileAttacking() AddMock(SYSTEM_ENTITY, IID_RangeManager, { - "CreateActiveQuery": function(ent, minRange, maxRange, players, iid, flags, accountForSize) { + "CreateActiveQuery": function(ent, minRange, maxRange, players, iid, flags, accountForSize) + { return 1; }, "EnableActiveQuery": function(id) { }, @@ -568,11 +573,13 @@ function TestAttemptObstructionMitigation() let canceledTimer = null; return { - "SetTimeout": function(entity, iid, functionName, time, data) { + "SetTimeout": function(entity, iid, functionName, time, data) + { timerId = 123; return timerId; }, - "CancelTimer": function(id) { + "CancelTimer": function(id) + { canceledTimer = id; }, "SetInterval": function() { return null; } @@ -611,7 +618,8 @@ function TestAttemptObstructionMitigation() "GetRotation": () => ({ "y": 0 }), "GetTurretParent": () => INVALID_ENTITY, "TurnTo": () => {}, - "JumpTo": function(x, z) { + "JumpTo": function(x, z) + { controllerX = x; controllerZ = z; }, @@ -676,7 +684,8 @@ function TestAttemptObstructionMitigation() } // Should not execute if already attempted - (function() { + (function() + { controllerAI.obstructionMitigationAttempted = true; const originalX = controllerX; const originalZ = controllerZ; @@ -691,7 +700,8 @@ function TestAttemptObstructionMitigation() })(); // Should not execute without formation component - (function() { + (function() + { const originalX = controllerX; const originalZ = controllerZ; @@ -703,7 +713,8 @@ function TestAttemptObstructionMitigation() })(); // Should not execute without valid destination - (function() { + (function() + { const formationMock = { "GetClosestMemberToPosition": () => member1ID }; // Test with missing destination @@ -717,19 +728,22 @@ function TestAttemptObstructionMitigation() })(); // Should not execute if no closest member found - (function() { + (function() + { const formationMock = { "GetClosestMemberToPosition": () => INVALID_ENTITY }; testObstructionMitigation(formationMock, { "x": 100, "z": 100 }, 0, 0, false); })(); // Should not execute if member or controller missing position component - (function() { + (function() + { const formationMock = { "GetClosestMemberToPosition": () => member1ID }; testObstructionMitigation(formationMock, { "x": 100, "z": 100 }, 0, 0, false); })(); // Should jump when member is more than 2 meters closer to destination - (function() { + (function() + { AddMock(member1ID, IID_Position, { "GetPosition2D": () => new Vector2D(90, 90) }); @@ -742,7 +756,8 @@ function TestAttemptObstructionMitigation() })(); // Should NOT jump when member is NOT more than 2 meters closer - (function() { + (function() + { AddMock(member1ID, IID_Position, { "GetPosition2D": () => new Vector2D(95, 96) }); @@ -765,7 +780,8 @@ function TestAttemptObstructionMitigation() })(); // Should NOT jump when member is actually farther away - (function() { + (function() + { AddMock(member1ID, IID_Position, { "GetPosition2D": () => new Vector2D(0, 0) }); @@ -788,7 +804,8 @@ function TestAttemptObstructionMitigation() })(); // Should jump when member is exactly 2.1 meters closer (edge case) - (function() { + (function() + { AddMock(member1ID, IID_Position, { "GetPosition2D": () => new Vector2D(2, 1) }); @@ -801,7 +818,8 @@ function TestAttemptObstructionMitigation() })(); // Test SetObstructionMitigationFlag and ResetObstructionMitigationFlag - (function() { + (function() + { // Use SetTimeout version for this test AddMock(SYSTEM_ENTITY, IID_Timer, createTimerMock(true)); @@ -816,7 +834,8 @@ function TestAttemptObstructionMitigation() })(); // Multiple members, should pick closest one - (function() { + (function() + { const members = [member1ID, member2ID, member3ID]; AddMock(member1ID, IID_Position, { @@ -835,7 +854,8 @@ function TestAttemptObstructionMitigation() }); const formationMock = { - "GetClosestMemberToPosition": function(targetPosition, filter) { + "GetClosestMemberToPosition": function(targetPosition, filter) + { const memberPositions = { [member1ID]: { "x": 80, "y": 80 }, [member2ID]: { "x": 90, "y": 90 }, diff --git a/binaries/data/mods/public/simulation/components/tests/test_UpgradeModification.js b/binaries/data/mods/public/simulation/components/tests/test_UpgradeModification.js index 995bb60073..7b45eea9ed 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_UpgradeModification.js +++ b/binaries/data/mods/public/simulation/components/tests/test_UpgradeModification.js @@ -2,7 +2,8 @@ Engine.LoadHelperScript("Player.js"); Engine.LoadHelperScript("Requirements.js"); Engine.LoadHelperScript("ValueModification.js"); Resources = { - "BuildSchema": type => { + "BuildSchema": type => + { let schema = ""; for (const res of ["food", "metal", "stone", "wood"]) schema += @@ -92,7 +93,8 @@ AddMock(SYSTEM_ENTITY, IID_Timer, { }); AddMock(SYSTEM_ENTITY, IID_ModifiersManager, { - "ApplyTemplateModifiers": (valueName, curValue, templ, player) => { + "ApplyTemplateModifiers": (valueName, curValue, templ, player) => + { // Called in helpers/ValueModification.js::ApplyValueModificationsToTemplate() // as part of Tests T2 and T5 below. const mods = isResearched ? templateTechModifications.with : templateTechModifications.without; @@ -101,7 +103,8 @@ AddMock(SYSTEM_ENTITY, IID_ModifiersManager, { return GetTechModifiedProperty(mods[valueName], GetIdentityClasses(template.Identity), curValue); return curValue; }, - "ApplyModifiers": (valueName, curValue, ent) => { + "ApplyModifiers": (valueName, curValue, ent) => + { // Called in helpers/ValueModification.js::ApplyValueModificationsToEntity() // as part of Tests T3, T6 and T7 below. const mods = isResearched ? entityTechModifications.with : entityTechModifications.without; diff --git a/binaries/data/mods/public/simulation/components/tests/test_Upkeep.js b/binaries/data/mods/public/simulation/components/tests/test_Upkeep.js index 9ec84bebbc..53ad9d0678 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_Upkeep.js +++ b/binaries/data/mods/public/simulation/components/tests/test_Upkeep.js @@ -3,7 +3,8 @@ Resources = { "GetTradableCodes": () => ["food", "metal"], "GetBarterableCodes": () => ["food", "metal"], "GetResource": () => ({}), - "BuildSchema": (type) => { + "BuildSchema": (type) => + { let schema = ""; for (const res of Resources.GetCodes()) schema += @@ -68,7 +69,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 300, "metal": 300 }); // Test that only requiring food works. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Rates/food") return currentValue + 1; @@ -91,7 +93,8 @@ TS_ASSERT_EQUALS(cmpUpkeep.ComputeRates(), false); cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 299, "metal": 300 }); -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Interval") return currentValue + 200; if (valueName == "Upkeep/Rates/food") @@ -108,7 +111,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 298, "metal": 300 }); // Interval becomes a normal timer, thus cancelled after the first execution. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Interval") return currentValue - 200; if (valueName == "Upkeep/Rates/food") @@ -127,7 +131,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 297, "metal": 300 }); // Timer became invalidated, check whether it's recreated properly after that. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Interval") return currentValue - 100; if (valueName == "Upkeep/Rates/food") @@ -146,7 +151,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 291, "metal": 300 }); // Value is now invalid, timer should be cancelled. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Interval") return currentValue - 201; if (valueName == "Upkeep/Rates/food") @@ -163,7 +169,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 291, "metal": 300 }); // Timer became invalidated, check whether it's recreated properly after that. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Rates/food") return currentValue + 1; @@ -180,7 +187,8 @@ cmpTimer.OnUpdate({ "turnLength": turnLength }); TS_ASSERT_UNEVAL_EQUALS(cmpPlayer.GetResourceCounts(), { "food": 288, "metal": 300 }); // Test multiple upkeep resources. -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Rates/food") return currentValue + 1; if (valueName == "Upkeep/Rates/metal") @@ -203,7 +211,8 @@ const cmpGUI = AddMock(SYSTEM_ENTITY, IID_GuiInterface, { "PushNotification": () => {} }); const notificationSpy = new Spy(cmpGUI, "PushNotification"); -ApplyValueModificationsToEntity = (valueName, currentValue, entity) => { +ApplyValueModificationsToEntity = (valueName, currentValue, entity) => +{ if (valueName == "Upkeep/Rates/food") return currentValue + 1; diff --git a/binaries/data/mods/public/simulation/components/tests/test_ValueModificationHelper.js b/binaries/data/mods/public/simulation/components/tests/test_ValueModificationHelper.js index bfb8d01ab8..09fefffc73 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_ValueModificationHelper.js +++ b/binaries/data/mods/public/simulation/components/tests/test_ValueModificationHelper.js @@ -10,7 +10,8 @@ const techKey = "Attack/BigAttack"; const otherKey = "Other/Key"; AddMock(SYSTEM_ENTITY, IID_ModifiersManager, { - "ApplyModifiers": (key, val, ent) => { + "ApplyModifiers": (key, val, ent) => + { if (key != techKey) return val; if (ent == playerEnt) diff --git a/binaries/data/mods/public/simulation/components/tests/test_VisionSharing.js b/binaries/data/mods/public/simulation/components/tests/test_VisionSharing.js index 56327179a6..c9bb2836f7 100644 --- a/binaries/data/mods/public/simulation/components/tests/test_VisionSharing.js +++ b/binaries/data/mods/public/simulation/components/tests/test_VisionSharing.js @@ -15,7 +15,8 @@ const template = { }; AddMock(SYSTEM_ENTITY, IID_TemplateManager, { - "GetTemplate": (name) => { + "GetTemplate": (name) => + { return name == "special/spy" ? { "Cost": { "Resources": { "wood": 1000 } }, diff --git a/binaries/data/mods/public/simulation/helpers/Commands.js b/binaries/data/mods/public/simulation/helpers/Commands.js index fe40891add..3412d26fd7 100644 --- a/binaries/data/mods/public/simulation/helpers/Commands.js +++ b/binaries/data/mods/public/simulation/helpers/Commands.js @@ -20,14 +20,16 @@ var g_Commands = { "collect-treasure": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.CollectTreasure(cmd.target, cmd.queued); }); }, "collect-treasure-near-position": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.CollectTreasureNearPosition(cmd.x, cmd.z, cmd.queued); }); }, @@ -107,13 +109,15 @@ var g_Commands = { const ents = data.entities.length; const uais = GetFormationUnitAIs(data.entities, player, cmd, data.formation); if (uais.length === 1 || uais.length !== ents) - uais.forEach(cmpUnitAI => { + uais.forEach(cmpUnitAI => + { cmpUnitAI.Walk(cmd.x, cmd.z, cmd.queued, cmd.pushFront); }); else { const positions = Engine.QueryInterface(SYSTEM_ENTITY, IID_Pathfinder).DistributeAround(data.entities, cmd.x, cmd.z); - uais.forEach((cmpUnitAI, index) => { + uais.forEach((cmpUnitAI, index) => + { cmpUnitAI.Walk(positions[index].x, positions[index].y, cmd.queued, cmd.pushFront); }); } @@ -122,7 +126,8 @@ var g_Commands = { "walk-custom": function(player, cmd, data) { for (const ent in data.entities) - GetFormationUnitAIs([data.entities[ent]], player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs([data.entities[ent]], player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Walk(cmd.targetPositions[ent].x, cmd.targetPositions[ent].y, cmd.queued, cmd.pushFront); }); }, @@ -143,13 +148,15 @@ var g_Commands = { const ents = data.entities.length; const uais = GetFormationUnitAIs(data.entities, player, cmd, data.formation); if (uais.length === 1 || uais.length !== ents) - uais.forEach(cmpUnitAI => { + uais.forEach(cmpUnitAI => + { cmpUnitAI.WalkAndFight(cmd.x, cmd.z, cmd.targetClasses, cmd.allowCapture, cmd.queued, cmd.pushFront); }); else { const positions = Engine.QueryInterface(SYSTEM_ENTITY, IID_Pathfinder).DistributeAround(data.entities, cmd.x, cmd.z); - uais.forEach((cmpUnitAI, index) => { + uais.forEach((cmpUnitAI, index) => + { cmpUnitAI.WalkAndFight(positions[index].x, positions[index].y, cmd.targetClasses, cmd.allowCapture, cmd.queued, cmd.pushFront); }); } @@ -158,14 +165,16 @@ var g_Commands = { "attack-walk-custom": function(player, cmd, data) { for (const ent in data.entities) - GetFormationUnitAIs([data.entities[ent]], player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs([data.entities[ent]], player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.WalkAndFight(cmd.targetPositions[ent].x, cmd.targetPositions[ent].y, cmd.targetClasses, cmd.allowCapture, cmd.queued, cmd.pushFront); }); }, "attack": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Attack(cmd.target, cmd.allowCapture, cmd.queued, cmd.pushFront); }); }, @@ -175,13 +184,15 @@ var g_Commands = { const ents = data.entities.length; const uais = GetFormationUnitAIs(data.entities, player, cmd, data.formation); if (uais.length === 1 || uais.length !== ents) - uais.forEach(cmpUnitAI => { + uais.forEach(cmpUnitAI => + { cmpUnitAI.Patrol(cmd.x, cmd.z, cmd.targetClasses, cmd.allowCapture, cmd.queued); }); else { const positions = Engine.QueryInterface(SYSTEM_ENTITY, IID_Pathfinder).DistributeAround(data.entities, cmd.x, cmd.z); - uais.forEach((cmpUnitAI, index) => { + uais.forEach((cmpUnitAI, index) => + { cmpUnitAI.Patrol(positions[index].x, positions[index].y, cmd.targetClasses, cmd.allowCapture, cmd.queued); }); } @@ -192,7 +203,8 @@ var g_Commands = { if (g_DebugCommands && !(IsOwnedByPlayer(player, cmd.target) || IsOwnedByAllyOfPlayer(player, cmd.target))) warn("Invalid command: heal target is not owned by player "+player+" or their ally: "+uneval(cmd)); - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Heal(cmd.target, cmd.queued, cmd.pushFront); }); }, @@ -203,7 +215,8 @@ var g_Commands = { if (g_DebugCommands && !IsOwnedByAllyOfPlayer(player, cmd.target)) warn("Invalid command: repair target is not owned by ally of player "+player+": "+uneval(cmd)); - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Repair(cmd.target, cmd.autocontinue, cmd.queued, cmd.pushFront); }); }, @@ -213,14 +226,16 @@ var g_Commands = { if (g_DebugCommands && !(IsOwnedByPlayer(player, cmd.target) || IsOwnedByGaia(cmd.target))) warn("Invalid command: resource is not owned by gaia or player "+player+": "+uneval(cmd)); - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Gather(cmd.target, cmd.queued, cmd.pushFront); }); }, "gather-near-position": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.GatherNearPosition(cmd.x, cmd.z, cmd.resourceType, cmd.resourceTemplate, cmd.queued, cmd.pushFront); }); }, @@ -230,7 +245,8 @@ var g_Commands = { if (g_DebugCommands && !IsOwnedByPlayer(player, cmd.target)) warn("Invalid command: dropsite is not owned by player "+player+": "+uneval(cmd)); - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.ReturnResource(cmd.target, cmd.queued, cmd.pushFront); }); }, @@ -251,7 +267,8 @@ var g_Commands = { MatchesClassList(Engine.QueryInterface(ent, IID_Identity).GetClassesList(), ["Soldier", "Warship", "Siege", "Healer"]) ); - GetFormationUnitAIs(unitsToMove, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(unitsToMove, player, cmd, data.formation).forEach(cmpUnitAI => + { if (cmd.pushFront) { cmpUnitAI.WalkAndFight(cmd.position.x, cmd.position.z, cmd.targetClasses, cmd.allowCapture, false, cmd.pushFront); @@ -448,7 +465,8 @@ var g_Commands = { "occupy-turret": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player).forEach(cmpUnitAI => + { cmpUnitAI.OccupyTurret(cmd.target, cmd.queued); }); }, @@ -462,7 +480,8 @@ var g_Commands = { return; } - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Garrison(cmd.target, cmd.queued, cmd.pushFront); }); }, @@ -476,14 +495,16 @@ var g_Commands = { return; } - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Guard(cmd.target, cmd.queued, cmd.pushFront); }); }, "stop": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.Stop(cmd.queued); }); }, @@ -607,7 +628,8 @@ var g_Commands = { "formation": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation, true).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation, true).forEach(cmpUnitAI => + { cmpUnitAI.MoveIntoFormation(cmd); }); }, @@ -660,14 +682,16 @@ var g_Commands = { "setup-trade-route": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.SetupTradeRoute(cmd.target, cmd.source, cmd.route, cmd.queued); }); }, "cancel-setup-trade-route": function(player, cmd, data) { - GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => { + GetFormationUnitAIs(data.entities, player, cmd, data.formation).forEach(cmpUnitAI => + { cmpUnitAI.CancelSetupTradeRoute(cmd.target); }); }, @@ -798,7 +822,8 @@ var g_Commands = { "spy-request": function(player, cmd, data) { const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager); - const ent = pickRandom(cmpRangeManager.GetEntitiesByPlayer(cmd.player).filter(entity => { + const ent = pickRandom(cmpRangeManager.GetEntitiesByPlayer(cmd.player).filter(entity => + { const cmpVisionSharing = Engine.QueryInterface(entity, IID_VisionSharing); return cmpVisionSharing && cmpVisionSharing.IsBribable() && !cmpVisionSharing.ShareVisionWith(player); })); diff --git a/binaries/data/mods/public/simulation/helpers/Player.js b/binaries/data/mods/public/simulation/helpers/Player.js index 7847b403c1..c3b29d0462 100644 --- a/binaries/data/mods/public/simulation/helpers/Player.js +++ b/binaries/data/mods/public/simulation/helpers/Player.js @@ -14,7 +14,8 @@ function LoadPlayerSettings(settings, newPlayers) if (!playerData) warn("Player.js: Setup has no player data - using defaults."); - const getPlayerSetting = (idx, property) => { + const getPlayerSetting = (idx, property) => + { if (playerData && playerData[idx] && (property in playerData[idx])) return playerData[idx][property]; diff --git a/binaries/data/mods/public/simulation/helpers/tests/test_Attack.js b/binaries/data/mods/public/simulation/helpers/tests/test_Attack.js index 050f1bcc73..7df103504c 100644 --- a/binaries/data/mods/public/simulation/helpers/tests/test_Attack.js +++ b/binaries/data/mods/public/simulation/helpers/tests/test_Attack.js @@ -30,8 +30,10 @@ Engine.LoadComponentScript("interfaces/StatusEffectsReceiver.js"); // TODO: Some of it is tested in components/test_Damage.js, which should be spliced and moved. -class testHandleAttackEffects { - constructor() { +class testHandleAttackEffects +{ + constructor() + { this.resultString = ""; this.TESTED_ENTITY_ID = 5; @@ -47,7 +49,8 @@ class testHandleAttackEffects { /** * This tests that we inflict multiple effect types. */ - testMultipleEffects() { + testMultipleEffects() + { AddMock(this.TESTED_ENTITY_ID, IID_Health, { "TakeDamage": x => { this.resultString += x; }, "GetHitpoints": () => 1, @@ -72,7 +75,8 @@ class testHandleAttackEffects { /** * This tests that we correctly handle effect types if one is not received. */ - testSkippedEffect() { + testSkippedEffect() + { AddMock(this.TESTED_ENTITY_ID, IID_Capturable, { "Capture": x => { this.resultString += x; }, }); @@ -107,7 +111,8 @@ class testHandleAttackEffects { /** * Check that the Attacked message is [not] sent if [no] receivers exist. */ - testAttackedMessage() { + testAttackedMessage() + { Engine.PostMessage = () => TS_ASSERT(false); AttackHelper.HandleAttackEffects(this.TESTED_ENTITY_ID, { "type": "Test", @@ -148,9 +153,11 @@ class testHandleAttackEffects { /** * Regression test that StatusEffects are handled correctly. */ - testStatusEffects() { + testStatusEffects() + { const cmpStatusEffectsReceiver = AddMock(this.TESTED_ENTITY_ID, IID_StatusEffectsReceiver, { - "ApplyStatus": (effectData, __, ___) => { + "ApplyStatus": (effectData, __, ___) => + { TS_ASSERT_UNEVAL_EQUALS(effectData, this.attackData.ApplyStatus); } }); @@ -168,16 +175,19 @@ class testHandleAttackEffects { /** * Regression test that bonus multiplier is handled correctly. */ - testBonusMultiplier() { + testBonusMultiplier() + { AddMock(this.TESTED_ENTITY_ID, IID_Health, { - "TakeDamage": (amount, __, ___) => { + "TakeDamage": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, this.attackData.Damage * 2); }, "GetHitpoints": () => 1, "GetMaxHitpoints": () => 1, }); AddMock(this.TESTED_ENTITY_ID, IID_Capturable, { - "Capture": (amount, __, ___) => { + "Capture": (amount, __, ___) => + { TS_ASSERT_EQUALS(amount, this.attackData.Capture * 2); }, }); diff --git a/binaries/data/tests/test_setup.js b/binaries/data/tests/test_setup.js index b0fda6a095..8e72fcbf3c 100644 --- a/binaries/data/tests/test_setup.js +++ b/binaries/data/tests/test_setup.js @@ -54,10 +54,13 @@ global.TS_ASSERT_UNEVAL_EQUALS = function(x, y) global.TS_ASSERT_EXCEPTION = function(func) { - try { + try + { func(); Engine.TS_FAIL("Missed exception at:\n" + new Error().stack); - } catch (e) { + } + catch(e) + { // noop } }; diff --git a/eslint.config.mjs b/eslint.config.mjs index 3b25636f48..dc829911aa 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -3,7 +3,6 @@ // [1] https://nodejs.org/api/esm.html#esm_no_node_path import { createRequire } from 'node:module'; const require = createRequire(import.meta.url); -const braceRules = require("eslint-plugin-brace-rules"); const stylistic = require("@stylistic/eslint-plugin"); @@ -123,6 +122,7 @@ const configStylistic = { }, "rules": { + "@stylistic/brace-style": ["warn", "allman", { "allowSingleLine": true }], "@stylistic/comma-spacing": "warn", "@stylistic/indent": ["warn", "tab", { "outerIIFEBody": "off" }], "@stylistic/key-spacing": "warn", @@ -147,41 +147,9 @@ const configStylistic = { }; -const configBracesRules = { - "plugins": { - "brace-rules": braceRules - }, - - "rules": { - "brace-rules/brace-on-same-line": [ - "warn", - { - "FunctionDeclaration": "never", - "FunctionExpression": "ignore", - "ArrowFunctionExpression": "always", - "IfStatement": "never", - "TryStatement": "ignore", - "CatchClause": "ignore", - "DoWhileStatement": "never", - "WhileStatement": "never", - "ForStatement": "never", - "ForInStatement": "never", - "ForOfStatement": "never", - "SwitchStatement": "never", - }, - { - "allowSingleLine": true, - } - ], - } -}; - - const configs = [configIgnores, configEslintRecommended]; Object.assign(configs[1].rules, configEslintExtra.rules); -configs[1].plugins = { ...configBracesRules.plugins }; -Object.assign(configs[1].rules, configBracesRules.rules); -Object.assign(configs[1].plugins, configStylistic.plugins); +configs[1].plugins = { ...configStylistic.plugins }; Object.assign(configs[1].rules, configStylistic.rules); export default configs; diff --git a/package.json b/package.json index 6ce0f7e3a8..0f8eaeac8a 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,8 @@ { "type": "module", "devDependencies": { - "@stylistic/eslint-plugin": "^4.4.0", - "eslint": "^9.27.0", - "eslint-plugin-brace-rules": "^0.1.6" + "@stylistic/eslint-plugin": "^5.6.1", + "eslint": "^9.39.2" }, "engines": { "node": ">=20.0.0" diff --git a/source/tools/profiler2/Profiler2Report.js b/source/tools/profiler2/Profiler2Report.js index 7a0b4d688e..a610a432d4 100644 --- a/source/tools/profiler2/Profiler2Report.js +++ b/source/tools/profiler2/Profiler2Report.js @@ -1,4 +1,4 @@ -// Copyright (C) 2025 Wildfire Games. +// Copyright (C) 2026 Wildfire Games. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -77,7 +77,8 @@ class Profiler2Report { self.refresh_from_jsonp(callback, e.target.result); }; - reader.onerror = function(e) { + reader.onerror = function(e) + { alert("Failed to load report file"); callback(false); return; @@ -95,7 +96,8 @@ class Profiler2Report script.parentNode.removeChild(script); var threads = []; - data.threads.forEach(function(thread) { + data.threads.forEach(function(thread) + { var canvas = $(''); threads.push({ 'name': thread.name, 'data': { 'events': concat_events(thread.data) }, 'canvas': canvas.get(0) }); }); @@ -114,14 +116,17 @@ class Profiler2Report $.ajax({ "url": `http://127.0.0.1:${$("#gameport").val()}/overview`, "dataType": 'json', - "success": function(data) { + "success": function(data) + { var threads = []; - data.threads.forEach(function(thread) { + data.threads.forEach(function(thread) + { threads.push({ 'name': thread.name }); }); var callback_data = { 'threads': threads, 'completed': 0 }; - threads.forEach(function(thread) { + threads.forEach(function(thread) + { self.refresh_thread(callback, thread, callback_data); }); }, @@ -140,7 +145,8 @@ class Profiler2Report "url": `http://127.0.0.1:${$("#gameport").val()}/query`, "dataType": 'json', "data": { 'thread': thread.name }, - "success": function(data) { + "success": function(data) + { data.events = concat_events(data); thread.data = data; @@ -151,7 +157,8 @@ class Profiler2Report callback(true); } }, - "error": function(jqXHR, textStatus, errorThrown) { + "error": function(jqXHR, textStatus, errorThrown) + { alert('Failed to connect to server ("'+textStatus+'")'); } }); diff --git a/source/tools/profiler2/ReportDraw.js b/source/tools/profiler2/ReportDraw.js index 515fb22c33..a924a14f34 100644 --- a/source/tools/profiler2/ReportDraw.js +++ b/source/tools/profiler2/ReportDraw.js @@ -1,4 +1,4 @@ -// Copyright (C) 2025 Wildfire Games. +// Copyright (C) 2026 Wildfire Games. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -141,7 +141,8 @@ function display_frames(data, canvas, range) canvas._tooltips.push({ 'x0': x0, 'x1': x1, 'y0': y0, 'y1': y1, - 'text': function() { + 'text': function() + { var t = 'Frame
'; t += 'Length: ' + time_label(duration) + '
'; if (frame.attrs) @@ -218,11 +219,13 @@ function display_events(data, canvas) canvas._tooltips.push({ 'x0': x0, 'x1': x1, 'y0': y0, 'y1': y1, - 'text': function() { + 'text': function() + { var t = '' + event.id + '
'; if (event.attrs) { - event.attrs.forEach(function(attr) { + event.attrs.forEach(function(attr) + { t += attr + '
'; }); } @@ -339,12 +342,14 @@ function display_hierarchy(main_data, data, canvas, range, zoom) canvas._tooltips.push({ 'x0': x0, 'x1': x1, 'y0': y0, 'y1': y1, - 'text': function() { + 'text': function() + { var t = '' + interval.id + '
'; t += 'Length: ' + time_label(interval.duration) + '
'; if (interval.attrs) { - interval.attrs.forEach(function(attr) { + interval.attrs.forEach(function(attr) + { t += attr + '
'; }); } diff --git a/source/tools/profiler2/profiler2.js b/source/tools/profiler2/profiler2.js index 483e249873..f1b60f604f 100644 --- a/source/tools/profiler2/profiler2.js +++ b/source/tools/profiler2/profiler2.js @@ -1,4 +1,4 @@ -// Copyright (C) 2025 Wildfire Games. +// Copyright (C) 2026 Wildfire Games. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -37,9 +37,11 @@ function save_as_file() { $.ajax({ "url": `http://127.0.0.1:${$("#gameport").val()}/download`, - "success": function() { + "success": function() + { }, - "error": function(jqXHR, textStatus, errorThrown) { + "error": function(jqXHR, textStatus, errorThrown) + { } }); } diff --git a/source/tools/profiler2/utilities.js b/source/tools/profiler2/utilities.js index 22776967be..292201eafb 100644 --- a/source/tools/profiler2/utilities.js +++ b/source/tools/profiler2/utilities.js @@ -1,4 +1,4 @@ -// Copyright (C) 2025 Wildfire Games. +// Copyright (C) 2026 Wildfire Games. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -37,7 +37,8 @@ function graph_colour(id) function concat_events(data) { var events = []; - data.events.forEach(function(ev) { + data.events.forEach(function(ev) + { ev.pop(); // remove the dummy null markers Array.prototype.push.apply(events, ev); }); @@ -152,10 +153,12 @@ function set_tooltip_handlers(canvas) } } - $(canvas).mousemove(function(event) { + $(canvas).mousemove(function(event) + { do_tooltip(event); }); - $(canvas).mouseleave(function(event) { + $(canvas).mouseleave(function(event) + { $('#tooltip').css('visibility', 'hidden'); }); } diff --git a/source/tools/replayprofile/graph.js b/source/tools/replayprofile/graph.js index c345a86e89..0dde5e2e69 100644 --- a/source/tools/replayprofile/graph.js +++ b/source/tools/replayprofile/graph.js @@ -33,7 +33,8 @@ var graphFormat = { "unit": "Megabytes", "digits": 2, "scale": 1 / 1024 / 1024, - "isColumn": function(label) { + "isColumn": function(label) + { return label.indexOf("bytes") != -1; } }, @@ -42,7 +43,8 @@ var graphFormat = { "unit": "", "scale": 1, "digits": 0, - "isColumn": function(label) { + "isColumn": function(label) + { return label == "number of GCs"; } } @@ -68,7 +70,8 @@ function showReplayData() } }); - $("#replayGraph").bind("plothover", function(event, pos, item) { + $("#replayGraph").bind("plothover", function(event, pos, item) + { $("#tooltip").remove(); if (!item) return;