This commit is contained in:
2025-09-12 15:20:28 +08:00
commit 3257a14c32
449 changed files with 388780 additions and 0 deletions

View File

@@ -0,0 +1,513 @@
# ****************************************************************************
# CUI
#
# The Advanced Framework for Simulation, Integration, and Modeling (AFSIM)
#
# The use, dissemination or disclosure of data in this file is subject to
# limitation or restriction. See accompanying README and LICENSE for details.
# ****************************************************************************
include_once ../common/weapon_defs.txt
behavior buddy_engage_weapon_task_target
script_debug_writes off
script_variables
//**********************************************************************//
//** platform / agent specific shooting parameters **//
//**********************************************************************//
bool mCoopEngageOne = false;
#bool mCoopEngageOneFlightOnly = false;
double mDegradedFiringAngle = 55.0; //negative if not valid
double mDegradedPercentRange = 0.50; //range constraint if past degraded firing angle
//specify orientation limits for shooting
double mMaxFiringRollAngle = 10.0; //dont shoot if rolled more/less than this
double mMaxFiringPitchAngle = 15.0; //dont shoot if pitched more than this
double mMinFiringPitchAngle = -10.0; //dont shoot if pitched less than this
//**********************************************************************//
//** threat specific shooting parameters **//
//**********************************************************************//
//require different track qualities to fire on different kinds of threats
double DefaultRequiredTrackQuality = 0.49;
Map<string, double> ThreatTypeRequiredTrackQuality = Map<string, double>();
ThreatTypeRequiredTrackQuality["bomber"] = 0.49;
ThreatTypeRequiredTrackQuality["fighter"] = 0.49;
//fire off different salvos at different types of threats
int DefaultAirSalvo = 1;
int DefaultGndSalvo = 1;
Map<string, int> ThreatTypeSalvo = Map<string, int>();
ThreatTypeSalvo["sam"] = 2;
ThreatTypeSalvo["ship"] = 2;
ThreatTypeSalvo["bomber"] = 2;
ThreatTypeSalvo["fighter"] = 1;
ThreatTypeSalvo["FIRE_CONTROL"] = 1;
ThreatTypeSalvo["primary_target"] = 2;
ThreatTypeSalvo["secondary_target"] = 2;
string mBuddyName = "platform_name";
double mMaxBuddyRelativeDistance = 1.10; //only use buddy if he is within 110% of leader range to target
//**********************************************************************//
//** weapon + threat specific shooting parameters **//
//**********************************************************************//
//specify an Rmax based on which weapon used and which threat engaged
double DefaultPercentRangeMax = 0.80; // don't launch unless within this percent of Rmax
double DefaultPercentRangeMin = 1.20; // don't launch unless beyond this percent of Rmin
Map<string, Map<string, double>> WeaponThreatRmaxMap = Map<string, Map<string, double>>();
WeaponThreatRmaxMap["base_weapon"] = Map<string, double>();
WeaponThreatRmaxMap["base_weapon"].Set("fighter", 0.80);
end_script_variables
script int GetSalvoForThreat(WsfTrack track)
#writeln_d("checking salvo size for category: ", category);
#WsfPlatform plat = WsfSimulation.FindPlatform( track.TargetIndex() );
WsfPlatform plat = WsfSimulation.FindPlatform( track.TargetName() );
if (plat.IsValid())
{
foreach( string aCategory : int salvo in ThreatTypeSalvo )
{
if( plat.CategoryMemberOf( aCategory ) )
{
writeln_d("salvo for type ", aCategory, " = ", salvo);
return salvo;
}
}
}
#extern string GetTargetDomain(WsfTrack);
string sTargetDomain = GetTargetDomain(track);
if ( (sTargetDomain == "LAND") || (sTargetDomain == "SURFACE") )
{
return DefaultGndSalvo;
}
return DefaultAirSalvo;
end_script
script double GetRequiredTrackQualityForThreat(WsfTrack threat)
writeln_d("checking required TQ for track: ", threat.TargetName());
WsfPlatform plat = WsfSimulation.FindPlatform( threat.TargetName() );
if (plat.IsValid())
{
foreach( string aCategory : double quality in ThreatTypeRequiredTrackQuality )
{
if( plat.CategoryMemberOf( aCategory ) )
{
writeln_d("TQ for type ", aCategory, " = ", quality);
return quality;
}
}
}
return DefaultRequiredTrackQuality;
end_script
script double GetLaunchPercentRangeMaxOnThreat(string weaponName, WsfTrack threat)
WsfPlatform plat = WsfSimulation.FindPlatform( threat.TargetName() );
if (plat.IsValid())
{
if (WeaponThreatRmaxMap.Exists(weaponName))
{
Map<string, double> categoryRangeMap = WeaponThreatRmaxMap.Get(weaponName);
foreach (string aCategory : double percent in categoryRangeMap)
{
if( plat.CategoryMemberOf( aCategory ) )
{
return percent;
}
}
}
}
return DefaultPercentRangeMax;
end_script
script bool WeaponCapableAvailableAgainstThreat(WsfWeapon weapon, WsfTrack track)
writeln_d(" checking weapon ", weapon.Name(), " valid=", weapon.IsValid());
if (weapon.IsNull() || !weapon.IsValid() || track.IsNull() || !track.IsValid())
{
writeln_d("weapon or track is not valid!");
return false;
}
struct weaponData = GetWeaponData(weapon.Type());
if (weaponData->type != weapon.Type())
{
writeln_d("could not find weapon type ", weapon.Type() ," in weapon database; query returned type ", weaponData->type);
return false; //dont have weapon data
}
if ((track.AirDomain() && !weaponData->domainAir) ||
(track.LandDomain() && !weaponData->domainLand) )
{
writeln_d("weapon not capable against target domain!");
return false;
}
if ((weapon.QuantityRemaining()-weapon.WeaponsPendingFor(WsfTrackId())) <= 0)
{
writeln_d("no unassigned weapons left to fire!");
return false;
}
return true;
end_script
script bool InRangeToFire(WsfPlatform shooter, WsfWeapon weapon, WsfTrack track)
##do not check this again
#if ( ! WeaponCapableAvailableAgainstThreat(weapon, track) )
#{
# return false;
#}
WsfLaunchComputer lcPtr = weapon.LaunchComputer();
if (lcPtr.IsValid() &&
lcPtr.IsA_TypeOf("WSF_AIR_TO_AIR_LAUNCH_COMPUTER"))
{
writeln_d(" using air-to-air launch computer");
// The returned array contains: Rmax, RmaxTOF, Rne, RneTOF, Rmin, RminTOF
// in that order. -1.0 means "not valid".
Array<double> returnedValues = lcPtr.LookupResult(track);
// Now have to consider whether we have enough information to continue with a weapon shot:
double theRmax = returnedValues[0]; //"Rmax";
double theRmaxTOF = returnedValues[1]; //"RmaxTOF";
double theRne = returnedValues[2]; //"Rne";
double theRneTOF = returnedValues[3]; //"RneTOF";
double theRmin = returnedValues[4]; //"Rmin";
double theRminTOF = returnedValues[5]; //"RminTOF";
double range = track.GroundRangeTo(shooter);
// Check for track range less than Rmin * scaleFactor, if not, return.
// But do not check for min range constraint at all unless we are likely to be needing it.
if (range < 5000)
{
if (theRmin == -1.0)
{
writeln_d(" Engagement did not shoot since Rmin was not valid.");
return false;
}
double RminConstraint = theRmin * DefaultPercentRangeMin;
if (range < RminConstraint)
{
writeln_d(" Engagement did not shoot since inside the k * Rmin constraint distance.");
writeln_d(" Range versus Rmin constraint = ", range, ", ", RminConstraint);
return false;
}
}
// Check for track range less than Rne, if so, FORCE a weapon fire.
bool forceWeaponFire = false;
if (range < theRne)
{
writeln_d(" Engagement is forcing a weapon fire due to inside Rne.");
writeln_d(" Range versus Rne constraint = ", range, ", ", theRne);
forceWeaponFire = true;
}
if (forceWeaponFire == false)
{
######################################TRY THIS######################################
WsfPlatform plat = WsfSimulation.FindPlatform( track.TargetName() );
if (plat.IsValid() && plat.CategoryMemberOf("fighter"))
{
#theRmax = theRne;
theRmax = (theRmax + theRne)/2.0; //for highly maneuverable fighter targets
}
####################################END TRY THIS####################################
// Check for track range less than k * Rmax, if not, return.
if (theRmax == -1.0)
{
writeln_d(" Engagement did not shoot since Rmax was not valid.");
return false;
}
//double RmaxConstraint = theRmax * DefaultPercentRangeMax;
double percentRMax = GetLaunchPercentRangeMaxOnThreat(weapon.Name(), track);
double RmaxConstraint = theRmax * percentRMax;
if (range > RmaxConstraint)
{
writeln_d(" Engagement did not shoot since outside the k * Rmax constraint distance.");
writeln_d(" Range versus Rne constraint = ", range, ", ", theRne);
return false;
}
}
writeln_d(" Engagement meets constraints for firing a weapon (continue).");
}
else if (lcPtr.IsValid() &&
lcPtr.IsA_TypeOf("WSF_ATG_LAUNCH_COMPUTER"))
{
writeln_d(" using air-to-ground launch computer");
if (lcPtr.CanIntercept(track))
{
//intercept works, this weapon is a candidate
}
else
{
return false;
}
}
else
{
struct weaponData = GetWeaponData(weapon.Type());
writeln_d(" using input WeaponData struct values");
//check our own ranges & angles --> hacky!!!
#extern double EffectiveRange(WsfPlatform, WsfTrack);
double effectiveRange = EffectiveRange(shooter, track);
double absRelativeBearing = MATH.Fabs(shooter.RelativeBearingTo( track ));
double rangeScale = GetLaunchPercentRangeMaxOnThreat(weapon.Name(), track);
if (absRelativeBearing > mDegradedFiringAngle)
{
rangeScale = MATH.Min(mDegradedPercentRange, rangeScale);
}
if (weaponData->rangeMin > effectiveRange)
{
writeln_d(" target too close");
return false;
}
if (absRelativeBearing > weaponData->maxFiringAngle)
{
writeln_d(" target firing angle too large");
return false;
}
if (weaponData->rangeMax * rangeScale < effectiveRange)
{
writeln_d(" target too far away");
return false;
}
double range = shooter.SlantRangeTo(track);
//double closingSpeed = PLATFORM.ClosingSpeedOf(track);
double relBearing = track.RelativeBearingTo(shooter);
if (relBearing > 90.0)
{
if (track.Speed() > weaponData->averageSpeed)
{
return false;
}
double speedDiff = weaponData->averageSpeed - track.Speed();
if ((range/speedDiff) > weaponData->maxTimeFlight)
{
return false;
}
}
}
return true;
end_script
#on_init
#end_on_init
precondition
#writeln_d("precondition engage-target");
if (!PROCESSOR.IsA_TypeOf("WSF_QUANTUM_TASKER_PROCESSOR"))
{
return Failure("behavior not attached to a quantum tasker processor!");
}
#extern WsfTrack GetTrackByName(WsfPlatform, string);
# todo - try using a state machine to setup the shot ??
double pitch = PLATFORM.Pitch();
if (MATH.Fabs(PLATFORM.Roll()) > mMaxFiringRollAngle ||
pitch > mMaxFiringPitchAngle ||
pitch < mMinFiringPitchAngle)
{
string msgStr = write_str(" ", PLATFORM.Name(), " orientation too far off to fire! (roll or pitch)");
writeln_d(msgStr);
//PLATFORM.Comment(msgStr);
return Failure(msgStr);
}
WsfQuantumTaskerProcessor proc = (WsfQuantumTaskerProcessor)PROCESSOR;
WsfTaskList tasks = proc.TasksReceivedOfType("weapon");
if (tasks.Count() > 0)
{
return true;
}
return Failure("no weapon task target to shoot at!");
end_precondition
execute
writeln_d(PLATFORM.Name(), " executing engage-target, T=", TIME_NOW);
#extern WsfTrack GetTrackByName(WsfPlatform, string);
#check all possible targets on all channels
########################################################################
### fire on any pursue-target jobs we are assigned to
########################################################################
WsfQuantumTaskerProcessor proc = (WsfQuantumTaskerProcessor)PROCESSOR;
WsfTaskList tasks = proc.TasksReceivedOfType("weapon");
foreach (WsfTask task in tasks)
{
WsfTrack targetTrack = PLATFORM.MasterTrackList().FindTrack(task.LocalTrackId());
if (targetTrack.IsNull() || !targetTrack.IsValid())
{
writeln_d("target track not valid");
continue;
}
bool launched = false;
writeln_d(" Time= ", TIME_NOW, " Attempting a shot against: ", targetTrack.TargetName(), " Index: ", targetTrack.TargetIndex(), " Type: ", targetTrack.TargetType());
if (mCoopEngageOne == false)
{
WsfLocalTrack targetLocalTrack = (WsfLocalTrack)targetTrack;
if (targetLocalTrack.IsValid())
{
if(!targetLocalTrack.ContributorOf(PLATFORM) &&
!targetLocalTrack.IsPredefined())
{
writeln_d(" FAIL: Not able to coop engage! ", PLATFORM.Name(), " targeting ",targetTrack.TargetName(), ". NumContributors: ", targetLocalTrack.NumContributors() );
return;
}
}
}
writeln_d (" targetTrack.TrackQuality == ", targetTrack.TrackQuality());
if (targetTrack.TrackQuality() < GetRequiredTrackQualityForThreat(targetTrack))
{
writeln_d(" FAIL: track quality not good enough to fire on target");
return;
}
if ((PLATFORM.WeaponsPendingFor(task.LocalTrackId()) + PLATFORM.WeaponsActiveFor(task.LocalTrackId())) > 0)
{
writeln_d("already have weapons assigned for target track");
return;
}
WsfPlatform buddyPlatform = WsfSimulation.FindPlatform(mBuddyName);
if (buddyPlatform.IsValid())
{
if ((buddyPlatform.WeaponsPendingFor(task.LocalTrackId()) + buddyPlatform.WeaponsActiveFor(task.LocalTrackId())) > 0)
{
writeln_d("already have buddy weapons assigned for target track");
return;
}
//check relative range too
double leadRange = PLATFORM.GroundRangeTo(targetTrack);
double buddyRange = buddyPlatform.GroundRangeTo(targetTrack);
if ((buddyRange/leadRange) > mMaxBuddyRelativeDistance)
{
//do not use buddy, make the platform variable invalid
WsfPlatform nullPlat;
buddyPlatform = nullPlat;
}
}
bool weaponUsable = false;
WsfWeapon weapon;
WsfPlatform shooter;
if (task.ResourceName() != "")
{
//check buddy weapon first
if (buddyPlatform.IsValid())
{
weapon = buddyPlatform.Weapon(task.ResourceName());
writeln_d("checking if buddy weapon ", weapon.Name(), " can be fired against track.");
#weaponUsable = CanFireWeaponAgainstThreat(buddyPlatform, weapon, targetTrack);
weaponUsable = WeaponCapableAvailableAgainstThreat(weapon, targetTrack);
shooter = buddyPlatform;
}
if (weaponUsable == false)
{
//buddy did not have any usable weapons, check our weapons now
weapon = PLATFORM.Weapon(task.ResourceName());
writeln_d("checking if weapon ", weapon.Name(), " can be fired against track.");
#weaponUsable = CanFireWeaponAgainstThreat(PLATFORM, weapon, targetTrack);
weaponUsable = WeaponCapableAvailableAgainstThreat(weapon, targetTrack);
shooter = PLATFORM;
}
}
else
{
//check buddy weapons first
if (buddyPlatform.IsValid())
{
for (int i=0; i < buddyPlatform.WeaponCount(); i+=1)
{
weapon = buddyPlatform.WeaponEntry(i);
writeln_d("checking if buddy weapon ", weapon.Name(), " is usable.");
#weaponUsable = CanFireWeaponAgainstThreat(buddyPlatform, weapon, targetTrack);
weaponUsable = WeaponCapableAvailableAgainstThreat(weapon, targetTrack);
if (weaponUsable)
{
shooter = buddyPlatform;
break;
}
}
}
if (weaponUsable == false)
{
//buddy did not have any usable weapons, check our weapons now
for (int i=0; i < PLATFORM.WeaponCount(); i+=1)
{
weapon = PLATFORM.WeaponEntry(i);
writeln_d("checking if weapon ", weapon.Name(), " is usable.");
#weaponUsable = CanFireWeaponAgainstThreat(PLATFORM, weapon, targetTrack);
weaponUsable = WeaponCapableAvailableAgainstThreat(weapon, targetTrack);
if (weaponUsable)
{
shooter = PLATFORM;
break;
}
}
}
}
if (weaponUsable == false)
{
writeln_d("!!! FAIL: usable weapon was not found!");
return;
}
if ( ! InRangeToFire(shooter, weapon, targetTrack) )
{
writeln_d("out of range");
return;
}
int salvoCount = GetSalvoForThreat(targetTrack);
writeln_d(" salvo count for ", targetTrack, " is: ", salvoCount);
if (weapon.IsTurnedOn())
{
writeln_d(" Attempting launch at ", targetTrack.TargetName());
if (salvoCount > 1)
{
writeln_d("FIRING SALVO AT ", targetTrack.TargetName());
launched = weapon.FireSalvo(targetTrack, salvoCount);
}
else
{
writeln_d("FIRING AT ", targetTrack.TargetName());
launched = weapon.Fire(targetTrack);
}
}
writeln_d(" launched == ", launched, ", weapon: ", weapon.Name());
if(launched == false)
{
writeln_d(" ", PLATFORM.Name(), " could NOT fire at track: ", targetTrack.TargetName(), " at time: ", TIME_NOW);
}
}
end_execute
end_behavior

