Compare commits

...

69 commits

Author SHA1 Message Date
phosit
6ffc251114
Make timedconfirmation.js a module
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
Refs: #8081
2026-08-14 12:41:45 +02:00
phosit
0f939b8abf
Make termsdialog.js a module
Refs: #8081
2026-08-14 12:41:45 +02:00
phosit
bf0c3af75a
Make mod/gui/pregame/mainmenu.js a module
Refs: #8081
2026-08-14 12:41:45 +02:00
phosit
497efe5a99
Make msgbox.js a module
Refs: #8081
2026-08-14 12:41:45 +02:00
phosit
609efa7e32
Make modmod/help/help.js a module
Refs: #8081
2026-08-14 12:41:44 +02:00
phosit
9adb3e7889
Make modmod.js a module
Actions in xml files only has access to the global scope, not the module
scope. So define them in the js file.

Refs: #8081
2026-08-14 12:41:44 +02:00
phosit
2c4f7d85b6
Make modio.js a module
Actions in xml files only has access to the global scope, not the module
scope. So define them in the js file.

Refs: #8081
2026-08-14 12:41:44 +02:00
phosit
8918cfb0a7
Make incompatible_mods.js a module
Refs: #8081
2026-08-14 12:41:44 +02:00
Atrik
1b07b799ec Add test for queries with visibility checks
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
2026-08-12 22:40:59 +02:00
Atrik
38b33b0484 Enable attacks on foes visible through shared LOS
Adds baseRange parameter to parabolic queries for combined
2D + parabolic detection. StandGround and Chase stances now
use attack range (parabolic) with vision as baseRange, allowing
units to attack enemies visible through friendly vision.
Buildings benefit as well via BuildingAI.
2026-08-12 22:40:59 +02:00
Atrik
ceca608848 Filter out hidden targets in CanAttack
Units should not be able to attack entities with "hidden" visibility.
Visible and fogged (mirage/retainInFog) targets remain attackable.
2026-08-12 22:40:59 +02:00
Atrik
f84b51212a Add tests for CanEverReachTarget and its helpers 2026-08-12 22:40:59 +02:00
Atrik
fc3c0d7876 Prevent targeting unreachable turreted entities
Introduce CanEverReachTarget in the Attack component to check whether
a target is geometrically reachable at all, accounting for height
offsets and turreted units inside buildings.

For non-parabolic attacks (e.g. melee), a simple 3D distance check
from the closest approach point is used.

For parabolic attacks (e.g. ranged), the parabolic range formula
is used to determine if the height difference is surmountable
from the closest horizontal distance to the target.

Add GetClosestApproachDistanceToTurretPoint to TurretHolder
to estimate the minimum horizontal distance to a turret point,
using its local offset and the holder's obstruction size.
Passable buildings are not considered obstacles.

Fixes units on the ground trying to attack unreachable units on walls
or towers when the projectile's arc cannot reach the required height.
2026-08-12 22:40:59 +02:00
Atrik
db23584fc3 Add GetEffectiveAttackRange wrapper
Wraps RangeManager.GetEffectiveParabolicRange for unified range
resolution. Maintains symmetry with GetRange(), improves readability,
and consistently translates NEVER_IN_RANGE.

Simplifies callers in UnitAI and Attack.
2026-08-12 22:40:59 +02:00
Atrik
f12975e9b9 Fix range target detection for StandGround stance
StandGround units now use parabolic range queries to detect enemies,
accounting for terrain elevation and height offsets. This ensures
units on hills or when 'turreted', can detect enemies
that are in parabolic range but outside flat range.

Previously, StandGround detection used flat circular queries,
causing units to miss enemies in their elevation-buffed range.
Other stances are unaffected since they chase targets anyway.
2026-08-12 22:40:59 +02:00
Atrik
2bc895bf0d Rename cmp to rangeManager for clarity 2026-08-12 22:40:59 +02:00
Atrik
3c215aff47 Add some tests for GetEffectiveParabolicRange 2026-08-12 22:40:59 +02:00
Atrik
121d428ebb Fix terrain elevation not affecting attack range
The parabolic range formula in GetEffectiveParabolicRange was only
computating height differences from manual HeightOffset values,
completely ignoring actual terrain elevation.
This meant units on hills received no tactical advantage
despite the UI stat tooltip correctly showing extended ranges.

Fixes #8889
2026-08-12 22:40:59 +02:00
Atrik
a8426f06a9 Fix renamed entities on TurretPoint
Oversights from fb1c0d2a82

Fixes #8808
2026-08-12 22:40:59 +02:00
Atrik
57a5740cce Remove dead territory ownership code 2026-08-12 22:40:59 +02:00
phosit
756b9b68c5
Expand the tooltip for population cap
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / pre-commit (push) Waiting to run
2026-08-12 17:17:04 +02:00
phosit
9f6a309434
Readd description for gatherers to the tooltip
It was removed in dee2b73c7d since it wasn't noticed that it referred to
the number in the top panel. Adding the number should make this more
clear. The color is only applied to the number instead of the whole line
so that it's harder to mistake it with just some fancy formatting.

Fixes: #7851
2026-08-12 17:17:04 +02:00
Jonny McCullagh
1c2dbf2eb0 Add more diverse quotes
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / pre-commit (push) Has been cancelled
2026-08-10 10:53:00 +02:00
Ralph Sennhauser
df72c1aad1
Support scroll-rotate in Atlas
Split mouse wheel scroll handling into horizontal and vertical. Keep
vertical scroll for zooming and use horizontal to rotate around the y
axis replicating the behaviour of the main game.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-10 09:00:07 +02:00
Dunedan
40ab70b804
Inline the pre-commit/action Github action
As the latest version of pre-commit is broken right now
(https://github.com/pre-commit/pre-commit/issues/3737) and the official
pre-commit Github action doesn't allow specifying an older pre-commit
version to use, this inlines the logic of the pre-commit action into our
action.
2026-08-09 07:20:49 +02:00
Stan
f90804c78f
Add macOS hint for game mode.
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
2026-08-07 14:09:25 +02:00
phosit
d6bdf51d83
Remove CStr::FromInt64$
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
For the usecase it's better to use `fmt::format`.
2026-08-06 18:03:05 +02:00
phosit
ae936e8177
Remove CStr::FromUInt
There is `std::to_string` which does the same. For most uses it's better
to use `fmt::format`.
2026-08-06 18:03:05 +02:00
phosit
06e199b12a
Remove CStr::FromInt
There is `std::to_string` which does the same. For most uses it's better
to use `fmt::format`.
2026-08-06 18:03:05 +02:00
ShadowOfHassen
84567e66c2 Fix catafalque aura typos
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-08-06 13:30:42 +02:00
Vladislav Belov
c4e7364802
Removes unused BuildColor4ub from ModelRenderer
We don't need to calculate shading on CPU since we always use shaders.

Refs: a9c27b412b
2026-08-06 11:32:02 +02:00
Vladislav Belov
867bdf318b
Fixes missing material reference in ModelRenderer
Missed in 18a16aa135
2026-08-06 10:31:16 +02:00
Vladislav Belov
e64a138f92
Fixes outdated state on disabling GPU skinning 2026-08-04 23:06:12 +02:00
Vladislav Belov
4a7b7e7df1
Removes smart pointers from ModelRenderer
We don't need to use pointers because we know lifetimes of all
renderers. And its list statically defined. A new renderer should follow
DOD and use a separate submission list with a separate inplace renderer.
2026-08-04 23:06:10 +02:00
Vladislav Belov
fa90ddc8b6
Refactors ModelRenderer and makes it closer to DOD
Separates submitted models and moder renderer and makes relations
explicit. Now it's clear that we don't need separate ModelRenderer and
ModelVertexRenderer.
2026-08-04 23:06:09 +02:00
Vladislav Belov
764a420797
Merges ModelRenderer and ShaderModelRenderer
We use only shaders to render models so we don't need a separate class.

BatchModelRenderer was renamed in 6bc33fe8bd.
m_Renderer became unused in 0346ba1b18.
2026-08-04 23:06:07 +02:00
Vladislav Belov
8a2bb10827
Renames ShaderModelRenderer instances 2026-08-04 23:06:06 +02:00
Vladislav Belov
af9d102126
Removes legacy logic of reused ModelRendererPtr
It became unused in 4a69e9117e.
2026-08-04 23:06:04 +02:00
Ralph Sennhauser
822092fcb4
Fix set camera tooltip in Atlas player section
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
Refs: fe192fe58f
Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-04 17:22:21 +02:00
Ralph Sennhauser
6e79dc2f70
Use dynamic events for Cinema Section
Replace static events with dynamic events and name delete path function
more aptly.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-04 17:04:22 +02:00
Dunedan
6fdcd68172
Update the actions used by the lint workflow
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-08-04 10:09:22 +02:00
Dunedan
e4f4030a5e
Update the actions used by the checkrefs workflow
The workaround for the authentication problems isn't necessary with the
new version of the checkout action anymore.
2026-08-04 10:09:09 +02:00
Ralph Sennhauser
2fb6347125
Delete .already-built file prior to new build
In case the build fails this will allow other Jenkins jobs to restore
the old working state themselves.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-08-03 20:54:04 +02:00
phosit
7aa756f6a4
Remove line numbers from cppcheck supression list
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
They have to be changed to ofthen when code gets moved.
2026-08-02 14:03:28 +02:00
phosit
e712601602
PreInitGame and InitGame in the Loader
This makes the frame before the simulation starts less stuttery. Doing
it in the Loader also allows to make the progressbar more acurate.
2026-08-02 14:03:28 +02:00
Dunedan
865ca4cd55
Update the pre-commit hooks
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
2026-08-01 16:19:18 +02:00
Dunedan
dcb7cef308
Update Github actions used for pre-commit action 2026-08-01 16:19:03 +02:00
vyordan
71be79791f Use turn_id_t (int32_t) for turn-count across simulation, network and replay
Some checks failed
checkrefs / lfscheck (push) Has been cancelled
checkrefs / checkrefs (push) Has been cancelled
lint / cppcheck (push) Has been cancelled
lint / copyright (push) Has been cancelled
lint / jenkinsfiles (push) Has been cancelled
pre-commit / build (push) Has been cancelled
CSimulation2 used , CSimulation2Impl mixed /, and
CTurnManager used  for the same turn-count concept, forcing a
static_cast<int64_t> at the one place these types already met
(rejoin-test comparison).

Add  (alias for std::int32_t) in SimulationCommand.h and use
it consistently for every turn counter in CSimulation2/Impl,
CTurnManager and its subclasses (CLocalTurnManager,
CReplayTurnManager), CNetServerTurnManager/CNetClientTurnManager, and
the network wire format (m_Turn in CEndCommandBatchMessage,
CSimulationMessage, CSyncCheckMessage, CSyncErrorMessage, and
m_CurrentTurn in CLoadedGameMessage).

Turn *duration* fields (m_TurnLength, m_CommandDelay,
DEFAULT_TURN_LENGTH, COMMAND_DELAY_SP/MP, SetTurnLength,
GetSavedTurnLength return type) are left as u32 — they're milliseconds,
not a counter, and out of scope here.

Remaining turn_id_t vs size_t comparisons use std::cmp_equal or
explicit casts, matching the existing pattern in Simulation2.cpp.

Fixes #8718
2026-07-31 10:34:20 +02:00
Atrik
9ab89b01c2 Add Langbart to art credits
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-07-30 20:54:19 +02:00
Atrik
dcce6666ae Add missing garrison flag to some houses
Art work by @Langbart

Fixes #6911
2026-07-30 20:54:19 +02:00
Atrik
202bdb133a Add Atrik to art credits 2026-07-30 20:54:19 +02:00
Atrik
46981d2b90 Add missing garrison flag to German houses 2026-07-30 20:54:19 +02:00
Ralph Sennhauser
49c887b7ca
Don't nest Paths in Common settings
Doesn't make sense to have the Paths StaticBox inside the Common
settings StaticBox so make it a top-level item as well.

While at it dissolve nested constructors to make the creation of the
widgets more readable.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-07-30 18:43:24 +02:00
Atrik
91a37e32f6 Sort units spatially for freehand selection
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-07-30 17:19:39 +02:00
Atrik
139b08fe6d Add tests for SelectionBoxTargeting 2026-07-30 17:19:39 +02:00
Atrik
dc6da217fd Enable using SelectionBox for targeting
Introduce a new  input, a command handler and adapt
UnitAI to handle arrays of targets in a single order
2026-07-30 17:19:39 +02:00
Atrik
e41dd2d3a4 Add Math.clamp utility function 2026-07-30 17:19:39 +02:00
phosit
c7953026dd
Use switchPage in autostart
Autostart used `OpenChildPage` to open the loading page. Because it's
started as child page the program doesn't end when closing it.
2026-07-30 12:36:51 +02:00
Ralph Sennhauser
0340cc9abd
Make NUSpline public members protected
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
Add a getter for MaxDistance and make members protected and inline
initialization.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-07-29 18:44:03 +02:00
Ralph Sennhauser
aeeda05433
Prefix NUSpline member variables
To follow coding convention rename the vector Node to m_Nodes,
MaxDistance to m_MaxDistance and NodeCount to m_NodeCount.

Signed-off-by: Ralph Sennhauser <ralph.sennhauser@gmail.com>
2026-07-29 18:44:03 +02:00
Atrik
0da1e0c398 Reveal Gaia wonders to players
Some checks are pending
checkrefs / lfscheck (push) Waiting to run
checkrefs / checkrefs (push) Waiting to run
lint / cppcheck (push) Waiting to run
lint / copyright (push) Waiting to run
lint / jenkinsfiles (push) Waiting to run
pre-commit / build (push) Waiting to run
2026-07-29 18:02:37 +02:00
Atrik
dc1e7179a3 Reveal and notify Wonders being constructed
Fixes #8683
2026-07-29 18:02:37 +02:00
Atrik
b6d9d87ba9 Add a test for ExploreCircle 2026-07-29 18:02:37 +02:00
Atrik
839226d542 Support revealing a small area of the map 2026-07-29 18:02:37 +02:00
Vladislav Belov
4125e5b645
Adds sRGB support to GLES 2026-07-29 01:29:11 +02:00
Vladislav Belov
f781181899
Adds sRGB support for proper lighting
Currently we're incorrectly using sRGB colors as raw inputs for lighting
instead of conversion to linear space. For proper PBR we need linear
values.
2026-07-29 01:29:09 +02:00
Vladislav Belov
e2f5b20922
Fixes GL internal format of textures in compute
In compute shaders load/store operations requires sized formats.
2026-07-28 23:32:23 +02:00
Vladislav Belov
b3165505b6
Fixes possible artifacts with GPU skinning on GL
std140 requires 16 bytes alignment and it makes alignment of uvec2 in
SkinData be equal to 16 bytes instead of 8 bytes.
2026-07-28 18:12:21 +02:00
Itms
15b9a39b00
Rebuild SPIRV shaders on all shader changes
Fixes #9096
2026-07-28 16:26:16 +02:00
172 changed files with 3412 additions and 1230 deletions

View file

@ -11,7 +11,7 @@ jobs:
lfscheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Fetch the base branch
run: git fetch origin ${{ env.BASE_SHA }}
@ -24,27 +24,14 @@ jobs:
env:
GIT_LFS_SKIP_SMUDGE: "1"
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.11"
- name: Add remote fork origin for LFS
run: |
PR_REPO="${{ gitea.event.pull_request.head.repo.full_name || gitea.repository }}"
git remote add ${{ gitea.actor }} https://gitea.wildfiregames.com/${PR_REPO}.git
- name: Workaround for authentication problem with LFS
# https://gitea.com/gitea/act_runner/issues/164
run: |
git config --local \
http.${{ gitea.server_url }}/${{ gitea.repository }}.git/info/lfs/objects/.extraheader ''
PR_REPO="${{ gitea.event.pull_request.head.repo.full_name || gitea.repository }}"
EXTRAHEADER="$(git config --get --local http.${{ gitea.server_url }}/.extraheader)"
git config --local \
http.${{ gitea.server_url }}/${PR_REPO}.git/info/lfs/objects/batch.extraheader \
'${EXTRAHEADER}'
git config --local \
http.${{ gitea.server_url }}/${PR_REPO}.git/info/lfs/objects/.extraheader ''
- name: Download necessary LFS assets
shell: sh {0}
run: |

View file

@ -12,7 +12,7 @@ jobs:
cppcheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
# cache only works for items in workspace, so configure apt to allow for caching.
- name: Setup apt cache locations
@ -26,7 +26,7 @@ jobs:
- name: Cache apt pkg db and and deb files
id: apt-cache
uses: actions/cache@v4
uses: actions/cache@v6
with:
path: |
apt-cache
@ -49,11 +49,11 @@ jobs:
copyright:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
with:
fetch-depth: 100
- uses: actions/setup-python@v5
- uses: actions/setup-python@v7
with:
python-version: "3.11"
@ -66,10 +66,10 @@ jobs:
jenkinsfiles:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Set up Node.js
uses: actions/setup-node@v4
uses: actions/setup-node@v7
with:
node-version: '20'

View file

@ -3,22 +3,27 @@ name: pre-commit
on:
- push
- pull_request
env:
PRE_COMMIT_VERSION: 4.6.0
jobs:
build:
pre-commit:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.11"
- id: restore-pip-cache
uses: actions/cache/restore@v4
- uses: actions/cache@v6
with:
key: pip-cache-v1-${{ github.workflow }}
key: pip-cache-v1-${{github.workflow}}-${{env.pythonLocation}}-${{env.PRE_COMMIT_VERSION}}
path: ~/.cache/pip
- uses: pre-commit/action@v3.0.1
- uses: actions/cache/save@v4
if: steps.restore-pip-cache.outcome == 'success'
- run: python -m pip install pre-commit=="${{ env.PRE_COMMIT_VERSION }}"
shell: bash
- run: python -m pip freeze --local
shell: bash
- uses: actions/cache@v6
with:
key: pip-cache-v1-${{ github.workflow }}
path: ~/.cache/pip
path: ~/.cache/pre-commit
key: pre-commit-3|${{ env.pythonLocation }}|${{ hashFiles('.pre-commit-config.yaml') }}
- run: pre-commit run --show-diff-on-failure --color=always --all-files
shell: bash

View file

@ -34,7 +34,7 @@ repos:
\.patch$
)
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.12.9
rev: v0.16.0
hooks:
- id: ruff-check
args:
@ -56,7 +56,7 @@ repos:
files: ^binaries/
exclude: (^binaries/data/mods/(mod|public)/art/.*\.xml|\.dae$)
- repo: https://github.com/scop/pre-commit-shfmt
rev: v3.12.0-2
rev: v3.13.1-1
hooks:
- id: shfmt
args:
@ -67,7 +67,7 @@ repos:
hooks:
- id: shellcheck
- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.45.0
rev: v0.47.0
hooks:
- id: markdownlint
language_version: 22.14.0
@ -77,13 +77,13 @@ repos:
^source/third_party/
)
- repo: https://github.com/adrienverge/yamllint
rev: v1.37.1
rev: v1.38.0
hooks:
- id: yamllint
args:
- --strict
- repo: https://github.com/eslint/eslint
rev: v9.39.2
rev: v10.8.0
hooks:
- id: eslint
language_version: 22.14.0

