Members
DEFAULT_CAPTURE
DefaultRelaxedMaxRange
How close to our goal do we consider it's OK to stop if the goal appears unreachable.
Currently 3 terrain tiles as that's relatively close but helps pathfinding.
MAX_TOTAL_TARGETS
Schema
UnitFsm
UnitFsmSpec
cheeringTime
expectedRoute
expectedRoute
expectedRoute
formationAnimationVariant
formationController
formationController
formationController
guardRange
guardRange
heldPosition
heldPosition
isGarrisoned
isGuardOf
isGuardOf
isGuardOf
isGuardOf
isIdle
isIdle
isImmobile
losAttackRangeQuery
losAttackRangeQuery
losAttackRangeQuery
losHealRangeQuery
losHealRangeQuery
losRangeQuery
losRangeQuery
notifyToCheerInRange
obstructionMitigationAttempted
obstructionMitigationTimer
order
order
order
order
order
order
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue
orderQueue[0]
orderQueue[1]
previousStance
previousStance
previousStance
roamAngle
roamAngle
stance
startAngle
timer
timer
timer
timer
workOrders
workOrders
workOrders
workOrders
workOrders
workOrders
workOrders
Methods
AbleToMove(cmpUnitMotion)
Parameters:
| Name | Type | Description |
|---|---|---|
cmpUnitMotion |
optionally pass unitMotion to avoid querying it here |
Returns:
true if the entity can move, i.e. has UnitMotion and isn't immobile.
AddGuard()
AddOrder()
AddOrders()
Attack()
Adds attack order to the queue, forced by the player.
AttackEntitiesByPreference()
AttackEntityInZone()
Try to find one of the given entities which can be attacked
and which is close to the hold position, and start attacking it.
Returns true if it found something to attack.
AttackGroup(targets, startingIndex, unitCount, allowCapture, 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.
Parameters:
| Name | Type | Description |
|---|---|---|
targets |
Array | Array of target entity IDs to attack (pre-sorted by distance) |
startingIndex |
number | This unit's position in the attacking group (0-based) |
unitCount |
number | Total number of units in the attacking group |
allowCapture |
boolean | Whether capturing is allowed |
queued |
boolean | If true, add to end of queue instead of replacing current order |
pushFront |
boolean | If true, add to front of queue (interrupt current order) |
AttackVisibleEntity()
Try to find one of the given entities which can be attacked,
and start attacking it.
Returns true if it found something to attack.
AttemptObstructionMitigation()
Attempts to mitigate formation obstruction by teleporting the formation controller
to the member closest to the destination.
This is used when the formation controller (with large clearance) is stuck on obstacles,
but individual units can still navigate. The controller jumps to a member's position
to bypass the obstruction.
The mitigation have a cooldown to prevent any weird behaviour.
BackToWork()
CallMemberFunction(resetFinishedEntities)
Call UnitAI.funcname(args) on all formation members.
Parameters:
| Name | Type | Description |
|---|---|---|
resetFinishedEntities |
If true, call ResetFinishedEntities first. If the controller wants to wait on its members to finish their order, this needs to be reset before sending new orders (in case they instafail) so it makes sense to do it here. Only set this to false if you're sure it's safe. |
CallPlayerOwnedEntitiesFunctionInRange()
Call obj.funcname(args) on UnitAI components owned by player in given range.
CanAttack()
CanGarrison()
CanGather()
CanGuard()
CanHeal()
CanOccupyTurret()
CanPack()
CanPatrol()
CanRepair()
CanReturnResource(checkCarriedResource, cmpResourceGatherer)
Check if the entity can return carried resources at @param target
Parameters:
| Name | Type | Description |
|---|---|---|
checkCarriedResource |
check we are carrying resources | |
cmpResourceGatherer |
if present, use this directly instead of re-querying. |
CanTrade()
CanUnpack()
CanUseFormation()
CancelPack()
CancelSetupTradeRoute()
CancelUnpack()
CheckFormationTargetAttackRange(target) → {boolean}
Check if the target is inside the attack range of the formation.
Parameters:
| Name | Type | Description |
|---|---|---|
target |
number | The target entity ID to attack. |
Returns:
- Whether the entity is within attacking distance.
- Type
- boolean
CheckPointRangeExplicit()
CheckPositionVisible()
Returns true if the given position is currentl visible (not in FoW/SoD).
CheckRange(iid, type)
Generic dispatcher for other Check...Range functions.
Parameters:
| Name | Type | Description |
|---|---|---|
iid |
Interface ID (optional) implementing GetRange | |
type |
Range type for the interface call |
CheckTargetAttackRange()
Check if the target is inside the attack range
For melee attacks, this goes straigt to the regular range calculation
For ranged attacks, the parabolic formula is used to accout for bigger ranges
when the target is lower, and smaller ranges when the target is higher
CheckTargetDistanceFromHeldPosition()
CheckTargetIsInVisionRange()
CheckTargetRange()
CheckTargetRangeExplicit()
CheckTargetVisible()
Returns true if the target entity is visible through the FoW/SoD.
Cheer()
CleanupAllGroupAttackStates()
CleanupGroupAttackState()
CollectTreasure()
Adds order to collect a treasure to queue, forced by the player.
CollectTreasureNearPosition()
Adds order to collect a treasure to queue, forced by the player.
ComputeWalkingDistance()
Returns the estimated distance that this unit will travel before either
finishing all of its orders, or reaching a non-walk target (attack, gather, etc).
Intended for Formation to switch to column layout on long walks.
ConstructionFinished()
Called directly by cmpFoundation and cmpRepairable to
inform builders that repairing has finished.
This not done by listening to a global message due to performance.
CountTotalTargetsInQueue() → {number}
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:
- Total number of target entity references in the order queue
- Type
- number
DeferMessage()
DropAtNearestDropSite()
The unit will drop all resources at the closest dropsite. If this unit is no gatherer or
no dropsite is available, it will do nothing.
EnsureCorrectPackStateForAttack(requirePacked) → {boolean}
For a unit that is packing and trying to attack something,
either cancel packing or continue with packing, as appropriate.
Precondition: if the unit is packing/unpacking, then orderQueue
should have the Attack order at index 0,
and the Pack/Unpack order at index 1.
This precondition holds because if we are packing while processing "Order.Attack",
then we must have come from ReplaceOrder, which guarantees it.
Parameters:
| Name | Type | Description |
|---|---|---|
requirePacked |
boolean | true if the unit needs to be packed to continue attacking, false if it needs to be unpacked. |
Returns:
true if the unit can attack now, false if it must continue packing (or unpacking) first.
- Type
- boolean
EnsureValidTargetIndex()
FaceTowardsTarget(target)
Let an entity face its target.
Parameters:
| Name | Type | Description |
|---|---|---|
target |
number | The entity-ID of the target. |
FindAndSetNextTarget()
FindNearbyFoundation()
Returns the entity ID of the nearest building that needs to be constructed.
"Nearest" is nearest from @param position.
FindNearbyResource()
Returns the entity ID of the nearest resource supply where the given
filter returns true, or undefined if none can be found.
"Nearest" is nearest from @param position.
TODO: extend this to exclude resources that already have lots of gatherers.
FindNearbyTreasure()
Returns the entity ID of the nearest treasure.
"Nearest" is nearest from @param position.
FindNearestDropsite()
Returns the entity ID of the nearest resource dropsite that accepts
the given type, or undefined if none can be found.
FindNewHealTargets()
Resets losHealRangeQuery, and if there are some targets in range that we can heal
then we start healing and this returns true; otherwise, returns false.
FindNewTargets()
Resets losAttackRangeQuery, and if there are some targets in range that we can
attack then we start attacking and this returns true; otherwise, returns false.
FindSightedEnemies() → {boolean}
Resets the losRangeQuery.
Returns:
- Whether there are targets in range that we ought to react upon.
- Type
- boolean
FindWalkAndFightTargets()
FinishOrder()
Call when the current order has been completed (or failed).
Removes the current order from the queue, and processes the
next one (if any). Returns false and defaults to IDLE
if there are no remaining orders or if the unit is not
inWorld and not garrisoned (thus usually waiting to be destroyed).
Must be called from inside the FSM.
Flee()
Adds flee order to the queue, not forced, so it can be
interrupted by attacks.
FsmStateNameChanged()
Garrison()
Adds garrison order to the queue, forced by the player.
Gather()
Adds gather order to the queue, forced by the player
until the target is reached
GatherNearPosition()
Adds gather-near-position order to the queue, not forced, so it can be
interrupted by attacks.
GetBestAttackAgainst()
GetCurrentState()
GetFacePointAfterMove()
GetFormationController()
GetFormationTemplate()
GetFormationsList()
GetHeldPosition()
GetOrderData()
GetOrders()
GetQueryRange(iid) → {Object}
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.
Parameters:
| Name | Type | Description |
|---|---|---|
iid |
number | IID_Vision, IID_Heal, or IID_Attack. |
Returns:
-
'parabolic' asks the caller for a parabolic query, where 'max' is the
elevation-aware parabola and 'base' a flat circle around it. A flat query
uses 'max' alone.
- Type
- Object
GetRange(iid, target, type) → {Object|undefined}
General getter for ranges.
Parameters:
| Name | Type | Description |
|---|---|---|
iid |
number | |
target |
number | [Optional] |
type |
string | [Optional] |
Returns:
- The range in the form
{ "min": number, "max": number }
Returns undefined when the entity does not have the requested component.
- Type
- Object | undefined
GetRunMultiplier()
GetSelectableStances()
GetStance()
GetStanceName()
GetTargetPositions()
GetWalkSpeed()
GetWorkOrders()
Guard()
Adds guard/escort order to the queue, forced by the player.
HandleTargetAsFormation()
Checks if the current target is a formation controller.
If it is a formation controller, we identify the closest individual
member within it and set this.order.data.target to it instead.
The original formation controller ID is stored in this.order.data.formationTarget
instead.
HasPickupOrder()
HasWorkOrders()
Heal()
Adds heal order to the queue, forced by the player.
Init()
IsAnimal()
For now, entities with a RoamDistance are animals.
IsAttackingAsFormation()
IsDangerousAnimal()
ToDo: Make this not needed by fixing gaia
range queries in BuildingAI and UnitAI regarding
animals and other gaia entities.
IsFleeing()
IsFormationController()
IsFormationMember()
IsGuardOf()
IsHealer()
IsIdle()
IsPacking()
IsTurret(cmpTurretable) → {boolean}
Parameters:
| Name | Type | Description |
|---|---|---|
cmpTurretable |
cmpTurretable | Optionally the component to save a query here. |
Returns:
- Whether we are occupying a turret point.
- Type
- boolean
IsWalking()
IsWalkingAndFighting()
Return true if the current order is WalkAndFight or Patrol.
LeaveFormation()
Order a unit to leave the formation it is in.
Used to handle queued no-formation orders for units in formation.
LeaveFoundation()
Adds leave foundation order to queue, treated as forced.
MarketRemoved()
MoveFormationControllerOutOfWorld()
MoveFormationToTargetAttackRange(target) → {boolean}
Move unit so we hope the target is in the attack range of the formation.
Parameters:
| Name | Type | Description |
|---|---|---|
target |
number | The target entity ID to attack. |
Returns:
- Whether the order to move has succeeded.
- Type
- boolean
MoveIntoFormation()
MoveRandomly()
MoveTo(iid, type)
Generic dispatcher for other MoveTo functions.
Parameters:
| Name | Type | Description |
|---|---|---|
iid |
Interface ID (optional) implementing GetRange | |
type |
Range type for the interface call |
Returns:
whether the move succeeded or failed.
MoveToMarket()
MoveToPoint()
MoveToPointRange()
MoveToTarget()
MoveToTargetAttackRange()
Move unit so we hope the target is in the attack range
for melee attacks, this goes straight to the default range checks
for ranged attacks, the parabolic range is used
MoveToTargetRange()
MoveToTargetRangeExplicit()
MustKillGatherTarget()
Returns true if the target exists and needs to be killed before
beginning to gather resources from it.
OccupyTurret()
Adds garrison order to the queue, forced by the player.
OnAttacked()
OnCreate()
OnDestroy()
OnDiplomacyChanged()
OnGlobalEntityRenamed()
OnGuardedAttacked()
OnMotionUpdate()
OnOwnershipChanged()
OnPackFinished()
OnPickupCanceled()
OnPickupRequested()
OnRangeUpdate()
OnVisionRangeChanged()
Pack()
Patrol()
PerformGather()
Internal function to abstract the force parameter.
PlaySound()
Play a sound appropriate to the current entity.
ProcessMessage(type, msg)
A general function to process messages sent from components.
Parameters:
| Name | Type | Description |
|---|---|---|
type |
string | The type of message to process. |
msg |
Object | Optionally extra data to use. |
PushOrder()
Add an order onto the back of the queue,
and execute it if we didn't already have an order.
PushOrderAfterForced()
Insert an order after the last forced order onto the queue
and after the other orders of the same type
PushOrderFront()
Add an order onto the front of the queue,
and execute it immediately.
RelaxedMaxRangeCheck()
Returns:
true if the unit is in the relaxed-range from the target.
RememberTargetPosition()
RemoveGuard()
Repair()
Adds repair/build order to the queue, forced by the player
until the target is reached
ReplaceOrder()
RequestFormationUpdate()
Requests the formation component to update member positions.
Called by formation controller when formation needs reorganization.
ResetAnimation()
ResetObstructionMitigationFlag()
ResetTurretStance()
RespondToHealableEntities()
Try to respond to healable entities.
Returns true if it responded.
RespondToSightedEntities(ents) → {boolean}
Parameters:
| Name | Type | Description |
|---|---|---|
ents |
number | An array of the IDs of the spotted entities. |
Returns:
- Whether we responded.
- Type
- boolean
RespondToTargetedEntities()
Try to respond appropriately given our current stance,
given a list of entities that match our stance's target criteria.
Returns true if it responded.
ReturnResource()
Adds return resource order to the queue, forced by the player.
Run()
SelectAnimation()
SetAnimationSync()
SetAnimationVariant()
SetDefaultAnimationVariant()
SetFacePointAfterMove()
SetFormationController()
SetGarrisoned()
SetGuardOf()
SetHeldPosition()
SetHeldPositionOnEntity()
SetImmobile()
SetMobile()
SetNextState()
SetNextTarget()
SetObstructionMitigationFlag()
SetSpeedMultiplier(speed)
Parameters:
| Name | Type | Description |
|---|---|---|
speed |
number | The multiplier to set the speed to. |
SetStance()
SetTargetMarket()
SetTurretStance()
SetWorkOrders()
SetupAttackRangeQuery(enable)
Set up a range query for all enemy and gaia units within range
which can be attacked.
Parameters:
| Name | Type | Description |
|---|---|---|
enable |
boolean | Optional parameter whether to enable the query. |
SetupHealRangeQuery(enable)
Set up a range query for all own or ally units within LOS range
which can be healed.
Parameters:
| Name | Type | Description |
|---|---|---|
enable |
boolean | Optional parameter whether to enable the query. |
SetupLOSRangeQuery(enable)
Set up a range query for all enemy units within LOS range.
Parameters:
| Name | Type | Description |
|---|---|---|
enable |
boolean | Optional parameter whether to enable the query. |
SetupRangeQueries()
Wrapper function that sets up the LOS, healer and attack range queries.
This should be called whenever our ownership changes.
SetupTradeRoute()
Adds trade order to the queue. Either walk to the first market, or
start a new route. Not forced, so it can be interrupted by attacks.
The possible route may be given directly as a SetupTradeRoute argument
if coming from a RallyPoint, or through this.expectedRoute if a user command.
ShouldAbandonChase()
Returns true if we should stop following the target entity.
ShouldChaseTargetedEntity()
ShouldGuard() → {boolean}
Returns:
- Whether it makes sense to guard the given entity.
- Type
- boolean
ShouldRespondToEndOfAlert()
StartTimer()
Set up the UnitAI timer to run after 'offset' msecs, and then
every 'repeat' msecs until StopTimer is called. A "Timer" message
will be sent each time the timer runs.
Stop()
Adds stop order to queue, forced by the player.
StopMoving()
StopTimer()
Stop the current UnitAI timer.
SwitchMarketOrder()
SwitchToStance()
TargetIsAlive()
Returns true if the target exists and has non-zero hitpoints.
TargetPosOrEntPos()
Returns the position of target or, if there is none,
the entity's position, or undefined.
TimerHandler()
TryMatchTargetSpeed(target, mayRun)
Try to match the targets current movement speed.
Parameters:
| Name | Type | Description |
|---|---|---|
target |
number | The entity ID of the target to match. |
mayRun |
boolean | Whether the entity is allowed to run to match the speed. |
Ungarrison()
Adds ungarrison order to the queue.
Unpack()
UnsetFormationController()
UnsetGarrisoned()
UpdateRangeQueries()
UpdateWorkOrders()
Walk()
Adds walk order to queue, forced by the player.
WalkAndFight()
Adds walk-and-fight order to queue, this only occurs in response
to a player order, and so is forced.
If targetClasses is given, only entities matching the targetClasses can be attacked.
WalkToHeldPosition()
WalkToPointRange()
Adds walk to point range order to queue, forced by the player.
WalkToTarget()
Adds walk-to-target order to queue, this only occurs in response
to a player order, and so is forced.
WalkToTargetRange()
Adds walk-to-target-range order to queue, this only occurs in response
to a player order, and so is forced.