View File

@@ -0,0 +1,498 @@
# ****************************************************************************
# CUI
#
# The Advanced Framework for Simulation, Integration, and Modeling (AFSIM)
#
# The use, dissemination or disclosure of data in this file is subject to
# limitation or restriction. See accompanying README and LICENSE for details.
# ****************************************************************************
behavior buddy_evade
script_debug_writes off
script_variables
//**********************************************************************//
//** debugging parameters **//
//**********************************************************************//
bool mDrawNearestThreat = false;
bool mDrawEvasionVector = false;
//**********************************************************************//
//** control / mode of operation parameters **//
//**********************************************************************//
double weightPeersForEvade = 0.25; //percentage to scale peers influence for evasion vector
bool mWobbleLeftRight = true;
bool mWobbleUpDown = true;
double cFAST_UPDATE_INTERVAL = 0.25;
double cSLOW_UPDATE_INTERVAL = 2.0;
//**********************************************************************//
//** flying parameters, for for evasive manuevering **//
//**********************************************************************//
double cNORMAL_SPEED = 200.0; // m/s
double cEVADE_SPEED = 1000.0; // m/s (faster than a speeding bullet...M3.0+)
double mAltitudeMin = 1000.0; //meters
double mAltitudeMax = 20000.0; //meters
double mAltitudeToDiveEvade = 1500.0; //distance to dive (meters) (~5000 ft)
double mBankAngleForEvading = 45.0; //banks left & right, back & forth, at this angle, while evading
double mMaxClimbRate = 500.0; // meters/second
double mVerticalAccel = 1.5 * Earth.ACCEL_OF_GRAVITY(); // meters/second^2
//**********************************************************************//
//** for referencing the buddy, to see if we should evade **//
//**********************************************************************//
string mBuddyName = "platform_name";
//**********************************************************************//
//********* VARIABLES BELOW THIS LINE ARE NOT FOR USER EDITING *********//
//**********************************************************************//
double mLastTime = 0.0;
double mClimbRate = 0.0;
Array<WsfPlatform> mIncoming = Array<WsfPlatform>();
WsfDraw mDraw = WsfDraw();
bool mDiveDownFlag = true;
bool mBankLeftFlag = true;
end_script_variables
script WsfThreatProcessor GetThreatProcessor(WsfPlatform aPlatform)
for (int i=0; i<aPlatform.ProcessorCount(); i+=1)
{
WsfProcessor proc = aPlatform.ProcessorEntry(i);
if (proc.IsValid() && proc.IsA_TypeOf("WSF_THREAT_PROCESSOR"))
{
return (WsfThreatProcessor)proc;
}
}
WsfThreatProcessor empty;
return empty;
end_script
script bool Fly(WsfPlatform flyer, double heading, double altitude, double speed)
WsfGeoPoint pt = flyer.Location();
pt.Extrapolate(heading, 1852*3);
pt.Set(pt.Latitude(), pt.Longitude(), MATH.Max(altitude, mAltitudeMin));
if (mDrawEvasionVector == true)
{
mDraw.SetLayer("behavior_evade");
mDraw.SetDuration(PROCESSOR.UpdateInterval());
mDraw.SetColor(0,1,0);
mDraw.SetLineSize(1);
mDraw.SetLineStyle("dash_dot");
mDraw.BeginLines();
mDraw.Vertex(PLATFORM.Location());
mDraw.Vertex(pt);
mDraw.End();
}
if (flyer.Mover().IsValid())
{
if (flyer.Mover().IsA_TypeOf("WSF_6DOF_MOVER"))
{
##flyer.GoToSpeed(speed);
##flyer.GoToAltitude(MATH.Max(altitude, mAltitudeMin), 200);
##flyer.TurnToHeading(heading, 500);
#flyer.GoToSpeed(speed);
#flyer.GoToLocation(pt);
flyer.GoToSpeed(speed);
double altRate = flyer.Speed() * MATH.Sin(40.0);
flyer.GoToAltitude(pt.Altitude(), altRate);
flyer.TurnToHeading(flyer.TrueBearingTo(pt), 500);
return true;
}
else if (flyer.Mover().IsA_TypeOf("WSF_AIR_MOVER"))
{
double delta = TIME_NOW - mLastTime;
mLastTime = TIME_NOW;
if (delta > cSLOW_UPDATE_INTERVAL)
{
delta = cSLOW_UPDATE_INTERVAL;
}
double deltaV = mVerticalAccel * delta;
if (altitude > PLATFORM.Altitude())
{
if (mClimbRate < 0.0)
{
//increase climb rate to a positive value (must keep pursuing a lower altitude though)
altitude = mAltitudeMin;
mClimbRate = mClimbRate + deltaV;
}
else if (mClimbRate < mMaxClimbRate)
{
//increase climb rate to max value (can pursue target altitude now)
mClimbRate = mClimbRate + deltaV;
}
}
else if (altitude < PLATFORM.Altitude())
{
if (mClimbRate > 0.0)
{
//decrease climb rate to a negative value (must keep pursuing a higher altitude though)
altitude = 9999999;
mClimbRate = mClimbRate - deltaV;
}
else if (mClimbRate > -mMaxClimbRate)
{
//decrease climb rate to max value (can pursue target altitude now)
mClimbRate = mClimbRate - deltaV;
}
}
double climbRateUsed = MATH.Fabs(mClimbRate);
flyer.GoToSpeed(speed);
flyer.GoToAltitude(altitude, climbRateUsed);
flyer.TurnToHeading(heading);
return true;
}
}
writeln_d(flyer.Name(), " aiai error: unknown or invalid mover for flight");
return false;
end_script
precondition
writeln_d(PLATFORM.Name(), " precondition evade, T=", TIME_NOW);
//always evade incoming weapons
int ownshipWeaponsIncoming = 0;
WsfProcessor proc = PLATFORM.Processor("incoming_threats");
if (proc.IsValid() && proc.ScriptExists("ThreatProcessorWeaponsIncoming"))
{
writeln_d("using incoming_threats threat processor!!!");
mIncoming = (Array<WsfPlatform>)(proc.Execute("ThreatProcessorWeaponsIncoming"));
ownshipWeaponsIncoming = mIncoming.Size();
}
else
{
writeln_d("using standard WSF_THREAT_PROCESSOR!!!");
mIncoming.Clear();
ownshipWeaponsIncoming = 0;
WsfThreatProcessor threatProc = GetThreatProcessor(PLATFORM);
if (!threatProc.IsNull() && threatProc.IsValid())
{
Array<WsfTrackId> threatIds = threatProc.Threats();
foreach(WsfTrackId id in threatIds)
{
WsfTrack track = PLATFORM.MasterTrackList().Find(id);
if (track.IsValid())
{
mIncoming.PushBack(track.Target());
}
}
ownshipWeaponsIncoming = mIncoming.Size();
}
if (ownshipWeaponsIncoming <= 0)
{
WsfPlatform buddyPlatform = WsfSimulation.FindPlatform(mBuddyName);
if (buddyPlatform.IsValid())
{
WsfThreatProcessor threatProc = GetThreatProcessor(buddyPlatform);
if (!threatProc.IsNull() && threatProc.IsValid())
{
Array<WsfTrackId> threatIds = threatProc.Threats();
foreach(WsfTrackId id in threatIds)
{
WsfTrack track = buddyPlatform.MasterTrackList().Find(id);
if (track.IsValid())
{
mIncoming.PushBack(track.Target());
}
}
ownshipWeaponsIncoming = mIncoming.Size();
}
}
}
}
if (ownshipWeaponsIncoming > 0)
{
//we now have weapons incoming, check to see if we are currently guiding any missiles with an uplink
//basically: check if we have any active weapons
int WeaponCount = PLATFORM.WeaponsActiveFor(WsfTrackId());
if (WeaponCount > 0)
{
writeln_d(PLATFORM.Name(), " weapons incoming, checking weapons active, count: ", WeaponCount);
double threat = 1000.0;
double asset = 1000.0;
//find most threatening incoming weapon
foreach(WsfPlatform p in mIncoming)
{
double range = PLATFORM.SlantRangeTo(p); # meters
double speed = p.Speed(); # meters/sec
double time = range / speed; # seconds
if (time < threat)
{
threat = time;
}
}
//find most valuable launched weapon (most threatening to enemy)
WsfPlatformList activeWeapons = PLATFORM.ActiveWeaponPlatformsFor(WsfTrackId());
for (int i=0; i< activeWeapons.Count(); i=i+1)
{
WsfPlatform w = activeWeapons.Entry(i);
WsfTrack t = w.CurrentTargetTrack();
//TODO - replace with check for weather or not the weapon has active sensors
# // include weapons we are uplinking to.
# if (((WsfRIPRProcessor)PROCESSOR).IsUplinkingTo(w) &&
# t.IsValid())
# {
double range = w.SlantRangeTo(t); # meters
double speed = w.Speed(); # meters/sec
double time = range / speed; # seconds
if (time < asset)
{
asset = time;
}
# }
}
extern double mEngagementAggressiveness;
//factor in our aggressiveness, and decide whether or not we should evade yet
double requiredAggressiveness = asset / (threat + asset);
writeln_d(PLATFORM.Name(), " threat: ", threat, ", asset: ", asset, ", required aggressiveness: ", requiredAggressiveness);
if (mEngagementAggressiveness < requiredAggressiveness)
{
#PROCESSOR.SetUpdateInterval(cFAST_UPDATE_INTERVAL);
return true;
}
else
{
Failure("my active weapons are closer, hold course");
}
}
else
{
#PROCESSOR.SetUpdateInterval(cFAST_UPDATE_INTERVAL);
return true;
}
}
else
{
writeln_d("no weapons incoming");
Failure("no weapons incoming");
}
#PROCESSOR.SetUpdateInterval(cSLOW_UPDATE_INTERVAL);
return false;
end_precondition
execute
writeln_d(PLATFORM.Name(), " executing evade, T=", TIME_NOW);
//PLATFORM.Comment("evade");
### transition to evade incoming
PLATFORM.GoToSpeed(cEVADE_SPEED);
writeln_d(" GoToSpeed( ", cEVADE_SPEED," )");
extern double cDEFAULT_ALTITUDE;
double safeAltitudeToDiveTo = MATH.Max(mAltitudeMin, (cDEFAULT_ALTITUDE - mAltitudeToDiveEvade));
// Calculate a heading to evade all incoming missiles, weighted by distance, and then turn to it
double evadeHeading = 0;
double evadeAltitude = 0;
double evadeDivisor = 0;
double distMod = 0;
double bearingMod = 0;
int incomingCount = mIncoming.Size();
writeln_d(PLATFORM.Name(), " evade. dive/climb between altitudes: ", cDEFAULT_ALTITUDE, " <-> ", safeAltitudeToDiveTo);
writeln_d("evading ", incomingCount, " threats");
double y = 0;
double x = 0;
double dist = MATH.DOUBLE_MAX();
WsfPlatform nearestThreat;
// calculate an average heading to incoming platforms weighted by distance
for (int i = 0; i < incomingCount; i = i + 1)
{
WsfPlatform temp = (WsfPlatform)(mIncoming[i]);
if (!temp.IsValid() || (temp.Index() == PLATFORM.Index()))
{
continue;
}
double range = PLATFORM.SlantRangeTo(temp);
if (range < dist)
{
dist = range;
nearestThreat = (WsfPlatform)(mIncoming[i]);
}
if (range > 0)
{
distMod = 1 / range;
}
else
{
distMod = 1000000;
}
bearingMod = MATH.NormalizeAngle0_360(PLATFORM.TrueBearingTo(temp));
x = x + MATH.Sin(bearingMod) * distMod;
y = y + MATH.Cos(bearingMod) * distMod;
writeln_d(" Incoming ", temp.Name(), " at distance: ", 1 / distMod, ", bearing: ", bearingMod, ", x: ", MATH.Sin(bearingMod), ", y: ", MATH.Cos(bearingMod), ", (", temp.Latitude(), ", ", temp.Longitude(), ", ", temp.Altitude(), ") @ ", temp.Speed(), "m/s");
evadeDivisor = evadeDivisor + distMod;
evadeHeading = evadeHeading + bearingMod * distMod;
}
# // get the GCI if there is one
WsfPlatform aiflPlat = PLATFORM.Commander();
WsfPlatform gciPlat;
if (aiflPlat.IsValid())
{
gciPlat = aiflPlat.Commander();
}
// if there's a gci, avoid centroids of all his subs
if (gciPlat.IsValid() && gciPlat.Index() != aiflPlat.Index())
{
writeln_d("found gci : ", gciPlat.Name());
foreach (WsfPlatform aifl in gciPlat.Subordinates())
{
if (!aifl.IsValid() || aifl == PLATFORM || aifl == aiflPlat)
{
continue;
}
WsfGeoPoint centroid = aifl.GetSubsCentroid();
if (centroid.X() == 0 && centroid.Y() == 0 && centroid.Z() == 0)
{
continue;
}
distMod = 1 / (PLATFORM.SlantRangeTo(centroid));
bearingMod = MATH.NormalizeAngle0_360(PLATFORM.TrueBearingTo(centroid));
x = x + MATH.Sin(bearingMod) * distMod * weightPeersForEvade;
y = y + MATH.Cos(bearingMod) * distMod * weightPeersForEvade;
writeln_d(" AIFL ", aifl.Name(), " at distance: ", 1 / distMod, ", bearing: ", bearingMod, ", x: ", MATH.Sin(bearingMod), ", y: ", MATH.Cos(bearingMod), ", (", centroid.Latitude(), ", ", centroid.Longitude(), ", ", centroid.Altitude(), ")");
// but we'll avoid peers with less strength than we avoid incoming missiles
// so let's divide the distMod by 2
evadeDivisor = evadeDivisor + distMod;
evadeHeading = evadeHeading + bearingMod * distMod;
}
}
// otherwise, avoid members in your own squadron
else if (aiflPlat.IsValid())
{
writeln_d("also evading flight lead subordinates (peers)");
foreach (WsfPlatform sub in aiflPlat.Subordinates())
{
writeln_d("considering peer ", sub.Name());
if (!sub.IsValid() ||
sub == PLATFORM)
{
continue;
}
distMod = 1 / (PLATFORM.SlantRangeTo(sub));
bearingMod = MATH.NormalizeAngle0_360(PLATFORM.TrueBearingTo(sub));
x = x + MATH.Sin(bearingMod) * distMod * weightPeersForEvade;
y = y + MATH.Cos(bearingMod) * distMod * weightPeersForEvade;
writeln_d(" Peer ", sub.Name(), " at distance: ", 1 / distMod, ", bearing: ", bearingMod, ", x: ", MATH.Sin(bearingMod), ", y: ", MATH.Cos(bearingMod), ", (", sub.Latitude(), ", ", sub.Longitude(), ", ", sub.Altitude(), ") @ ", sub.Speed(), "m/s");
// but we'll avoid peers with less strength than we avoid incoming missiles
// so let's divide the distMod by 2
evadeDivisor = evadeDivisor + distMod;
evadeHeading = evadeHeading + bearingMod * distMod;
}
}
else
{
writeln_d("evade : no commanders found!!!");
}
if (evadeDivisor == 0)
{
return;
}
// correct for quadrant
double theta = MATH.NormalizeAngle0_360(MATH.ATan(x/y));
if (y < 0)
{
theta = MATH.NormalizeAngle0_360(theta - 180);
}
writeln_d(" x: ", x, ", y: ", y, ", theta: ", theta);
evadeHeading = MATH.NormalizeAngle0_360(theta - 180);
if (mWobbleLeftRight == true)
{
//turn to angle to evade
if (mBankLeftFlag == true)
{
evadeHeading = MATH.NormalizeAngle0_360(theta - 180 - mBankAngleForEvading);
double headDiff = MATH.NormalizeAngleMinus180_180( evadeHeading - MATH.NormalizeAngle0_360(PLATFORM.Heading()) );
if (MATH.Fabs(headDiff) < 2.0 &&
nearestThreat.RelativeBearingTo(PLATFORM) > 0.0)
{
mBankLeftFlag = false;
}
}
else // bank right
{
evadeHeading = MATH.NormalizeAngle0_360(theta - 180 + mBankAngleForEvading);
double headDiff = MATH.NormalizeAngleMinus180_180(evadeHeading - MATH.NormalizeAngle0_360(PLATFORM.Heading()));
if (MATH.Fabs(headDiff) < 2.0 &&
nearestThreat.RelativeBearingTo(PLATFORM) < 0.0)
{
mBankLeftFlag = true;
}
}
}
evadeAltitude = MATH.Max(safeAltitudeToDiveTo, evadeAltitude);
if (mWobbleUpDown == true)
{
//compute the dive or climb
if (mDiveDownFlag == true)
{
writeln_d(PLATFORM.Name(), " diving to ", safeAltitudeToDiveTo);
evadeAltitude = safeAltitudeToDiveTo;
if (PLATFORM.Altitude() <= (cDEFAULT_ALTITUDE - 0.95*(cDEFAULT_ALTITUDE-safeAltitudeToDiveTo)))
{
mDiveDownFlag = false;
}
}
else
{
writeln_d(PLATFORM.Name(), " climbing to ", cDEFAULT_ALTITUDE);
evadeAltitude = cDEFAULT_ALTITUDE;
if (PLATFORM.Altitude() >= (safeAltitudeToDiveTo + 0.95*(cDEFAULT_ALTITUDE-safeAltitudeToDiveTo)))
{
mDiveDownFlag = true;
}
}
}
writeln_d(" Evading incoming at heading ", evadeHeading);
writeln_d(" Evading incoming, dive/climb to ", evadeAltitude);
Fly(PLATFORM, evadeHeading, evadeAltitude, cEVADE_SPEED);
if (mDrawNearestThreat)
{
mDraw.SetLayer("behavior_evade");
mDraw.SetDuration(PROCESSOR.UpdateInterval());
mDraw.SetColor(1,0,0);
mDraw.SetLineSize(5);
mDraw.SetLineStyle("dashed");
mDraw.BeginLines();
mDraw.Vertex(PLATFORM.Location());
mDraw.Vertex(nearestThreat.Location());
mDraw.End();
}
end_execute
end_behavior