View file

@ -78,6 +78,9 @@
<optional>
<attribute name="define"/>
</optional>
<optional>
<attribute name="srgb"/>
</optional>
</element>
</zeroOrMore>
</interleave>

View file

@ -1,6 +1,8 @@
var g_IncompatibleModsFile = "gui/incompatible_mods/incompatible_mods.txt";
/* eslint-disable prefer-const -- Mods should be able to change it */
let g_IncompatibleModsFile = "gui/incompatible_mods/incompatible_mods.txt";
/* eslint-enable prefer-const */
function init(data)
export function init(data)
{
Engine.GetGUIObjectByName("mainText").caption = Engine.TranslateLines(Engine.ReadFile(g_IncompatibleModsFile));
return new Promise(closePageCallback =>

View file

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<objects>
<script directory="gui/common/"/>
<script directory="gui/incompatible_mods/"/>
<script module="gui/incompatible_mods/incompatible_mods.js"/>
<!-- Add a translucent black background to fade out the menu page -->
<object type="image" sprite="ModernFade"/>

View file

@ -1,4 +1,4 @@
var g_ModsAvailableOnline = [];
let g_ModsAvailableOnline = [];
/**
* Indicates if we have encountered an error in one of the network-interaction attempts.
@ -8,7 +8,7 @@ var g_ModsAvailableOnline = [];
* Set to `true` by showErrorMessageBox
* Set to `false` by init, updateModList, downloadFile, and cancelRequest
*/
var g_Failure;
let g_Failure;
/**
* Indicates if the user has cancelled a request.
@ -19,11 +19,11 @@ var g_Failure;
* Set to `true` by cancelRequest
* Set to `false` by updateModList, and downloadFile
*/
var g_RequestCancelled;
let g_RequestCancelled;
var g_RequestStartTime;
let g_RequestStartTime;
var g_ModIOState = {
const g_ModIOState = {
/**
* Finished status indicators
*/
@ -142,7 +142,7 @@ var g_ModIOState = {
}
};
function init(data)
export function init(data)
{
const promise = progressDialog(
translate("Initializing mod.io interface."),
@ -153,6 +153,21 @@ function init(data)
g_Failure = false;
Engine.ModIoStartGetGameId();
Object.assign(Engine.GetGUIObjectByName("modFilter"), {
"onPress": displayMods,
"onTextEdit": displayMods
});
Object.assign(Engine.GetGUIObjectByName("modsAvailableList"), {
"onSelectionChange": showModDescription,
"onSelectionColumnChange": displayMods,
"onMouseLeftDoubleClickItem": downloadMod
});
Engine.GetGUIObjectByName("compatibilityFilter").onPress = displayMods;
Engine.GetGUIObjectByName("refreshButton").onPress = updateModList;
Engine.GetGUIObjectByName("downloadButton").onPress = downloadMod;
return Promise.race([
promise,
new Promise(closePageCallback =>

View file

@ -3,7 +3,7 @@
<objects>
<script directory="gui/common/"/>
<script directory="gui/modio/"/>
<script module="gui/modio/modio.js"/>
<object type="image" sprite="ModernFade"/>
@ -25,8 +25,6 @@
style="ModernInput"
size="16 0 200 24"
>
<action on="Press">displayMods();</action>
<action on="TextEdit">displayMods();</action>
<translatableAttribute id="placeholder_text" context="placeholder text for input field to filter mods">Filter</translatableAttribute>
</object>
@ -39,10 +37,6 @@
selected_column_order="1"
font="sans-stroke-13"
>
<action on="SelectionChange">showModDescription();</action>
<action on="SelectionColumnChange">displayMods();</action>
<action on="MouseLeftDoubleClickItem">downloadMod();</action>
<!-- List headers -->
<!-- Keep in sync with mod property names -->
<column id="name_id" textcolor="255 255 255" width="20%">
@ -69,9 +63,7 @@
<!-- Right Panel: Compatibility Filter-->
<object name="rightPanel" size="100%-250 20 100%-10 40" >
<!-- Compatibility Filter Checkbox -->
<object name="compatibilityFilter" type="checkbox" checked="true" style="ModernTickBox" size="0 4 20 100%">
<action on="Press">displayMods();</action>
</object>
<object name="compatibilityFilter" type="checkbox" checked="true" style="ModernTickBox" size="0 4 20 100%" />
<!-- Compatibility Filter Label -->
<object type="text" size="20 2 100% 100%" text_align="left" textcolor="white">
<translatableAttribute id="caption">Filter valid mods</translatableAttribute>
@ -85,12 +77,10 @@
<object name="refreshButton" type="button" style="ModernButtonRed" size="100%-368 100%-44 100%-188 100%-16" enabled="false">
<translatableAttribute id="caption">Refresh List</translatableAttribute>
<action on="Press">updateModList();</action>
</object>
<object name="downloadButton" type="button" style="ModernButtonRed" size="100%-184 100%-44 100%-16 100%-16" enabled="false">
<translatableAttribute id="caption">Download</translatableAttribute>
<action on="Press">downloadMod();</action>
</object>
</object>

View file

@ -1,4 +1,4 @@
function init(data)
export function init(data)
{
Engine.GetGUIObjectByName("mainText").caption = Engine.TranslateLines(Engine.ReadFile("gui/modmod/help/help.txt"));
return new Promise(closePageCallback =>

View file

@ -3,7 +3,7 @@
<objects>
<script directory="gui/common/"/>
<script directory="gui/modmod/help/"/>
<script module="gui/modmod/help/help.js"/>
<!-- Add a translucent black background to fade out the menu page -->
<object type="image" sprite="ModernFade"/>

View file

@ -19,33 +19,37 @@
* This allows mods to express upwards and downwards compatibility.
*/
import { downloadModsButton } from "gui/modmod/modmodio.js";
import { regExpComparisonOperator, validateMod } from "gui/modmod/validatemod.js";
/**
* Mod definitions loaded from the files, including invalid mods.
*/
var g_Mods = {};
let g_Mods = {};
/**
* Folder names of all mods that are or can be launched.
*/
var g_ModsEnabled = [];
var g_ModsDisabled = [];
let g_ModsEnabled = [];
let g_ModsDisabled = [];
var g_ModsEnabledFiltered = [];
var g_ModsDisabledFiltered = [];
let g_ModsEnabledFiltered = [];
let g_ModsDisabledFiltered = [];
/**
* Cache mod compatibility recomputed when some mod is enbaled/disabled.
*/
var g_ModsCompatibility = [];
const g_ModsCompatibility = [];
/**
* Name of the mods installed by the ModInstaller.
*/
var g_InstalledMods;
let g_InstalledMods;
var g_HasIncompatibleMods;
let g_HasIncompatibleMods;
var g_FakeMod = {
/* eslint-disable prefer-const -- Mods should be able to change them */
let g_FakeMod = {
"name": translate("This mod does not exist"),
"version": "",
"label": "",
@ -54,12 +58,34 @@ var g_FakeMod = {
"dependencies": []
};
var g_ColorNoModSelected = "255 255 100";
var g_ColorDependenciesMet = "100 255 100";
var g_ColorDependenciesNotMet = "255 100 100";
let g_ColorNoModSelected = "255 255 100";
let g_ColorDependenciesMet = "100 255 100";
let g_ColorDependenciesNotMet = "255 100 100";
/* eslint-enable prefer-const */
function init(data, hotloadData)
export function init(data, hotloadData)
{
Object.assign(Engine.GetGUIObjectByName("modsDisabledList"), {
"onSelectionChange": selectedMod.bind(undefined, "modsDisabledList"),
"onSelectionColumnChange": displayModLists,
"onMouseLeftDoubleClickItem": enableMod
});
Object.assign(Engine.GetGUIObjectByName("modsEnabledList"), {
"onSelectionChange": selectedMod.bind(undefined, "modsEnabledList"),
"onMouseLeftDoubleClickItem": disableMod
});
Engine.GetGUIObjectByName("enabledModUp").onPress =
moveCurrItem.bind(undefined, "modsEnabledList", true);
Engine.GetGUIObjectByName("enabledModDown").onPress =
moveCurrItem.bind(undefined, "modsEnabledList", false);
Engine.GetGUIObjectByName("visitWebButton").onPress = visitModWebsite;
Engine.GetGUIObjectByName("downloadButton").onPress = downloadModsButton.bind(undefined, initMods);
Engine.GetGUIObjectByName("saveConfigurationButton").onPress = saveMods;
Engine.GetGUIObjectByName("startButton").onPress = startMods;
g_InstalledMods = data && data.installedMods || hotloadData && hotloadData.installedMods || [];
g_HasIncompatibleMods = Engine.HasIncompatibleMods();
@ -354,7 +380,7 @@ function recomputeCompatibility(disabledAction = false)
*/
function isDependencyMet(dependency)
{
const operator = dependency.match(g_RegExpComparisonOperator);
const operator = dependency.match(regExpComparisonOperator);
const [name, version] = operator ? dependency.split(operator[0]) : [dependency, undefined];
return g_ModsEnabled.some(folder =>
@ -403,7 +429,7 @@ function sortEnabledMods()
{
const dependencies = {};
for (const folder of g_ModsEnabled)
dependencies[folder] = getMod(folder).dependencies.map(d => d.split(g_RegExpComparisonOperator)[0]);
dependencies[folder] = getMod(folder).dependencies.map(d => d.split(regExpComparisonOperator)[0]);
g_ModsEnabled.sort((folder1, folder2) =>
dependencies[folder1].indexOf(getMod(folder2).name) != -1 ? 1 :

View file

@ -3,7 +3,7 @@
<objects>
<script directory="gui/common/"/>
<script directory="gui/modmod/"/>
<script module="gui/modmod/modmod.js"/>
<object type="image" style="ModernWindow">
@ -80,10 +80,6 @@
font="sans-stroke-13"
auto_scroll="true"
>
<action on="SelectionChange">selectedMod(this.name);</action>
<action on="SelectionColumnChange">displayModLists();</action>
<action on="MouseLeftDoubleClickItem">enableMod();</action>
<!-- List headers -->
<!-- Keep the column names in sync with the property names of mods -->
<column id="name" textcolor="255 255 255" width="10%">
@ -123,9 +119,6 @@
tooltip_style="pgToolTip"
auto_scroll="true"
>
<action on="SelectionChange">selectedMod(this.name);</action>
<action on="MouseLeftDoubleClickItem">disableMod();</action>
<!-- List headers -->
<column id="name" textcolor="255 255 255" width="10%">
<translatableAttribute id="heading">Name</translatableAttribute>
@ -159,7 +152,6 @@
sprite_disabled="ModernArrowUpGrey"
>
<translatableAttribute id="tooltip">Change the order in which mods are launched. This should match the mods dependencies.</translatableAttribute>
<action on="Press">moveCurrItem("modsEnabledList", true);</action>
</object>
<object
name="enabledModDown"
@ -173,7 +165,6 @@
sprite_disabled="ModernArrowDownGrey"
>
<translatableAttribute id="tooltip">Change the order in which mods are launched. This should match the mods dependencies.</translatableAttribute>
<action on="Press">moveCurrItem("modsEnabledList", false);</action>
</object>
</object>
@ -181,7 +172,6 @@
<object name="toggleModButton" type="button" style="ModernButtonRed" size="16 100%-80 196 100%-52" enabled="false"/>
<object name="visitWebButton" type="button" style="ModernButtonRed" size="200 100%-80 380 100%-52" enabled="false">
<translatableAttribute id="caption">Visit Website</translatableAttribute>
<action on="Press">visitModWebsite();</action>
</object>
<!-- Message -->
@ -198,22 +188,19 @@
<object type="button" style="ModernButtonRed" size="100%-748 100%-44 100%-568 100%-16">
<translatableAttribute id="caption">Help</translatableAttribute>
<action on="Press">Engine.OpenChildPage("page_modhelp.xml");</action>
<action on="Press">Engine.OpenChildPage("page_modhelp.xml");</action>
</object>
<object type="button" style="ModernButtonRed" size="100%-564 100%-44 100%-384 100%-16">
<object name="downloadButton" type="button" style="ModernButtonRed" size="100%-564 100%-44 100%-384 100%-16">
<translatableAttribute id="caption">Download Mods</translatableAttribute>
<action on="Press">downloadModsButton();</action>
</object>
<object name="saveConfigurationButton" type="button" style="ModernButtonRed" size="100%-380 100%-44 100%-200 100%-16">
<translatableAttribute id="caption">Save Configuration</translatableAttribute>
<action on="Press">saveMods();</action>
</object>
<object name="startButton" type="button" style="ModernButtonRed" size="100%-196 100%-44 100%-16 100%-16">
<translatableAttribute id="caption">Save and Restart</translatableAttribute>
<action on="Press">startMods();</action>
</object>
</object>
</objects>

View file

@ -1,4 +1,4 @@
function downloadModsButton()
export function downloadModsButton(initMods)
{
initTerms({
"Disclaimer": {
@ -6,7 +6,7 @@ function downloadModsButton()
"file": "gui/modio/Disclaimer.txt",
"config": "modio.disclaimer",
"accepted": false,
"callback": openModIo,
"callback": openModIo.bind(undefined, initMods),
"urlButtons": [
{
"caption": translate("mod.io Terms"),
@ -23,7 +23,7 @@ function downloadModsButton()
openTerms("Disclaimer");
}
async function openModIo(data)
async function openModIo(initMods, data)
{
if (!data.accepted)
return;

View file

@ -48,12 +48,12 @@ const g_RegExpVersion= /[0-9]+(\.[0-9]+){0,2}/;
/**
* Version checks in mod dependencies can use these operators.
*/
const g_RegExpComparisonOperator = /(<=|>=|<|>|=)/;
export const regExpComparisonOperator = /(<=|>=|<|>|=)/;
/**
* Tests if a dependency compares a mod version against another, for instance "0ad<=0.0.16".
*/
const g_RegExpComparison = globalRegExp(new RegExp(g_RegExpName.source + g_RegExpComparisonOperator.source + g_RegExpVersion.source));
const g_RegExpComparison = globalRegExp(new RegExp(g_RegExpName.source + regExpComparisonOperator.source + g_RegExpVersion.source));
/**
* The label may not be empty.
@ -69,7 +69,7 @@ function globalRegExp(regexp)
* Returns whether the mod defines all required properties and whether all properties are valid.
* Shows a notification if not.
*/
function validateMod(folder, modData, notify)
export function validateMod(folder, modData, notify)
{
let valid = true;

View file

@ -2,7 +2,7 @@
* Currently limited to at most 3 buttons per message box.
* The convention is to have "cancel" appear first.
*/
function init(data)
export function init(data)
{
// Set title
Engine.GetGUIObjectByName("mbTitleBar").caption = data.title;

View file

@ -3,7 +3,7 @@
<objects>
<script directory="gui/common/"/>
<script directory="gui/msgbox/"/>
<script module="gui/msgbox/msgbox.js"/>
<!-- Fade out the background because it's non-interactable -->
<object sprite="ModernFade" type="image"/>

View file

@ -1,4 +1,4 @@
async function init()
export async function init()
{
return { [Engine.openRequest]: {
"page": "page_modmod.xml",

View file

@ -1,5 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<objects>
<script directory="gui/pregame/"/>
<script module="gui/pregame/mainmenu.js"/>
</objects>

View file

@ -7,11 +7,11 @@
* The user should be able to save and print the text of the terms.
*/
var g_TermsPage;
var g_TermsFile;
var g_TermsSprintf;
let g_TermsPage;
let g_TermsFile;
let g_TermsSprintf;
async function init(data)
export async function init(data)
{
g_TermsPage = data.page;
g_TermsFile = data.file;

View file

@ -2,7 +2,7 @@
<objects>
<script directory="gui/common/"/>
<script directory="gui/termsdialog/"/>
<script module="gui/termsdialog/termsdialog.js"/>
<object type="image" sprite="ModernFade"/>

View file

@ -69,7 +69,7 @@ class TimedConfirmation
}
}
function init(data)
export function init(data)
{
return new TimedConfirmation().setup(data);
}

View file

@ -3,7 +3,7 @@
<objects>
<script directory="gui/common/"/>
<script directory="gui/timedconfirmation/"/>
<script module="gui/timedconfirmation/timedconfirmation.js"/>
<!-- Fade out the background because it's non-interactable -->
<object sprite="ModernFade" type="image"/>

View file

@ -12,10 +12,10 @@
layout(set = 2, binding = LOCATION, FORMAT) uniform image2D NAME
#if USE_DESCRIPTOR_INDEXING
#define STORAGE_BUFFER(LOCATION) \
layout(set = 2, binding = LOCATION)
layout(std430, set = 2, binding = LOCATION)
#else
#define STORAGE_BUFFER(LOCATION) \
layout(set = 1, binding = LOCATION)
layout(std430, set = 1, binding = LOCATION)
#endif
#else
// We use offset to the binding slot for OpenGL to avoid overlapping with other
@ -23,7 +23,7 @@
#define STORAGE_2D(LOCATION, FORMAT, NAME) \
layout(binding = LOCATION, FORMAT) uniform image2D NAME
#define STORAGE_BUFFER(LOCATION) \
layout(binding = LOCATION)
layout(std430, binding = LOCATION)
#endif
#endif // STAGE_COMPUTE

View file

@ -51,6 +51,18 @@
</textures>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_achaemenids.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -33,6 +33,18 @@
</textures>
</variant>
</group>
<group>
<variant frequency="1" name="ungarrisoned" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_celt.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -53,6 +53,18 @@
</textures>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_celt.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -134,6 +134,20 @@
</props>
</variant>
</group>
<group>
<variant frequency="1" name="ungarrisoned" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_germ.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -106,6 +106,18 @@
</props>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_iber.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -47,6 +47,18 @@
</textures>
</variant>
</group>
<group>
<variant name="ungarrisoned" frequency="1" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_rome.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/destruction_small.xml"/>

View file

@ -43,6 +43,18 @@
</textures>
</variant>
</group>
<group>
<variant frequency="1" name="ungarrisoned" />
<variant name="garrisoned">
<props>
<prop
actor="props/special/common/garrison_flag_seleucids.xml"
attachpoint="garrisoned"
selectable="false"
/>
</props>
</variant>
</group>
<group>
<variant name="alive" frequency="1"/>
<variant file="structures/sele/light_damage.xml"/>

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:995da95e21261ae0a2718baee69d76ae5f6823d21eaefaa708a89651f2099bb0
size 586243
oid sha256:ed243a229225ec51ee090588a63307cbd2efedecca06f4f1a0922a4d51ee3967
size 586427

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:d8e022a3ac132a32061583743d1322fc8792cdd6e7be57857547a8ed3cefbed6
size 525300
oid sha256:3ce649aa943771357d7c19f48294af719c50ca14178c32be60992f17845d685d
size 525483

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:21971f20f5567f820e0f3fffdd21015e2a5ffaee309be7b6efc38d3fc56aecd3
size 503936
oid sha256:d1d867c2e9f3db233847da547c466325ba9f0a9e7478175281f3538cbb694709
size 504112

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:3c37b1b7f12a429cd07873d0fdb7cc8692f6578b3e5320a6be0e68420fb4688e
size 780868
oid sha256:cc9c95992889a4c2930a39bd20f7c86b73f7c7ddb3b36492650afae2ae424641
size 781051

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:1230a92373c4e4684f791594efb35bb7d6c091377a11bd8f0daafd13816d04ec
size 56755
oid sha256:6779d6ca2067d6dd5594b3d2e5ef82d08de97ad058ce7084eb0bf8ae3290f4c2
size 56953

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:30a395c3b5a50214a689abe968ad15edb60212c3ea14041a2edc07295a4462c6
size 45317
oid sha256:9e6aca91d66df31b5820f39025c57937ce6a1593199b8a068722fdec5b0675f6
size 45523

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:ce554ad452cf75bd4dbb9da5de9830309a1dccf72f72f6a74475078af7f0e1c4
size 42851
oid sha256:07013561c7e46b020acbd03d4f371300c38d3e364c99a1e7bbcf7467aa8a34e6
size 43041

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:60f0614c1092395065c4ba8fe6bed64da873d38c579c9cbc400e9a9b8f30f3a8
size 272099
oid sha256:1416efa429cd64471d50e969c43ee723382c031c676414433f8fcd58176cfa77
size 272274

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c6e7d6264d7b3e03466bf1de58ab366a023120c6f78142aebc6570218a4803d9
size 274339
oid sha256:9f9e6debd5f2a9659e19e74b5826d3488167edb9a897ae1ed6e4db10742d94e8
size 274543

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:0624fc07116aa70c14527457fced3afcf7b36df1535bbf10250455e6254aeed6
size 372821
oid sha256:091d68b7800d9141e87ba8aaf0fa93c5bc7d260dd459774075de610ca34855e2
size 372997

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:6ef199b28b9d9ef19e0817b189d9e6f1e2f9861ca211890b8d714f9fe05f5c61
size 420601
oid sha256:c1413de5371443f1249d87fa40a821c880c749513a0347d9128a99472bec7b33
size 420808

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:adf219c08e65bd7a149726d325b6f2b4fd67effc3dd1bc211c3163774ac8308e
size 201143
oid sha256:8aba3f3dc5a909ddadd9af5e7abfe9094f55ed6c97b39e7f97b09dc1cb951f4d
size 201315

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:f8c688df60c4880dc92b6898728d4cef443c86831a2a2e87e61dd44661b58240
size 205000
oid sha256:0c3298efebf687a07d4693d9014c51e1e870e95fb9d9024c9126b40adfec75a5
size 205172

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:9d86be00b7e911108e6666422a56eb061a996e6cf0bfe489d6c99f84be752444
size 216525
oid sha256:b97f6dff13f4639e746e1ce79c120169bccb2e09d4507dc900075cf85e788590
size 216697

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:5e258d0b3a7b5c3fe2275c2816c636b7478ee1051df31a2cbe2f516465c692f9
size 239166
oid sha256:8d764a2d5a712f53f08560504f6841ed00b5268fea2a283d2d5254d57ce1df76
size 239339

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:82ff53473c25d6e17aeb97f795b543df3ec1c423e8ecb8398d0d014beac57f4e
size 101895
oid sha256:dccc1521e6e626e75ac2f05d2c8b2c2963ee751da08a9e819e4c28954b19f01a
size 102099

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:2377bddedc6251acbe8f03bf1820d368b21cbf88fc2783695ff31036af8ed4e3
size 82812
oid sha256:ae1042461639bca3d3d73fb3e723ca404c8a897ee0e2ad417af1eebb5849d23f
size 83027

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:b5f1530adecb42af05b6b81719a5c4d00fa06a5eff33f50eda8312ce2e0fcd5f
size 77866
oid sha256:b71b8848a0a2e503adbff9c1e09c06c1e76e16537f38af5b35395a04f11b365a
size 78066

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:c393e007e24473c1332c7d0c3a8093e0b542974da00b51b853ee413e45818ade
size 91109
oid sha256:256b3864edc754955814d5eec113e73fded49525d2e855a1171a4e4b495ffcc4
size 91304

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:e8fb0f356f48284704d81b601c7947f32e91995757e8c2fc390ecaf772fbd950
size 84604
oid sha256:4ef0415cce15f4d1ff4e342c23a995ee5081d21b7f84eb6c19fb89c1d63f84a7
size 84789

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:7c2b0d0a461535e0802d2a07395afb4546515ef4d3ccc3eab18d55a0993bc165
size 184407
oid sha256:2ab540ad518de662ba9a4dbe4d0d0590b6ee0b771bc482073296c949ee33d571
size 184610

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:828e2e63b9686a601b3641be10f26e3b099ced5b8dc8d453ab94d41270f22b39
size 213385
oid sha256:39a6a575b8bbb0f82ed8cf4056e0df932a59fd6e3343005625b3b76644c6879c
size 213561

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:4825c81a245ddae5637f3b2dee78f7749e27a48d2efa244bc95af075ddabcd1a
size 144598
oid sha256:93341f17ad185e28ce62a533f1db457aec4b69bb2f67c98e4b89e4bcf9503b6a
size 144784

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:427f9512af696afaae0721374a86ceb0e1432602013cb3dde818bfcd2791c163
size 212264
oid sha256:dc27dba302816891bb8f33bc65d9d68b2b330f946256aa966e5d684714af9fe2
size 212447

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:19ca2828e5e6b99065d3d901c1a90f1b73df065dc94b3a4b76b4e5804890c137
size 349847
oid sha256:270fe9095c3894fb448cb91668ad48d886088006c689f0efa148e8a78a3de043
size 350053

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:57039fff36fbba71de79b89614fea988a98bdc85b2bdc5ef88ce3a632da95a55
size 340693
oid sha256:977b2ffb5dc9cf0364d125f0b3dd17e1fb0cd482b5c96fbf7c61b6e6a030db86
size 340906

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:221eeca4ee2e46023d346e80c7a3b4b3852699e0c193e31fa58e0619e858f7a2
size 272252
oid sha256:f177172ef923455050064af60377f2e1b171ff4ec72fa9aa5fdc5c4c28000550
size 272435

View file

@ -1,3 +1,3 @@
version https://git-lfs.github.com/spec/v1
oid sha256:afc01d8e7e7efc988b2f78b58cfb6b48b5453b8786609e9ce5db38bc617a7984
size 279942
oid sha256:acdaaf09848dc5cb7cf207c7bb535865aa4199a5a50609ca3b632ce5d88d95a2
size 280139

View file

@ -330,3 +330,20 @@ Math.euclidDistance3D = function(x1, y1, z1, x2, y2, z2)
{
return Math.sqrt(Math.euclidDistance3DSquared(x1, y1, z1, x2, y2, z2));
};
/**
* Clamps a value between a minimum and maximum range.
*
* @param {number} value - The value to clamp
* @param {number} min - Minimum allowed value
* @param {number} max - Maximum allowed value
* @returns {number} The clamped value (min <= result <= max)
*/
Math.clamp = function(value, min, max)
{
if (value < min)
return min;
if (value > max)
return max;
return value;
};

View file

@ -442,3 +442,17 @@ Vector3D.div = function(v, f)
{
return new Vector3D(v.x / f, v.y / f, v.z / f);
};
/**
* Linear interpolation between this vector and another.
* @param {Vector2D} v - The target vector.
* @param {number} t - Interpolation factor (0 = this, 1 = v).
* @returns {Vector2D} A new vector at the interpolated position.
*/
Vector2D.prototype.lerp = function(v, t)
{
return new Vector2D(
this.x + (v.x - this.x) * t,
this.y + (v.y - this.y) * t
);
};

View file

@ -72,6 +72,7 @@
"List": [
{ "nick": "Alexandermb", "name": "Daniel Morgado" },
{ "nick": "Athos" },
{ "nick": "Atrik" },
{ "nick": "Basshunter", "name": "Sebastián Gómez" },
{ "nick": "BigTiger", "name": "Nathanael P. Moore" },
{ "nick": "Brightgalrs", "name": "Robert D. Schultz" },
@ -80,6 +81,7 @@
{ "nick": "Enrique", "name": "Enrique Keykens Espolio" },
{ "nick": "Gen.Kenobi", "name": "Daniel Schubert" },
{ "nick": "Historicity", "name": "Shane" },
{ "nick": "Langbart" },
{ "nick": "Leyto", "name": "Valentin Levalet" },
{ "nick": "LordGood", "name": "Johnathan B. Good" },
{ "nick": "m7600" },

View file

@ -507,6 +507,49 @@ var unitFilters = {
}
};
// Choose, inside a list of entities, which ones are targetable foes for boxtargeting.
// We also filter out entities that aren't visible, or low priority like livestocks
function getTargetableEntities(ents)
{
const player = g_ViewedPlayer;
const simState = GetSimState();
const isEnemy = simState.players[player].isEnemy;
// Filter valid target candidates
const candidates = ents.filter(entity =>
{
const entState = GetEntityState(entity);
return entState &&
unitFilters.isUnit(entity) &&
entState.visibility != "hidden";
});
// Enemy players
const enemyPlayers = candidates.filter(entity =>
{
const entState = GetEntityState(entity);
return isEnemy[entState.player] && entState.player !== 0 && !hasClass(entState, "Domestic");
});
if (enemyPlayers.length > 0)
return enemyPlayers;
// Gaia
const gaiaUnits = candidates.filter(entity =>
{
const entState = GetEntityState(entity);
return entState.player === 0;
});
if (gaiaUnits.length > 0)
return gaiaUnits;
// Domestic animals
return candidates.filter(entity =>
{
const entState = GetEntityState(entity);
return hasClass(entState, "Domestic");
});
}
// Choose, inside a list of entities, which ones will be selected.
// We may use several entity filters, until one returns at least one element.
function getPreferredEntities(ents)
@ -572,16 +615,19 @@ function handleInputBeforeGui(ev, hoveredObject)
case INPUT_BANDBOXING:
{
const bandbox = Engine.GetGUIObjectByName("bandbox");
const isAttackMode = Engine.HotkeyIsPressed("session.attack") && !g_IsObserver;
switch (ev.type)
{
case "mousemotion":
{
const rect = updateBandbox(bandbox, ev, false);
const ents = Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], g_ViewedPlayer);
const preferredEntities = getPreferredEntities(ents);
g_Selection.setHighlightList(preferredEntities);
const player = isAttackMode ? -1 : g_ViewedPlayer;
const ents = Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], player);
const highlightEntities = isAttackMode ? getTargetableEntities(ents) : getPreferredEntities(ents);
g_Selection.setHighlightList(highlightEntities);
return false;
}
@ -589,6 +635,30 @@ function handleInputBeforeGui(ev, hoveredObject)
if (ev.button == SDL_BUTTON_LEFT)
{
const rect = updateBandbox(bandbox, ev, true);
if (isAttackMode)
{
// Box attack behavior
const ents = Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], -1);
// Filter to only enemy units
const enemyUnits = getTargetableEntities(ents);
// Get currently selected friendly units
const selectedUnits = g_Selection.toList();
if (selectedUnits.length && enemyUnits.length)
{
// Sort entities by position
const sortedCombattants = sortEntitiesForEngagement(selectedUnits, enemyUnits);
// Distribute attack orders
distributeAttackOrders(sortedCombattants.attackers, sortedCombattants.targets);
}
g_Selection.setHighlightList([]);
inputState = INPUT_NORMAL;
return true;
}
const ents = getPreferredEntities(Engine.PickPlayerEntitiesInRect(rect[0], rect[1], rect[2], rect[3], g_ViewedPlayer));
g_Selection.setHighlightList([]);
@ -1371,6 +1441,7 @@ function positionUnitsFreehandSelectionMouseUp(ev)
for (let i = 1; i < inputLine.length; ++i)
lengthOfLine += inputLine[i].distanceTo(inputLine[i - 1]);
// Filter units that can move
const selection = g_Selection.filter(ent => !!GetEntityState(ent).unitAI).sort((a, b) => a - b);
// Checking the line for a minimum length to save performance.
@ -1380,39 +1451,43 @@ function positionUnitsFreehandSelectionMouseUp(ev)
return !!action && doAction(action, ev);
}
// Even distribution of the units on the line.
let p0 = inputLine[0];
let entityDistribution = [p0];
const distanceBetweenEnts = lengthOfLine / (selection.length - 1);
let freeDist = -distanceBetweenEnts;
// Sort units by their projection onto the line direction (parallel sorting)
const sortedSelection = sortEntitiesAlongLine(selection, inputLine[0], inputLine[inputLine.length - 1], true);
for (let i = 1; i < inputLine.length; ++i)
const selectionCount = sortedSelection.length;
const targetPositions = [];
// Distribute units evenly along the polyline
for (let i = 0; i < selectionCount; ++i)
{
const p1 = inputLine[i];
freeDist += inputLine[i - 1].distanceTo(p1);
const t = i / (selectionCount - 1);
const targetDistance = t * lengthOfLine;
while (freeDist >= 0)
let accumulated = 0;
let targetPoint = inputLine[0];
for (let j = 1; j < inputLine.length; ++j)
{
p0 = Vector2D.sub(p0, p1).normalize().mult(freeDist).add(p1);
entityDistribution.push(p0);
freeDist -= distanceBetweenEnts;
const segStart = inputLine[j - 1];
const segEnd = inputLine[j];
const segLength = segEnd.distanceTo(segStart);
if (accumulated + segLength >= targetDistance)
{
// Interpolate within this segment
const remaining = targetDistance - accumulated;
const frac = remaining / segLength;
targetPoint = segStart.lerp(segEnd, frac);
break;
}
accumulated += segLength;
}
targetPositions.push(targetPoint);
}
// Rounding errors can lead to missing or too many points.
entityDistribution = entityDistribution.slice(0, selection.length);
entityDistribution = entityDistribution.concat(new Array(selection.length - entityDistribution.length).fill(inputLine[inputLine.length - 1]));
if (Vector2D.from3D(GetEntityState(selection[0]).position).distanceTo(entityDistribution[0]) +
Vector2D.from3D(GetEntityState(selection[selection.length - 1]).position).distanceTo(entityDistribution[selection.length - 1]) >
Vector2D.from3D(GetEntityState(selection[0]).position).distanceTo(entityDistribution[selection.length - 1]) +
Vector2D.from3D(GetEntityState(selection[selection.length - 1]).position).distanceTo(entityDistribution[0]))
entityDistribution.reverse();
Engine.PostNetworkCommand({
"type": isAttackMovePressed() ? "attack-walk-custom" : "walk-custom",
"entities": selection,
"targetPositions": entityDistribution.map(pos => pos.toFixed(2)),
"entities": sortedSelection,
"targetPositions": targetPositions.map(pos => pos.toFixed(2)),
"targetClasses": Engine.HotkeyIsPressed("session.attackmoveUnit") ? { "attack": ["Unit"] } : { "attack": ["Unit", "Structure"] },
"queued": Engine.HotkeyIsPressed("session.queue"),
"pushFront": Engine.HotkeyIsPressed("session.pushorderfront"),
@ -1420,9 +1495,10 @@ function positionUnitsFreehandSelectionMouseUp(ev)
});
// Add target markers with a minimum distance of 5 to each other.
const entitiesBetweenMarker = Math.ceil(5 / distanceBetweenEnts);
for (let i = 0; i < entityDistribution.length; i += entitiesBetweenMarker)
DrawTargetMarker({ "x": entityDistribution[i].x, "z": entityDistribution[i].y });
const stepDistance = lengthOfLine / (selectionCount - 1);
const entitiesBetweenMarker = Math.max(1, Math.ceil(5 / stepDistance));
for (let i = 0; i < targetPositions.length; i += entitiesBetweenMarker)
DrawTargetMarker({ "x": targetPositions[i].x, "z": targetPositions[i].y });
Engine.GuiInterfaceCall("PlaySound", {
"name": "order_walk",
@ -1929,3 +2005,108 @@ function clearSelection()
g_Selection.reset();
preSelectedAction = ACTION_NONE;
}
function distributeAttackOrders(attackers, targets)
{
if (targets.length < 1)
return;
// Play attack sounds from a sample of units in selection
const soundCount = Math.min(3, attackers.length);
for (let i = 0; i < soundCount; i++)
{
const t = soundCount === 1 ? 0 : i / (soundCount - 1);
const attackerIndex = Math.floor(t * (attackers.length - 1));
setTimeout(() =>
{
Engine.GuiInterfaceCall("PlaySound", {
"name": "order_attack",
"entity": attackers[attackerIndex]
});
}, i * 180);
}
Engine.PostNetworkCommand({
"type": "attack-group",
"entities": attackers,
"targets": targets,
"queued": Engine.HotkeyIsPressed("session.queue"),
"allowCapture": false
});
}
/**
* Sorts attackers and targets for left-to-right engagement across the battle line.
*
* Entities are sorted by their perpendicular distance to the line connecting the
* two army centers, creating natural pairings across the battle front.
*
* @param {number[]} attackers - Array of attacking entity IDs.
* @param {number[]} targets - Array of target entity IDs.
* @returns {Object} { attackers: number[], targets: number[] } - Both arrays sorted
* for cross-line engagement (targets automatically reversed).
*/
function sortEntitiesForEngagement(attackers, targets)
{
const getPosition = (id) => GetEntityState(id).position;
const computeAveragePosition = (entities) =>
{
if (entities.length === 0) return new Vector2D(0, 0);
const vectors = entities.map(id => Vector2D.from3D(getPosition(id)));
return Vector2D.average(vectors);
};
// Calculate the axis of engagement - the line between the groups' average positions
const avgAttackers = computeAveragePosition(attackers);
const avgTargets = computeAveragePosition(targets);
// Sort each group by perpendicular distance to the engagement line
const sortedAttackers = sortEntitiesAlongLine(attackers, avgAttackers, avgTargets);
const sortedTargets = sortEntitiesAlongLine(targets, avgAttackers, avgTargets);
// Reverse targets so the leftmost attacker pairs with leftmost target
return {
"attackers": sortedAttackers,
"targets": sortedTargets.reverse()
};
}
/**
* Sorts entity IDs by their projection onto a line's direction or perpendicular axis.
*
* @param {number[]} entities - Array of entity IDs.
* @param {Vector2D} lineStart - Start point of the reference line.
* @param {Vector2D} lineEnd - End point of the reference line.
* @param {boolean} sortByDirection - If true, sort by parallel projection (along line);
* If false, sort by perpendicular distance (default).
* @returns {number[]} Sorted entity IDs.
*/
function sortEntitiesAlongLine(entities, lineStart, lineEnd, sortByDirection = false)
{
const dir = lineEnd.sub(lineStart);
const length = dir.length();
if (length === 0)
return entities.slice();
// Choose basis vector: either parallel or perpendicular to the line
let basis;
if (sortByDirection)
basis = dir.mult(1 / length); // Unit direction vector
else
basis = new Vector2D(-dir.y, dir.x).normalize(); // Perpendicular
const withCoord = entities.map(id =>
{
const pos = GetEntityState(id).position;
const point2D = Vector2D.from3D(pos);
const rel = point2D.sub(lineStart);
const coord = rel.dot(basis); // Project onto basis vector
return { id, coord };
});
// Sort by that coordinate
withCoord.sort((a, b) => a.coord - b.coord);
return withCoord.map(item => item.id);
}

View file

@ -25,13 +25,17 @@ class CounterPopulation
for (const resCode of g_ResourceData.GetCodes())
total += playerState.resourceGatherers[resCode];
this.stats.caption = coloredText(total, total ? this.DefaultTotalGatherersColor : this.DefaultTotalGatherersColorZero);
const colorizedTotal = coloredText(total,
total ? this.DefaultTotalGatherersColor : this.DefaultTotalGatherersColorZero);
this.stats.caption = colorizedTotal;
this.isTrainingBlocked = playerState.trainingBlocked;
this.panel.tooltip =
setStringTags(translate(this.PopulationTooltip), CounterManager.ResourceTitleTags) +
getAllyStatTooltip(this.getTooltipData.bind(this));
setStringTags(translate(this.PopulationTooltipTitle), CounterManager.ResourceTitleTags) +
"\n" + sprintf(this.PopulationTooltip, state) +
getAllyStatTooltip(this.getTooltipData.bind(this)) + "\n" +
sprintf(this.CurrentGatherersTooltip, { "currentGatherers": colorizedTotal });
}
getTooltipData(playerState, playername)
@ -62,10 +66,20 @@ class CounterPopulation
// Translation: Do not insert spaces around the slash symbol for this exact string. Keep only one space between popLimit and popMax.
CounterPopulation.prototype.CounterCaption = markForTranslation("%(popCount)s/%(popLimit)s (%(popMax)s)");
CounterPopulation.prototype.PopulationTooltip = markForTranslation("Population: current/limit (max)");
CounterPopulation.prototype.PopulationTooltipTitle = markForTranslation("Population");
CounterPopulation.prototype.PopulationTooltip =
translate("Current population: %(popCount)s\nPopulation limit: %(popLimit)s\nMaximum population: %(popMax)s");
CounterPopulation.prototype.AllyPopulationTooltip = markForTranslation("%(popCount)s/%(popLimit)s (%(popMax)s)");
/**
* Storing the translated and formatted gatherer string in the prototype.
* Including the number might seem redundant but is required since the collor
* isn't enough to associate it with the number in the top panel.
*/
CounterPopulation.prototype.CurrentGatherersTooltip =
setStringTags(translate("Current gatherers: %(currentGatherers)s"), { "font": "sans-14" });
/**
* Color to highlight the total number of gatherers at zero.
*/

View file

@ -17,7 +17,9 @@ class CounterResource
this.count.caption = abbreviateLargeNumbers(Math.floor(playerState.resourceCounts[this.resCode]));
const gatherers = playerState.resourceGatherers[this.resCode];
this.stats.caption = coloredText(gatherers, gatherers ? this.DefaultResourceGatherersColor : this.DefaultResourceGatherersColorZero);
const colorizedGatherers = coloredText(gatherers,
gatherers ? this.DefaultResourceGatherersColor : this.DefaultResourceGatherersColorZero);
this.stats.caption = colorizedGatherers;
// TODO: Set the tooltip only if hovered?
@ -28,7 +30,9 @@ class CounterResource
this.panel.tooltip =
setStringTags(resourceNameFirstWord(this.resCode), CounterManager.ResourceTitleTags) +
description +
getAllyStatTooltip(this.getTooltipData.bind(this));
getAllyStatTooltip(this.getTooltipData.bind(this)) + "\n" +
sprintf(CounterPopulation.prototype.CurrentGatherersTooltip,
{ "currentGatherers": colorizedGatherers });
}
getTooltipData(playerState, playername)

View file

@ -208,3 +208,13 @@
“This is a woman's resolve; as for men, they may live and be slaves.” \n— Boudicca, rallying against Roman occupation (Tacitus's Annals, Book 14, Chapter 35)
“There are two things, knowledge and opinion; one makes its possessor know, the other to be ignorant.” \n— (Hippocratic treatise known as “The Law”, part of the Hippocratic Corpus)
“Let them hate me, so long as they fear me.” \n— Caligula (Suetonius, The Twelve Caesars, Book30)
“There is no instance of a nation benefiting from prolonged warfare.” \n— Sun Tzu (“The Art of War”, Chapter 2)
“To subdue the enemy without fighting is the acme of skill.” \n— Sun Tzu (“The Art of War”, Chapter 3)
“One defends when his strength is inadequate; he attacks when it is abundant.” \n— Sun Tzu (“The Art of War”, Chapter 4)
“When torrential water tosses boulders, it is because of its momentum. When the strike of a hawk breaks the body of its prey, it is because of timing.” \n— Sun Tzu (“The Art of War”, Chapter 5)
“Treat your men as you would your own beloved sons. And they will follow you into the deepest valley.” \n— Sun Tzu (“The Art of War”, Chapter 10)
“Woe to the defeated!” \n— Brennus disputing the weight of gold ransom while sacking Rome c. 387 BC (Livy, “Ab Urbe Condita”, Book 5, Chapter 48)
“\[Brutus] found the women fighting and perishing in company with the men with such bravery that they uttered no cry even in the midst of slaughter.” \n— Brutus in Lusitania during the battles with Viriathus (Appian of Alexandria, “The Spanish Wars”, 15)
“What I desire for my own children, I desire for all men.” \n— Ashoka the Great (“The Kalinga Rock Edicts”)
“If you Romans choose to lord it over the world, does it follow that the world is to accept slavery ?” \n— Caratacus pleading for pardon from Roman Emperor Claudius in Rome (Tacitus, “Annals”, 12.37)
“And where am I to get so many soldiers ?” \n— Septimius Severus, frustrated with the challenge of controlling his own men and the harsh realities of frontier warfare against the northern tribes in Britannia. (Cassius Dio, “Roman History”, Vol IX, Book LXXVI, Section 11)

View file

@ -603,4 +603,147 @@ TriggerHelper.SpawnAndTurretAtClasses = function(playerID, classes, templates, c
return results;
};
/**
* Makes an entity permanently visible to all players by:
* - Setting alwaysVisible flag
* - Deactivating fogging (no mirages)
* - Exploring the surrounding area
* - Forcing a visibility update
*
* @param {number} ent - Entity ID to make permanently visible
*/
TriggerHelper.MakeEntityPermanentlyVisible = function(ent)
{
const cmpVisibility = Engine.QueryInterface(ent, IID_Visibility);
if (cmpVisibility)
{
cmpVisibility.alwaysVisible = true;
cmpVisibility.SetActivated(true);
}
const cmpFogging = Engine.QueryInterface(ent, IID_Fogging);
if (cmpFogging)
cmpFogging.PermanentlyReveal("all");
const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager);
const cmpPosition = Engine.QueryInterface(ent, IID_Position);
if (cmpRangeManager && cmpPosition && cmpPosition.IsInWorld())
{
const pos = cmpPosition.GetPosition2D();
const numPlayers = Engine.QueryInterface(SYSTEM_ENTITY, IID_PlayerManager).GetNumPlayers();
const exploreRadius = TriggerHelper.CalculateExplorationRadius(ent);
for (let i = 1; i < numPlayers; ++i)
cmpRangeManager.ExploreCircle(i, pos.x, pos.y, exploreRadius);
cmpRangeManager.RequestVisibilityUpdate(ent);
}
};
/**
* Calculate a reasonable exploration radius from an entity's footprint.
* Calculates the radius as the entity's full extent to reveal the surrounding area.
* This is equivalent to (extent/2) * 2, giving a 2x margin around the entity.
*/
TriggerHelper.CalculateExplorationRadius = function(ent)
{
const cmpFootprint = Engine.QueryInterface(ent, IID_Footprint);
if (!cmpFootprint)
return 50;
const shapeInfo = cmpFootprint.GetShape();
let halfExtent; // The radius of the entity (half its size)
if (shapeInfo && shapeInfo.type === "circle")
halfExtent = shapeInfo.radius || shapeInfo.size0;
else if (shapeInfo && shapeInfo.type === "square")
halfExtent = Math.max(shapeInfo.width || shapeInfo.size0, shapeInfo.depth || shapeInfo.size1) / 2;
else
return 50;
// Use 2x the entity's radius to reveal surrounding area
// This gives a comfortable margin around the entity
const radius = halfExtent * 2;
return radius;
};
/**
* Sends a notification to specific players.
*
* @param {string} message - The message to display (use markForTranslation)
* @param {number[]} players - Array of player IDs to send the notification to
* @param {number} duration - Duration in milliseconds
* @param {Object} parameters - Translation parameters (optional)
*/
TriggerHelper.SendNotification = function(message, players, duration = 30000, parameters = {}, translateParameters = [])
{
const cmpGuiInterface = Engine.QueryInterface(SYSTEM_ENTITY, IID_GuiInterface);
if (!cmpGuiInterface)
return;
// Ensure all parameter values are primitive types
const primitiveParameters = {};
for (const key in parameters)
{
const value = parameters[key];
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean")
primitiveParameters[key] = value;
else
primitiveParameters[key] = String(value);
}
cmpGuiInterface.AddTimeNotification(
{
"message": message,
"players": players,
"parameters": primitiveParameters,
"translateMessage": true,
"translateParameters": translateParameters
},
duration
);
};
/**
* Sends a notification to a specific player and a different notification to all other active players.
*
* @param {number} player - The player ID who gets the 'owner' message
* @param {string} ownerMessage - Message for the specified player (use markForTranslation)
* @param {string} othersMessage - Message for all other active players (use markForTranslation)
* @param {number} duration - Duration in milliseconds
* @param {Object} parameters - Translation parameters shared by both messages (optional)
* @param {Object} ownerParameters - Additional parameters for the owner message (optional)
* @param {Object} othersParameters - Additional parameters for the others message (optional)
*/
TriggerHelper.SendDualNotification = function(player, ownerMessage, othersMessage, duration = 30000, parameters = {}, ownerParameters = {}, othersParameters = {})
{
const numPlayers = Engine.QueryInterface(SYSTEM_ENTITY, IID_PlayerManager).GetNumPlayers();
const others = [-1]; // Include observers (player id -1)
for (let playerID = 1; playerID < numPlayers; ++playerID)
{
if (playerID == player)
continue;
const cmpPlayer = QueryPlayerIDInterface(playerID);
if (cmpPlayer && cmpPlayer.GetState() == "defeated")
continue;
others.push(playerID);
}
const mergedOwnerParams = Object.assign({}, parameters, ownerParameters);
const mergedOthersParams = Object.assign({}, parameters, othersParameters);
// Auto-detect translatable parameters (those starting with "_" or named "player")
const translateParameters = Object.keys(mergedOthersParams).filter(key => key.startsWith("_") || key == "player");
TriggerHelper.SendNotification(ownerMessage, [player], duration, mergedOwnerParams, translateParameters);
TriggerHelper.SendNotification(othersMessage, others, duration, mergedOthersParams, translateParameters);
};
TriggerHelper.SendWonderNotifications = function(owner, othersMessage, ownerMessage)
{
TriggerHelper.SendDualNotification(owner, ownerMessage, othersMessage, 30000, { "_player_": owner });
};
Engine.RegisterGlobal("TriggerHelper", TriggerHelper);

View file

@ -1,16 +1,42 @@
Trigger.prototype.WonderVictoryEntityRenamed = function(data)
{
if (this.wonderVictoryMessages[data.entity] && Engine.QueryInterface(data.newentity, IID_Wonder))
{
// When an entity is renamed, we first create a new entity,
// which in case it is a wonder will receive a timer.
// However on a rename we want to use the timer from the old entity,
// so we need to remove the timer of the new entity.
this.WonderVictoryDeleteTimer(data.newentity);
if (!Engine.QueryInterface(data.newentity, IID_Wonder))
return;
// Check if wonder victory is enabled
const cmpEndGameManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_EndGameManager);
if (!cmpEndGameManager)
return;
const victoryConditions = cmpEndGameManager.GetVictoryConditions();
if (!victoryConditions || !victoryConditions.includes("wonder"))
return;
// Handle timer transfer (only if old entity had the timer)
if (this.wonderVictoryMessages[data.entity])
{
this.WonderVictoryDeleteTimer(data.newentity);
this.wonderVictoryMessages[data.newentity] = this.wonderVictoryMessages[data.entity];
delete this.wonderVictoryMessages[data.entity];
}
// Make the completed wonder permanently visible
TriggerHelper.MakeEntityPermanentlyVisible(data.newentity);
// Send "wonder completed" notifications (only for non-Gaia wonders)
const cmpOwnership = Engine.QueryInterface(data.newentity, IID_Ownership);
if (cmpOwnership)
{
const owner = cmpOwnership.GetOwner();
if (owner > 0)
{
TriggerHelper.SendWonderNotifications(
owner,
markForTranslation("%(_player_)s has built a Wonder!"),
markForTranslation("You have built a Wonder!")
);
}
}
};
Trigger.prototype.WonderVictoryOwnershipChanged = function(data)
@ -18,6 +44,15 @@ Trigger.prototype.WonderVictoryOwnershipChanged = function(data)
if (!Engine.QueryInterface(data.entity, IID_Wonder))
return;
// Check if wonder victory is enabled
const cmpEndGameManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_EndGameManager);
if (!cmpEndGameManager)
return;
const victoryConditions = cmpEndGameManager.GetVictoryConditions();
if (!victoryConditions || !victoryConditions.includes("wonder"))
return;
this.WonderVictoryDeleteTimer(data.entity);
if (data.to > 0)
@ -146,11 +181,69 @@ Trigger.prototype.WonderVictorySetWinner = function(playerID)
n));
};
Trigger.prototype.WonderStartNotification = function(data)
{
// Check if wonder victory is enabled in game settings
const cmpEndGameManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_EndGameManager);
if (!cmpEndGameManager)
return;
// Don't show the wonder foundation if it's not a wonder victory game
const victoryConditions = cmpEndGameManager.GetVictoryConditions();
if (!victoryConditions || !victoryConditions.includes("wonder"))
return;
const cmpTemplateManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TemplateManager);
if (!cmpTemplateManager)
return;
const template = cmpTemplateManager.GetTemplate(data.template);
if (!template || !("Wonder" in template))
return;
const owner = TriggerHelper.GetOwner(data.foundation);
if (owner <= 0)
return;
TriggerHelper.MakeEntityPermanentlyVisible(data.foundation);
TriggerHelper.SendWonderNotifications(
owner,
markForTranslation("%(_player_)s has started building a Wonder."),
markForTranslation("You have started building a Wonder.")
);
};
Trigger.prototype.RevealGaiaWonders = function()
{
Engine.ProfileStart("RevealGaiaWonders");
const cmpEndGameManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_EndGameManager);
if (!cmpEndGameManager)
return;
const victoryConditions = cmpEndGameManager.GetVictoryConditions();
if (!victoryConditions || !victoryConditions.includes("wonder"))
return;
// Find and reveal all Gaia wonders
const gaiaWonders = Engine.GetEntitiesWithInterface(IID_Wonder).filter(
ent => TriggerHelper.GetOwner(ent) === 0
);
for (const ent of gaiaWonders)
TriggerHelper.MakeEntityPermanentlyVisible(ent);
Engine.ProfileStop();
};
{
const cmpTrigger = Engine.QueryInterface(SYSTEM_ENTITY, IID_Trigger);
cmpTrigger.RegisterTrigger("OnEntityRenamed", "WonderVictoryEntityRenamed", { "enabled": true });
cmpTrigger.RegisterTrigger("OnOwnershipChanged", "WonderVictoryOwnershipChanged", { "enabled": true });
cmpTrigger.RegisterTrigger("OnDiplomacyChanged", "WonderVictoryDiplomacyChanged", { "enabled": true });
cmpTrigger.RegisterTrigger("OnPlayerWon", "WonderVictoryPlayerWon", { "enabled": true });
cmpTrigger.RegisterTrigger("OnConstructionStarted", "WonderStartNotification", { "enabled": true });
cmpTrigger.DoAfterDelay(0, "RevealGaiaWonders", {});
cmpTrigger.wonderVictoryMessages = {};
}

View file

@ -286,17 +286,21 @@ Attack.prototype.CanAttack = function(target, wantedTypes)
if (!cmpTargetPlayer || !cmpEntityPlayer)
return false;
// Must be visible or miraged / with retainInFog flag, not completely hidden
const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager);
if (cmpRangeManager)
{
const visibility = cmpRangeManager.GetLosVisibility(target, cmpEntityPlayer.GetPlayerID());
if (visibility == "hidden")
return false;
}
const types = this.GetAttackTypes(wantedTypes);
const entityOwner = cmpEntityPlayer.GetPlayerID();
const targetOwner = cmpTargetPlayer.GetPlayerID();
const cmpCapturable = QueryMiragedInterface(target, IID_Capturable);
const cmpDiplomacy = QueryPlayerIDInterface(entityOwner, IID_Diplomacy);
// Check if the relative height difference is larger than the attack range
// If the relative height is bigger, it means they will never be able to
// reach each other, no matter how close they come.
const heightDiff = Math.abs(cmpThisPosition.GetHeightOffset() - cmpTargetPosition.GetHeightOffset());
for (const type of types)
{
if (type != "Capture" && (!cmpDiplomacy?.IsEnemy(targetOwner) || !cmpHealth || !cmpHealth.GetHitpoints()))
@ -305,7 +309,8 @@ Attack.prototype.CanAttack = function(target, wantedTypes)
if (type == "Capture" && (!cmpCapturable || !cmpCapturable.CanCapture(entityOwner)))
continue;
if (heightDiff > this.GetRange(type).max)
// Check if the target is currently in range, or could ever be reached
if (!this.IsTargetInRange(target, type) && !this.CanEverReachTarget(target, type))
continue;
const restrictedClasses = this.GetRestrictedClasses(type);
@ -319,6 +324,77 @@ Attack.prototype.CanAttack = function(target, wantedTypes)
return false;
};
/**
* Check if the target could potentially ever be reached with the given attack type,
* as an optimistic estimate. This assumes the attacker can move to the closest
* possible position to the target ignoring obstructions and terrain features
* (e.g., hills) that might help or hinder.
*
* This is a best-effort guess:
* - It may return true even when the target is actually unreachable (e.g., turreted
* units on walls with a height offset too large for the projectile to overcome).
* - It may return false even when the target is reachable (e.g., a nearby hill could
* provide enough elevation to hit a "too high" target, but we don't check for that).
*
* Currently these checks are mostly useful to determine if we can reach turreted units
* (e.g. on a wall, outpost...).
*
* @param {number} targetId - The target entity ID.
* @param {string} type - The attack type.
* @return {boolean} - Whether the target is estimated to be reachable (see caveats above).
*/
Attack.prototype.CanEverReachTarget = function(targetId, type)
{
const cmpThisPosition = Engine.QueryInterface(this.entity, IID_Position);
const cmpTargetPosition = Engine.QueryInterface(targetId, IID_Position);
const thisHeightOffset = cmpThisPosition.GetHeightOffset();
const targetHeightOffset = cmpTargetPosition.GetHeightOffset();
const range = this.GetRange(type);
// Find the closest horizontal distance we could ever get to the target.
// We first determine the closest horizontal distance we could ever get to the target,
// accounting for turreted units inside buildings:
// - If the building blocks movement, we can only reach its exterior edge.
// - If the building is passable, we can walk right up to the turret point.
const cmpTurretable = Engine.QueryInterface(targetId, IID_Turretable);
const holderId = cmpTurretable?.HolderID();
let closestDistance = 0;
if (holderId && holderId != INVALID_ENTITY)
{
const cmpTurretHolder = Engine.QueryInterface(holderId, IID_TurretHolder);
if (cmpTurretHolder)
{
const turretPoint = cmpTurretHolder.GetOccupiedTurretPoint(targetId);
closestDistance = cmpTurretHolder.GetClosestApproachDistanceToTurretPoint(turretPoint);
}
}
if (!range.parabolic)
{
// For non-parabolic attacks (e.g., "Melee" attack type), we check if the height offset
// is within max range at the closest possible horizontal distance (simple 3D distance check).
const heightDiff = Math.abs(targetHeightOffset - thisHeightOffset);
return Math.sqrt(closestDistance * closestDistance + heightDiff * heightDiff) <= range.max;
}
// For parabolic attacks (generally "Ranged" attack type), we use the parabolic formula
// to determine if the height offset is surmountable at the closest possible distance.
// Typical scenario: units on walls/towers may be unreachable if the attacker's
// projectiles can't arc high enough, even at point-blank range.
const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager);
if (!cmpRangeManager)
return true;
const yOrigin = this.GetAttackYOrigin(type);
const maxReachableHeightDiff = cmpRangeManager.GetMaxReachableParabolicHeight(
range.max, yOrigin, closestDistance);
return targetHeightOffset - thisHeightOffset <= maxReachableHeightDiff;
};
/**
* Returns undefined if we have no preference or the lowest index of a preferred class.
*/
@ -353,12 +429,14 @@ Attack.prototype.GetPreference = function(target)
*/
Attack.prototype.GetFullAttackRange = function()
{
const ret = { "min": Infinity, "max": 0 };
const ret = { "min": Infinity, "max": 0, "parabolic": false };
for (const type of this.GetAttackTypes())
{
const range = this.GetRange(type);
ret.min = Math.min(ret.min, range.min);
ret.max = Math.max(ret.max, range.max);
if (range.parabolic)
ret.parabolic = true;
}
return ret;
};
@ -475,7 +553,39 @@ Attack.prototype.GetRange = function(type)
let min = +(this.template[type].MinRange || 0);
min = ApplyValueModificationsToEntity("Attack/" + type + "/MinRange", min, this.entity);
return { "max": max, "min": min };
return {
"max": max,
"min": min,
"parabolic": type === "Ranged"
};
};
/**
* Get the effective range for attacking a specific target, accounting
* for elevation and projectile physics where applicable.
* @param {number} target - The target entity ID.
* @param {string} type - The attack type.
* @return {{ min: number, max: number }} - The min and max effective range.
*/
Attack.prototype.GetEffectiveAttackRange = function(target, type)
{
const range = this.GetRange(type);
// Only Parabolic attacks get parabolic elevation adjustment
if (!range.parabolic)
return range;
const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager);
if (!cmpRangeManager)
return range;
const effectiveMax = cmpRangeManager.GetEffectiveParabolicRange(
this.entity, target, range.max, this.GetAttackYOrigin(type));
if (effectiveMax < 0)
return { "min": Infinity, "max": 0 }; // Out of range
return { "min": range.min, "max": effectiveMax };
};
Attack.prototype.GetAttackYOrigin = function(type)
@ -813,14 +923,9 @@ Attack.prototype.PerformAttack = function(type, target)
*/
Attack.prototype.IsTargetInRange = function(target, type)
{
const range = this.GetRange(type);
return Engine.QueryInterface(SYSTEM_ENTITY, IID_ObstructionManager).IsInTargetParabolicRange(
this.entity,
target,
range.min,
range.max,
this.GetAttackYOrigin(type),
false);
const range = this.GetEffectiveAttackRange(target, type);
return Engine.QueryInterface(SYSTEM_ENTITY, IID_ObstructionManager).IsInTargetRange(
this.entity, target, range.min, range.max, false);
};
Attack.prototype.OnValueModification = function(msg)

View file

@ -127,10 +127,20 @@ BuildingAI.prototype.SetupRangeQuery = function()
const range = cmpAttack.GetRange(attackType);
const yOrigin = cmpAttack.GetAttackYOrigin(attackType);
// Get building's vision range
const cmpVision = Engine.QueryInterface(this.entity, IID_Vision);
const visionRange = cmpVision ? cmpVision.GetRange() : 0;
// Base range
const baseRange = Math.min(visionRange, range.max);
// This takes entity sizes into accounts, so no need to compensate for structure size.
this.enemyUnitsQuery = cmpRangeManager.CreateActiveParabolicQuery(
this.entity, range.min, range.max, yOrigin,
enemies, IID_Resistance, cmpRangeManager.GetEntityFlagMask("normal"));
this.entity, range.min, range.max, baseRange, yOrigin,
enemies, IID_Resistance, cmpRangeManager.GetEntityFlagMask("normal"),
true // Allow mirages for attack queries
);
cmpRangeManager.EnableActiveQuery(this.enemyUnitsQuery);
};
@ -156,10 +166,17 @@ BuildingAI.prototype.SetupGaiaRangeQuery = function()
const range = cmpAttack.GetRange(attackType);
const yOrigin = cmpAttack.GetAttackYOrigin(attackType);
// Get building's vision range
const cmpVision = Engine.QueryInterface(this.entity, IID_Vision);
const visionRange = cmpVision ? cmpVision.GetRange() : 0;
// Base range
const baseRange = Math.min(visionRange, range.max);
// This query is only interested in Gaia entities that can attack.
// This takes entity sizes into accounts, so no need to compensate for structure size.
this.gaiaUnitsQuery = cmpRangeManager.CreateActiveParabolicQuery(
this.entity, range.min, range.max, yOrigin,
this.entity, range.min, range.max, baseRange, yOrigin,
[0], IID_Attack, cmpRangeManager.GetEntityFlagMask("normal"));
cmpRangeManager.EnableActiveQuery(this.gaiaUnitsQuery);
@ -170,7 +187,6 @@ BuildingAI.prototype.SetupGaiaRangeQuery = function()
*/
BuildingAI.prototype.OnRangeUpdate = function(msg)
{
var cmpAttack = Engine.QueryInterface(this.entity, IID_Attack);
if (!cmpAttack)
return;
@ -189,10 +205,10 @@ BuildingAI.prototype.OnRangeUpdate = function(msg)
// Add new targets.
for (const entity of msg.added)
if (cmpAttack.CanAttack(entity))
if (!this.targetUnits.includes(entity))
this.targetUnits.push(entity);
// Remove targets outside of vision-range.
// Remove targets out of range.
for (const entity of msg.removed)
{
const index = this.targetUnits.indexOf(entity);
@ -375,13 +391,7 @@ BuildingAI.prototype.FireArrows = function()
{
const selectedTarget = targets[targetIndex].entityId;
if (this.CheckTargetVisible(selectedTarget) && cmpObstructionManager.IsInTargetParabolicRange(
this.entity,
selectedTarget,
range.min,
range.max,
yOrigin,
false))
if (cmpAttack.CanAttack(selectedTarget, [attackType]))
{
cmpAttack.PerformAttack(attackType, selectedTarget);
PlaySound("attack_" + attackType.toLowerCase(), this.entity);

View file

@ -29,6 +29,7 @@ Fogging.prototype.Init = function()
this.mirages = [];
this.miraged = [];
this.seen = [];
this.revealed = [];
const numPlayers = Engine.QueryInterface(SYSTEM_ENTITY, IID_PlayerManager).GetNumPlayers();
for (let player = 0; player < numPlayers; ++player)
@ -36,6 +37,7 @@ Fogging.prototype.Init = function()
this.mirages.push(INVALID_ENTITY);
this.miraged.push(false);
this.seen.push(false);
this.revealed.push(false);
}
};
@ -169,6 +171,45 @@ Fogging.prototype.WasSeen = function(player)
return this.seen[player];
};
/**
* Permanently reveal this entity to one or all players.
* Destroys existing mirages and optionally deactivates fogging entirely.
* @param {number|string} player - Player ID to reveal to, or "all" for all players.
*/
Fogging.prototype.PermanentlyReveal = function(player = "all")
{
const cmpRangeManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager);
// Validate single player case
if (player !== "all" && (player < 0 || player >= this.mirages.length))
return;
// Determine which players to reveal
const startPlayer = (player === "all") ? 0 : player;
const endPlayer = (player === "all") ? this.mirages.length : player + 1;
// Reveal each player in the range
for (let i = startPlayer; i < endPlayer; ++i)
{
if (this.mirages[i] != INVALID_ENTITY)
{
Engine.DestroyEntity(this.mirages[i]);
this.mirages[i] = INVALID_ENTITY;
this.miraged[i] = false;
}
this.revealed[i] = true;
this.seen[i] = true;
}
// Deactivate fogging if revealing to all players
if (player === "all")
this.activated = false;
// Request visibility update
if (cmpRangeManager)
cmpRangeManager.RequestVisibilityUpdate(this.entity);
};
Fogging.prototype.OnOwnershipChanged = function(msg)
{
// Always activate fogging for non-Gaia entities.
@ -209,7 +250,8 @@ Fogging.prototype.OnVisibilityChanged = function(msg)
this.seen[msg.player] = true;
}
if (msg.newVisibility == VIS_FOGGED && this.activated)
// Only create a mirage if the player hasnt been permanently revealed
if (msg.newVisibility == VIS_FOGGED && this.activated && !this.revealed[msg.player])
this.LoadMirage(msg.player);
};

View file

@ -240,6 +240,39 @@ class TurretHolder
return turret ? turret.name : "";
}
/**
* Calculate the closest horizontal distance an external entity could ever get
* to the specified turret point. If the holder is passable, returns 0.
* Otherwise returns the perpendicular distance from the turret point to the
* nearest edge of the holder's obstruction.
*
* @param {string|Object} turretPoint - The turret point name or object.
* @return {number} - The minimum possible horizontal distance.
*/
GetClosestApproachDistanceToTurretPoint(turretPoint)
{
if (typeof turretPoint === "string")
turretPoint = this.TurretPointByName(turretPoint);
if (!turretPoint)
return 0;
const cmpObstruction = Engine.QueryInterface(this.entity, IID_Obstruction);
if (!cmpObstruction || !cmpObstruction.GetBlockMovementFlag(false))
return 0;
const dxLocal = turretPoint.offset.x;
const dzLocal = turretPoint.offset.z;
const halfSizes = cmpObstruction.GetObstructionHalfSizes();
const hw = halfSizes.x;
const hh = halfSizes.y;
if (hw == null || hh == null || hw < 0 || hh < 0)
return 0;
return Math.max(0, Math.min(hw - Math.abs(dxLocal), hh - Math.abs(dzLocal)));
}
/**
* @return {number[]} - The turretted entityIDs.
*/

View file

@ -424,10 +424,42 @@ UnitAI.prototype.UnitFsmSpec = {
"Order.Attack": function(msg)
{
const type = this.GetBestAttackAgainst(msg.data.target, msg.data.allowCapture);
if (!type)
return this.FinishOrder();
// Check if this is a group attack
const isGroupAttack = !!msg.data.targetArray;
// For group attacks with invalid initial target, find one from the array
if (isGroupAttack && (!msg.data.target || msg.data.target === INVALID_ENTITY))
{
if (!this.FindAndSetNextTarget(msg.data))
{
this.FinishOrder();
return ACCEPT_ORDER;
}
}
// Get the attack type for the current target
const type = this.GetBestAttackAgainst(msg.data.target, msg.data.allowCapture);
if (!type)
{
// Current target can't be attacked
if (isGroupAttack)
{
if (this.FindAndSetNextTarget(msg.data))
{
msg.data.attackType = this.GetBestAttackAgainst(msg.data.target, msg.data.allowCapture);
if (msg.data.attackType)
{
this.SetNextState("INDIVIDUAL.COMBAT.ATTACKING");
return ACCEPT_ORDER;
}
}
}
this.FinishOrder();
return ACCEPT_ORDER;
}
// Set attackType before range check
msg.data.attackType = type;
this.RememberTargetPosition();
@ -1366,6 +1398,12 @@ UnitAI.prototype.UnitFsmSpec = {
// Wait for individual members to finish
"enter": function(msg)
{
if (this.order.data.targetArray)
{
// For group attacks, we're done once we distributed targets
this.FinishOrder();
return true;
}
const target = this.order.data.target;
if (!this.CheckFormationTargetAttackRange(target))
{
@ -1602,6 +1640,26 @@ UnitAI.prototype.UnitFsmSpec = {
"INDIVIDUAL": {
"Attacked": function(msg)
{
// First, check if we have a group attack order and the attacker is in our target array
if (this.order?.type === "Attack" &&
this.order.data?.targetArray?.includes(msg.data.attacker))
{
// Switch to attack the entity that's attacking us
this.order.data.target = msg.data.attacker;
this.order.data.attackType = this.GetBestAttackAgainst(msg.data.attacker, this.order.data.allowCapture);
// Update the current target index
const currentIndex = this.order.data.targetArray.indexOf(msg.data.attacker);
if (currentIndex !== -1)
this.order.data.currentTargetIndex = currentIndex;
// Make sure we're in the right state to handle this
const currentState = this.GetCurrentState();
if (currentState === "INDIVIDUAL.IDLE" || currentState === "INDIVIDUAL.WALKING")
this.SetNextState("INDIVIDUAL.COMBAT.APPROACHING");
return;
}
if (this.GetStance().targetAttackersAlways || !this.order || !this.order.data || !this.order.data.force)
this.RespondToTargetedEntities([msg.data.attacker]);
},
@ -2150,6 +2208,35 @@ UnitAI.prototype.UnitFsmSpec = {
"Attacked": function(msg)
{
// Check if we're doing a group attack and the attacker is in our target array
if (!this.order.data.targetArray ||
!this.order.data.targetArray.includes(msg.data.attacker) ||
msg.data.attacker === this.order.data.target)
return;
// Switch to attack the entity that's attacking us
this.order.data.target = msg.data.attacker;
this.order.data.attackType = this.GetBestAttackAgainst(msg.data.attacker, this.order.data.allowCapture);
// Update the current target index
const currentIndex = this.order.data.targetArray.indexOf(msg.data.attacker);
if (currentIndex !== -1)
this.order.data.currentTargetIndex = currentIndex;
// Re-evaluate our approach to the new target
if (this.CheckTargetAttackRange(this.order.data.target, this.order.data.attackType))
{
if (this.CanUnpack())
{
this.PushOrderFront("Unpack", { "force": true });
return;
}
this.SetNextState("ATTACKING");
}
// Continue approaching the new target
else if (!this.MoveToTargetAttackRange(this.order.data.target, this.order.data.attackType))
this.FinishOrder();
// 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))
@ -2209,7 +2296,23 @@ UnitAI.prototype.UnitFsmSpec = {
"MovementUpdate": function(msg)
{
if (msg.likelyFailure)
if (!msg.likelyFailure)
{
if (!this.CheckTargetAttackRange(this.order.data.target, this.order.data.attackType))
return;
if (this.CanUnpack())
{
this.PushOrderFront("Unpack", { "force": true });
return;
}
this.SetNextState("ATTACKING");
return;
}
// For group attacks, try next target instead of moving to last position
if (!this.order.data.targetArray || this.order.data.currentTargetIndex === undefined)
{
// This also handles hunting.
if (this.orderQueue.length > 1)
@ -2217,11 +2320,13 @@ UnitAI.prototype.UnitFsmSpec = {
this.FinishOrder();
return;
}
else if (!this.order.data.force || !this.order.data.lastPos)
if (!this.order.data.force || !this.order.data.lastPos)
{
this.SetNextState("COMBAT.FINDINGNEWTARGET");
return;
}
// If the order was forced, try moving to the target position,
// under the assumption that this is desirable if the target
// was somewhat far away - we'll likely end up closer to where
@ -2234,21 +2339,30 @@ UnitAI.prototype.UnitFsmSpec = {
return;
}
if (this.CheckTargetAttackRange(this.order.data.target, this.order.data.attackType))
// Handle group attack case
// Remove current unreachable target from array
const currentIndex = this.order.data.currentTargetIndex;
if (currentIndex < this.order.data.targetArray.length)
this.order.data.targetArray.splice(currentIndex, 1);
// Try to find next valid target
if (this.order.data.targetArray.length === 0 || !this.FindAndSetNextTarget(this.order.data))
{
if (this.CanUnpack())
{
this.PushOrderFront("Unpack", { "force": true });
return;
}
this.SetNextState("ATTACKING");
this.FinishOrder();
return;
}
else if (msg.likelySuccess)
// Try moving again,
// attack range uses a height-related formula and our actual max range might have changed.
if (!this.MoveToTargetAttackRange(this.order.data.target, this.order.data.attackType))
this.FinishOrder();
},
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
// Try approaching the new target
if (this.MoveToTargetAttackRange(this.order.data.target, this.order.data.attackType))
return;
// If we can't approach the new target either, remove it and continue
this.order.data.targetArray.splice(this.order.data.currentTargetIndex, 1);
if (this.order.data.targetArray.length === 0)
this.FinishOrder();
}
},
"ATTACKING": {
@ -2322,6 +2436,18 @@ UnitAI.prototype.UnitFsmSpec = {
"OutOfRange": function()
{
// Check if the target is garrisoned or in a turret (turreted entities cannot be attacked by melee units)
const cmpTargetUnitAI = Engine.QueryInterface(this.order.data.target, IID_UnitAI);
const isTargetGarrisoned = cmpTargetUnitAI && cmpTargetUnitAI.isGarrisoned;
const isTargetInTurret = cmpTargetUnitAI && cmpTargetUnitAI.IsTurret();
// If target is garrisoned or in a turret (and we're not ranged), treat as invalid
if (isTargetGarrisoned || (isTargetInTurret && this.order.data.attackType !== "Ranged"))
{
this.ProcessMessage("TargetInvalidated");
return;
}
if (this.ShouldChaseTargetedEntity(this.order.data.target, this.order.data.force))
{
if (this.CanPack())
@ -2332,11 +2458,53 @@ UnitAI.prototype.UnitFsmSpec = {
this.SetNextState("CHASING");
return;
}
// For group attacks, try next target instead of finding new ones
if (this.order.data.targetArray && this.order.data.currentTargetIndex !== undefined)
{
const currentIndex = this.order.data.currentTargetIndex;
// Remove current target since it's out of range and we can't chase
this.order.data.targetArray.splice(currentIndex, 1);
// Try to find next valid target in sequence
if (this.order.data.targetArray.length > 0 && this.FindAndSetNextTarget(this.order.data))
{
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
this.SetNextState("INDIVIDUAL.COMBAT.ATTACKING");
return;
}
}
this.SetNextState("FINDINGNEWTARGET");
},
"TargetInvalidated": function()
{
// For group attacks, remove current target and move to next in array
if (this.order.data.targetArray && this.order.data.currentTargetIndex !== undefined)
{
// Remove the current target from the array
const currentIndex = this.order.data.currentTargetIndex;
if (currentIndex < this.order.data.targetArray.length)
{
this.order.data.targetArray.splice(currentIndex, 1);
// If we have more targets, continue with the next one
if (this.order.data.targetArray.length > 0)
{
// Try to find next valid target in sequence
if (this.FindAndSetNextTarget(this.order.data))
{
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
this.SetNextState("INDIVIDUAL.COMBAT.ATTACKING");
return;
}
}
}
}
// No more targets or not a group attack - use original behavior
this.SetNextState("FINDINGNEWTARGET");
},
@ -2360,7 +2528,26 @@ UnitAI.prototype.UnitFsmSpec = {
"enter": function()
{
// Check if we are attacking a formation.
// First, check if we have pending targets in a group attack
if (this.order.data.targetArray && this.order.data.currentTargetIndex !== undefined)
{
// Try to find next valid target from the array
if (this.FindAndSetNextTarget(this.order.data))
{
this.order.data.attackType = this.GetBestAttackAgainst(this.order.data.target, this.order.data.allowCapture);
this.SetNextState("COMBAT.ATTACKING");
return true;
}
// No valid targets in array - clean up and continue with normal behavior
this.order.data.targetArray = [];
this.order.data.currentTargetIndex = undefined;
}
if (!this.order.data.target)
return false;
// Try to find the formation the target was a part of.
let cmpFormation = Engine.QueryInterface(this.order.data.target, IID_Formation);
if (cmpFormation)
this.order.data.formationTarget = this.order.data.target;
@ -2468,6 +2655,12 @@ UnitAI.prototype.UnitFsmSpec = {
{
if (msg.likelyFailure)
{
// If this is a group attack with pending targets, try the next one
if (this.order.data.targetArray && this.order.data.targetArray.length > 0)
{
this.SetNextState("COMBAT.FINDINGNEWTARGET");
return;
}
// This also handles hunting.
if (this.orderQueue.length > 1)
{
@ -3887,6 +4080,9 @@ UnitAI.prototype.OnOwnershipChanged = function(msg)
UnitAI.prototype.OnDestroy = function()
{
// Clean up all group attack states before destruction
this.CleanupAllGroupAttackStates();
// Switch to an empty state to let states execute their leave handlers.
this.UnitFsm.SwitchToNextState(this, "");
@ -4048,10 +4244,31 @@ UnitAI.prototype.SetupAttackRangeQuery = function(enable = true)
return;
const range = this.GetQueryRange(IID_Attack);
// Do not compensate for entity sizes: LOS doesn't, and UnitAI relies on that.
this.losAttackRangeQuery = cmpRangeManager.CreateActiveQuery(this.entity,
range.min, range.max, players, IID_Resistance,
cmpRangeManager.GetEntityFlagMask("normal"), false);
if (range.parabolic)
{
const cmpAttack = Engine.QueryInterface(this.entity, IID_Attack);
const yOrigin = cmpAttack ? cmpAttack.GetAttackYOrigin("Ranged") : 0;
// Do not compensate for entity sizes: LOS doesn't, and UnitAI relies on that.
this.losAttackRangeQuery = cmpRangeManager.CreateActiveParabolicQuery(
this.entity,
range.min,
range.max,
range.base,
yOrigin,
players,
IID_Resistance,
cmpRangeManager.GetEntityFlagMask("normal"),
true // Allow mirages for attack queries
);
}
else
this.losAttackRangeQuery = cmpRangeManager.CreateActiveQuery(this.entity,
range.min, range.max, players, IID_Resistance,
cmpRangeManager.GetEntityFlagMask("normal"),
false,
true // Allow mirages for attack queries
);
if (enable)
cmpRangeManager.EnableActiveQuery(this.losAttackRangeQuery);
@ -4093,6 +4310,9 @@ UnitAI.prototype.FsmStateNameChanged = function(state)
*/
UnitAI.prototype.FinishOrder = function()
{
// Clean up any group attack state before removing order
this.CleanupGroupAttackState(this.order);
if (!this.orderQueue.length)
{
const stack = new Error().stack.trimRight().replace(/^/mg, ' '); // indent each line
@ -4318,15 +4538,24 @@ UnitAI.prototype.ReplaceOrder = function(type, data)
const idx = this.orderQueue.findIndex(o => o.type == "LeaveFormation");
if (idx === -1)
{
// Clean up all queued orders before clearing them
this.CleanupAllGroupAttackStates();
this.orderQueue = [];
this.order = undefined;
}
else
{
// Clean up orders being discarded
for (let i = 0; i < idx; ++i)
this.CleanupGroupAttackState(this.orderQueue[i]);
this.orderQueue.splice(0, idx);
}
this.PushOrderFront(type, data);
}
else
{
// Clean up all queued orders before clearing them
this.CleanupAllGroupAttackStates();
this.orderQueue = [];
this.PushOrder(type, data);
}
@ -4405,6 +4634,7 @@ UnitAI.prototype.BackToWork = function()
if (this.IsTurret(cmpTurretable) && !cmpTurretable.LeaveTurret())
return false;
this.CleanupAllGroupAttackStates();
this.orderQueue = [];
this.AddOrders(this.workOrders);
@ -4948,24 +5178,24 @@ UnitAI.prototype.MoveToTargetAttackRange = function(target, type)
if (cmpFormation)
target = cmpFormation.GetClosestMemberToEntity(this.entity);
if (type != "Ranged")
return this.MoveToTargetRange(target, IID_Attack, type);
if (!this.CheckTargetVisible(target))
return false;
const cmpAttack = Engine.QueryInterface(this.entity, IID_Attack);
if (!cmpAttack)
return false;
const range = cmpAttack.GetRange(type);
// In case the range returns negative, we are probably too high compared to the target. Hope we come close enough.
const parabolicMaxRange = Math.max(0, Engine.QueryInterface(SYSTEM_ENTITY, IID_RangeManager).GetEffectiveParabolicRange(this.entity, target, range.max, cmpAttack.GetAttackYOrigin(type)));
const flatRange = cmpAttack.GetRange(type);
const effectiveRange = cmpAttack.GetEffectiveAttackRange(target, type);
if (effectiveRange.max < 0)
return false;
// The parabole changes while walking so be cautious:
const guessedMaxRange = parabolicMaxRange > range.max ? (range.max + parabolicMaxRange) / 2 : parabolicMaxRange;
// The parabola changes while walking so be cautious:
const guessedMaxRange = effectiveRange.max > flatRange.max ?
(flatRange.max + effectiveRange.max) / 2 :
effectiveRange.max;
return cmpUnitMotion && cmpUnitMotion.MoveToTargetRange(target, range.min, guessedMaxRange);
return cmpUnitMotion && cmpUnitMotion.MoveToTargetRange(target, effectiveRange.min, guessedMaxRange);
};
UnitAI.prototype.MoveToTargetRangeExplicit = function(target, min, max)
@ -5060,6 +5290,9 @@ UnitAI.prototype.CheckTargetRange = function(target, iid, type)
*/
UnitAI.prototype.CheckTargetAttackRange = function(target, type)
{
if (!target || target === INVALID_ENTITY || !type)
return false;
// for formation members, the formation will take care of the range check
if (this.IsFormationMember())
{
@ -5372,8 +5605,16 @@ UnitAI.prototype.ShouldChaseTargetedEntity = function(target, force)
if (!this.AbleToMove())
return false;
// Check if we should chase based on stance
if (this.GetStance().respondChase)
return true;
{
// If we're allowed to chase beyond vision, always chase
if (this.GetStance().respondChaseBeyondVision)
return true;
// Otherwise, only chase if the target is within our personal vision
return this.CheckTargetIsInVisionRange(target);
}
// If we are guarding/escorting, chase at least as long as the guarded unit is in target range of the attacker
if (this.isGuardOf)
@ -5793,6 +6034,75 @@ UnitAI.prototype.Attack = function(target, allowCapture = this.DEFAULT_CAPTURE,
this.AddOrder("Attack", order, queued, pushFront);
};
/**
* Adds a group attack order to the queue.
* Used when some unit(s) are ordered to attack multiple targets.
* Each unit receives the full target list (from Commands) but starts at a different position
* based on the startingIndex in the attacking group.
*
* @param {Array} targets - Array of target entity IDs to attack (pre-sorted by distance)
* @param {number} startingIndex - This unit's position in the attacking group (0-based)
* @param {number} unitCount - Total number of units in the attacking group
* @param {boolean} allowCapture - Whether capturing is allowed
* @param {boolean} queued - If true, add to end of queue instead of replacing current order
* @param {boolean} pushFront - If true, add to front of queue (interrupt current order)
*/
UnitAI.prototype.AttackGroup = function(targets, startingIndex, unitCount, allowCapture = this.DEFAULT_CAPTURE, queued = false, pushFront = false)
{
if (!targets?.length)
return;
// Check if adding these targets would exceed the limit
const currentTotal = this.CountTotalTargetsInQueue();
const newTargetCount = targets.length;
if (currentTotal + newTargetCount > this.MAX_TOTAL_TARGETS)
{
// Trim the targets to fit within the limit
const allowedNewTargets = Math.max(0, this.MAX_TOTAL_TARGETS - currentTotal);
if (allowedNewTargets === 0)
return;
// Trim the target array
targets = targets.slice(0, allowedNewTargets);
// If trimming results in no targets, just return
if (targets.length === 0)
return;
}
// If this unit is in a formation, move the formation controller out of the world
// This prevents the controller from staying at the coordinates where the units received the order
// That can potentially be far apart from where the fighting will occur.
// Result: The formation will reform into a more logical position once members are done (idle).
this.MoveFormationControllerOutOfWorld();
const stride = targets.length / unitCount;
const startIdx = Math.min(Math.round((startingIndex + 0.5) * stride), targets.length - 1);
const order = {
"force": true,
"allowCapture": allowCapture,
"targetArray": targets.slice(),
"target": INVALID_ENTITY,
"currentTargetIndex": startIdx,
"originalFirstTarget": targets[0],
};
this.RememberTargetPosition(order);
this.AddOrder("Attack", order, queued, pushFront);
};
UnitAI.prototype.MoveFormationControllerOutOfWorld = function()
{
if (!this.IsFormationMember() || !this.formationController)
return;
const cmpControllerPosition = Engine.QueryInterface(this.formationController, IID_Position);
if (cmpControllerPosition?.IsInWorld())
cmpControllerPosition.MoveOutOfWorld();
};
/**
* Adds garrison order to the queue, forced by the player.
*/
@ -6339,9 +6649,22 @@ UnitAI.prototype.FindWalkAndFightTargets = function()
return false;
};
/**
* Returns the detection range for the given interface, adjusted by stance.
*
* The query range depends on stance because it represents the distance at which
* the unit should "notice" an enemy and potentially start moving toward it.
*
* @param {number} iid - IID_Vision, IID_Heal, or IID_Attack
* @returns {{min: number, max: number, base: number, parabolic: boolean}}
* 'parabolic' indicates that the caller
* should use a parabolic range query (accounting for elevation) instead of a
* flat 2D one. Generally used for projectile attacks.
* 'base' is a non-parabolic 2D detection range that always counts as in-range.
*/
UnitAI.prototype.GetQueryRange = function(iid)
{
const ret = { "min": 0, "max": 0 };
const ret = { "min": 0, "max": 0, "base": 0, "parabolic": false };
const cmpVision = Engine.QueryInterface(this.entity, IID_Vision);
if (!cmpVision)
@ -6354,27 +6677,35 @@ UnitAI.prototype.GetQueryRange = function(iid)
return ret;
}
if (this.GetStance().respondStandGround)
{
const range = this.GetRange(iid);
if (!range)
return ret;
ret.min = range.min;
ret.max = Math.min(range.max, visionRange);
}
else if (this.GetStance().respondChase)
ret.max = visionRange;
const range = this.GetRange(iid);
if (!range)
return ret;
// The query range depends on stance because it represents the distance at which
// the unit should "notice" an enemy and potentially start moving toward it.
// In all stances, always spot targets within effective attack/heal range.
Object.assign(ret, range);
let nonParabolicMax = 0;
if (this.GetStance().respondChase)
// Chase: Always spot targets within vision range, so we can chase them.
nonParabolicMax = visionRange;
else if (this.GetStance().respondHoldGround)
{
const range = this.GetRange(iid);
if (!range)
return ret;
ret.max = Math.min(range.max + visionRange / 2, visionRange);
}
// HoldGround: willing to move a bit, so spot targets within attack range + half vision.
nonParabolicMax = Math.min(range.max + visionRange / 2, visionRange);
// StandGround: nonParabolicMax stays 0, using only parabolic range.
// We probably have stance 'passive' and we wouldn't have a range,
// but as it is the default for healers we need to set it to something sane.
else if (iid === IID_Heal)
ret.max = visionRange;
nonParabolicMax = visionRange;
if (ret.parabolic)
ret.base = nonParabolicMax;
else
ret.max = nonParabolicMax;
return ret;
};
@ -6726,6 +7057,72 @@ UnitAI.prototype.AttackEntitiesByPreference = function(ents)
return this.RespondToTargetedEntities(entsWithoutPref);
};
UnitAI.prototype.FindAndSetNextTarget = function(data)
{
if (!this.EnsureValidTargetIndex(data))
return false;
const startIdx = data.currentTargetIndex;
const currentTarget = data.targetArray[startIdx];
// First check the starting target
if (this.CanAttack(currentTarget) && this.CheckTargetVisible(currentTarget))
return this.SetNextTarget(data, startIdx);
// Search forward using find
const forwardFound = data.targetArray
.slice(startIdx + 1)
.findIndex((target, i) =>
this.CanAttack(target) && this.CheckTargetVisible(target)
);
if (forwardFound !== -1)
return this.SetNextTarget(data, startIdx + 1 + forwardFound);
// Search backward using find
const backwardFound = data.targetArray
.slice(0, startIdx)
.reverse()
.findIndex((target, i) =>
this.CanAttack(target) && this.CheckTargetVisible(target)
);
if (backwardFound !== -1)
{
// Convert reverse index back to original index
const originalIndex = startIdx - 1 - backwardFound;
return this.SetNextTarget(data, originalIndex);
}
return false;
};
UnitAI.prototype.SetNextTarget = function(data, index)
{
const target = data.targetArray[index];
data.target = target;
data.attackType = this.GetBestAttackAgainst(target, data.allowCapture);
data.currentTargetIndex = index;
return true;
};
UnitAI.prototype.EnsureValidTargetIndex = function(data)
{
if (!data.targetArray || data.currentTargetIndex === undefined)
return false;
// If array is empty, clear the index
if (data.targetArray.length === 0)
{
data.currentTargetIndex = undefined;
return false;
}
data.currentTargetIndex = Math.clamp(data.currentTargetIndex, 0, data.targetArray.length - 1);
return true;
};
/**
* Call UnitAI.funcname(args) on all formation members.
* @param resetFinishedEntities - If true, call ResetFinishedEntities first.
@ -6837,6 +7234,50 @@ UnitAI.prototype.ResetObstructionMitigationFlag = function()
delete this.obstructionMitigationAttempted;
};
/**
* Counts the total number of target entities across all queued orders.
* This includes targetArray from group attacks and single targets.
* Each target reference is counted separately, even if the same entity
* appears in multiple orders or in both targetArray and target.
* @returns {number} - Total number of target entity references in the order queue
*/
UnitAI.prototype.CountTotalTargetsInQueue = function()
{
let total = 0;
for (const order of this.orderQueue)
{
if (order.data)
{
// Count group attack targets
if (order.data.targetArray && Array.isArray(order.data.targetArray))
total += order.data.targetArray.length;
// Add single target for consistency
if (order.data.target && order.data.target !== INVALID_ENTITY)
total++;
}
}
return total;
};
UnitAI.prototype.CleanupGroupAttackState = function(order)
{
if (order?.data?.targetArray)
{
delete order.data.targetArray;
delete order.data.currentTargetIndex;
}
};
UnitAI.prototype.CleanupAllGroupAttackStates = function()
{
for (const order of this.orderQueue)
this.CleanupGroupAttackState(order);
};
// Maximum number of target entities allowed across all queued orders
UnitAI.prototype.MAX_TOTAL_TARGETS = 1000;
UnitAI.prototype.UnitFsm = new FSM(UnitAI.prototype.UnitFsmSpec);
Engine.RegisterComponentType(IID_UnitAI, "UnitAI", UnitAI);

View file

@ -32,6 +32,8 @@ Engine.LoadComponentScript("interfaces/Formation.js");
Engine.LoadComponentScript("interfaces/Health.js");
Engine.LoadComponentScript("interfaces/Resistance.js");
Engine.LoadComponentScript("interfaces/TechnologyManager.js");
Engine.LoadComponentScript("interfaces/Turretable.js");
Engine.LoadComponentScript("interfaces/TurretHolder.js");
Engine.LoadComponentScript("Attack.js");
let entityID = 903;
@ -52,6 +54,16 @@ function attackComponentTest(defenderClass, isEnemy, test_function)
"IsEnemy": () => isEnemy
});
AddMock(SYSTEM_ENTITY, IID_ObstructionManager, {
"IsInTargetRange": () => true
});
AddMock(SYSTEM_ENTITY, IID_RangeManager, {
"GetEffectiveParabolicRange": () => 25,
"GetMaxReachableParabolicHeight": () => 15,
"GetLosVisibility": (target, owner) => "visible"
});
const attacker = entityID;
AddMock(attacker, IID_Position, {
@ -201,7 +213,7 @@ attackComponentTest(undefined, true, (attacker, cmpAttack, defender) =>
TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetPreferredClasses("Melee"), ["Civilian"]);
TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetRestrictedClasses("Melee"), ["Elephant", "Archer"]);
TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetFullAttackRange(), { "min": 0, "max": 80 });
TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetFullAttackRange(), { "min": 0, "max": 80, "parabolic": true });
TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetAttackEffectsData("Capture"), { "Capture": 8 });
TS_ASSERT_UNEVAL_EQUALS(cmpAttack.GetAttackEffectsData("Ranged"), {
@ -416,3 +428,101 @@ function testAttackPreference()
TS_ASSERT_EQUALS(cmpAttack.GetPreference(attacker+4), undefined);
}
testAttackPreference();
function testCanEverReachTarget()
{
const attacker = ++entityID;
AddMock(attacker, IID_Position, {
"IsInWorld": () => true,
"GetHeightOffset": () => 0,
"GetPosition2D": () => new Vector2D(1, 2)
});
const cmpAttack = ConstructComponent(attacker, "Attack", {
"Melee": {
"Damage": { "Hack": 10, "Pierce": 0, "Crush": 0 },
"MaxRange": 5
},
"Ranged": {
"Damage": { "Hack": 0, "Pierce": 10, "Crush": 0 },
"MaxRange": 30,
"Projectile": { "Speed": 50, "Spread": 1, "Gravity": 1, "FriendlyFire": "false" }
}
});
// Melee target within 3D range
{
const defender = ++entityID;
AddMock(defender, IID_Position, {
"IsInWorld": () => true,
"GetHeightOffset": () => 0
});
TS_ASSERT_EQUALS(cmpAttack.CanEverReachTarget(defender, "Melee"), true);
}
// Melee target too high
{
const defender = ++entityID;
AddMock(defender, IID_Position, {
"IsInWorld": () => true,
"GetHeightOffset": () => 10
});
TS_ASSERT_EQUALS(cmpAttack.CanEverReachTarget(defender, "Melee"), false);
}
// Melee target at same height, within range (close distance)
{
const defender = ++entityID;
AddMock(defender, IID_Position, {
"IsInWorld": () => true,
"GetHeightOffset": () => 4
});
// sqrt(0² + 4²) = 4 <= 5
TS_ASSERT_EQUALS(cmpAttack.CanEverReachTarget(defender, "Melee"), true);
}
// Ranged: target at same height — reachable from current position (check 1)
{
const defender = ++entityID;
AddMock(defender, IID_Position, {
"IsInWorld": () => true,
"GetHeightOffset": () => 0,
"GetPosition": () => new Vector3D(1, 0, 2)
});
// Need RangeManager mock for IsTargetInRange (check 1) to work
AddMock(SYSTEM_ENTITY, IID_RangeManager, {
"GetEffectiveParabolicRange": () => 25,
"GetMaxReachableParabolicHeight": () => 15
});
AddMock(SYSTEM_ENTITY, IID_ObstructionManager, {
"IsInTargetRange": () => true
});
TS_ASSERT_EQUALS(cmpAttack.CanEverReachTarget(defender, "Ranged"), true);
}
// Ranged: target too high for parabolic arc even at closest approach (check 2)
{
const defender = ++entityID;
AddMock(defender, IID_Position, {
"IsInWorld": () => true,
"GetHeightOffset": () => 20,
"GetPosition": () => new Vector3D(1, 20, 2)
});
AddMock(SYSTEM_ENTITY, IID_RangeManager, {
"GetEffectiveParabolicRange": () => -1, // out of range
"GetMaxReachableParabolicHeight": () => 10
});
AddMock(SYSTEM_ENTITY, IID_ObstructionManager, {
"IsInTargetRange": () => false
});
// heightDiff = 20 - 0 = 20, maxReachableHeightDiff = 10 → unreachable
TS_ASSERT_EQUALS(cmpAttack.CanEverReachTarget(defender, "Ranged"), false);
}
}
testCanEverReachTarget();

View file

@ -15,6 +15,7 @@ const enemyPlayer = 2;
const alliedPlayer = 3;
const turretHolderID = 9;
const entitiesToTest = [10, 11, 12, 13];
let entityID = 100;
AddMock(turretHolderID, IID_Ownership, {
"GetOwner": () => player
@ -244,3 +245,80 @@ cmpTurretHolder.OnOwnershipChanged({
"from": INVALID_PLAYER
});
TS_ASSERT(cmpTurretHolder.OccupiesTurretPoint(spawned));
// Test GetClosestApproachDistanceToTurretPoint
{
const holder = ++entityID;
// Mock the holder's obstruction
AddMock(holder, IID_Obstruction, {
"GetBlockMovementFlag": () => true,
"GetObstructionHalfSizes": () => ({ "x": 10, "y": 15 })
});
const cmpHolder = ConstructComponent(holder, "TurretHolder", {
"TurretPoints": {
"center": {
"X": "0",
"Y": "5.0",
"Z": "0"
},
"edge": {
"X": "8.0",
"Y": "5.0",
"Z": "0"
},
"corner": {
"X": "10.0",
"Y": "5.0",
"Z": "15.0"
},
"outside": {
"X": "15.0",
"Y": "5.0",
"Z": "0"
}
}
});
// Center point (0,0) in 20x30 building → min(10, 15) = 10
TS_ASSERT_EQUALS(cmpHolder.GetClosestApproachDistanceToTurretPoint("center"), 10);
// Edge point (8,0) in 20x30 building → min(10-8, 15-0) = 2
TS_ASSERT_EQUALS(cmpHolder.GetClosestApproachDistanceToTurretPoint("edge"), 2);
// Corner point (10,15) in 20x30 building → min(10-10, 15-15) = 0
TS_ASSERT_EQUALS(cmpHolder.GetClosestApproachDistanceToTurretPoint("corner"), 0);
// Outside point (15,0) in 20x30 building → min(10-15, 15-0) = -5 → clamped to 0
TS_ASSERT_EQUALS(cmpHolder.GetClosestApproachDistanceToTurretPoint("outside"), 0);
// Nonexistent turret point
TS_ASSERT_EQUALS(cmpHolder.GetClosestApproachDistanceToTurretPoint("nonexistent"), 0);
// Pass object directly
const turretPoint = cmpHolder.TurretPointByName("center");
TS_ASSERT_EQUALS(cmpHolder.GetClosestApproachDistanceToTurretPoint(turretPoint), 10);
// Passable building (no obstruction or doesn't block movement)
const passableHolder = ++entityID;
AddMock(passableHolder, IID_Obstruction, {
"GetBlockMovementFlag": () => false
});
const cmpHolderPassable = ConstructComponent(passableHolder, "TurretHolder", {
"TurretPoints": {
"center": { "X": "0", "Y": "5.0", "Z": "0" }
}
});
TS_ASSERT_EQUALS(cmpHolderPassable.GetClosestApproachDistanceToTurretPoint("center"), 0);
// No obstruction component at all
++entityID;
const cmpHolderNoObst = ConstructComponent(entityID, "TurretHolder", {
"TurretPoints": {
"center": { "X": "0", "Y": "5.0", "Z": "0" }
}
});
TS_ASSERT_EQUALS(cmpHolderNoObst.GetClosestApproachDistanceToTurretPoint("center"), 0);
}

View file

@ -138,6 +138,7 @@ function TestFormationExiting(mode)
"ResetActiveQuery": function(id) { if (mode == 0) return []; return [enemy]; },
"DisableActiveQuery": function(id) { },
"GetEntityFlagMask": function(identifier) { },
"GetLosVisibility": (ent, player) => "visible"
});
AddMock(SYSTEM_ENTITY, IID_TemplateManager, {
@ -319,8 +320,11 @@ function TestMoveIntoFormationWhileAttacking()
"ResetActiveQuery": function(id) { return [enemy]; },
"DisableActiveQuery": function(id) { },
"GetEntityFlagMask": function(identifier) { },
"GetLosVisibility": (target, player) => "visible",
"GetLosVisibilityPosition": (x, z, player) => "visible"
});
AddMock(SYSTEM_ENTITY, IID_TemplateManager, {
"GetCurrentTemplateName": function(ent) { return "special/formations/line_closed"; },
});
@ -406,6 +410,10 @@ function TestMoveIntoFormationWhileAttacking()
"GetHitpoints": function() { return 40; },
});
AddMock(enemy, IID_Ownership, {
"GetOwner": () => 2 // Different player ID (enemy)
});
const controllerFormation = ConstructComponent(controller, "Formation", {
"FormationShape": "square",
"ShiftRows": "false",
@ -421,6 +429,10 @@ function TestMoveIntoFormationWhileAttacking()
"DefaultStance": "aggressive"
});
AddMock(controller, IID_Ownership, {
"GetOwner": () => 1
});
AddMock(controller, IID_Position, {
"GetTurretParent": () => INVALID_ENTITY,
"JumpTo": function(x, z) { this.x = x; this.z = z; },
@ -458,7 +470,7 @@ function TestMoveIntoFormationWhileAttacking()
controllerFormation.SetMembers(units);
controllerAI.Attack(enemy, []);
controllerAI.Attack(enemy);
for (const ent of unitAIs)
TS_ASSERT_EQUALS(unitAI.fsmStateName, "INDIVIDUAL.COMBAT.ATTACKING");
@ -889,4 +901,362 @@ function TestAttemptObstructionMitigation()
})();
}
TestAttemptObstructionMitigation();
TestAttemptObstructionMitigation();
function TestFindAndSetNextTargetBehavior()
{
ResetState();
const attacker = 10;
const targets = [20, 21, 22, 23, 24]; // Multiple targets for comprehensive testing
// Basic mocks needed for unitAI creation
AddMock(SYSTEM_ENTITY, IID_Timer, {
"SetInterval": () => {},
"SetTimeout": () => {}
});
AddMock(SYSTEM_ENTITY, IID_RangeManager, {
"CreateActiveQuery": () => 1,
"EnableActiveQuery": () => {},
"ResetActiveQuery": () => [],
"DisableActiveQuery": () => {},
"GetEntityFlagMask": () => 0
});
AddMock(SYSTEM_ENTITY, IID_ObstructionManager, {
"IsInTargetRange": () => false
});
// Create the unitAI component
const unitAI = ConstructComponent(attacker, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
AddMock(attacker, IID_Attack, {
"GetBestAttackAgainst": () => "Melee"
});
unitAI.OnCreate();
// Mock the visibility and attackability checks
unitAI.CanAttack = (target) =>
{
// Target 21 is always unattackable (e.g., garrisoned, dead, etc.)
return target !== 21;
};
unitAI.CheckTargetVisible = (target) =>
{
// Target 22 is always not visible
return target !== 22;
};
// First target is valid
(function()
{
const data = {
"targetArray": [20, 21, 22, 23, 24],
"currentTargetIndex": 0, // Currently targeting 20
"target": 20,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(data.target, 20);
TS_ASSERT_EQUALS(data.currentTargetIndex, 0);
})();
// End of array behavior
(function()
{
const data = {
"targetArray": [18, 19, 20, 21, 22],
"currentTargetIndex": 2, // Currently targeting 22
"allowCapture": false
};
// 21 and 22 are invalid, should go backward and find 20
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(data.target, 20); // Should be assigned targetArray[initialTarget - 1]
})();
// No valid targets found
(function()
{
const data = {
"targetArray": [21, 22], // Both are invalid (21 unattackable, 22 not visible)
"currentTargetIndex": 0,
"target": 21,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(!found);
TS_ASSERT_EQUALS(data.target, 21); // Should remain unchanged
TS_ASSERT_EQUALS(data.currentTargetIndex, 0);
})();
// Empty target array
(function()
{
const data = {
"targetArray": [],
"currentTargetIndex": 0,
"target": 20,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(!found);
TS_ASSERT_EQUALS(data.target, 20); // Should remain unchanged
TS_ASSERT_EQUALS(data.currentTargetIndex, void 0); // Should nullify currentTargetIndex
})();
// Current target is last in array
(function()
{
const data = {
"targetArray": [20, 21, 22, 23, 24],
"currentTargetIndex": 4, // Currently targeting 24 (last element)
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(data.target, 24); // Should remain unchanged
TS_ASSERT_EQUALS(data.currentTargetIndex, 4);
})();
// Single invalid target
(function()
{
const data = {
"targetArray": [21], // Only one target, which is invalid
"currentTargetIndex": 0,
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(!found);
})();
// Verify if we don't do more calls then necessary
(function()
{
const searchOrder = [];
unitAI.CanAttack = (target) =>
{
searchOrder.push(target);
return target == 20;
};
unitAI.CheckTargetVisible = (target) => true; // All visible
const data = {
"targetArray": [20, 21, 22, 23],
"currentTargetIndex": 1, // Currently targeting 21
"allowCapture": false
};
const found = unitAI.FindAndSetNextTarget(data);
TS_ASSERT(found);
TS_ASSERT_EQUALS(searchOrder.length, 4); // Should find at 20 (4 calls)
})();
}
TestFindAndSetNextTargetBehavior();
function TestAttackGroupBehavior()
{
ResetState();
const attacker1 = 100;
const attacker2 = 101;
const targets = [200, 201, 202, 203, 204];
// Basic mocks needed for unitAI creation
AddMock(SYSTEM_ENTITY, IID_Timer, {
"SetInterval": () => {},
"SetTimeout": () => {}
});
AddMock(SYSTEM_ENTITY, IID_RangeManager, {
"CreateActiveQuery": () => 1,
"EnableActiveQuery": () => {},
"ResetActiveQuery": () => [],
"DisableActiveQuery": () => {},
"GetEntityFlagMask": () => 0
});
AddMock(SYSTEM_ENTITY, IID_ObstructionManager, {
"IsInTargetRange": () => false
});
// Create two unitAI components
const unitAI1 = ConstructComponent(attacker1, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
const unitAI2 = ConstructComponent(attacker2, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
AddMock(attacker1, IID_Attack, {
"GetBestAttackAgainst": () => "Melee"
});
AddMock(attacker2, IID_Attack, {
"GetBestAttackAgainst": () => "Melee"
});
unitAI1.OnCreate();
unitAI2.OnCreate();
// Basic AttackGroup distribution
(function()
{
let orderAdded1 = null;
let orderAdded2 = null;
// Mock AddOrder to capture what orders are created
unitAI1.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded1 = { type, data, queued, pushFront };
};
unitAI2.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded2 = { type, data, queued, pushFront };
};
// Call AttackGroup for both units
unitAI1.AttackGroup(targets, 0, 2, false, false, false);
unitAI2.AttackGroup(targets, 1, 2, false, false, false);
// Verify unit1's order
TS_ASSERT(orderAdded1);
TS_ASSERT_EQUALS(orderAdded1.type, "Attack");
TS_ASSERT_EQUALS(orderAdded1.data.targetArray.length, 5);
TS_ASSERT_EQUALS(orderAdded1.data.target, INVALID_ENTITY);
// Unit 0 should start at position 1 ==> Math.round((0 + 0.5) * 2.5) = Math.round(1.25) = 1
TS_ASSERT_EQUALS(orderAdded1.data.currentTargetIndex, 1);
// Verify unit2's order
TS_ASSERT(orderAdded2);
TS_ASSERT_EQUALS(orderAdded2.type, "Attack");
TS_ASSERT_EQUALS(orderAdded2.data.targetArray.length, 5);
TS_ASSERT_EQUALS(orderAdded2.data.target, INVALID_ENTITY);
// Unit 1 should start at position 4 ==> Math.round((1 + 0.5) * 2.5) = Math.round(3.75) = 4
TS_ASSERT_EQUALS(orderAdded2.data.currentTargetIndex, 4);
})();
// More units than targets
(function()
{
let orderAdded1 = null;
let orderAdded2 = null;
let orderAdded3 = null;
const unitAI3 = ConstructComponent(102, "UnitAI", {
"FormationController": "false",
"DefaultStance": "aggressive"
});
AddMock(102, IID_Attack, { "GetBestAttackAgainst": () => "Melee" });
unitAI3.OnCreate();
unitAI1.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded1 = { type, data, queued, pushFront };
};
unitAI2.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded2 = { type, data, queued, pushFront };
};
unitAI3.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded3 = { type, data, queued, pushFront };
};
const smallTargets = [300, 301];
unitAI1.AttackGroup(smallTargets, 0, 3, true, true, false);
unitAI2.AttackGroup(smallTargets, 1, 3, true, true, false);
unitAI3.AttackGroup(smallTargets, 2, 3, true, true, false);
// Verify distribution when more units than targets
TS_ASSERT(orderAdded1);
TS_ASSERT_EQUALS(orderAdded1.data.currentTargetIndex, 0); // 0 * 2 / 3 = 0
TS_ASSERT_EQUALS(orderAdded1.data.allowCapture, true);
TS_ASSERT_EQUALS(orderAdded1.queued, true);
TS_ASSERT(orderAdded2);
TS_ASSERT_EQUALS(orderAdded2.data.currentTargetIndex, 1); // 1 * 2 / 3 = 0.66, round = 1
TS_ASSERT(orderAdded2.data.currentTargetIndex < smallTargets.length);
TS_ASSERT(orderAdded3);
TS_ASSERT_EQUALS(orderAdded3.data.currentTargetIndex, 1); // 2 * 2 / 3 = 1.33, round = 1
TS_ASSERT(orderAdded3.data.currentTargetIndex < smallTargets.length);
})();
// Edge case - single target
(function()
{
let orderAdded = null;
unitAI1.AddOrder = (type, data, queued, pushFront) =>
{
orderAdded = { type, data, queued, pushFront };
};
const singleTarget = [400];
unitAI1.AttackGroup(singleTarget, 0, 1, false, false, true);
TS_ASSERT(orderAdded);
TS_ASSERT_EQUALS(orderAdded.data.targetArray.length, 1);
TS_ASSERT_EQUALS(orderAdded.data.currentTargetIndex, 0);
TS_ASSERT_EQUALS(orderAdded.pushFront, true);
})();
// Empty targets array should do nothing
(function()
{
let callCount = 0;
unitAI1.AddOrder = () => { callCount++; };
unitAI1.AttackGroup([], 0, 1);
TS_ASSERT_EQUALS(callCount, 0);
unitAI1.AttackGroup(null, 0, 1);
TS_ASSERT_EQUALS(callCount, 0);
unitAI1.AttackGroup(undefined, 0, 1);
TS_ASSERT_EQUALS(callCount, 0);
})();
// Verify RememberTargetPosition is called
(function()
{
let rememberedOrder = null;
unitAI1.RememberTargetPosition = (order) =>
{
rememberedOrder = order;
};
unitAI1.AddOrder = () => {};
const testTargets = [500, 501];
unitAI1.AttackGroup(testTargets, 0, 1);
TS_ASSERT(rememberedOrder);
TS_ASSERT_EQUALS(rememberedOrder.targetArray.length, 2);
})();
}
TestAttackGroupBehavior();

View file

@ -8,5 +8,5 @@
{ "value": "Researcher/TechCostMultiplier/metal", "multiply": 0.9 }
],
"auraName": "Economic Fortune",
"auraDescription": "Solon brought in a new system of weights and measures, fathers were encouraged to find trades for their sons.\nEconomic technologies 10% resource costs."
"auraDescription": "Solon brought in a new system of weights and measures, and fathers were encouraged to find trades for their sons.\nEconomic technologies 10% resource costs."
}

View file

@ -5,5 +5,5 @@
{ "value": "TerritoryInfluence/Radius", "multiply": 1.2 }
],
"auraName": "Territorial Expansion",
"auraDescription": "At its height, the Empire's borders spanned from the Fergana Valley in the west, to Korea in the east, and to northern Vietnam in the south.\nTerritory influence bonus +20%."
"auraDescription": "At its height, the Empire's borders spanned from the Fergana Valley in the west to Korea in the east and to northern Vietnam in the south.\nTerritory influence bonus +20%."
}

View file

@ -7,5 +7,5 @@
{ "value": "Resistance/Entity/Damage/Crush", "add": 1 }
],
"auraName": "Founder and Defender of the Republic",
"auraDescription": "Brutus was one of the key figures in the overthrow of the monarchy and the founding of the Roman Republic. Later, as consul he led a Roman army to victory against the Etruscan King Tarquinius who sought to retake the throne.\nHumans and Siege Engines +1 crush, hack, pierce resistance."
"auraDescription": "Brutus was one of the key figures in the overthrow of the monarchy and the founding of the Roman Republic. Later, as consul, he led a Roman army to victory against the Etruscan King Tarquinius who sought to retake the throne.\nHumans and Siege Engines +1 crush, hack, and pierce resistance."
}

View file

@ -179,6 +179,28 @@ var g_Commands = {
});
},
"attack-group": function(player, cmd, data)
{
const unitAIs = data.entities.flatMap(ent =>
{
const cmpUnitAI = Engine.QueryInterface(ent, IID_UnitAI);
const cmpAttack = Engine.QueryInterface(ent, IID_Attack);
// Check if unit can move and has attack capability
const canAttack = cmpAttack && cmpAttack.GetAttackTypes().length > 0;
return (cmpUnitAI && cmpUnitAI.AbleToMove() && canAttack) ? [cmpUnitAI] : [];
});
if (!unitAIs.length || !cmd.targets?.length)
return;
// Pass the entire target array and unit count to each UnitAI
unitAIs.forEach((cmpUnitAI, index) =>
{
cmpUnitAI.AttackGroup(cmd.targets, index, unitAIs.length, cmd.allowCapture, cmd.queued, cmd.pushFront);
});
},
"patrol": function(player, cmd, data)
{
const ents = data.entities.length;

View file

@ -24,6 +24,12 @@ function ChangeEntityTemplate(oldEnt, newTemplate)
if (cmpVisual && cmpNewVisual)
cmpNewVisual.SetActorSeed(cmpVisual.GetActorSeed());
// Set ownership so turret checks work properly
const cmpOwnership = Engine.QueryInterface(oldEnt, IID_Ownership);
const cmpNewOwnership = Engine.QueryInterface(newEnt, IID_Ownership);
if (cmpOwnership && cmpNewOwnership)
cmpNewOwnership.SetOwner(cmpOwnership.GetOwner());
const cmpOldTurretable = Engine.QueryInterface(oldEnt, IID_Turretable);
// If the old entity is turreted, we need to handle it before copying position
@ -39,9 +45,15 @@ function ChangeEntityTemplate(oldEnt, newTemplate)
// Check if it's allowed to occupy the turret point
const cmpTurretHolderOfOldEnt = Engine.QueryInterface(cmpOldTurretable.HolderID(), IID_TurretHolder);
if (cmpTurretHolderOfNewEnt &&
!cmpTurretHolderOfOldEnt.AllowedToOccupyTurretPoint(newEnt, cmpOldTurretable.GetTurretPointName(), true))
cmpOldTurretable.LeaveTurret(true);
if (cmpTurretHolderOfOldEnt)
{
// Find the actual turret point object using the old entity
const turretPoint = cmpTurretHolderOfOldEnt.GetOccupiedTurretPoint(oldEnt);
if (!turretPoint || !cmpTurretHolderOfOldEnt.AllowedToOccupyTurretPoint(newEnt, turretPoint, true))
cmpOldTurretable.LeaveTurret(true);
// If allowed, don't leave the turret - OnEntityRenamed will handle the swap
}
}
}
@ -86,24 +98,6 @@ function ChangeEntityTemplate(oldEnt, newTemplate)
for (const entity of cmpTurretHolder.GetEntities())
cmpNewTurretHolder.SetReservedTurretPoint(cmpTurretHolder.GetOccupiedTurretPointName(entity));
let owner;
const cmpTerritoryDecay = Engine.QueryInterface(newEnt, IID_TerritoryDecay);
if (cmpTerritoryDecay && cmpTerritoryDecay.HasTerritoryOwnership() && cmpNewPosition)
{
const pos = cmpNewPosition.GetPosition2D();
const cmpTerritoryManager = Engine.QueryInterface(SYSTEM_ENTITY, IID_TerritoryManager);
owner = cmpTerritoryManager.GetOwner(pos.x, pos.y);
}
else
{
const cmpOwnership = Engine.QueryInterface(oldEnt, IID_Ownership);
if (cmpOwnership)
owner = cmpOwnership.GetOwner();
}
const cmpNewOwnership = Engine.QueryInterface(newEnt, IID_Ownership);
if (cmpNewOwnership)
cmpNewOwnership.SetOwner(owner);
CopyControlGroups(oldEnt, newEnt);
// Rescale capture points

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -54,7 +54,7 @@ pipeline {
stage('Check for shader changes') {
when {
anyOf {
changeset 'binaries/data/mods/**/shaders/**/*.xml'
changeset 'binaries/data/mods/**/shaders/**/*'
changeset 'source/tools/spirv/compile.py'
}
}

View file

@ -33,6 +33,8 @@ echo "Building cpp-httplib..."
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -33,6 +33,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -49,6 +49,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -49,6 +49,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -36,6 +36,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -56,6 +56,8 @@ echo "Building SpiderMonkey..."
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
OS="${OS:=$(uname -s)}"

View file

@ -33,6 +33,8 @@ done
if [ -e .already-built ] && [ "$(cat .already-built || true)" = "${LIB_VERSION}" ]; then
echo "Skipping - already built (use --force-rebuild to override)"
exit
else
rm -f .already-built
fi
# fetch

View file

@ -33,6 +33,7 @@ ignore = [
"ANN",
"C90",
"COM812",
"CPY001",
"D10",
"EM",
"FIX002",

View file

@ -92,12 +92,12 @@ void CCinemaManager::DrawSpline(Renderer::Backend::IDeviceCommandContext& device
if (spline.GetAllNodes().size() == 2)
smoothness = 2;
const float start = spline.MaxDistance.ToFloat() / smoothness;
const float start = spline.GetMaxDistance().ToFloat() / smoothness;
std::vector<CVector3D> line;
for (int i = 0; i <= smoothness; ++i)
{
const float time = start * i / spline.MaxDistance.ToFloat();
const float time = start * i / spline.GetMaxDistance().ToFloat();
line.emplace_back(spline.GetPosition(time));
}
@ -108,7 +108,7 @@ void CCinemaManager::DrawSpline(Renderer::Backend::IDeviceCommandContext& device
{
for (int i = 0; i <= smoothness; ++i)
{
const float time = start * i / spline.MaxDistance.ToFloat();
const float time = start * i / spline.GetMaxDistance().ToFloat();
const CVector3D tmp = spline.GetPosition(time);
const float groundY = g_Game->GetWorld()->GetTerrain().GetExactGroundLevel(tmp.X, tmp.Z);
g_Renderer.GetDebugRenderer().DrawLine(deviceCommandContext, tmp, CVector3D(tmp.X, groundY, tmp.Z), splineColor, 0.1f, false);

View file

@ -53,25 +53,6 @@ public:
void SetElevation(float f);
void SetRotation(float f);
/**
* Calculate brightness of a point of a unit with the given normal vector,
* for rendering with CPU lighting.
* The resulting color contains both ambient and diffuse light.
* To cope with sun overbrightness, the color is scaled by 0.5.
*
* @param normal normal vector (must have length 1)
*/
RGBColor EvaluateUnitScaled(const CVector3D& normal) const
{
float dot = -normal.Dot(m_SunDir);
RGBColor color = m_AmbientColor;
if (dot > 0)
color += m_SunColor * dot;
return color * 0.5f;
}
// Comparison operators
bool operator==(const CLightEnv& o) const
{

View file

@ -62,8 +62,7 @@ void CMaterial::AddRenderQuery(const char* key)
m_RenderQueries.Add(key);
}
void CMaterial::AddRequiredSampler(const CStr& samplerName)
void CMaterial::AddRequiredSampler(RequiredSampler sampler)
{
CStrIntern string(samplerName);
m_RequiredSamplers.push_back(string);
m_RequiredSamplers.emplace_back(std::move(sampler));
}

View file

@ -53,6 +53,12 @@ public:
CTexturePtr Sampler;
};
struct RequiredSampler
{
CStrIntern name;
bool sRGB;
};
typedef std::vector<TextureSampler> SamplersVector;
CMaterial();
@ -82,8 +88,8 @@ public:
void AddRenderQuery(const char* key);
const CShaderRenderQueries& GetRenderQueries() const { return m_RenderQueries; }
void AddRequiredSampler(const CStr& samplerName);
const std::vector<CStrIntern>& GetRequiredSampler() const { return m_RequiredSamplers; }
void AddRequiredSampler(RequiredSampler sampler);
const std::vector<RequiredSampler>& GetRequiredSamplers() const { return m_RequiredSamplers; }
private:
@ -92,7 +98,7 @@ private:
CTexturePtr m_DiffuseTexture;
SamplersVector m_Samplers;
std::vector<CStrIntern> m_RequiredSamplers;
std::vector<RequiredSampler> m_RequiredSamplers;
std::array<CStrIntern, static_cast<size_t>(Pass::COUNT)> m_ShaderEffects;
CShaderDefines m_ShaderDefines;

View file

@ -103,6 +103,7 @@ CMaterial CMaterialManager::LoadMaterial(const VfsPath& pathname)
AT(material);
AT(name);
AT(pass);
AT(srgb);
AT(value);
#undef AT
#undef EL
@ -161,7 +162,8 @@ CMaterial CMaterialManager::LoadMaterial(const VfsPath& pathname)
}
else if (token == el_required_texture)
{
material.AddRequiredSampler(attrs.GetNamedItem(at_name));
const bool sRGB{attrs.GetNamedItem(at_srgb) == "true"};
material.AddRequiredSampler({CStrIntern{attrs.GetNamedItem(at_name)}, sRGB});
if (!attrs.GetNamedItem(at_define).empty())
material.AddShaderDefine(CStrIntern(attrs.GetNamedItem(at_define)), str_1);
}

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -69,7 +69,7 @@ CObjectBase::CObjectBase(CObjectManager& objectManager, CActorDef& actorDef, u8
m_Properties.m_FloatOnWater = false;
// Remove leading art/actors/ & include quality level.
m_Identifier = m_ActorDef.m_Pathname.string8().substr(11) + CStr::FromInt(m_QualityLevel);
m_Identifier = fmt::format("{}{}", m_ActorDef.m_Pathname.string8().substr(11), m_QualityLevel);
}
std::unique_ptr<CObjectBase> CObjectBase::CopyWithQuality(u8 newQualityLevel) const

View file

@ -51,6 +51,22 @@
#include <sstream>
#include <utility>
namespace
{
bool ShouldInterpretTextureAsSRGB(const CObjectBase::Samp& sampler, const CMaterial& material)
{
const auto requiredSamplers{material.GetRequiredSamplers()};
auto it{std::find_if(requiredSamplers.begin(), requiredSamplers.end(),
[&](const CMaterial::RequiredSampler& requiredSampler)
{
return requiredSampler.name == sampler.m_SamplerName;
})};
return it != requiredSamplers.end() && it->sRGB;
}
}
CObjectEntry::CObjectEntry(const std::shared_ptr<CObjectBase>& base, const CSimulation2& simulation) :
m_Base(base), m_Color(1.0f, 1.0f, 1.0f, 1.0f), m_Simulation(simulation)
{
@ -155,6 +171,7 @@ bool CObjectEntry::BuildVariation(const std::vector<const std::set<CStr>*>& comp
{
CTextureProperties textureProps(samp.m_SamplerFile);
textureProps.SetAddressMode(Renderer::Backend::Sampler::AddressMode::CLAMP_TO_EDGE);
textureProps.SetSRGB(ShouldInterpretTextureAsSRGB(samp, material));
CTexturePtr texture = g_Renderer.GetTextureManager().CreateTexture(textureProps);
// if we've loaded this model we're probably going to render it soon, so prefetch its texture.
// All textures are prefetched even in the fixed pipeline, including the normal maps etc.
@ -167,11 +184,14 @@ bool CObjectEntry::BuildVariation(const std::vector<const std::set<CStr>*>& comp
CModel* model = newModel.get();
m_Model = std::move(newModel);
for (const CStrIntern& requSampName : model->GetMaterial().GetRequiredSampler())
for (const auto& requiredSampler : model->GetMaterial().GetRequiredSamplers())
{
if (std::find_if(m_Samplers.begin(), m_Samplers.end(),
[&](const CObjectBase::Samp& sampler) { return sampler.m_SamplerName == requSampName; }) == m_Samplers.end())
LOGERROR("Actor %s: required texture sampler %s not found (material %s)", m_Base->GetIdentifier(), requSampName.string().c_str(), m_Base->m_Material.string8().c_str());
[&](const CObjectBase::Samp& sampler) { return sampler.m_SamplerName == requiredSampler.name; }) == m_Samplers.end())
{
LOGERROR("Actor %s: required texture sampler %s not found (material %s)",
m_Base->GetIdentifier(), requiredSampler.name.string().c_str(), m_Base->m_Material.string8().c_str());
}
}
// calculate initial object space bounds, based on vertex positions

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -156,7 +156,8 @@ bool ResolveIncludesImpl(
it = includeCache.emplace(path, std::move(includeContent)).first;
}
// We need to insert #line directives to have correct line numbers in errors.
chunks.emplace_back(lineDirective + "1\n" + it->second + "\n" + lineDirective + CStr::FromUInt(line + 1) + "\n");
chunks.emplace_back(fmt::format("{}1\n{}\n{}{}\n", lineDirective, it->second, lineDirective,
line + 1));
processedParts.emplace_back(currentPart.substr(0, lineStart));
if (!ResolveIncludesImpl(chunks.back(), includeCache, includeCallback, chunks, processedParts))
return false;

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -60,7 +60,7 @@ namespace
{
Renderer::Backend::Format ChooseFormatAndTransformTextureDataIfNeeded(
Renderer::Backend::IDevice* device, Tex& textureData, const bool hasS3TC)
Renderer::Backend::IDevice* device, Tex& textureData, const bool hasS3TC, const bool sRGB)
{
const bool alpha = (textureData.m_Flags & TEX_ALPHA) != 0;
const bool grey = (textureData.m_Flags & TEX_GREY) != 0;
@ -81,13 +81,13 @@ Renderer::Backend::Format ChooseFormatAndTransformTextureDataIfNeeded(
switch (dxt)
{
case DXT1A:
return Renderer::Backend::Format::BC1_RGBA_UNORM;
return sRGB ? Renderer::Backend::Format::BC1_RGBA_SRGB : Renderer::Backend::Format::BC1_RGBA_UNORM;
case 1:
return Renderer::Backend::Format::BC1_RGB_UNORM;
return sRGB ? Renderer::Backend::Format::BC1_RGB_SRGB : Renderer::Backend::Format::BC1_RGB_UNORM;
case 3:
return Renderer::Backend::Format::BC2_UNORM;
return sRGB ? Renderer::Backend::Format::BC2_SRGB : Renderer::Backend::Format::BC2_UNORM;
case 5:
return Renderer::Backend::Format::BC3_UNORM;
return sRGB ? Renderer::Backend::Format::BC3_SRGB : Renderer::Backend::Format::BC3_UNORM;
default:
LOGERROR("Unknown DXT compression.");
return Renderer::Backend::Format::UNDEFINED;
@ -101,9 +101,12 @@ Renderer::Backend::Format ChooseFormatAndTransformTextureDataIfNeeded(
{
case 8:
ENSURE(grey);
ENSURE(!sRGB);
return Renderer::Backend::Format::L8_UNORM;
case 24:
ENSURE(grey);
ENSURE(!alpha);
ENSURE(!sRGB);
if (device->IsTextureFormatSupported(Renderer::Backend::Format::R8G8B8_UNORM))
return Renderer::Backend::Format::R8G8B8_UNORM;
else
@ -114,7 +117,7 @@ Renderer::Backend::Format ChooseFormatAndTransformTextureDataIfNeeded(
}
case 32:
ENSURE(alpha);
return Renderer::Backend::Format::R8G8B8A8_UNORM;
return sRGB ? Renderer::Backend::Format::R8G8B8A8_SRGB : Renderer::Backend::Format::R8G8B8A8_UNORM;
default:
LOGERROR("Unsupported BPP: %zu", textureData.m_Bpp);
}
@ -336,6 +339,7 @@ struct TPhash
hash_combine(seed, textureProperties.m_AnisotropicFilterEnabled);
hash_combine(seed, textureProperties.m_FormatOverride);
hash_combine(seed, textureProperties.m_IgnoreQuality);
hash_combine(seed, textureProperties.m_SRGB);
return seed;
}
@ -358,7 +362,8 @@ struct TPequal_to
lhs.m_AddressModeV == rhs.m_AddressModeV &&
lhs.m_AnisotropicFilterEnabled == rhs.m_AnisotropicFilterEnabled &&
lhs.m_FormatOverride == rhs.m_FormatOverride &&
lhs.m_IgnoreQuality == rhs.m_IgnoreQuality;
lhs.m_IgnoreQuality == rhs.m_IgnoreQuality &&
lhs.m_SRGB == rhs.m_SRGB;
}
bool operator()(const CTexturePtr& lhs, const CTexturePtr& rhs) const
@ -526,7 +531,8 @@ public:
}
else
{
format = ChooseFormatAndTransformTextureDataIfNeeded(m_Device, textureData, m_HasS3TC);
format = ChooseFormatAndTransformTextureDataIfNeeded(
m_Device, textureData, m_HasS3TC, texture->m_Properties.m_SRGB);
}
if (format == Renderer::Backend::Format::UNDEFINED)

View file

@ -1,4 +1,4 @@
/* Copyright (C) 2025 Wildfire Games.
/* Copyright (C) 2026 Wildfire Games.
* This file is part of 0 A.D.
*
* 0 A.D. is free software: you can redistribute it and/or modify
@ -245,6 +245,8 @@ public:
void SetIgnoreQuality(bool ignore) { m_IgnoreQuality = ignore; }
void SetSRGB(const bool sRGB) { m_SRGB = sRGB; }
private:
// Must update TPhash, TPequal_to when changing these fields
VfsPath m_Path;
@ -257,6 +259,7 @@ private:
Renderer::Backend::Format m_FormatOverride =
Renderer::Backend::Format::UNDEFINED;
bool m_IgnoreQuality = false;
bool m_SRGB{false};
};
/**

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