View File

@@ -0,0 +1,173 @@
# ****************************************************************************
# CUI
#
# The Advanced Framework for Simulation, Integration, and Modeling (AFSIM)
#
# The use, dissemination or disclosure of data in this file is subject to
# limitation or restriction. See accompanying README and LICENSE for details.
# ****************************************************************************
behavior formation
script_debug_writes off
script_variables
//**********************************************************************//
//** debugging parameters **//
//**********************************************************************//
bool mDrawFormationData = false;
//**********************************************************************//
//** formation flying parameters, for offset and tightness **//
//**********************************************************************//
Array<string> mLeadNames = Array<string>();
double mFormationPositionX = -500; #meters in front of of package
double mFormationPositionY = 3000; #meters off right wing of package
double mGoodFormationRatio = 0.15; #percentage of total offset
double mFormationLookAhead = 30.0; #seconds
double mFormationAltitude = -1.0; #used if positive
//**********************************************************************//
//********* VARIABLES BELOW THIS LINE ARE NOT FOR USER EDITING *********//
//**********************************************************************//
WsfDraw mDraw = WsfDraw();
bool mLastInPosition = false; #boolean flag, utility, don't change
end_script_variables
### find escorted platform, return it
script WsfPlatform GetFormationLead()
WsfPlatform leadPlatform;
foreach ( string sLeadName in mLeadNames )
{
leadPlatform = WsfSimulation.FindPlatform(sLeadName);
if (leadPlatform.IsValid() )
{
break;
}
}
return leadPlatform;
end_script
precondition
writeln_d("precondition formation");
WsfPlatform leadPlatform = GetFormationLead();
if (!leadPlatform.IsValid() )
{
return Failure("no listed lead for formation found!");
}
writeln_d("--- agent ", PLATFORM.Name(), " is in formation with ", leadPlatform.Name());
return true;
end_precondition
script bool AmInFormationPosition(WsfGeoPoint formationPoint, double radius)
//make it fly to the inner 50% of the acceptable radius on re-entry
if (!mLastInPosition)
{
radius = 0.5 * radius;
}
mLastInPosition = false;
double range = PLATFORM.GroundRangeTo(formationPoint);
if (range <= radius)
{
mLastInPosition = true;
}
return mLastInPosition;
end_script
execute
writeln_d("executing formation.");
//make sure escorted platform exists, find it, save it
WsfPlatform leadPlatform = GetFormationLead();
if (!leadPlatform.IsValid() )
{
writeln_d("--- fighter ", PLATFORM.Name(), " no valid platform to escort!");
return;
}
//check if I am approximately in my formation position
WsfGeoPoint formationPoint = leadPlatform.Location();
if (mFormationAltitude > 0)
{
formationPoint.Set(formationPoint.Latitude(), formationPoint.Longitude(), mFormationAltitude);
}
if (mFormationPositionX > 0)
{
formationPoint.Extrapolate(leadPlatform.Heading(), mFormationPositionX);
}
else
{
formationPoint.Extrapolate(leadPlatform.Heading()+180, -mFormationPositionX);
}
if (mFormationPositionY > 0)
{
formationPoint.Extrapolate(leadPlatform.Heading()+90.0, mFormationPositionY);
}
else
{
formationPoint.Extrapolate(leadPlatform.Heading()-90.0, -mFormationPositionY);
}
if (!formationPoint.IsValid())
{
writeln_d("--- fighter ", PLATFORM.Name(), " invalid formation point from ", leadPlatform.Name());
return;
}
if (mDrawFormationData == true)
{
mDraw.SetLayer("behavior_formation");
mDraw.SetDuration(PROCESSOR.UpdateInterval());
// draw line to desired formation position
mDraw.SetColor(0, 1, 0); //green
mDraw.SetLineSize(4);
mDraw.BeginLines();
mDraw.Vertex(leadPlatform.Location());
mDraw.Vertex(formationPoint);
mDraw.End();
}
double radius = mGoodFormationRatio * leadPlatform.SlantRangeTo(formationPoint);
double formAlt = leadPlatform.Altitude();
double formSpeed = leadPlatform.Speed();
double formYaw = leadPlatform.Heading();
if (formAlt < PLATFORM.Altitude())
{
formAlt = PLATFORM.Altitude();
}
WsfGeoPoint tgt = WsfGeoPoint.Construct(formationPoint.Latitude(), formationPoint.Longitude(), formAlt);
double lookAheadDistance = mFormationLookAhead * leadPlatform.Speed();
tgt.Extrapolate(formYaw, lookAheadDistance);
if (! AmInFormationPosition(formationPoint, radius))
{
//fly towards formation position, extrapolated ahead X seconds, in order to catch up to the point in X seconds
formSpeed = PLATFORM.GroundRangeTo(tgt) / mFormationLookAhead;
}
#extern bool FlyTarget (WsfPlatform, WsfGeoPoint, double);
FlyTarget (PLATFORM, tgt, formSpeed);
end_execute
end_behavior

View File

@@ -0,0 +1,30 @@
# ****************************************************************************
# CUI
#
# The Advanced Framework for Simulation, Integration, and Modeling (AFSIM)
#
# The use, dissemination or disclosure of data in this file is subject to
# limitation or restriction. See accompanying README and LICENSE for details.
# ****************************************************************************
include_once processors/quantum_agents/aiai/ai_quantum_tasker.txt
include_once processors/quantum_agents/aiww/behavior_formation.txt
#include_once processors/ripr_agents/aiww/behavior_buddy_uplink.txt
processor WW_BUDDY_TASKER AI_QUANTUM_TASKER
#script_variables
#end_script_variables
behavior_tree
selector
behavior_node go_home
behavior_node formation
end_selector
#behavior_node buddy_uplink
end_behavior_tree
end_processor

View File

@@ -0,0 +1,39 @@
# ****************************************************************************
# CUI
#
# The Advanced Framework for Simulation, Integration, and Modeling (AFSIM)
#
# The use, dissemination or disclosure of data in this file is subject to
# limitation or restriction. See accompanying README and LICENSE for details.
# ****************************************************************************
#always requires a commander (in order to do anything interesting)
#does not create any jobs
#include_once processors/ripr_agents/aiai/aiai_processor.txt
include_once processors/quantum_agents/aiai/ai_quantum_tasker.txt
include_once processors/quantum_agents/aiww/behavior_buddy_evade.txt
include_once processors/quantum_agents/aiww/behavior_buddy_engage_weapon_task_target.txt
processor WW_LEAD_TASKER AI_QUANTUM_TASKER
script_variables
#extern Array<Map<string, Object>> mWeaponArray;
end_script_variables
behavior_tree
selector
behavior_node buddy_evade
behavior_node go_home
behavior_node pursue_weapon_task_target
#behavior_node pursue-point
behavior_node planned_route
end_selector
behavior_node buddy_engage_weapon_task_target
end_behavior_tree
end_processor