Vegastrike 0.5.1 rc1  1.0
Original sources for Vegastrike Evolved
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Unit Class Reference

#include <unit.h>

Inheritance diagram for Unit:
Asteroid Building Enhancement GameUnit< Unit > Missile Nebula Planet GameUnit< Asteroid > GameUnit< Building > GameUnit< Enhancement > AtmosphereHalo GameUnit< Missile > GameUnit< Nebula > GameAsteroid GameBuilding GameEnhancement GameMissile GameNebula

Classes

class  Computer
 
class  graphic_options
 
class  Limits
 
struct  UnitJump
 
struct  XML
 

Public Types

enum  DAMAGES {
  NO_DAMAGE =0x00, SHIELD_DAMAGED =0x01, COMPUTER_DAMAGED =0x02, MOUNT_DAMAGED =0x04,
  CARGOFUEL_DAMAGED =0x08, JUMP_DAMAGED =0x10, CLOAK_DAMAGED =0x20, LIMITS_DAMAGED =0x40,
  ARMOR_DAMAGED =0x80
}
 
enum  schedulepriorityenum { scheduleDefault, scheduleAField, scheduleRoid }
 
enum  COLLIDELOCATIONTYPES { UNIT_ONLY =0, UNIT_BOLT =1, NUM_COLLIDE_MAPS =2 }
 
enum  DOCKENUM { NOT_DOCKED =0x0, DOCKED_INSIDE =0x1, DOCKED =0x2, DOCKING_UNITS =0x4 }
 
enum  tractorHow { tractorImmune =0, tractorPush =1, tractorIn =2, tractorBoth =3 }
 

Public Member Functions

 Unit (bool kill)
 
void Kill ()
 
bool Killed ()
 
void Ref ()
 
void UnRef ()
 
 Unit ()
 
 Unit (int dummy)
 
 Unit (std::vector< Mesh * > &meshes, bool Subunit, int faction)
 
 Unit (const char *filename, bool SubUnit, int faction, std::string customizedUnit=std::string(""), Flightgroup *flightgroup=NULL, int fg_subnumber=0, std::string *netxml=NULL)
 
void Init ()
 
void Init (const char *filename, bool SubUnit, int faction, std::string customizedUnit=std::string(""), Flightgroup *flightgroup=NULL, int fg_subnumber=0, std::string *netxml=NULL)
 
void LoadRow (class CSVRow &row, std::string unitMod, std::string *netxml=NULL)
 
virtual ~Unit ()
 
void SetNetworkMode (bool mode=true)
 
ObjSerial GetSerial () const
 
void SetSerial (ObjSerial)
 
void BackupState ()
 
bool UpgradeSubUnitsWithFactory (const Unit *up, int subunitoffset, bool touchme, bool downgrade, int &numave, double &percentage, Unit *(*createupgradesubunit)(std::string s, int faction))
 
virtual bool UpgradeSubUnits (const Unit *up, int subunitoffset, bool touchme, bool downgrade, int &numave, double &percentage)
 
bool UpgradeMounts (const Unit *up, int subunitoffset, bool touchme, bool downgrade, int &numave, const Unit *templ, double &percentage)
 
un_iter getSubUnits ()
 
un_kiter viewSubUnits () const
 
bool isSubUnit () const
 
void setFaceCamera ()
 
bool UpAndDownGrade (const Unit *up, const Unit *templ, int mountoffset, int subunitoffset, bool touchme, bool downgrade, int additive, bool forcetransaction, double &percentage, const Unit *downgrade_min, bool force_change_on_nothing, bool gen_downgrade_list)
 
void ImportPartList (const std::string &category, float price, float pricedev, float quantity, float quantdev)
 
int GetNumMounts () const
 
void ClearMounts ()
 
virtual void UpgradeInterface (Unit *base)
 
bool canUpgrade (const Unit *upgrador, int mountoffset, int subunitoffset, int additive, bool force, double &percentage, const Unit *templ=NULL, bool force_change_on_nothing=false, bool gen_downgrade_list=true)
 
bool Upgrade (const Unit *upgrador, int mountoffset, int subunitoffset, int additive, bool force, double &percentage, const Unit *templ=NULL, bool force_change_on_nothing=false, bool gen_downgrade_list=true)
 
int RepairCost ()
 
int RepairUpgrade ()
 
bool RepairUpgradeCargo (Cargo *item, Unit *baseUnit, float *credits)
 
Vector MountPercentOperational (int whichmount)
 
bool ReduceToTemplate ()
 
virtual double Upgrade (const std::string &file, int mountoffset, int subunitoffset, bool force, bool loop_through_mounts)
 
bool canDowngrade (const Unit *downgradeor, int mountoffset, int subunitoffset, double &percentage, const Unit *downgradelimit, bool gen_downgrade_list=true)
 
bool Downgrade (const Unit *downgradeor, int mountoffset, int subunitoffset, double &percentage, const Unit *downgradelimit, bool gen_downgrade_list=true)
 
unsigned attackPreference () const
 
void attackPreference (unsigned char)
 
unsigned unitRole () const
 
void unitRole (unsigned char)
 
void setCombatRole (const std::string &s)
 
const std::string & getCombatRole () const
 
const std::string & getUnitRole () const
 
void setUnitRole (const std::string &s)
 
const std::string & getAttackPreference () const
 
void setAttackPreference (const std::string &s)
 
void DamageRandSys (float dam, const Vector &vec, float randum=1, float degrees=1)
 
void SetNebula (Nebula *)
 
NebulaGetNebula () const
 
const std::string & getCockpit () const
 
class CockpitGetVelocityDifficultyMult (float &) const
 
void RemoveFromSystem ()
 
void RequestPhysics ()
 
bool InCorrectStarSystem (StarSystem *)
 
virtual int nummesh () const
 
virtual void Split (int level)
 
virtual void addHalo (const char *filename, const QVector &loc, const Vector &size, const GFXColor &col, std::string halo_type, float activation)
 
std::vector< Mesh * > StealMeshes ()
 
virtual bool Explode (bool draw, float timeit)
 
void Destroy ()
 
virtual void Draw (const Transformation &quat=identity_transformation, const Matrix &m=identity_matrix)
 
virtual void DrawNow (const Matrix &m=identity_matrix, float lod=1000000000)
 
virtual void UpdateHudMatrix (int whichcam)
 
virtual VSSpritegetHudImage () const
 
virtual void applyTechniqueOverrides (const std::map< std::string, std::string > &overrides)
 
const std::vector< std::string > & GetDestinations () const
 
void AddDestination (const std::string &)
 
void SwitchCombatFlightMode ()
 
bool CombatMode ()
 
virtual bool TransferUnitToSystem (StarSystem *NewSystem)
 
virtual bool TransferUnitToSystem (unsigned int whichJumpQueue, class StarSystem *&previouslyActiveStarSystem, bool DoSightAndSound)
 
StarSystemgetStarSystem ()
 
const StarSystemgetStarSystem () const
 
const UnitJumpGetJumpStatus () const
 
float CourseDeviation (const Vector &OriginalCourse, const Vector &FinalCourse) const
 
ComputerGetComputerData ()
 
const ComputerViewComputerData () const
 
void ActivateJumpDrive (int destination=0)
 
void DeactivateJumpDrive ()
 
void beginElement (const std::string &name, const XMLSupport::AttributeList &attributes)
 
void endElement (const std::string &name)
 
void WriteUnit (const char *modificationname="")
 
std::string WriteUnitString ()
 
void LoadXML (const char *filename, const char *unitModifications="", std::string *xmlbuffer=NULL)
 
void LoadXML (VSFileSystem::VSFile &f, const char *unitModifications="", std::string *xmlbuffer=NULL)
 
bool AutoPilotToErrorMessage (Unit *un, bool automaticenergyrealloc, std::string &failuremessage, int recursive_level=2)
 
bool AutoPilotTo (Unit *un, bool automaticenergyrealloc)
 
Vector LocalCoordinates (Unit *un) const
 
float CloakVisible () const
 
virtual void Cloak (bool cloak)
 
void Kill (bool eraseFromSave=true, bool quitting=false)
 
bool Killed () const
 
bool IsExploding () const
 
float ExplodingProgress () const
 
float AfterburnData () const
 
void SetAfterBurn (float aft)
 
float FuelData () const
 
float WarpCapData () const
 
void SetFuel (float f)
 
float EnergyRechargeData () const
 
void SetEnergyRecharge (float enrech)
 
void SetMaxEnergy (float maxen)
 
float MaxEnergyData () const
 
float ShieldRechargeData () const
 
float EnergyData () const
 
float WarpEnergyData () const
 
float GetWarpEnergy () const
 
void DecreaseWarpEnergy (bool insystem, float time=1.0f)
 
void IncreaseWarpEnergy (bool insystem, float time=1.0f)
 
bool RefillWarpEnergy ()
 
float rSize () const
 
QVector Position () const
 
const MatrixGetTransformation () const
 
QVector LocalPosition () const
 
void SetPosition (const QVector &pos)
 
void SetCurPosition (const QVector &pos)
 Sets the cumulative transformation matrix's position...for setting up to be out in the middle of nowhere. More...
 
void SetPosAndCumPos (const QVector &pos)
 
void SetVisible (bool isvis)
 
void SetAllVisible (bool isvis)
 
void SetGlowVisible (bool isvis)
 
void Rotate (const Vector &axis)
 
void FireEngines (const Vector &Direction, float FuelSpeed, float FMass)
 
void ApplyForce (const Vector &Vforce)
 
void ApplyLocalForce (const Vector &Vforce)
 
void Accelerate (const Vector &Vforce)
 
void ApplyTorque (const Vector &Vforce, const QVector &Location)
 
void ApplyLocalTorque (const Vector &Vforce, const Vector &Location)
 
void ApplyBalancedLocalTorque (const Vector &Vforce, const Vector &Location)
 
void ApplyLocalTorque (const Vector &torque)
 
float ApplyLocalDamage (const Vector &pnt, const Vector &normal, float amt, Unit *affectedSubUnit, const GFXColor &, float phasedamage=0)
 
void ApplyNetDamage (Vector &pnt, Vector &normal, float amt, float ppercentage, float spercentage, GFXColor &color)
 
void ApplyDamage (const Vector &pnt, const Vector &normal, float amt, Unit *affectedSubUnit, const GFXColor &, void *ownerDoNotDereference, float phasedamage=0)
 
void LightShields (const Vector &pnt, const Vector &normal, float amt, const GFXColor &color)
 
float DealDamageToHullReturnArmor (const Vector &pnt, float Damage, float *&targ)
 
virtual void ArmorDamageSound (const Vector &pnt)
 
virtual void HullDamageSound (const Vector &pnt)
 
float DealDamageToHull (const Vector &pnt, float Damage)
 
Vector ClampThrust (const Vector &thrust, bool afterburn)
 
Vector MaxThrust (const Vector &thrust)
 
virtual void Thrust (const Vector &amt, bool afterburn=false)
 
void LateralThrust (float amt)
 
void VerticalThrust (float amt)
 
void LongitudinalThrust (float amt)
 
Vector ClampVelocity (const Vector &velocity, const bool afterburn)
 
Vector ClampAngVel (const Vector &vel)
 
Vector ClampTorque (const Vector &torque)
 
Vector MaxTorque (const Vector &torque)
 
void YawTorque (float amt)
 
void PitchTorque (float amt)
 
void RollTorque (float amt)
 
void Repair ()
 
void UpdatePhysics (const Transformation &trans, const Matrix &transmat, const Vector &CumulativeVelocity, bool ResolveLast, UnitCollection *uc, Unit *superunit)
 
virtual void UpdatePhysics2 (const Transformation &trans, const Transformation &old_physical_state, const Vector &accel, float difficulty, const Matrix &transmat, const Vector &CumulativeVelocity, bool ResolveLast, UnitCollection *uc=NULL)
 
virtual void UpdateSubunitPhysics (const Transformation &trans, const Matrix &transmat, const Vector &CumulativeVelocity, bool ResolveLast, UnitCollection *uc, Unit *superunit)
 
virtual void UpdateSubunitPhysics (Unit *subunit, const Transformation &trans, const Matrix &transmat, const Vector &CumulativeVelocity, bool ResolveLast, UnitCollection *uc, Unit *superunit)
 
void AddVelocity (float difficulty)
 
virtual Vector ResolveForces (const Transformation &, const Matrix &)
 
void SetOrientation (QVector q, QVector r)
 
void SetOrientation (Quaternion Q)
 
void SetOrientation (QVector p, QVector q, QVector r)
 
void GetOrientation (Vector &p, Vector &q, Vector &r) const
 
Vector GetNetAcceleration ()
 
Vector GetAcceleration () const
 
float GetMaxAccelerationInDirectionOf (const Vector &ref, bool afterburn) const
 
Vector UpCoordinateLevel (const Vector &v) const
 
Vector DownCoordinateLevel (const Vector &v) const
 
Vector ToLocalCoordinates (const Vector &v) const
 
Vector ToWorldCoordinates (const Vector &v) const
 
const VectorGetAngularVelocity () const
 
const VectorGetVelocity () const
 
Vector GetWarpVelocity () const
 
void SetVelocity (const Vector &)
 
void SetAngularVelocity (const Vector &)
 
float GetMoment () const
 
float GetMass () const
 
float GetElasticity ()
 
const LimitsLimits () const
 
void SetResolveForces (bool)
 
void setAverageGunSpeed ()
 
int LockMissile () const
 
void LockTarget (bool myboo)
 
bool TargetLocked () const
 
float TrackingGuns (bool &missileLock)
 
void ToggleWeapon (bool Missile, bool forward=true)
 
void SelectAllWeapon (bool Missile)
 
void getAverageGunSpeed (float &speed, float &grange, float &mrange) const
 
QVector PositionITTS (const QVector &firingposit, Vector firingvelocity, float gunspeed, bool smooth_itts) const
 
float FShieldData () const
 
float RShieldData () const
 
float LShieldData () const
 
float BShieldData () const
 
void ArmorData (float armor[8]) const
 
float GetHull () const
 
float GetHullPercent () const
 
void Fire (unsigned int bitmask, bool beams_target_owner=false)
 
void UnFire ()
 
void leach (float XshieldPercent, float YrechargePercent, float ZenergyPercent)
 
bool InRange (Unit *target, bool cone=true, bool cap=true) const
 
bool InRange (Unit *target, double &mm, bool cone, bool cap, bool lock) const
 
UnitTarget ()
 
UnitVelocityReference ()
 
UnitThreat ()
 
void VelocityReference (Unit *targ)
 
void TargetTurret (Unit *targ)
 
void Threaten (Unit *targ, float danger)
 
void ResetThreatLevel ()
 
float cosAngleTo (Unit *target, float &distance, float speed=0.001, float range=0.001, bool turnmargin=true) const
 
float cosAngleFromMountTo (Unit *target, float &distance) const
 
float computeLockingPercent ()
 
void Select ()
 
void Deselect ()
 
void Target (Unit *targ)
 
void setTargetFg (std::string primary, std::string secondary=std::string(), std::string tertiary=std::string())
 
void ReTargetFg (int which_target=0)
 
bool CanAddCargo (const Cargo &carg) const
 
void AddCargo (const Cargo &carg, bool sort=true)
 
int RemoveCargo (unsigned int i, int quantity, bool eraseZero=true)
 
float PriceCargo (const std::string &s)
 
CargoGetCargo (unsigned int i)
 
const CargoGetCargo (unsigned int i) const
 
void GetSortedCargoCat (const std::string &category, size_t &catbegin, size_t &catend)
 
CargoGetCargo (const std::string &s, unsigned int &i)
 
const CargoGetCargo (const std::string &s, unsigned int &i) const
 
unsigned int numCargo () const
 
std::string GetManifest (unsigned int i, Unit *scanningUnit, const Vector &original_velocity) const
 
bool SellCargo (unsigned int i, int quantity, float &creds, Cargo &carg, Unit *buyer)
 
bool SellCargo (const std::string &s, int quantity, float &creds, Cargo &carg, Unit *buyer)
 
bool BuyCargo (const Cargo &carg, float &creds)
 
bool BuyCargo (unsigned int i, unsigned int quantity, Unit *buyer, float &creds)
 
bool BuyCargo (const std::string &cargo, unsigned int quantity, Unit *buyer, float &creds)
 
void EjectCargo (unsigned int index)
 
float getEmptyCargoVolume (void) const
 
float getCargoVolume (void) const
 
float getEmptyUpgradeVolume (void) const
 
float getUpgradeVolume (void) const
 
float getHiddenCargoVolume (void) const
 
class csOPCODECollidergetCollideTree (const Vector &scale=Vector(1, 1, 1), const std::vector< struct mesh_polygon > *=NULL)
 
OrdergetAIState () const
 
void PrimeOrders ()
 
void PrimeOrdersLaunched ()
 
void PrimeOrders (Order *newAI)
 
void SetAI (Order *newAI)
 
void EnqueueAI (Order *newAI)
 
void EnqueueAIFirst (Order *newAI)
 
void LoadAIScript (const std::string &aiscript)
 
bool LoadLastPythonAIScript ()
 
bool EnqueueLastPythonAIScript ()
 
double getMinDis (const QVector &pnt)
 
void SetTurretAI ()
 
void DisableTurretAI ()
 
std::string getFullAIDescription ()
 
void eraseOrderType (unsigned int type)
 
void ExecuteAI ()
 
void SetCollisionParent (Unit *name)
 
void SetOwner (Unit *target)
 
void SetRecursiveOwner (Unit *target)
 
UnitrayCollide (const QVector &st, const QVector &end, Vector &normal, float &distance)
 
void calculate_extent (bool update_collide_queue)
 
bool Inside (const QVector &position, const float radius, Vector &normal, float &dist)
 
void UpdateCollideQueue (StarSystem *ss, CollideMap::iterator hint[NUM_COLLIDE_MAPS])
 
bool querySphere (const QVector &pnt, float err) const
 
float querySphere (const QVector &start, const QVector &end, float my_unit_radius=0) const
 
float querySphereNoRecurse (const QVector &start, const QVector &end, float my_unit_radius=0) const
 
float querySphereClickList (const QVector &st, const QVector &dir, float err) const
 
bool queryFrustum (double frustum[6][4]) const
 
virtual bool querySphereClickList (int, int, float err, Camera *activeCam)
 
bool InsideCollideTree (Unit *smaller, QVector &bigpos, Vector &bigNormal, QVector &smallpos, Vector &smallNormal, bool bigasteroid=false, bool smallasteroid=false)
 
virtual void reactToCollision (Unit *smaller, const QVector &biglocation, const Vector &bignormal, const QVector &smalllocation, const Vector &smallnormal, float dist)
 
bool jumpReactToCollision (Unit *smaller)
 
bool Collide (Unit *target)
 
void CollideAll ()
 
int CanDockWithMe (Unit *dockingunit, bool forcedock=false)
 
int ForceDock (Unit *utdw, unsigned int whichdockport)
 
void PerformDockingOperations ()
 
void FreeDockingPort (unsigned int whichport)
 
const std::vector< struct
DockingPorts > & 
DockingPortLocations () const
 
char DockedOrDocking () const
 
bool IsCleared (const Unit *dockignunit) const
 
bool isDocked (const Unit *dockingUnit) const
 
bool UnDock (Unit *unitToDockWith)
 
bool RequestClearance (Unit *dockingunit)
 
bool EndRequestClearance (Unit *dockingunit)
 
bool hasPendingClearanceRequests () const
 
int Dock (Unit *unitToDockWith)
 
void RestoreGodliness ()
 
void SetFg (Flightgroup *fg, int fg_snumber)
 
void SetFaction (int faction)
 
FlightgroupgetFlightgroup () const
 
int getFgSubnumber () const
 
const std::string getFgID ()
 
std::vector< class CargoColor > & FilterDowngradeList (std::vector< class CargoColor > &mylist, bool downgrade=true)
 
std::vector< class CargoColor > & FilterUpgradeList (std::vector< class CargoColor > &mylist)
 
bool IsBase () const
 
bool isTractorable (enum tractorHow how=tractorBoth) const
 
void setTractorability (enum tractorHow how)
 
enum tractorHow getTractorability () const
 
void setFullname (std::string name)
 
const string & getFullname () const
 
const string & getFilename () const
 
virtual enum clsptr isUnit () const
 
void Ref ()
 
void UnRef ()
 
UnitImages< void > & GetImageInformation ()
 
bool isStarShip () const
 
bool isPlanet () const
 
bool isJumppoint () const
 
bool isEnemy (const Unit *other) const
 
bool isFriend (const Unit *other) const
 
bool isNeutral (const Unit *other) const
 
float getRelation (const Unit *other) const
 
void TurretFAW ()
 

Static Public Member Functions

static void ProcessDeleteQueue ()
 
static void beginElement (void *userData, const XML_Char *name, const XML_Char **atts)
 
static void endElement (void *userData, const XML_Char *name)
 
static UnitmakeMasterPartList ()
 

Public Attributes

bool killed
 
bool zapped
 
int ucref
 
UnitSoundssound
 
StringPool::Reference name
 
StringPool::Reference filename
 
ClientState old_state
 
unsigned short damages
 
UnitCollection SubUnits
 
std::vector< Mountmounts
 
float gunspeed
 
float gunrange
 
float missilerange
 
bool inertialmode
 
char turretstatus
 
bool autopilotactive
 
class Unit::graphic_options graphicOptions
 
std::vector< Mesh * > meshdata
 
StarSystemactiveStarSystem
 
class Unit::Computer computer
 
struct Unit::UnitJump jump
 
Pilotpilot
 
bool selected
 
XMLxml
 
void * owner
 
unsigned int sim_atom_multiplier
 
unsigned int predicted_priority
 
Transformation prev_physical_state
 
Transformation curr_physical_state
 
unsigned int cur_sim_queue_slot
 
unsigned int last_processed_sqs
 
bool do_subunit_scheduling
 
enum Unit::schedulepriorityenum schedule_priority
 
Matrix cumulative_transformation_matrix
 
Transformation cumulative_transformation
 
Vector cumulative_velocity
 
Vector NetForce
 
Vector NetLocalForce
 
Vector NetTorque
 
Vector NetLocalTorque
 
Vector AngularVelocity
 
Vector Velocity
 
UnitImages< void > * pImage
 
float specInterdiction
 
float Mass
 
float HeatSink
 
class Unit::Limits limits
 
int cloaking
 
int cloakmin
 
float radial_size
 
Vector corner_min
 
Vector corner_max
 
bool resolveforces
 
Armor armor
 
Shield shield
 
float hull
 
float energy
 
Orderaistate
 
CollideMap::iterator location [2]
 
struct collideTreescolTrees
 
unsigned char docked
 
int faction
 
MeshAnimationpMeshAnimation
 

Protected Types

enum  INVIS { DEFAULTVIS =0x0, INVISGLOW =0x1, INVISUNIT =0x2, INVISCAMERA =0x4 }
 

Protected Member Functions

 Unit (const Unit &)
 
Unitoperator= (const Unit &)
 
virtual float ExplosionRadius ()
 
void ActivateGuns (const weapon_info *, bool Missile)
 cycles through the loop twice turning on all matching to ms weapons of size or after size More...
 
float MaxShieldVal () const
 
void RegenShields ()
 
virtual float DealDamageToShield (const Vector &pnt, float &Damage)
 
bool ShieldUp (const Vector &) const
 
void SortCargo ()
 

Static Protected Member Functions

static std::string massSerializer (const struct XMLType &input, void *mythis)
 
static std::string cargoSerializer (const struct XMLType &input, void *mythis)
 
static std::string mountSerializer (const struct XMLType &input, void *mythis)
 
static std::string shieldSerializer (const struct XMLType &input, void *mythis)
 
static std::string subunitSerializer (const struct XMLType &input, void *mythis)
 

Protected Attributes

StringPool::Reference csvRow
 
bool networked
 
ObjSerial serial
 
Vector net_accel
 
unsigned char attack_preference
 
unsigned char unit_role
 
Nebulanebula
 
float shieldtight
 
float fuel
 
float afterburnenergy
 
int afterburntype
 
float Momentofinertia
 
Vector SavedAccel
 
unsigned char invisible
 
float maxhull
 
float recharge
 
float maxenergy
 
float maxwarpenergy
 
float warpenergy
 
StringPool::Reference target_fgid [3]
 
Flightgroupflightgroup
 
int flightgroup_subnumber
 
std::string fullname
 

Friends

class UnitFactory
 
class Mount
 
class PlanetaryOrbit
 
class ContinuousTerrain
 
class VDU
 
class UpgradingInfo
 

Detailed Description

Unit contains any physical object that may collide with something And may be physically affected by forces. Units are assumed to have various damage and explode when they are dead. Units may have any number of weapons which, themselves may be units the aistate indicates how the unit will behave in the upcoming phys frame

Definition at line 5 of file unit.h.

Member Enumeration Documentation

Enumerator
UNIT_ONLY 
UNIT_BOLT 
NUM_COLLIDE_MAPS 

Definition at line 1348 of file unit_generic.h.

Enumerator
NO_DAMAGE 
SHIELD_DAMAGED 
COMPUTER_DAMAGED 
MOUNT_DAMAGED 
CARGOFUEL_DAMAGED 
JUMP_DAMAGED 
CLOAK_DAMAGED 
LIMITS_DAMAGED 
ARMOR_DAMAGED 

Definition at line 297 of file unit_generic.h.

298  {
301  };
Enumerator
NOT_DOCKED 
DOCKED_INSIDE 
DOCKED 
DOCKING_UNITS 

Definition at line 1425 of file unit_generic.h.

1425 {NOT_DOCKED=0x0, DOCKED_INSIDE=0x1, DOCKED=0x2, DOCKING_UNITS=0x4};
enum Unit::INVIS
protected
Enumerator
DEFAULTVIS 
INVISGLOW 
INVISUNIT 
INVISCAMERA 

Definition at line 865 of file unit_generic.h.

865 {DEFAULTVIS=0x0, INVISGLOW=0x1, INVISUNIT=0x2, INVISCAMERA=0x4};
Enumerator
scheduleDefault 
scheduleAField 
scheduleRoid 

Definition at line 781 of file unit_generic.h.

Enumerator
tractorImmune 
tractorPush 
tractorIn 
tractorBoth 

Definition at line 1487 of file unit_generic.h.

Constructor & Destructor Documentation

Unit::Unit ( bool  kill)
inline

Definition at line 11 of file unit.h.

References ucref, and zapped.

11  : killed( kill )
12  {
13  ucref = 0;
14  zapped = false;
15  }
Unit::Unit ( const Unit )
protected
Unit::Unit ( )

Definition at line 759 of file unit_generic.cpp.

References aistate, UnitImages< BOGUS >::cockpit_damage, FactionUtil::GetNeutralFaction(), Init(), pilot, pImage, and sound.

Referenced by makeMasterPartList().

760 {
761  ZeroAll();
762  pImage = (new UnitImages< void >);
763  sound = new UnitSounds;
764  aistate = NULL;
765  pImage->cockpit_damage = NULL;
767  Init();
768 }
Unit::Unit ( int  dummy)

Default constructor. This is just to figure out where default constructors are used. The useless argument will be removed again later.

Definition at line 748 of file unit_generic.cpp.

References aistate, UnitImages< BOGUS >::cockpit_damage, FactionUtil::GetNeutralFaction(), Init(), pilot, pImage, and sound.

749 {
750  ZeroAll();
751  pImage = (new UnitImages< void >);
752  sound = new UnitSounds;
753  aistate = NULL;
754  pImage->cockpit_damage = NULL;
756  Init();
757 }
Unit::Unit ( std::vector< Mesh * > &  meshes,
bool  Subunit,
int  faction 
)

Constructor that creates aa mesh with meshes as submeshes (number of them) as either as subunit with faction faction

Definition at line 770 of file unit_generic.cpp.

References aistate, calculate_extent(), UnitImages< BOGUS >::cockpit_damage, faction, graphicOptions, hull, Init(), maxhull, meshdata, pilot, pImage, Pilot::SetComm(), sound, and Unit::graphic_options::SubUnit.

771 {
772  ZeroAll();
773  pImage = (new UnitImages< void >);
774  sound = new UnitSounds;
775  pilot = new Pilot( fact );
776  aistate = NULL;
777  pImage->cockpit_damage = NULL;
778  Init();
779  hull = 1000;
780  maxhull = 100000;
781  this->faction = fact;
782  graphicOptions.SubUnit = SubU;
783  meshdata = meshes;
784  meshes.clear();
785  meshdata.push_back( NULL );
786  calculate_extent( false );
787  pilot->SetComm( this );
788 }
Unit::Unit ( const char *  filename,
bool  SubUnit,
int  faction,
std::string  customizedUnit = std::string(""),
Flightgroup flightgroup = NULL,
int  fg_subnumber = 0,
std::string *  netxml = NULL 
)

Constructor that creates a mesh from an XML file If it is a customizedUnit, it will check in that directory in the home dir for the unit.

Unit::~Unit ( )
virtual

Definition at line 809 of file unit_generic.cpp.

References UnitImages< BOGUS >::cockpit_damage, killed, meshdata, mounts, name, UnitImages< BOGUS >::pHudImage, pilot, pImage, pMeshAnimation, sound, ucref, UnitImages< BOGUS >::unitwriter, and VSFileSystem::vs_fprintf().

810 {
811  if(pMeshAnimation) {
812  delete pMeshAnimation;
813  pMeshAnimation = NULL;
814  }
815 
816  free( pImage->cockpit_damage );
817  if ( (!killed) )
818  VSFileSystem::vs_fprintf( stderr, "Assumed exit on unit %s(if not quitting, report error)\n", name.get().c_str() );
819  if (ucref)
820  VSFileSystem::vs_fprintf( stderr, "DISASTER AREA!!!!" );
821 #ifdef DESTRUCTDEBUG
822  VSFileSystem::vs_fprintf( stderr, "stage %d %x %d\n", 0, this, ucref );
823  fflush( stderr );
824 #endif
825 #ifdef DESTRUCTDEBUG
826  VSFileSystem::vs_fprintf( stderr, "%d %x ", 1, planet );
827  fflush( stderr );
828  VSFileSystem::vs_fprintf( stderr, "%d %x\n", 2, pImage->pHudImage );
829  fflush( stderr );
830 #endif
831  if (pImage->unitwriter)
832  delete pImage->unitwriter;
833  delete pImage;
834 #ifdef DESTRUCTDEBUG
835  VSFileSystem::vs_fprintf( stderr, "%d %x", 3, pImage );
836  fflush( stderr );
837 #endif
838  delete sound;
839  delete pilot;
840 #ifdef DESTRUCTDEBUG
841  VSFileSystem::vs_fprintf( stderr, "%d", 5 );
842  fflush( stderr );
843 #endif
844 #ifdef DESTRUCTDEBUG
845  VSFileSystem::vs_fprintf( stderr, "%d %x", 6, &mounts );
846  fflush( stderr );
847 #endif
848 
849 #ifdef DESTRUCTDEBUG
850  VSFileSystem::vs_fprintf( stderr, "%d %x ", 9, halos );
851  fflush( stderr );
852 #endif
853 #ifdef DESTRUCTDEBUG
854  VSFileSystem::vs_fprintf( stderr, "%d %x ", 1, &mounts );
855  fflush( stderr );
856 #endif
857 #ifndef NO_MOUNT_STAR
858  for (vector< Mount* >::iterator jj = mounts.begin(); jj != mounts.end(); ++jj)
859  //Free all mounts elements
860  if ( (*jj) != NULL )
861  delete (*jj);
862 #endif
863  mounts.clear();
864 #ifdef DESTRUCTDEBUG
865  VSFileSystem::vs_fprintf( stderr, "%d", 0 );
866  fflush( stderr );
867 #endif
868  for (unsigned int meshcount = 0; meshcount < meshdata.size(); ++meshcount)
869  if (meshdata[meshcount])
870  delete meshdata[meshcount];
871  meshdata.clear();
872 }

Member Function Documentation

void Unit::Accelerate ( const Vector Vforce)

Definition at line 3235 of file unit_generic.cpp.

References FINITE, and VSFileSystem::vs_fprintf().

3236 {
3237  if ( FINITE( Vforce.i ) && FINITE( Vforce.j ) && FINITE( Vforce.k ) )
3238  NetForce += Vforce*GetMass();
3239  else
3240  VSFileSystem::vs_fprintf( stderr, "fatal force" );
3241 }
void Unit::ActivateGuns ( const weapon_info sz,
bool  Missile 
)
protected

cycles through the loop twice turning on all matching to ms weapons of size or after size

Definition at line 5414 of file unit_generic.cpp.

References Mount::DESTROYED, isMissile(), j, and weapon_info::type.

5415 {
5416  for (int j = 0; j < 2; ++j)
5417  for (int i = 0; i < GetNumMounts(); ++i)
5418  if (mounts[i].type == sz) {
5419  if ( mounts[i].status < Mount::DESTROYED && mounts[i].ammo != 0 && (isMissile( mounts[i].type ) == ms) )
5420  mounts[i].Activate( ms );
5421  else
5422  sz = mounts[(i+1)%GetNumMounts()].type;
5423  }
5424 }
void Unit::ActivateJumpDrive ( int  destination = 0)

Definition at line 621 of file unit_generic.cpp.

Referenced by Orders::AggressiveAI::Execute(), FlyByKeyboard::Execute(), Orders::AggressiveAI::ExecuteNoEnemies(), and GameUnit< UnitType >::TransferUnitToSystem().

622 {
623  if ( ( ( docked&(DOCKED|DOCKED_INSIDE) ) == 0 ) && jump.drive != -2 )
624  jump.drive = destination;
625 }
void Unit::AddCargo ( const Cargo carg,
bool  sort = true 
)

Definition at line 8232 of file unit_generic.cpp.

References _Universe, NetServer::BroadcastCargoUpgrade(), NetClient::cargoRequest(), Cargo::GetContent(), VegaConfig::getVariable(), Cargo::mass, Cargo::mission, Universe::netLocked(), Network, XMLSupport::parse_bool(), Cargo::price, Cargo::quantity, SERVER, Cargo::volume, vs_config, VSServer, and Universe::whichPlayerStarship().

Referenced by AddCarg(), UnitUtil::addCargo(), Beam::Collide(), BaseComputer::SellUpgradeOperation::concludeTransaction(), Enslave(), UnitUtil::forceAddCargo(), UnitUtil::incrementCargo(), makeMasterPartList(), and SellCargo().

8233 {
8234  if ( Network && !_Universe->netLocked() ) {
8235  int playernum = _Universe->whichPlayerStarship( this );
8236  if (playernum >= 0)
8237  Network[playernum].cargoRequest( this->serial, 0, carg.GetContent(), carg.quantity, 0, 0 );
8238  else
8239  return;
8240  return;
8241  }
8242  if ( SERVER && !_Universe->netLocked() && getStarSystem() ) {
8243  VSServer->BroadcastCargoUpgrade( this->serial, this->serial, 0, carg.GetContent(),
8244  carg.price, carg.mass, carg.volume, carg.mission,
8245  carg.quantity, 0, 0, getStarSystem()->GetZone() );
8246  }
8247  static bool usemass = XMLSupport::parse_bool( vs_config->getVariable( "physics", "use_cargo_mass", "true" ) );
8248  if (usemass)
8249  Mass += carg.quantity*carg.mass;
8250  pImage->cargo.push_back( carg );
8251  if (sort)
8252  SortCargo();
8253 }
void Unit::AddDestination ( const std::string &  dest)

Definition at line 1605 of file unit_generic.cpp.

Referenced by Planet::InitPlanet().

1606 {
1607  pImage->destination.push_back( dest );
1608 }
virtual void Unit::addHalo ( const char *  filename,
const QVector loc,
const Vector size,
const GFXColor col,
std::string  halo_type,
float  activation 
)
inlinevirtual
void Unit::AddVelocity ( float  difficulty)

Definition at line 2674 of file unit_generic.cpp.

References _Universe, CalculateNearestWarpUnit(), cumulative_velocity, VegaConfig::getVariable(), Universe::isPlayerStarship(), XMLSupport::parse_float(), SIMULATION_ATOM, UniverseUtil::sqrt(), v, Vector, and vs_config.

2675 {
2676  Vector VelocityRef( 0, 0, 0 );
2677  {
2679  if (vr)
2680  VelocityRef = vr->cumulative_velocity;
2681  }
2682  //for the heck of it.
2683  static float humanwarprampuptime = XMLSupport::parse_float( vs_config->getVariable( "physics", "warprampuptime", "5" ) );
2684  //for the heck of it.
2685  static float compwarprampuptime =
2686  XMLSupport::parse_float( vs_config->getVariable( "physics", "computerwarprampuptime", "10" ) );
2687  static float warprampdowntime = XMLSupport::parse_float( vs_config->getVariable( "physics", "warprampdowntime", "0.5" ) );
2688  Vector v = Velocity-VelocityRef;
2689  float len = v.Magnitude();
2690  float lastWarpField = graphicOptions.WarpFieldStrength;
2691  if (len > .01) //only get velocity going in DIRECTIOn of cumulative transformation for warp calc...
2692  v = v*( cumulative_transformation_matrix.getR().Dot( v*(1./len) ) );
2693  bool playa = _Universe->isPlayerStarship( this ) ? true : false;
2694  float warprampuptime = playa ? humanwarprampuptime : compwarprampuptime;
2695  //Warp Turning on/off
2697  //Warp Turning on
2698  if (graphicOptions.InWarp == 1)
2699  graphicOptions.RampCounter = warprampuptime;
2700  //Warp Turning off
2701  else
2702  graphicOptions.RampCounter = warprampdowntime;
2704  }
2705  if (graphicOptions.InWarp == 1 || graphicOptions.RampCounter != 0) {
2706  //Pi^2
2707  static float warpMultiplierMin =
2708  XMLSupport::parse_float( vs_config->getVariable( "physics", "warpMultiplierMin", "9.86960440109" ) );
2709  //C
2710  static float warpMultiplierMax =
2711  XMLSupport::parse_float( vs_config->getVariable( "physics", "warpMultiplierMax", "300000000" ) );
2712  //Pi^2 * C
2713  static float warpMaxEfVel = XMLSupport::parse_float( vs_config->getVariable( "physics", "warpMaxEfVel", "2960881320" ) );
2714  //inverse fractional effect of ship vs real big object
2715  float minmultiplier = warpMultiplierMax*graphicOptions.MaxWarpMultiplier;
2716  Unit *nearest_unit = NULL;
2717  minmultiplier = CalculateNearestWarpUnit( this, minmultiplier, &nearest_unit, true );
2718  float rampmult = 1;
2719  if (graphicOptions.RampCounter != 0) {
2721  if (graphicOptions.RampCounter <= 0)
2723  if (graphicOptions.InWarp == 0 && graphicOptions.RampCounter > warprampdowntime)
2724  graphicOptions.RampCounter = (1-graphicOptions.RampCounter/warprampuptime)*warprampdowntime;
2725  if (graphicOptions.InWarp == 1 && graphicOptions.RampCounter > warprampuptime)
2726  graphicOptions.RampCounter = warprampuptime;
2727  rampmult = (graphicOptions.InWarp) ? 1.0
2729  /warprampuptime)
2731  /warprampuptime) ) : (graphicOptions.RampCounter
2732  /warprampdowntime)*(graphicOptions.RampCounter/warprampdowntime);
2733  }
2734  float minWarp = warpMultiplierMin*graphicOptions.MinWarpMultiplier;
2735  float maxWarp = warpMultiplierMax*graphicOptions.MaxWarpMultiplier;
2736  if (minmultiplier < minWarp)
2737  minmultiplier = minWarp;
2738  if (minmultiplier > maxWarp)
2739  minmultiplier = maxWarp; //SOFT LIMIT
2740  minmultiplier *= rampmult;
2741  if (minmultiplier < 1)
2742  minmultiplier = 1;
2743  v *= minmultiplier;
2744  float vmag = sqrt( v.i*v.i+v.j*v.j+v.k*v.k );
2745  if (vmag > warpMaxEfVel) {
2746  v *= warpMaxEfVel/vmag; //HARD LIMIT
2747  minmultiplier *= warpMaxEfVel/vmag;
2748  }
2749  graphicOptions.WarpFieldStrength = minmultiplier;
2750  } else {
2752  }
2753  //not any more? lastWarpField=1;
2754  if (graphicOptions.WarpFieldStrength != 1.0)
2755  v = GetWarpVelocity();
2756  else
2757  v = Velocity;
2758  static float WARPMEMORYEFFECT = XMLSupport::parse_float( vs_config->getVariable( "physics", "WarpMemoryEffect", "0.9" ) );
2759  graphicOptions.WarpFieldStrength = lastWarpField*WARPMEMORYEFFECT+(1.0-WARPMEMORYEFFECT)*graphicOptions.WarpFieldStrength;
2761  //now we do this later in update physics
2762  //I guess you have to, to be robust}
2763 }
float Unit::AfterburnData ( ) const
inline

Definition at line 896 of file unit_generic.h.

References afterburnenergy.

Referenced by ZoneMgr::addDamage().

897  {
898  return afterburnenergy;
899  }
void Unit::ApplyBalancedLocalTorque ( const Vector Vforce,
const Vector Location 
)

Definition at line 3257 of file unit_generic.cpp.

3258 {
3259  NetTorque += Vforce.Cross( Location );
3260 }
void Unit::ApplyDamage ( const Vector pnt,
const Vector normal,
float  amt,
Unit affectedSubUnit,
const GFXColor color,
void *  ownerDoNotDereference,
float  phasedamage = 0 
)

Definition at line 4206 of file unit_generic.cpp.

References _Universe, AllUnitsCloseAndEngage(), c, Order::Communicate(), faction, findUnitInStarsystem(), CommunicationMessage::fsm, getAIState(), Pilot::getCommFaces(), FSM::GetDamagedNode(), FSM::GetDealtDamageNode(), FSM::GetHitNode(), FactionUtil::GetNeutralFaction(), Cockpit::GetParent(), VegaConfig::getVariable(), InvTransform(), Universe::isPlayerStarship(), Universe::isPlayerStarshipVoid(), isUnit(), Network, owner, XMLSupport::parse_bool(), XMLSupport::parse_float(), pilot, ScoreKill(), SERVER, CommunicationMessage::SetCurrentState(), UNITPTR, Vector, and vs_config.

Referenced by MissileEffect::ApplyDamage(), UnitWrapper::ApplyDamage(), Bolt::Collide(), ContinuousTerrain::Collide(), Beam::Collide(), DealPossibleJumpDamage(), and reactToCollision().

4213 {
4214  Cockpit *cp = _Universe->isPlayerStarshipVoid( ownerDoNotDereference );
4215  float hullpercent = GetHullPercent();
4216  //Only on client side
4217  bool mykilled = hull < 0;
4219  Vector localnorm( ToLocalCoordinates( normal ) );
4220  //Only call when on servre side or non-networking
4221  //If networking damages are applied as they are received
4222  static float hull_percent_for_comm = XMLSupport::parse_float( vs_config->getVariable( "AI", "HullPercentForComm", ".75" ) );
4223  bool armor_damage = false;
4224  if (SERVER || Network == NULL)
4225  armor_damage = (ApplyLocalDamage( localpnt, localnorm, amt, affectedUnit, color, phasedamage ) == 2);
4226  if (!Network && cp) {
4227  static int MadnessForShieldDamage = XMLSupport::parse_bool( vs_config->getVariable( "AI", "ShieldDamageAnger", "1" ) );
4228  static int MadnessForHullDamage = XMLSupport::parse_bool( vs_config->getVariable( "AI", "HullDamageAnger", "10" ) );
4229  int howmany = armor_damage ? MadnessForHullDamage : MadnessForShieldDamage;
4230  for (int i = 0; i < howmany; ++i) {
4231  //now we can dereference it because we checked it against the parent
4232  CommunicationMessage c( reinterpret_cast< Unit* > (ownerDoNotDereference), this, NULL, 0 );
4233  c.SetCurrentState( c.fsm->GetHitNode(), NULL, 0 );
4234  if ( this->getAIState() ) this->getAIState()->Communicate( c );
4235  }
4236  //the dark danger is real!
4237  Threaten( reinterpret_cast< Unit* > (ownerDoNotDereference), 10 );
4238  } else if (!Network) {
4239  //if only the damage contained which faction it belonged to
4240  pilot->DoHit( this, ownerDoNotDereference, FactionUtil::GetNeutralFaction() );
4241  }
4242  if (hull < 0) {
4243  ClearMounts();
4244  if (!mykilled) {
4245  if (cp) {
4246  ScoreKill( cp, reinterpret_cast< Unit* > (ownerDoNotDereference), this );
4247  } else {
4248  Unit *tmp;
4249  if ( ( tmp = findUnitInStarsystem( ownerDoNotDereference ) ) != NULL ) {
4250  if ( ( NULL != ( cp = _Universe->isPlayerStarshipVoid( tmp->owner ) ) )
4251  && (cp->GetParent() != NULL) )
4252  ScoreKill( cp, cp->GetParent(), this );
4253  else
4254  ScoreKill( NULL, tmp, this );
4255  }
4256  }
4257  }
4258  } else if ( hullpercent >= hull_percent_for_comm && ( (float) GetHullPercent() ) < hull_percent_for_comm
4259  && ( cp || _Universe->isPlayerStarship( this ) ) ) {
4260  Unit *computerai = NULL;
4261  Unit *player = NULL;
4262  if (cp == NULL) {
4263  computerai = findUnitInStarsystem( ownerDoNotDereference );
4264  player = this;
4265  } else {
4266  computerai = this;
4267  //cp != NULL
4268  player = cp->GetParent();
4269  }
4270  if (computerai && player && computerai->getAIState() && player->getAIState() && computerai->isUnit() == UNITPTR
4271  && player->isUnit() == UNITPTR) {
4272  unsigned char gender;
4273  vector< Animation* > *anim = computerai->pilot->getCommFaces( gender );
4274  if (cp) {
4275  static bool assistallyinneed =
4276  XMLSupport::parse_bool( vs_config->getVariable( "AI", "assist_friend_in_need", "true" ) );
4277  if (assistallyinneed)
4278  AllUnitsCloseAndEngage( player, computerai->faction );
4279  }
4280  if (GetHullPercent() > 0 || !cp) {
4281  CommunicationMessage c( computerai, player, anim, gender );
4282  c.SetCurrentState( cp ? c.fsm->GetDamagedNode() : c.fsm->GetDealtDamageNode(), anim, gender );
4283  player->getAIState()->Communicate( c );
4284  }
4285  }
4286  }
4287 }
void Unit::ApplyForce ( const Vector Vforce)

Definition at line 3218 of file unit_generic.cpp.

References FINITE, Vforce, and VSFileSystem::vs_fprintf().

Referenced by ContinuousTerrain::Collide(), Beam::Collide(), reactToCollision(), and GameUnit< UnitType >::Split().

3219 {
3220  if ( FINITE( Vforce.i ) && FINITE( Vforce.j ) && FINITE( Vforce.k ) )
3221  NetForce += Vforce;
3222  else
3223  VSFileSystem::vs_fprintf( stderr, "fatal force" );
3224 }
float Unit::ApplyLocalDamage ( const Vector pnt,
const Vector normal,
float  amt,
Unit affectedSubUnit,
const GFXColor color,
float  phasedamage = 0 
)

Definition at line 4079 of file unit_generic.cpp.

References _Universe, GFXColor::a, ApplyLocalDamage(), GFXColor::b, game_data_t::difficulty, GFXColor::g, g_game, VegaConfig::getVariable(), Universe::isPlayerStarship(), XMLSupport::parse_bool(), XMLSupport::parse_float(), GFXColor::r, NetServer::sendDamages(), SERVER, Vector, vs_config, and VSServer.

Referenced by ApplyLocalDamage().

4085 {
4086  static float nebshields = XMLSupport::parse_float( vs_config->getVariable( "physics", "nebula_shield_recharge", ".5" ) );
4087  Cockpit *cpt;
4088  if ( ( cpt = _Universe->isPlayerStarship( this ) ) != NULL ) {
4089  if (color.a != 2) {
4090  static bool apply_difficulty_enemy_damage =
4091  XMLSupport::parse_bool( vs_config->getVariable( "physics", "difficulty_based_enemy_damage", "true" ) );
4092  if (apply_difficulty_enemy_damage) {
4093  phasedamage *= g_game.difficulty;
4094  amt *= g_game.difficulty;
4095  }
4096  }
4097  }
4098  float absamt = amt >= 0 ? amt : -amt;
4099  float ppercentage = 0;
4100  //We also do the following lock on client side in order not to display shield hits
4101  static bool nodockdamage = XMLSupport::parse_float( vs_config->getVariable( "physics", "no_damage_to_docked_ships", "true" ) );
4102  if (nodockdamage)
4104  return -1;
4105  if (affectedUnit != this) {
4106  affectedUnit->ApplyLocalDamage( pnt, normal, amt, affectedUnit, color, phasedamage );
4107  return -1;
4108  }
4109  if (aistate)
4110  aistate->ChooseTarget();
4111  float leakamt = phasedamage+amt*.01*shield.leak;
4112  amt *= 1-.01*shield.leak;
4113  //Percentage returned by DealDamageToShield
4114  float spercentage = 0;
4115  //If not a nebula or if shields recharge in nebula => WE COMPUTE SHIELDS DAMAGE AND APPLY
4116  if ( GetNebula() == NULL || (nebshields > 0) ) {
4117  float origabsamt = absamt;
4118  spercentage = DealDamageToShield( pnt, absamt );
4119 
4120  amt = amt >= 0 ? absamt : -absamt;
4121  //shields are up
4122  if ( meshdata.back() && spercentage > 0 && (origabsamt-absamt > shield.recharge || amt == 0) ) {
4123  //calculate percentage
4124  if (cpt)
4125  cpt->Shake( amt, 0 );
4126  if (GetNebula() == NULL)
4127  LightShields( pnt, normal, spercentage, color );
4128  }
4129  }
4130  //If shields failing or... => WE COMPUTE DAMAGE TO HULL
4131  if (shield.leak > 0 || !meshdata.back() || spercentage == 0 || absamt > 0 || phasedamage) {
4132  float tmp = this->GetHull();
4133  ppercentage = DealDamageToHull( pnt, leakamt+amt );
4134  if (cpt)
4135  cpt->Shake( amt+leakamt, tmp != this->GetHull() ? 2 : 1 );
4136  if (ppercentage != -1) {
4137  //returns -1 on death--could delete
4138  for (int i = 0; i < nummesh(); ++i)
4139  if (ppercentage)
4140  meshdata[i]->AddDamageFX( pnt, shieldtight ? shieldtight*normal : Vector( 0, 0, 0 ), ppercentage, color );
4141  }
4142  }
4143  //If server and there is damage to shields or if unit is not killed (ppercentage>0)
4144  if ( SERVER && (ppercentage > 0 || spercentage > 0) ) {
4145 #if 1 //def NET_SHIELD_SYSTEM_1
4146  //FIRST METHOD : send each time a unit is hit all the damage info to all clients in the current zone
4147  //If server side, we send the unit serial + serialized shields + shield recharge + shield leak + ...
4148  Vector netpnt = pnt;
4149  Vector netnormal = normal;
4150  GFXColor col( color.r, color.g, color.b, color.a );
4151  VSServer->sendDamages( this->serial,
4152  this->getStarSystem()->GetZone(), hull, shield, armor, ppercentage, spercentage, amt, netpnt,
4153  netnormal, col );
4154  //This way the client computes damages based on what we send to him => less reliable
4155 #endif
4156 #if 1
4157  //SECOND METHOD : we just put a flag on the unit telling its shield/armor data has changed
4158  if (spercentage > 0)
4159  this->damages |= SHIELD_DAMAGED;
4160  if (ppercentage > 0)
4161  this->damages |= ARMOR_DAMAGED;
4162 #endif
4163  }
4164  return ppercentage > 0 ? 2.0f : 1.0f;
4165 }
void Unit::ApplyLocalForce ( const Vector Vforce)

Definition at line 3227 of file unit_generic.cpp.

References FINITE, Vforce, and VSFileSystem::vs_fprintf().

Referenced by Orders::MoveToParent::Execute().

3228 {
3229  if ( FINITE( Vforce.i ) && FINITE( Vforce.j ) && FINITE( Vforce.k ) )
3230  NetLocalForce += Vforce;
3231  else
3232  VSFileSystem::vs_fprintf( stderr, "fatal local force" );
3233 }
void Unit::ApplyLocalTorque ( const Vector Vforce,
const Vector Location 
)

Definition at line 3250 of file unit_generic.cpp.

References Vforce.

Referenced by Orders::MatchAngularVelocity::Execute(), Orders::ChangeHeading::Execute(), and GameUnit< UnitType >::Split().

3251 {
3252  NetForce += Vforce;
3253  NetTorque += Vforce.Cross( Location );
3254 }
void Unit::ApplyLocalTorque ( const Vector torque)

Definition at line 3262 of file unit_generic.cpp.

3263 {
3264  NetLocalTorque += ClampTorque( torque );
3265 }
void Unit::ApplyNetDamage ( Vector pnt,
Vector normal,
float  amt,
float  ppercentage,
float  spercentage,
GFXColor color 
)

Definition at line 4167 of file unit_generic.cpp.

References _Universe, VegaConfig::getVariable(), Universe::isPlayerStarship(), XMLSupport::parse_float(), Cockpit::Shake(), Vector, and vs_config.

4168 {
4169  static float nebshields = XMLSupport::parse_float( vs_config->getVariable( "physics", "nebula_shield_recharge", ".5" ) );
4170  Cockpit *cpt;
4171  if ( ( cpt = _Universe->isPlayerStarship( this ) ) != NULL ) {}
4172  if (GetNebula() == NULL || nebshields > 0) {
4173  //shields are up
4174  if (meshdata.back() && spercentage > 0 && amt == 0) {
4175  if (GetNebula() == NULL)
4176  meshdata.back()->AddDamageFX( pnt, shieldtight ? shieldtight*normal : Vector( 0, 0, 0 ), spercentage, color );
4177  if (cpt)
4178  cpt->Shake( amt, 0 );
4179  }
4180  }
4181  if (shield.leak > 0 || !meshdata.back() || spercentage == 0 || amt > 0) {
4182  if (ppercentage != -1) {
4183  //returns -1 on death--could delete
4184  for (int i = 0; i < nummesh(); ++i)
4185  if (ppercentage) {
4186  meshdata[i]->AddDamageFX( pnt, shieldtight ? shieldtight*normal : Vector( 0, 0, 0 ), ppercentage, color );
4187  if (cpt)
4188  cpt->Shake( amt, 2 );
4189  }
4190  }
4191  }
4192 }
void Unit::applyTechniqueOverrides ( const std::map< std::string, std::string > &  overrides)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 8965 of file unit_generic.cpp.

8966 {
8967  // No-op
8968  // FIXME ?
8969 }
void Unit::ApplyTorque ( const Vector Vforce,
const QVector Location 
)

Definition at line 3243 of file unit_generic.cpp.

References Vforce.

Referenced by reactToCollision().

3244 {
3245  //Not completely correct
3246  NetForce += Vforce;
3247  NetTorque += Vforce.Cross( (Location-curr_physical_state.position).Cast() );
3248 }
virtual void Unit::ArmorDamageSound ( const Vector pnt)
inlinevirtual
void Unit::ArmorData ( float  armor[8]) const

Definition at line 4704 of file unit_generic.cpp.

Referenced by GameCockpit::LookupUnitStat(), UnitUtil::PercentOperational(), Cockpit::SetParent(), and SuicideKey().

4705 {
4706  armor[0] = this->armor.frontrighttop;
4707  armor[1] = this->armor.backrighttop;
4708  armor[2] = this->armor.frontlefttop;
4709  armor[3] = this->armor.backlefttop;
4710  armor[4] = this->armor.frontrightbottom;
4711  armor[5] = this->armor.backrightbottom;
4712  armor[6] = this->armor.frontleftbottom;
4713  armor[7] = this->armor.backleftbottom;
4714 }
unsigned Unit::attackPreference ( ) const
inline

Definition at line 455 of file unit_generic.h.

References attack_preference.

Referenced by AssignTBin(), Orders::FireAt::ChooseTargets(), getProperScript(), Priority(), and Missile::UpdatePhysics2().

456  {
457  return attack_preference;
458  }
void Unit::attackPreference ( unsigned char  c)

Definition at line 103 of file unit_generic.cpp.

References c.

104 {
106 }
bool Unit::AutoPilotTo ( Unit un,
bool  automaticenergyrealloc 
)

Definition at line 143 of file unit_generic.cpp.

Referenced by Cockpit::Autopilot(), GameCockpit::LookupUnitStat(), GameCockpit::UpdAutoPilot(), Cockpit::UpdAutoPilot(), and WarpToP().

144 {
145  std::string tmp;
146  return AutoPilotToErrorMessage( un, automaticenergyrealloc, tmp );
147 }
bool Unit::AutoPilotToErrorMessage ( Unit un,
bool  automaticenergyrealloc,
std::string &  failuremessage,
int  recursive_level = 2 
)

Definition at line 2844 of file unit_generic.cpp.

References _Universe, Universe::activeStarSystem(), AddWarp(), UniverseUtil::asin(), Mission::AUTO_NORMAL, Mission::AUTO_OFF, AutoPilotToErrorMessage(), AutoSafeEntrancePoint(), UniverseUtil::cacheAnimation(), ComputeAutoGuarantee(), UnitCollection::createIterator(), XMLSupport::escaped_string(), Unit::graphic_options::FaceCamera, FINITE, GenerateAutoError(), getAIState(), getAutoRSize(), UnitUtil::getDistance(), getFlightgroup(), UniverseUtil::getPlanetRadiusPercent(), getRelation(), UnitContainer::GetUnit(), StarSystem::getUnitList(), VegaConfig::getVariable(), globQueryShell(), graphicOptions, UnitUtil::isAsteroid(), Universe::isPlayerStarship(), UnitUtil::isSun(), isUnit(), Flightgroup::leader, Magnitude(), NEBULAPTR, XMLSupport::parse_bool(), XMLSupport::parse_float(), PI, PLANETPTR, UniverseUtil::playAnimationGrow(), Position(), Order::PursueTarget(), q, QVector, RealPosition(), Rotate(), rSize(), UniverseUtil::SafeEntrancePoint(), SetPosition(), start, v, Vector, viewSubUnits(), and vs_config.

Referenced by GameCockpit::Autopilot(), and AutoPilotToErrorMessage().

2848 {
2849  static bool auto_valid =
2850  XMLSupport::parse_bool( vs_config->getVariable( "physics", "insystem_jump_or_timeless_auto-pilot", "false" ) );
2851  if (!auto_valid) {
2852  static std::string err = "No Insystem Jump";
2853  failuremessage = err;
2854  return false;
2855  }
2856  if (target->isUnit() == PLANETPTR) {
2857  Unit *targ = *(target->viewSubUnits());
2858  if (targ && 0 == targ->graphicOptions.FaceCamera)
2859  return AutoPilotToErrorMessage( targ, ignore_energy_requirements, failuremessage, recursive_level );
2860  }
2861  if (warpenergy < jump.insysenergy)
2862  if (!ignore_energy_requirements)
2863  return false;
2864  signed char Guaranteed = ComputeAutoGuarantee( this );
2865  if (Guaranteed == Mission::AUTO_OFF)
2866  return false;
2867  static float autopilot_term_distance =
2868  XMLSupport::parse_float( vs_config->getVariable( "physics", "auto_pilot_termination_distance", "6000" ) );
2869  static float atd_no_enemies =
2870  XMLSupport::parse_float( vs_config->getVariable( "physics", "auto_pilot_termination_distance_no_enemies",
2871  vs_config->getVariable( "physics", "auto_pilot_termination_distance",
2872  "6000" ) ) );
2873  static float autopilot_no_enemies_multiplier =
2874  XMLSupport::parse_float( vs_config->getVariable( "physics", "auto_pilot_no_enemies_distance_multiplier", "4" ) );
2875  if ( isSubUnit() ) {
2876  static std::string err = "Return To Cockpit for Auto";
2877  failuremessage = err;
2878  return false; //we can't auto here;
2879  }
2881  if (ss == NULL)
2882  ss = _Universe->activeStarSystem();
2883  Unit *un = NULL;
2884  QVector start( Position() );
2885  QVector end( RealPosition( target ) );
2886  float totallength = (start-end).Magnitude();
2887  bool nanspace = false;
2888  if ( !FINITE( totallength ) ) {
2889  nanspace = true;
2890  start = QVector( 100000000.0, 100000000.0, 10000000000000.0 );
2891  totallength = (start-end).Magnitude();
2892  if ( !FINITE( totallength ) ) {
2893  end = QVector( 200000000.0, 100000000.0, 10000000000000.0 );
2894  totallength = (start-end).Magnitude();
2895  }
2896  }
2897  QVector endne( end );
2898 
2899  float totpercent = 1;
2900  if (totallength > 1) {
2901  float apt =
2902  (target->isUnit() == PLANETPTR) ? ( autopilot_term_distance+target->rSize()
2903  *UniverseUtil::getPlanetRadiusPercent() ) : autopilot_term_distance;
2904  float aptne =
2905  (target->isUnit() == PLANETPTR) ? ( atd_no_enemies+target->rSize()
2906  *UniverseUtil::getPlanetRadiusPercent() ) : atd_no_enemies;
2907  float percent = (getAutoRSize( this, this )+rSize()+target->rSize()+apt)/totallength;
2908  float percentne = (getAutoRSize( this, this )+rSize()+target->rSize()+aptne)/totallength;
2909  if (percentne > 1)
2910  endne = start;
2911 
2912  else
2913  endne = start*percentne+end*(1-percentne);
2914  if (percent > 1) {
2915  end = start;
2916  totpercent = 0;
2917  } else {
2918  totpercent *= (1-percent);
2919  end = start*percent+end*(1-percent);
2920  }
2921  }
2922  bool ok = true;
2923 
2924  static bool teleport_autopilot = XMLSupport::parse_bool( vs_config->getVariable( "physics", "teleport_autopilot", "true" ) );
2925  bool unsafe = false;
2926  if ( (!teleport_autopilot) && (!nanspace) ) {
2927  if (Guaranteed == Mission::AUTO_NORMAL && CloakVisible() > .5) {
2928  bool ignore_friendlies = true;
2929  for (un_iter i = ss->getUnitList().createIterator(); (un = *i) != NULL; ++i) {
2930  static bool canflythruplanets =
2931  XMLSupport::parse_bool( vs_config->getVariable( "physics", "can_auto_through_planets", "true" ) );
2932  if ( ( !(un->isUnit() == PLANETPTR
2933  && canflythruplanets) ) && un->isUnit() != NEBULAPTR && ( !UnitUtil::isSun( un ) ) ) {
2934  if (un != this && un != target) {
2935  float tdis = ( start-un->Position() ).Magnitude()-rSize()-un->rSize();
2936  float nedis = ( end-un->Position() ).Magnitude()-rSize()-un->rSize();
2937  float trad = getAutoRSize( this, un, ignore_friendlies )+getAutoRSize( this, this, ignore_friendlies );
2938  if (tdis <= trad) {
2939  failuremessage = GenerateAutoError( this, un );
2940  return false;
2941  }
2942  if ( (nedis < trad*autopilot_no_enemies_multiplier
2943  || tdis <= trad*autopilot_no_enemies_multiplier) && un->getRelation( this ) < 0 ) {
2944  unsafe = true;
2945  failuremessage = GenerateAutoError( this, un );
2946  }
2947  float intersection =
2948  globQueryShell( start-un->Position(), end-start, getAutoRSize( this,
2949  un,
2950  ignore_friendlies )+un->rSize() );
2951  if (intersection > 0) {
2952  unsafe = true;
2953  end = start+(end-start)*intersection;
2954  totpercent *= intersection;
2955  ok = false;
2956  failuremessage = GenerateAutoError( this, un );
2957  }
2958  }
2959  }
2960  }
2961  }
2962  } else if (!nanspace) {
2963  //just make sure we aren't in an asteroid field
2964  Unit *un;
2965  for (un_iter i = ss->getUnitList().createIterator(); (un = *i) != NULL; ++i)
2966  if ( UnitUtil::isAsteroid( un ) ) {
2967  static float minasteroiddistance =
2968  XMLSupport::parse_float( vs_config->getVariable( "physics", "min_asteroid_distance", "-100" ) );
2969  if (UnitUtil::getDistance( this, un ) < minasteroiddistance) {
2970  failuremessage = GenerateAutoError( this, un );
2971  return false; //no auto in roid field
2972  }
2973  }
2974  }
2975  bool nowhere = false;
2976  if (this != target) {
2977  if ( (end-start).MagnitudeSquared() < rSize()*rSize() ) {
2978  failuremessage =
2979  XMLSupport::escaped_string( vs_config->getVariable( "graphics", "hud", "AlreadyNearMessage",
2980  "#ff0000Already Near#000000" ) );
2981  return false;
2982  }
2983  warpenergy -= totpercent*jump.insysenergy;
2984  if (unsafe == false && totpercent == 0)
2985  end = endne;
2987  if ( (sep-end).MagnitudeSquared() > 16*rSize()*rSize() )
2988  //DOn't understand why rsize is so bigsep = AutoSafeEntrancePoint (end,(RealPosition(target)-end).Magnitude()-target->rSize(),target);
2989  sep = AutoSafeEntrancePoint( end, rSize(), target );
2990  if ( ( sep-RealPosition( target ) ).MagnitudeSquared()
2991  > ( RealPosition( this )-RealPosition( target ) ).MagnitudeSquared() ) {
2992  sep = RealPosition( this );
2993  nowhere = true;
2994  }
2995  static bool auto_turn_towards = XMLSupport::parse_bool( vs_config->getVariable( "physics", "auto_turn_towards", "true" ) );
2996  if (auto_turn_towards) {
2997  for (int i = 0; i < 3; ++i) {
2998  Vector methem( RealPosition( target ).Cast()-sep.Cast() );
2999  methem.Normalize();
3000  Vector p, q, r;
3001  GetOrientation( p, q, r );
3002  p = methem.Cross( r );
3003  float theta = p.Magnitude();
3004  if (theta*theta > .00001) {
3005  p *= (asin( theta )/theta);
3006  Rotate( p );
3007  GetOrientation( p, q, r );
3008  }
3009  if (r.Dot( methem ) < 0)
3010  Rotate( p*(PI/theta) );
3011  Velocity = methem*Velocity.Magnitude();
3012  }
3013  }
3014  static string insys_jump_ani = vs_config->getVariable( "graphics", "insys_jump_animation", "warp.ani" );
3015  if (
3016 
3017  insys_jump_ani.length() ) {
3018  static bool docache = true;
3019  if (docache) {
3020  UniverseUtil::cacheAnimation( insys_jump_ani );
3021  docache = false;
3022  }
3023  static float insys_jump_ani_size =
3024  XMLSupport::parse_float( vs_config->getVariable( "graphics", "insys_jump_animation_size", "4" ) );
3025  static float insys_jump_ani_growth =
3026  XMLSupport::parse_float( vs_config->getVariable( "graphics", "insys_jump_animation_growth", ".99" ) );
3027  UniverseUtil::playAnimationGrow( insys_jump_ani, RealPosition( this ),
3028  rSize()*insys_jump_ani_size, insys_jump_ani_growth );
3029 
3030  Vector v( GetVelocity() );
3031  v.Normalize();
3032  Vector p, q, r;
3033  GetOrientation( p, q, r );
3034  static float sec = XMLSupport::parse_float( vs_config->getVariable( "graphics", "insys_jump_ani_second_ahead", "4" ) );
3035  UniverseUtil::playAnimationGrow( insys_jump_ani, sep+GetVelocity()*sec+v*rSize(), rSize()*8, .97 );
3036  UniverseUtil::playAnimationGrow( insys_jump_ani, sep+GetVelocity()*sec+2*v*rSize()+r*4*rSize(), rSize()*16, .97 );
3037  }
3038  static bool warptrail = XMLSupport::parse_bool( vs_config->getVariable( "graphics", "warp_trail", "true" ) );
3039  if ( warptrail && (!nowhere) ) {
3040  static float warptrailtime = XMLSupport::parse_float( vs_config->getVariable( "graphics", "warp_trail_time", "20" ) );
3041  AddWarp( this, RealPosition( this ), warptrailtime );
3042  }
3043  if (!nowhere)
3044  SetCurPosition( sep );
3045  Cockpit *cp;
3046  if ( ( cp = _Universe->isPlayerStarship( this ) ) != NULL ) {
3047  std::string followermessage;
3048  if (getFlightgroup() != NULL) {
3049  Unit *other = NULL;
3050  if (recursive_level > 0) {
3051  for (un_iter ui = ss->getUnitList().createIterator(); NULL != (other = *ui); ++ui) {
3052  Flightgroup *ff = other->getFlightgroup();
3053  bool leadah = ( ff == getFlightgroup() );
3054  if (ff)
3055  if (ff->leader.GetUnit() == this)
3056  leadah = true;
3057  Order *otherord = other->getAIState();
3058  if (otherord) {
3059  if ( otherord->PursueTarget( this, leadah ) ) {
3060  other->AutoPilotToErrorMessage( this,
3061  ignore_energy_requirements,
3062  followermessage,
3063  recursive_level-1 );
3064  if (leadah)
3065  if ( NULL == _Universe->isPlayerStarship( other ) )
3066  other->SetPosition( AutoSafeEntrancePoint( LocalPosition(), other->rSize()*1.5, other ) );
3067  }
3068  }
3069  }
3070  }
3071  }
3072  }
3073  }
3074  return ok;
3075 }
void Unit::BackupState ( )

Definition at line 298 of file unit_generic.cpp.

Referenced by NetClient::AddClientObject().

299 {
302  this->old_state.setVelocity( this->Velocity );
303  this->old_state.setAcceleration( this->net_accel );
304 }
void Unit::beginElement ( void *  userData,
const XML_Char *  name,
const XML_Char **  atts 
)
static

Definition at line 104 of file unit_xml.cpp.

105 {
106  ( (Unit*) userData )->beginElement( name, AttributeList( atts ) );
107 }
void Unit::beginElement ( const std::string &  name,
const XMLSupport::AttributeList attributes 
)
float Unit::BShieldData ( ) const

Definition at line 4780 of file unit_generic.cpp.

Referenced by GameCockpit::LookupTargetStat(), GameCockpit::LookupUnitStat(), Orders::AggressiveAI::ProcessLogicItem(), Orders::AggressiveAI::SetParent(), and UpAndDownGrade().

4781 {
4782  switch (shield.number)
4783  {
4784  case 2:
4785  {
4786  if (shield.shield2fb.backmax != 0)
4787  return shield.shield2fb.back/shield.shield2fb.backmax;
4788  break;
4789  }
4790  case 4:
4791  {
4792  if (shield.shield4fbrl.backmax != 0)
4793  return (shield.shield4fbrl.back)/shield.shield4fbrl.backmax;
4794  break;
4795  }
4796  case 8:
4797  {
4798  if (shield.shield8.backrighttopmax != 0 || shield.shield8.backrightbottommax != 0
4799  || shield.shield8.backlefttopmax != 0 || shield.shield8.backleftbottommax
4800  != 0) {
4801  return (shield.shield8.backrighttop+shield.shield8.backrightbottom+shield.shield8.backlefttop
4802  +shield.shield8.backleftbottom)
4803  /(shield.shield8.backrighttopmax+shield.shield8.backrightbottommax+shield.shield8.backlefttopmax
4804  +shield.shield8.backleftbottommax);
4805  }
4806  break;
4807  }
4808  }
4809  return 0;
4810 }
bool Unit::BuyCargo ( const Cargo carg,
float creds 
)

Definition at line 8483 of file unit_generic.cpp.

References _Universe, Universe::netLocked(), Network, Cargo::price, Cargo::quantity, NetServer::sendCredits(), SERVER, and VSServer.

Referenced by BaseComputer::buySelectedCargo(), and BaseComputer::buyUpgrade().

8484 {
8485  if (!CanAddCargo( carg ) || creds < carg.quantity*carg.price)
8486  return false;
8487  AddCargo( carg );
8488  creds -= carg.quantity*carg.price;
8489  if ( Network && !_Universe->netLocked() )
8490  creds = 0;
8491  if ( SERVER && !_Universe->netLocked() )
8492  VSServer->sendCredits( serial, creds );
8493  return true;
8494 }
bool Unit::BuyCargo ( unsigned int  i,
unsigned int  quantity,
Unit buyer,
float creds 
)

Definition at line 8496 of file unit_generic.cpp.

References UnitImages< BOGUS >::cargo, pImage, Cargo::quantity, and RemoveCargo().

8497 {
8498  Cargo soldcargo = seller->pImage->cargo[i];
8499  if (quantity > (unsigned int) soldcargo.quantity)
8500  quantity = soldcargo.quantity;
8501  if (quantity == 0)
8502  return false;
8503  soldcargo.quantity = quantity;
8504  if ( BuyCargo( soldcargo, creds ) ) {
8505  seller->RemoveCargo( i, quantity, false );
8506  return true;
8507  }
8508  return false;
8509 }
bool Unit::BuyCargo ( const std::string &  cargo,
unsigned int  quantity,
Unit buyer,
float creds 
)

Definition at line 8511 of file unit_generic.cpp.

References GetCargo().

8512 {
8513  unsigned int i;
8514  if ( seller->GetCargo( cargo, i ) )
8515  return BuyCargo( i, quantity, seller, creds );
8516  return false;
8517 }
void Unit::calculate_extent ( bool  update_collide_queue)

Definition at line 1359 of file unit_generic.cpp.

References a, corner_max, corner_min, FINITE, LocalPosition(), PLANETPTR, tmpmax(), and Vector.

Referenced by LoadRow(), and Unit().

1360 {
1361  int a;
1362  corner_min = Vector( FLT_MAX, FLT_MAX, FLT_MAX );
1363  corner_max = Vector( -FLT_MAX, -FLT_MAX, -FLT_MAX );
1364  for (a = 0; a < nummesh(); ++a) {
1365  corner_min = corner_min.Min( meshdata[a]->corner_min() );
1366  corner_max = corner_max.Max( meshdata[a]->corner_max() );
1367  } /* have subunits now in table*/
1368  const Unit *un;
1369  for (un_kiter iter = SubUnits.constIterator(); (un = *iter); ++iter) {
1370  corner_min = corner_min.Min( un->LocalPosition().Cast()+un->corner_min );
1371  corner_max = corner_max.Max( un->LocalPosition().Cast()+un->corner_max );
1372  }
1373  if ( corner_min.i == FLT_MAX || corner_max.i == -FLT_MAX || !FINITE( corner_min.i ) || !FINITE( corner_max.i ) ) {
1374  radial_size = 0;
1375  corner_min.Set( 0, 0, 0 );
1376  corner_max.Set( 0, 0, 0 );
1377  } else {
1378  float tmp1 = corner_min.Magnitude();
1379  float tmp2 = corner_max.Magnitude();
1380  radial_size = tmp1 > tmp2 ? tmp1 : tmp2;
1381  }
1382  if ( !isSubUnit() && update_collide_queue && (maxhull > 0) ) {
1383  //only do it in Unit::CollideAll UpdateCollideQueue();
1384  }
1385  if (isUnit() == PLANETPTR)
1387 }
bool Unit::CanAddCargo ( const Cargo carg) const

Definition at line 8265 of file unit_generic.cpp.

References CanAddCargo(), cargoIsUpgrade(), Cargo::quantity, and Cargo::volume.

Referenced by UnitUtil::addCargo(), CanAddCargo(), Beam::Collide(), Enslave(), UnitUtil::incrementCargo(), BaseComputer::isTransactionOK(), and SellCargo().

8266 {
8267  //Always can, in this case (this accounts for some odd precision issues)
8268  if ( (carg.quantity == 0) || (carg.volume == 0) )
8269  return true;
8270  //Test volume availability
8271  bool upgradep = cargoIsUpgrade( carg );
8272  float total_volume = carg.quantity*carg.volume+( upgradep ? getUpgradeVolume() : getCargoVolume() );
8273  if ( total_volume <= ( upgradep ? getEmptyUpgradeVolume() : getEmptyCargoVolume() ) )
8274  return true;
8275  //Hm... not in main unit... perhaps a subunit can take it
8276  const Unit *un;
8277  for (un_kiter i = viewSubUnits(); (un = *i) != NULL; ++i)
8278  if ( un->CanAddCargo( carg ) )
8279  return true;
8280  //Bad luck
8281  return false;
8282 }
int Unit::CanDockWithMe ( Unit dockingunit,
bool  forcedock = false 
)

Definition at line 5937 of file unit_generic.cpp.

References docked, UnitImages< BOGUS >::dockingports, GetTransformation(), insideDock(), InvTransform(), j, pImage, Position(), rSize(), and Transform().

Referenced by Orders::AutoDocking::ApproachState(), CrashForceDock(), Dock(), and GameCockpit::LookupUnitStat().

5938 {
5939  //don't need to check relation: already cleared.
5940 
5941  // If your unit has docking ports then we check if any of our docking
5942  // ports overlap with any of the station's docking ports.
5943  // Otherwise we simply check if our unit overlaps with any of the
5944  // station's docking ports.
5945  for (unsigned int i = 0; i < pImage->dockingports.size(); ++i)
5946  {
5947  if ( !un->pImage->dockingports.empty() )
5948  {
5949  for (unsigned int j = 0; j < un->pImage->dockingports.size(); ++j)
5950  {
5951  if ( insideDock( pImage->dockingports[i],
5953  Transform( un->GetTransformation(),
5954  un->pImage->dockingports[j].GetPosition().Cast() ) ),
5955  un->pImage->dockingports[j].GetRadius() ) )
5956  {
5957  // We cannot dock if we are already docked
5958  if ( ( ( un->docked&(DOCKED_INSIDE|DOCKED) ) == 0 ) && ( !(docked&DOCKED_INSIDE) ) )
5959  return i;
5960  }
5961  }
5962  }
5963  else if ( insideDock( pImage->dockingports[i],
5964  InvTransform( GetTransformation(), un->Position() ),
5965  un->rSize() ) )
5966  {
5967  return i;
5968  }
5969  }
5970  if (force) {
5971  for (unsigned int i = 0; i < pImage->dockingports.size(); ++i)
5972  if (!pImage->dockingports[i].IsOccupied())
5973  return i;
5974  }
5975  return -1;
5976 }
bool Unit::canDowngrade ( const Unit downgradeor,
int  mountoffset,
int  subunitoffset,
double &  percentage,
const Unit downgradelimit,
bool  gen_downgrade_list = true 
)

Definition at line 6660 of file unit_generic.cpp.

Referenced by BaseComputer::SellUpgradeOperation::checkTransaction(), and BaseComputer::SellUpgradeOperation::concludeTransaction().

6666 {
6667  return UpAndDownGrade( downgradeor,
6668  NULL,
6669  mountoffset,
6670  subunitoffset,
6671  false,
6672  true,
6673  false,
6674  true,
6675  percentage,
6676  downgradelimit,
6677  false,
6678  gen_downgrade_list );
6679 }
bool Unit::canUpgrade ( const Unit upgrador,
int  mountoffset,
int  subunitoffset,
int  additive,
bool  force,
double &  percentage,
const Unit templ = NULL,
bool  force_change_on_nothing = false,
bool  gen_downgrade_list = true 
)

Definition at line 6612 of file unit_generic.cpp.

Referenced by BaseComputer::BuyUpgradeOperation::checkTransaction(), BaseComputer::BuyUpgradeOperation::concludeTransaction(), UnitUtil::PercentOperational(), and BaseComputer::BuyUpgradeOperation::selectMount().

6621 {
6622  return UpAndDownGrade( upgrador,
6623  templ,
6624  mountoffset,
6625  subunitoffset,
6626  false,
6627  false,
6628  additive,
6629  force,
6630  percentage,
6631  this,
6632  force_change_on_nothing,
6633  gen_downgrade_list );
6634 }
std::string Unit::cargoSerializer ( const struct XMLType input,
void *  mythis 
)
staticprotected

Definition at line 8753 of file unit_generic.cpp.

References UnitImages< BOGUS >::cargo, CargoToString(), pImage, and SortCargo().

8754 {
8755  Unit *un = (Unit*) mythis;
8756  if (un->pImage->cargo.size() == 0)
8757  return string( "0" );
8758  un->SortCargo();
8759  string retval( "" );
8760  if ( !( un->pImage->cargo.empty() ) ) {
8761  retval = un->pImage->cargo[0].GetCategory()+string( "\">\n" )+CargoToString( un->pImage->cargo[0] );
8762  for (unsigned int kk = 1; kk < un->pImage->cargo.size(); ++kk) {
8763  if (un->pImage->cargo[kk].category != un->pImage->cargo[kk-1].category)
8764  retval += string( "\t\t</Category>\n\t\t<Category file=\"" )+un->pImage->cargo[kk].GetCategory()+string(
8765  "\">\n" );
8766  retval += CargoToString( un->pImage->cargo[kk] );
8767  }
8768  retval += string( "\t\t</Category>\n\t\t<Category file=\"nothing" );
8769  } else {
8770  retval = string( "nothing" );
8771  }
8772  return retval;
8773 }
Vector Unit::ClampAngVel ( const Vector vel)

Definition at line 3376 of file unit_generic.cpp.

References Vector.

Referenced by Orders::FireAt::MatchAngularVelocity(), and Orders::FireAt::MatchVelocity().

3377 {
3378  Vector res( velocity );
3379  if (res.i >= 0) {
3380  if (res.i > computer.max_pitch_down)
3381  res.i = computer.max_pitch_down;
3382  } else if (-res.i > computer.max_pitch_up) {
3383  res.i = -computer.max_pitch_up;
3384  }
3385  if (res.j >= 0) {
3386  if (res.j > computer.max_yaw_left)
3387  res.j = computer.max_yaw_left;
3388  } else if (-res.j > computer.max_yaw_right) {
3389  res.j = -computer.max_yaw_right;
3390  }
3391  if (res.k >= 0) {
3392  if (res.k > computer.max_roll_left)
3393  res.k = computer.max_roll_left;
3394  } else if (-res.k > computer.max_roll_right) {
3395  res.k = -computer.max_roll_right;
3396  }
3397  return res;
3398 }
Vector Unit::ClampThrust ( const Vector thrust,
bool  afterburn 
)

Definition at line 3410 of file unit_generic.cpp.

References copysign(), fprintf, GetFuelUsage(), VegaConfig::getVariable(), ISNAN, XMLSupport::parse_bool(), XMLSupport::parse_float(), SIMULATION_ATOM, Vector, and vs_config.

3411 {
3412  static bool WCfuelhack = XMLSupport::parse_bool( vs_config->getVariable( "physics", "fuel_equals_warp", "false" ) );
3413  static float staticfuelclamp = XMLSupport::parse_float( vs_config->getVariable( "physics", "NoFuelThrust", ".4" ) );
3414  static float staticabfuelclamp = XMLSupport::parse_float( vs_config->getVariable( "physics", "NoFuelAfterburn", ".1" ) );
3415  static bool finegrainedFuelEfficiency =
3416  XMLSupport::parse_bool( vs_config->getVariable( "physics", "VariableFuelConsumption", "false" ) );
3417  if (WCfuelhack) {
3418  if (fuel > warpenergy)
3419  fuel = warpenergy;
3420  if (fuel < warpenergy)
3421  warpenergy = fuel;
3422  }
3423  float instantenergy = afterburnenergy*SIMULATION_ATOM;
3424  if ( (afterburntype == 0) && energy < instantenergy )
3425  afterburn = false;
3426  if ( (afterburntype == 1) && fuel < 0 ) {
3427  fuel = 0;
3428  afterburn = false;
3429  }
3430  if ( (afterburntype == 2) && warpenergy < 0 ) {
3431  warpenergy = 0;
3432  afterburn = false;
3433  }
3434  if (3 == afterburntype) //no afterburner -- we should really make these types an enum :-/
3435  afterburn = false;
3436  Vector Res = amt1;
3437 
3438  float fuelclamp = (fuel <= 0) ? staticfuelclamp : 1;
3439  float abfuelclamp = (fuel <= 0) ? staticabfuelclamp : 1;
3440  if ( fabs( amt1.i ) > fabs( fuelclamp*limits.lateral ) )
3441  Res.i = copysign( fuelclamp*limits.lateral, amt1.i );
3442  if ( fabs( amt1.j ) > fabs( fuelclamp*limits.vertical ) )
3443  Res.j = copysign( fuelclamp*limits.vertical, amt1.j );
3444  float ablimit =
3445  afterburn
3446  ? ( (limits.afterburn-limits.forward)*abfuelclamp+limits.forward*fuelclamp )
3447  : limits.forward;
3448  if (amt1.k > ablimit)
3449  Res.k = ablimit;
3450  if (amt1.k < -limits.retro)
3451  Res.k = -limits.retro;
3452  static float Lithium6constant =
3453  XMLSupport::parse_float( vs_config->getVariable( "physics", "DeuteriumRelativeEfficiency_Lithium", "1" ) );
3454  //1/5,000,000 m/s
3455  static float FMEC_exit_vel_inverse =
3456  XMLSupport::parse_float( vs_config->getVariable( "physics", "FMEC_exit_vel", "0.0000002" ) );
3457  if (afterburntype == 2) {
3458  //Energy-consuming afterburner
3459  //HACK this forces the reaction to be Li-6+Li-6 fusion with efficiency governed by the getFuelUsage function
3460  warpenergy -= afterburnenergy*GetFuelUsage( afterburn )*SIMULATION_ATOM*Res.Magnitude()*FMEC_exit_vel_inverse
3461  /Lithium6constant;
3462  }
3463  if (3 == afterburntype || afterburntype == 1) {
3464  //fuel-burning overdrive - uses afterburner efficiency. In NO_AFTERBURNER case, "afterburn" will always be false, so can reuse code.
3465  //HACK this forces the reaction to be Li-6+Li-6 fusion with efficiency governed by the getFuelUsage function
3466  fuel -=
3467  ( (afterburn
3468  && finegrainedFuelEfficiency) ? afterburnenergy : GetFuelUsage( afterburn ) )*SIMULATION_ATOM*Res.Magnitude()
3469  *FMEC_exit_vel_inverse/Lithium6constant;
3470 #ifndef __APPLE__
3471  if ( ISNAN( fuel ) ) {
3472  fprintf( stderr, "Fuel is NAN A\n" );
3473  fuel = 0;
3474  }
3475 #endif
3476  }
3477  if (afterburntype == 0) {
3478  //fuel-burning afterburner - uses default efficiency - appears to check for available energy? FIXME
3479  //HACK this forces the reaction to be Li-6+Li-6 fusion with efficiency governed by the getFuelUsage function
3480  fuel -= GetFuelUsage( false )*SIMULATION_ATOM*Res.Magnitude()*FMEC_exit_vel_inverse/Lithium6constant;
3481 #ifndef __APPLE__
3482  if ( ISNAN( fuel ) ) {
3483  fprintf( stderr, "Fuel is NAN B\n" );
3484  fuel = 0;
3485  }
3486 #endif
3487  }
3488  if ( (afterburn) && (afterburntype == 0) )
3489  energy -= instantenergy;
3490  if (WCfuelhack) {
3491  if (fuel > warpenergy)
3492  fuel = warpenergy;
3493  if (fuel < warpenergy)
3494  warpenergy = fuel;
3495  }
3496  return Res;
3497 }
Vector Unit::ClampTorque ( const Vector torque)

Definition at line 3284 of file unit_generic.cpp.

References copysign(), fprintf, GetFuelUsage(), VegaConfig::getVariable(), ISNAN, XMLSupport::parse_bool(), XMLSupport::parse_float(), SIMULATION_ATOM, Vector, and vs_config.

3285 {
3286  Vector Res = amt1;
3287  static bool WCfuelhack = XMLSupport::parse_bool( vs_config->getVariable( "physics", "fuel_equals_warp", "false" ) );
3288  if (WCfuelhack)
3289  fuel = warpenergy;
3290  static float staticfuelclamp = XMLSupport::parse_float( vs_config->getVariable( "physics", "NoFuelThrust", ".4" ) );
3291  float fuelclamp = (fuel <= 0) ? staticfuelclamp : 1;
3292  if (fabs( amt1.i ) > fuelclamp*limits.pitch)
3293  Res.i = copysign( fuelclamp*limits.pitch, amt1.i );
3294  if (fabs( amt1.j ) > fuelclamp*limits.yaw)
3295  Res.j = copysign( fuelclamp*limits.yaw, amt1.j );
3296  if (fabs( amt1.k ) > fuelclamp*limits.roll)
3297  Res.k = copysign( fuelclamp*limits.roll, amt1.k );
3298  static float Lithium6constant =
3299  XMLSupport::parse_float( vs_config->getVariable( "physics", "LithiumRelativeEfficiency_Lithium", "1" ) );
3300  //1/5,000,000 m/s
3301  static float FMEC_exit_vel_inverse =
3302  XMLSupport::parse_float( vs_config->getVariable( "physics", "FMEC_exit_vel", "0.0000002" ) );
3303  //HACK this forces the reaction to be Li-6+D fusion with efficiency governed by the getFuelUsage function
3304  fuel -= GetFuelUsage( false )*SIMULATION_ATOM*Res.Magnitude()*FMEC_exit_vel_inverse/Lithium6constant;
3305 #ifndef __APPLE__
3306  if ( ISNAN( fuel ) ) {
3307  fprintf( stderr, "FUEL is NAN\n" );
3308  fuel = 0;
3309  }
3310 #endif
3311  if (fuel < 0) fuel = 0;
3312  if (warpenergy < 0) warpenergy = 0;
3313  if (WCfuelhack) warpenergy = fuel;
3314  return Res;
3315 }
Vector Unit::ClampVelocity ( const Vector velocity,
const bool  afterburn 
)

Definition at line 3343 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_float(), SIMULATION_ATOM, and vs_config.

Referenced by AfterburnerSlide(), AfterburnTurnAway(), AfterburnTurnTowards(), AfterburnTurnTowardsITTS(), AfterburnVeerAndTurnAway(), CloakForScript(), CoastToStop(), FlyStraight(), FlyStraightAfterburner(), KickstopBase(), Orders::FireAt::MatchLinearVelocity(), Orders::FireAt::MatchVelocity(), Orders::AggressiveAI::ProcessCurrentFgDirective(), SheltonSlide(), SkilledABSlide(), Stop(), Takeoff(), TakeoffEveryZig(), TurnAway(), TurnTowards(), TurnTowardsITTS(), and VectorThrustHelper().

3344 {
3345  static float staticfuelclamp = XMLSupport::parse_float( vs_config->getVariable( "physics", "NoFuelThrust", ".4" ) );
3346  static float staticabfuelclamp = XMLSupport::parse_float( vs_config->getVariable( "physics", "NoFuelAfterburn", ".1" ) );
3347  float fuelclamp = (fuel <= 0) ? staticfuelclamp : 1;
3348  float abfuelclamp = ( fuel <= 0 || (energy < afterburnenergy*SIMULATION_ATOM) ) ? staticabfuelclamp : 1;
3349  float limit =
3350  afterburn ? ( abfuelclamp
3351  *( computer.max_ab_speed()
3352  -computer.max_speed() )+( fuelclamp*computer.max_speed() ) ) : fuelclamp*computer.max_speed();
3353  float tmp = velocity.Magnitude();
3354  if ( tmp > fabs( limit ) )
3355  return velocity*(limit/tmp);
3356  return velocity;
3357 }
void Unit::ClearMounts ( )

Definition at line 3359 of file unit_generic.cpp.

References AUDDeleteSound(), weapon_info::BEAM, ClearMounts(), DestroyMount(), and j.

Referenced by ClearMounts().

3360 {
3361  for (unsigned int j = 0; j < mounts.size(); ++j) {
3362  DestroyMount( &mounts[j] );
3363  AUDDeleteSound( mounts[j].sound );
3364  if (mounts[j].ref.gun && mounts[j].type->type == weapon_info::BEAM) {
3365  //hope we're not killin' em twice...they don't go in gunqueue
3366  delete mounts[j].ref.gun;
3367  mounts[j].ref.gun = NULL;
3368  }
3369  }
3370  mounts.clear();
3371  Unit *su;
3372  for (un_iter i = getSubUnits(); (su = *i) != NULL; ++i)
3373  su->ClearMounts();
3374 }
void Unit::Cloak ( bool  cloak)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 5344 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_bool(), and vs_config.

Referenced by CloakFor::Execute(), FireKeyboard::Execute(), and CloakFor::~CloakFor().

5345 {
5347  if (loak) {
5348  static bool warp_energy_for_cloak =
5349  XMLSupport::parse_bool( vs_config->getVariable( "physics", "warp_energy_for_cloak", "true" ) );
5350  if ( pImage->cloakenergy < (warp_energy_for_cloak ? warpenergy : energy) ) {
5352  //short fix
5353  if (cloaking < -1 && pImage->cloakrate != 0) {
5354  //short fix
5355  cloaking = 2147483647;
5356  } else {}
5357  }
5358  } else {
5360  if (cloaking == cloakmin)
5361  ++cloaking;
5362  }
5363 }
float Unit::CloakVisible ( ) const
inline

Definition at line 876 of file unit_generic.h.

References cloaking.

Referenced by Orders::FireAt::Execute(), InRange(), and ChooseTargetClass< numTuple >::ShouldTargetUnit().

877  {
878  if (cloaking < 0) return 1;
879  return ( (float) cloaking )/2147483647;
880  }
bool Unit::Collide ( Unit target)

Definition at line 246 of file unit_collide.cpp.

References _Universe, Universe::activeStarSystem(), ASTEROIDPTR, collideTrees::colTree(), colTrees, DOCKED, DOCKED_INSIDE, DockedOrDocking(), VegaConfig::getVariable(), Inside(), InsideCollideTree(), isDocked(), Universe::isPlayerStarship(), isUnit(), StarSystem::last_collisions, mysqr(), NEBULAPTR, Network, owner, XMLSupport::parse_float(), Position(), QVector, radial_size, reactToCollision(), rSize(), Vector, Velocity, and vs_config.

Referenced by CollideChecker< T, canbebolt >::CheckCollision().

247 {
248  //now first OF ALL make sure they're within bubbles of each other...
249  if ( ( Position()-target->Position() ).MagnitudeSquared() > mysqr( radial_size+target->radial_size ) )
250  return false;
251  clsptr targetisUnit = target->isUnit();
252  clsptr thisisUnit = this->isUnit();
253  static float NEBULA_SPACE_DRAG = XMLSupport::parse_float( vs_config->getVariable( "physics", "nebula_space_drag", "0.01" ) );
254  if (targetisUnit == NEBULAPTR)
255  //why? why not?
256  this->Velocity *= (1-NEBULA_SPACE_DRAG);
257  if ( target == this
258  || ( (targetisUnit != NEBULAPTR
259  && thisisUnit != NEBULAPTR)
260  && ( owner == target || target->owner == this
261  || (owner != NULL
262  && target->owner == owner) ) )
263  || (Network != NULL && _Universe->isPlayerStarship( target ) == NULL && _Universe->isPlayerStarship( this ) == NULL) )
264  return false;
265  if (targetisUnit == ASTEROIDPTR && thisisUnit == ASTEROIDPTR)
266  return false;
267  std::multimap< Unit*, Unit* > *last_collisions = &_Universe->activeStarSystem()->last_collisions;
268  last_collisions->insert( std::pair< Unit*, Unit* > ( this, target ) );
269  //unit v unit? use point sampling?
270  if ( ( this->DockedOrDocking()&(DOCKED_INSIDE|DOCKED) ) || ( target->DockedOrDocking()&(DOCKED_INSIDE|DOCKED) ) )
271  return false;
272  //now do some serious checks
273  Unit *bigger;
274  Unit *smaller;
275  if (radial_size < target->radial_size) {
276  bigger = target;
277  smaller = this;
278  } else {
279  bigger = this;
280  smaller = target;
281  }
282  bool usecoltree = (this->colTrees && target->colTrees)
283  ? this->colTrees->colTree( this, Vector( 0, 0, 0 ) ) && target->colTrees->colTree( this, Vector( 0, 0, 0 ) )
284  : false;
285  if (usecoltree) {
286  QVector bigpos, smallpos;
287  Vector bigNormal, smallNormal;
288  if ( bigger->InsideCollideTree( smaller, bigpos, bigNormal, smallpos, smallNormal ) ) {
289  if ( !bigger->isDocked( smaller ) && !smaller->isDocked( bigger ) )
290  bigger->reactToCollision( smaller, bigpos, bigNormal, smallpos, smallNormal, 10 );
291  else return false;
292  } else {return false; }
293  } else {
294  Vector normal( -1, -1, -1 );
295  float dist = 0.0;
296  if ( bigger->Inside( smaller->Position(), smaller->rSize(), normal, dist ) ) {
297  if ( !bigger->isDocked( smaller ) && !smaller->isDocked( bigger ) )
298  bigger->reactToCollision( smaller, bigger->Position(), normal, smaller->Position(), -normal, dist );
299  else return false;
300  } else {
301  return(false);
302  }
303 
304  }
305  return true;
306 }
void Unit::CollideAll ( )

Definition at line 94 of file unit_collide.cpp.

References CollideMap::CheckCollisions(), StarSystem::collidemap, getStarSystem(), VegaConfig::getVariable(), CollideArray::insert(), is_null(), isSubUnit(), killed, location, NUM_COLLIDE_MAPS, XMLSupport::parse_bool(), UNIT_BOLT, and vs_config.

Referenced by StarSystem::UpdateUnitPhysics().

95 {
96  static bool noUnitCollisions = XMLSupport::parse_bool( vs_config->getVariable( "physics", "no_unit_collisions", "false" ) );
97  if (isSubUnit() || killed || noUnitCollisions)
98  return;
99  for (unsigned int locind = 0; locind < NUM_COLLIDE_MAPS; ++locind)
100  if ( is_null( this->location[locind] ) )
101  this->location[locind] = this->getStarSystem()->collidemap[locind]->insert( Collidable( this ) );
103  cm->CheckCollisions( this, *this->location[Unit::UNIT_BOLT] );
104 }
bool Unit::CombatMode ( )

Definition at line 3338 of file unit_generic.cpp.

Referenced by GameCockpit::LookupUnitStat().

3339 {
3340  return computer.combat_mode;
3341 }
float Unit::computeLockingPercent ( )

Definition at line 51 of file cockpit_generic.cpp.

References Mount::ACTIVE, weapon_info::CAPSHIPHEAVYMISSILE, weapon_info::CAPSHIPLIGHTMISSILE, GetNumMounts(), weapon_info::HEAVYMISSILE, i, weapon_info::LIGHTMISSILE, weapon_info::MEDIUMMISSILE, mounts, weapon_info::PROJECTILE, weapon_info::SPECIAL, and weapon_info::SPECIALMISSILE.

52 {
53  float most = -1024;
54  for (int i = 0; i < GetNumMounts(); i++)
55  if ( mounts[i].type->type == weapon_info::PROJECTILE
56  || ( mounts[i].type->size
59  if (mounts[i].status == Mount::ACTIVE && mounts[i].type->LockTime > 0) {
60  float rat = mounts[i].time_to_lock/mounts[i].type->LockTime;
61  if (rat < .99)
62  if (rat > most)
63  most = rat;
64  }
65  }
66  return (most == -1024) ? 1 : most;
67 }
float Unit::cosAngleFromMountTo ( Unit target,
float distance 
) const

Definition at line 1760 of file unit_generic.cpp.

References Transformation::Compose(), Matrix::getR(), Transformation::position, PositionITTS(), QVector, rSize(), Transformation::to_matrix(), and Vector.

Referenced by UnitWrapper::cosAngleFromMountTo().

1761 {
1762  float retval = -1;
1763  dist = FLT_MAX;
1764  float tmpcos;
1765  Matrix mat;
1766  for (int i = 0; i < GetNumMounts(); ++i) {
1767  float tmpdist = .001;
1768  Transformation finaltrans( mounts[i].GetMountOrientation(), mounts[i].GetMountLocation().Cast() );
1770  finaltrans.to_matrix( mat );
1771  Vector Normal( mat.getR() );
1772 
1773  QVector totarget( targ->PositionITTS( finaltrans.position, cumulative_velocity, mounts[i].type->Speed, false ) );
1774 
1775  tmpcos = Normal.Dot( totarget.Cast() );
1776  tmpdist = totarget.Magnitude();
1777  if (tmpcos > 0) {
1778  tmpcos = tmpdist*tmpdist-tmpcos*tmpcos;
1779  //one over distance perpendicular away from straight ahead times the size...high is good WARNING POTENTIAL DIV/0
1780  tmpcos = targ->rSize()/tmpcos;
1781  } else {
1782  tmpcos /= tmpdist;
1783  }
1784  //UNLIKELY DIV/0
1785  tmpdist /= mounts[i].type->Range;
1786  if (tmpdist < 1 || tmpdist < dist) {
1787  if (tmpcos-tmpdist/2 > retval-dist/2) {
1788  dist = tmpdist;
1789  retval = tmpcos;
1790  }
1791  }
1792  }
1793  return retval;
1794 }
float Unit::cosAngleTo ( Unit target,
float distance,
float  speed = 0.001,
float  range = 0.001,
bool  turnmargin = true 
) const

Definition at line 1727 of file unit_generic.cpp.

References UniverseUtil::cos(), cumulative_transformation_matrix, faction, FINITE, GetDestinations(), Matrix::getP(), PositionITTS(), QVector, rSize(), safeacos(), SIMULATION_ATOM, tmpmax(), and Vector.

Referenced by UnitWrapper::cosAngleToITTS(), and GameCockpit::LookupUnitStat().

1728 {
1730  Normalize( Normal );
1731  QVector totarget( targ->PositionITTS( cumulative_transformation.position, cumulative_velocity, speed, false ) );
1732  totarget = totarget-cumulative_transformation.position;
1733  dist = totarget.Magnitude();
1734 
1735  //Trial code
1736  float turnlimit =
1738  float turnangle = SIMULATION_ATOM
1739  *tmpmax( turnlimit,
1742  float ittsangle = safeacos( Normal.Cast().Dot( totarget.Scale( 1./totarget.Magnitude() ) ) );
1743  QVector edgeLocation = (targ->cumulative_transformation_matrix.getP()*targ->rSize()+totarget);
1744  float radangle = safeacos( edgeLocation.Cast().Scale( 1./edgeLocation.Magnitude() ).Dot( totarget.Normalize() ) );
1745  float rv = ittsangle-radangle-(turnmargin ? turnangle : 0);
1746 
1747  float rsize = targ->rSize()+rSize();
1748  if ( (!targ->GetDestinations().empty() && jump.drive >= 0) || (targ->faction == faction) )
1749  rsize = 0; //HACK so missions work well
1750  if (range != 0)
1751  dist = (dist-rsize)/range;
1752 
1753  else
1754  dist = 0;
1755  if (!FINITE( dist ) || dist < 0)
1756  dist = 0;
1757  return (rv < 0) ? 1 : cos( rv );
1758 }
float Unit::CourseDeviation ( const Vector OriginalCourse,
const Vector FinalCourse 
) const

Definition at line 8775 of file unit_generic.cpp.

Referenced by CommunicatingAI::UpdateContrabandSearch().

8776 {
8777  if (ViewComputerData().max_ab_speed() > .001)
8778  return ( OriginalCourse-(FinalCourse) ).Magnitude()/ViewComputerData().max_ab_speed();
8779  else
8780  return (FinalCourse-OriginalCourse).Magnitude();
8781 }
void Unit::DamageRandSys ( float  dam,
const Vector vec,
float  randum = 1,
float  degrees = 1 
)

Definition at line 4290 of file unit_generic.cpp.

References DestroyMount(), float_to_int(), VegaConfig::getVariable(), M_PI, MAXVDUS, mymax(), mymin, XMLSupport::parse_float(), rand01(), and vs_config.

4291 {
4292  float deg = fabs( 180*atan2( vec.i, vec.k )/M_PI );
4293  randnum = rand01();
4294  static float inv_min_dam = 1.0f-XMLSupport::parse_float( vs_config->getVariable( "physics", "min_damage", ".001" ) );
4295  static float inv_max_dam = 1.0f-XMLSupport::parse_float( vs_config->getVariable( "physics", "min_damage", ".999" ) );
4296  if (dam < inv_max_dam) dam = inv_max_dam;
4297  if (dam > inv_min_dam) dam = inv_min_dam;
4298  degrees = deg;
4299  if (degrees > 180)
4300  degrees = 360-degrees;
4301  if (degrees >= 0 && degrees < 20) {
4302  int which = rand()%(1+UnitImages< void >::NUMGAUGES+MAXVDUS);
4303  pImage->cockpit_damage[which] *= dam;
4304  if (pImage->cockpit_damage[which] < .1)
4305  pImage->cockpit_damage[which] = 0;
4306  //DAMAGE COCKPIT
4307  if (randnum >= .85) {//do 25% damage to a gauge
4308  pImage->cockpit_damage[which] *= .75;
4309  if (pImage->cockpit_damage[which] < .1)
4310  pImage->cockpit_damage[which] = 0;
4311  } else if (randnum >= .775) {
4312  computer.itts = false; //Set the computer to not have an itts
4313  } else if (randnum >= .7) {
4314  // Gradually degrade radar capabilities
4315  typedef Computer::RADARLIM::Capability Capability;
4316  int& capability = computer.radar.capability;
4317  if (capability & Capability::IFF_THREAT_ASSESSMENT)
4318  {
4319  capability &= ~Capability::IFF_THREAT_ASSESSMENT;
4320  }
4321  else if (capability & Capability::IFF_OBJECT_RECOGNITION)
4322  {
4323  capability &= ~Capability::IFF_OBJECT_RECOGNITION;
4324  }
4325  else if (capability & Capability::IFF_FRIEND_FOE)
4326  {
4327  capability &= ~Capability::IFF_FRIEND_FOE;
4328  }
4329  } else if (randnum >= .5) {
4330  //THIS IS NOT YET SUPPORTED IN NETWORKING
4331  computer.target = NULL; //set the target to NULL
4332  } else if (randnum >= .4) {
4333  limits.retro *= dam;
4334  } else if (randnum >= .3275) {
4335  static float maxdam = XMLSupport::parse_float( vs_config->getVariable( "physics", "max_radar_cone_damage", ".9" ) );
4336  computer.radar.maxcone += (1-dam);
4337  if (computer.radar.maxcone > maxdam)
4338  computer.radar.maxcone = maxdam;
4339  } else if (randnum >= .325) {
4340  static float maxdam =
4341  XMLSupport::parse_float( vs_config->getVariable( "physics", "max_radar_lockcone_damage", ".95" ) );
4342  computer.radar.lockcone += (1-dam);
4343  if (computer.radar.lockcone > maxdam)
4344  computer.radar.lockcone = maxdam;
4345  } else if (randnum >= .25) {
4346  static float maxdam =
4347  XMLSupport::parse_float( vs_config->getVariable( "physics", "max_radar_trackcone_damage", ".98" ) );
4348  computer.radar.trackingcone += (1-dam);
4349  if (computer.radar.trackingcone > maxdam)
4350  computer.radar.trackingcone = maxdam;
4351  } else if (randnum >= .175) {
4352  computer.radar.maxrange *= dam;
4353  } else {
4354  int which = rand()%(1+UnitImages< void >::NUMGAUGES+MAXVDUS);
4355  pImage->cockpit_damage[which] *= dam;
4356  if (pImage->cockpit_damage[which] < .1)
4357  pImage->cockpit_damage[which] = 0;
4358  }
4360  return;
4361  }
4362  static float thruster_hit_chance = XMLSupport::parse_float( vs_config->getVariable( "physics", "thruster_hit_chance", ".25" ) );
4363  if (rand01() < thruster_hit_chance) {
4364  //DAMAGE ROLL/YAW/PITCH/THRUST
4365  float orandnum = rand01()*.82+.18;
4366  if (randnum >= .9)
4367  computer.max_pitch_up *= orandnum;
4368  else if (randnum >= .8)
4369  computer.max_yaw_right *= orandnum;
4370  else if (randnum >= .6)
4371  computer.max_yaw_left *= orandnum;
4372  else if (randnum >= .4)
4373  computer.max_pitch_down *= orandnum;
4374  else if (randnum >= .2)
4375  computer.max_roll_right *= orandnum;
4376  else if (randnum >= .18)
4377  computer.max_roll_left *= orandnum;
4378  else if (randnum >= .17)
4379  limits.roll *= dam;
4380  else if (randnum >= .10)
4381  limits.yaw *= dam;
4382  else if (randnum >= .03)
4383  limits.pitch *= dam;
4384  else
4385  limits.lateral *= dam;
4387  return;
4388  }
4389  if (degrees >= 20 && degrees < 35) {
4390  //DAMAGE MOUNT
4391  if (randnum >= .65 && randnum < .9) {
4392  pImage->ecm *= float_to_int( dam );
4393  } else if ( GetNumMounts() ) {
4394  unsigned int whichmount = rand()%GetNumMounts();
4395  if (randnum >= .9)
4396  DestroyMount( &mounts[whichmount] );
4397  else if (mounts[whichmount].ammo > 0 && randnum >= .75)
4398  mounts[whichmount].ammo *= float_to_int( dam );
4399  else if (randnum >= .7)
4400  mounts[whichmount].time_to_lock += ( 100-(100*dam) );
4401  else if (randnum >= .2)
4402  mounts[whichmount].functionality *= dam;
4403  else
4404  mounts[whichmount].maxfunctionality *= dam;
4405  }
4407  return;
4408  }
4409  if (degrees >= 35 && degrees < 60) {
4410  //DAMAGE FUEL
4411  static float fuel_damage_prob = 1.f
4412  -XMLSupport::parse_float( vs_config->getVariable( "physics", "fuel_damage_prob", ".25" ) );
4413  static float warpenergy_damage_prob = fuel_damage_prob
4415  "warpenergy_damage_prob",
4416  "0.05" ) );
4417  static float ab_damage_prob = warpenergy_damage_prob
4418  -XMLSupport::parse_float( vs_config->getVariable( "physics", "ab_damage_prob", ".2" ) );
4419  static float cargovolume_damage_prob = ab_damage_prob
4421  "cargovolume_damage_prob",
4422  ".15" ) );
4423  static float upgradevolume_damage_prob = cargovolume_damage_prob
4425  "upgradevolume_damage_prob",
4426  ".1" ) );
4427  static float cargo_damage_prob = upgradevolume_damage_prob
4428  -XMLSupport::parse_float( vs_config->getVariable( "physics", "cargo_damage_prob", "1" ) );
4429  if (randnum >= fuel_damage_prob) {
4430  fuel *= dam;
4431  } else if (randnum >= warpenergy_damage_prob) {
4432  warpenergy *= dam;
4433  } else if (randnum >= ab_damage_prob) {
4434  this->afterburnenergy += ( (1-dam)*recharge );
4435  } else if (randnum >= cargovolume_damage_prob) {
4436  pImage->CargoVolume *= dam;
4437  } else if (randnum >= upgradevolume_damage_prob) {
4438  pImage->UpgradeVolume *= dam;
4439  } else if (randnum >= cargo_damage_prob) {
4440  //Do something NASTY to the cargo
4441  if (pImage->cargo.size() > 0) {
4442  unsigned int i = 0;
4443  unsigned int cargorand_o = rand();
4444  unsigned int cargorand;
4445  do
4446  cargorand = (cargorand_o+i)%pImage->cargo.size();
4447  while ( (pImage->cargo[cargorand].quantity == 0
4448  || pImage->cargo[cargorand].mission) && (++i) < pImage->cargo.size() );
4449  pImage->cargo[cargorand].quantity *= float_to_int( dam );
4450  }
4451  }
4453  return;
4454  }
4455  if (degrees >= 90 && degrees < 120) {
4456  //DAMAGE Shield
4457  //DAMAGE cloak
4458  if (randnum >= .95) {
4459  this->cloaking = -1;
4461  } else if (randnum >= .78) {
4462  pImage->cloakenergy += ( (1-dam)*recharge );
4464  } else if (randnum >= .7) {
4465  cloakmin += ( rand()%(32000-cloakmin) );
4467  }
4468  switch (shield.number)
4469  {
4470  case 2:
4471  if (randnum >= .25 && randnum < .75)
4472  shield.shield2fb.frontmax *= dam;
4473  else
4474  shield.shield2fb.backmax *= dam;
4475  break;
4476  case 4:
4477  if (randnum >= .5 && randnum < .75)
4478  shield.shield4fbrl.frontmax *= dam;
4479  else if (randnum >= .75)
4480  shield.shield4fbrl.backmax *= dam;
4481  else if (randnum >= .25)
4482  shield.shield4fbrl.leftmax *= dam;
4483  else
4484  shield.shield4fbrl.rightmax *= dam;
4485  break;
4486  case 8:
4487  if (randnum < .125)
4488  shield.shield8.frontrighttopmax *= dam;
4489  else if (randnum < .25)
4490  shield.shield8.backrighttopmax *= dam;
4491  else if (randnum < .375)
4492  shield.shield8.frontlefttopmax *= dam;
4493  else if (randnum < .5)
4494  shield.shield8.backrighttopmax *= dam;
4495  else if (randnum < .625)
4496  shield.shield8.frontrightbottommax *= dam;
4497  else if (randnum < .75)
4498  shield.shield8.backrightbottommax *= dam;
4499  else if (randnum < .875)
4500  shield.shield8.frontleftbottommax *= dam;
4501  else
4502  shield.shield8.backrightbottommax *= dam;
4503  break;
4504  }
4506  return;
4507  }
4508  if (degrees >= 120 && degrees < 150) {
4509  //DAMAGE Reactor
4510  //DAMAGE JUMP
4511  if (randnum >= .9) {
4512  static char max_shield_leak =
4513  (char) mymax( 0.0,
4514  mymin( 100.0, XMLSupport::parse_float( vs_config->getVariable( "physics", "max_shield_leak", "90" ) ) ) );
4515  static char min_shield_leak =
4516  (char) mymax( 0.0,
4517  mymin( 100.0, XMLSupport::parse_float( vs_config->getVariable( "physics", "max_shield_leak", "0" ) ) ) );
4518  char newleak = float_to_int( mymax( min_shield_leak, mymax( max_shield_leak, (char) ( (randnum-.9)*10.0*100.0 ) ) ) );
4519  if (shield.leak < newleak)
4520  shield.leak = newleak;
4521  } else if (randnum >= .7) {
4522  shield.recharge *= dam;
4523  } else if (randnum >= .5) {
4524  static float mindam = XMLSupport::parse_float( vs_config->getVariable( "physics", "min_recharge_shot_damage", "0.5" ) );
4525  if (dam < mindam)
4526  dam = mindam;
4527  this->recharge *= dam;
4528  } else if (randnum >= .2) {
4529  static float mindam =
4530  XMLSupport::parse_float( vs_config->getVariable( "physics", "min_maxenergy_shot_damage", "0.2" ) );
4531  if (dam < mindam)
4532  dam = mindam;
4533  this->maxenergy *= dam;
4534  } else if (pImage->repair_droid > 0) {
4535  pImage->repair_droid--;
4536  }
4537  damages |= JUMP_DAMAGED;
4538  return;
4539  }
4540  if (degrees >= 150 && degrees <= 180) {
4541  //DAMAGE ENGINES
4542  if (randnum >= .8)
4544  else if (randnum >= .6)
4545  computer.max_combat_speed *= dam;
4546  else if (randnum >= .4)
4547  limits.afterburn *= dam;
4548  else if (randnum >= .2)
4549  limits.vertical *= dam;
4550  else
4551  limits.forward *= dam;
4553  return;
4554  }
4555 }
void Unit::DeactivateJumpDrive ( )

Definition at line 627 of file unit_generic.cpp.

Referenced by FlyByKeyboard::Execute(), and jumpReactToCollision().

628 {
629  if (jump.drive >= 0)
630  jump.drive = -1;
631 }
float Unit::DealDamageToHull ( const Vector pnt,
float  Damage 
)

Definition at line 197 of file unit_generic.cpp.

Referenced by GameMissile::reactToCollision(), Missile::reactToCollision(), SuicideKey(), GameMissile::UpdatePhysics2(), and Missile::UpdatePhysics2().

198 {
199  float *nullvar = NULL; //short fix
200  return DealDamageToHullReturnArmor( pnt, Damage, nullvar );
201 }
float Unit::DealDamageToHullReturnArmor ( const Vector pnt,
float  Damage,
float *&  targ 
)

Definition at line 4972 of file unit_generic.cpp.

References _Universe, Universe::AccessCockpit(), apply_float_to_unsigned_int(), Cargo::category, DamagedCategory, DestroyPlayerSystem(), DestroySystem(), UnitCollection::empty(), FINITE, UnitUtil::GetCargo(), Cargo::GetCategory(), FactionUtil::GetFactionIndex(), FactionUtil::GetNeutralFaction(), GetNumMounts(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), Cockpit::godliness, Universe::isPlayerStarship(), loadUnitByCache(), Network, FactionUtil::neutralfac, XMLSupport::parse_bool(), XMLSupport::parse_float(), XMLSupport::parse_int(), VSRandom::rand(), rand01(), SERVER, SubUnits, UNITPTR, vs_config, VS_RAND_MAX, and vsrandom.

4973 {
4974  float percent;
4975 #ifndef ISUCK
4976  if (hull < 0)
4977  return -1;
4978 #endif
4979  if (pnt.i > 0) {
4980  if (pnt.j > 0) {
4981  if (pnt.k > 0)
4982  targ = &armor.frontlefttop;
4983  else
4984  targ = &armor.backlefttop;
4985  } else {
4986  if (pnt.k > 0)
4987  targ = &armor.frontleftbottom;
4988  else
4989  targ = &armor.backleftbottom;
4990  }
4991  } else {
4992  if (pnt.j > 0) {
4993  if (pnt.k > 0)
4994  targ = &armor.frontrighttop;
4995  else
4996  targ = &armor.backrighttop;
4997  } else {
4998  if (pnt.k > 0)
4999  targ = &armor.frontrightbottom;
5000  else
5001  targ = &armor.backrightbottom;
5002  }
5003  }
5004  //short fix
5005  float absdamage = damage >= 0 ? damage : -damage;
5006  float denom = (*targ+hull);
5007  percent = (denom > absdamage && denom != 0) ? absdamage/denom : (denom == 0 ? 0.0 : 1.0);
5008  //ONLY APLY DAMAGE ON SERVER SIDE
5009  if (Network == NULL || SERVER) {
5010  if (percent == -1)
5011  return -1;
5012  static float damage_factor_for_sound =
5013  XMLSupport::parse_float( vs_config->getVariable( "audio", "damage_factor_for_sound", ".001" ) );
5014  bool did_hull_damage = true;
5015  if (absdamage < *targ) {
5016  if ( (*targ)*damage_factor_for_sound <= absdamage )
5017  ArmorDamageSound( pnt );
5018  //short fix
5019  *targ -= apply_float_to_unsigned_int( absdamage );
5020  did_hull_damage = false;
5021  }
5022  static bool system_damage_on_armor =
5023  XMLSupport::parse_bool( vs_config->getVariable( "physics", "system_damage_on_armor", "false" ) );
5024  if (system_damage_on_armor || did_hull_damage) {
5025  if (did_hull_damage) {
5026  absdamage -= *targ;
5027  damage = damage >= 0 ? absdamage : -absdamage;
5028  *targ = 0;
5029  }
5030  if (numCargo() > 0) {
5031  if ( DestroySystem( hull, maxhull, numCargo() ) ) {
5032  int which = rand()%numCargo();
5033  static std::string Restricted_items = vs_config->getVariable( "physics", "indestructable_cargo_items", "" );
5034  //why not downgrade _add GetCargo(which).content.find("add_")!=0&&
5035  if (GetCargo( which ).GetCategory().find( "upgrades/" ) == 0
5036  && GetCargo( which ).GetCategory().find( DamagedCategory ) != 0
5037  && GetCargo( which ).GetContent().find( "mult_" ) != 0
5038  && Restricted_items.find( GetCargo( which ).GetContent() ) == string::npos) {
5039  int lenupgrades = strlen( "upgrades/" );
5040  GetCargo( which ).category = string( DamagedCategory )+GetCargo( which ).GetCategory().substr(
5041  lenupgrades );
5042  static bool NotActuallyDowngrade =
5043  XMLSupport::parse_bool( vs_config->getVariable( "physics", "separate_system_flakiness_component",
5044  "false" ) );
5045  if (!NotActuallyDowngrade) {
5046  const Unit *downgrade =
5047  loadUnitByCache( GetCargo( which ).content, FactionUtil::GetFactionIndex( "upgrades" ) );
5048  if (downgrade) {
5049  if ( 0 == downgrade->GetNumMounts() && downgrade->SubUnits.empty() ) {
5050  double percentage = 0;
5051  this->Downgrade( downgrade, 0, 0, percentage, NULL );
5052  }
5053  }
5054  }
5055  }
5056  }
5057  }
5058  bool isplayer = _Universe->isPlayerStarship( this );
5059  //hull > damage is similar to hull>absdamage|| damage<0
5060  if ( (!isplayer) || _Universe->AccessCockpit()->godliness <= 0 || hull > damage || system_damage_on_armor ) {
5061  static float system_failure =
5062  XMLSupport::parse_float( vs_config->getVariable( "physics", "indiscriminate_system_destruction", ".25" ) );
5063  if ( (!isplayer) && DestroySystem( hull, maxhull, 1 ) )
5064  DamageRandSys( system_failure*rand01()+(1-system_failure)*( 1-(hull > 0 ? absdamage/hull : 1.0f) ), pnt );
5065  else if ( isplayer && DestroyPlayerSystem( hull, maxhull, 1 ) )
5066  DamageRandSys( system_failure*rand01()+(1-system_failure)*( 1-(hull > 0 ? absdamage/hull : 1.0f) ), pnt );
5067  if (did_hull_damage) {
5068  if (damage > 0) {
5069  if (hull*damage_factor_for_sound <= damage)
5070  HullDamageSound( pnt );
5071  //FIXME
5072  hull -= damage;
5073  } else {
5074  //DISABLING WEAPON CODE HERE
5075  static float disabling_constant =
5076  XMLSupport::parse_float( vs_config->getVariable( "physics", "disabling_weapon_constant", "1" ) );
5077  if (hull > 0)
5078  pImage->LifeSupportFunctionality += disabling_constant*damage/hull;
5079  if (pImage->LifeSupportFunctionality < 0) {
5084  }
5085  }
5086  }
5087  } else {
5088  _Universe->AccessCockpit()->godliness -= absdamage;
5089  if ( DestroyPlayerSystem( hull, maxhull, 1 ) )
5090  //get system damage...but live!
5091  DamageRandSys( rand01()*.5+.2, pnt );
5092  }
5093  }
5094  if (hull < 0) {
5096  int upgradesfac = FactionUtil::GetUpgradeFaction();
5097 
5098  static float cargoejectpercent =
5099  XMLSupport::parse_float( vs_config->getVariable( "physics", "eject_cargo_percent", "1" ) );
5100 
5101  static float hulldamtoeject =
5102  XMLSupport::parse_float( vs_config->getVariable( "physics", "hull_damage_to_eject", "100" ) );
5103  if (hull > -hulldamtoeject) {
5104  static float autoejectpercent =
5105  XMLSupport::parse_float( vs_config->getVariable( "physics", "autoeject_percent", ".5" ) );
5106  if (SERVER || Network == NULL) {
5107  if (rand() < (RAND_MAX*autoejectpercent) && isUnit() == UNITPTR) {
5108  static bool player_autoeject =
5109  XMLSupport::parse_bool( vs_config->getVariable( "physics", "player_autoeject", "true" ) );
5110  if ( faction != neutralfac && faction != upgradesfac
5111  && ( player_autoeject || NULL == _Universe->isPlayerStarship( this ) ) )
5112  EjectCargo( (unsigned int) -1 );
5113  }
5114  }
5115  }
5116  static unsigned int max_dump_cargo =
5117  XMLSupport::parse_int( vs_config->getVariable( "physics", "max_dumped_cargo", "15" ) );
5118  unsigned int dumpedcargo = 0;
5119  if (SERVER || Network == NULL) {
5120  if (faction != neutralfac && faction != upgradesfac) {
5121  for (unsigned int i = 0; i < numCargo(); ++i)
5122  if (vsrandom.rand() < (VS_RAND_MAX*cargoejectpercent) && dumpedcargo++ < max_dump_cargo)
5123  EjectCargo( i );
5124  }
5125  }
5126 #ifdef ISUCK
5127  Destroy();
5128 #endif
5129  PrimeOrders();
5130  maxenergy = energy = 0;
5131  Split( rand()%3+1 );
5132 #ifndef ISUCK
5133  Destroy();
5134  return -1;
5135 #endif
5136  }
5137  }
5139  if ( !FINITE( percent ) )
5140  percent = 0;
5141  return percent;
5142 }
float Unit::DealDamageToShield ( const Vector pnt,
float Damage 
)
protectedvirtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 5152 of file unit_generic.cpp.

References UniverseUtil::atan(), FINITE, Network, SERVER, UniverseUtil::sqrt(), and withinShield().

5153 {
5154  float percent = 0;
5155  float *targ = NULL; //short fix
5156  float theta = atan2( pnt.i, pnt.k );
5157  float rho = atan( pnt.j/sqrt( pnt.k*pnt.k+pnt.i*pnt.i ) );
5158  //ONLY APPLY DAMAGES IN NON-NETWORKING OR ON SERVER SIDE
5159  for (int i = 0; i < shield.number; ++i)
5160  if ( withinShield( shield.range[i], theta, rho ) ) {
5161  if (shield.shield.max[i]) {
5162  //comparing with max
5163  float tmp = damage/shield.shield.max[i];
5164  if (tmp > percent) percent = tmp;
5165  }
5166  targ = &shield.shield.cur[i];
5167  if (Network == NULL || SERVER) {
5168  if (damage > *targ) {
5169  damage -= *targ;
5170  *targ = 0;
5171  } else {
5172  //short fix
5173  *targ -= damage;
5174  damage = 0;
5175  break;
5176  }
5177  }
5178  }
5179  if ( !FINITE( percent ) )
5180  percent = 0;
5181  return percent;
5182 }
void Unit::DecreaseWarpEnergy ( bool  insystem,
float  time = 1.0f 
)

Definition at line 3087 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_bool(), XMLSupport::parse_float(), and vs_config.

Referenced by ForceDock(), and StarSystem::ProcessPendingJumps().

3088 {
3089  static float bleedfactor = XMLSupport::parse_float( vs_config->getVariable( "physics", "warpbleed", "20" ) );
3090  static bool WCfuelhack = XMLSupport::parse_bool( vs_config->getVariable( "physics", "fuel_equals_warp", "false" ) );
3091  if (WCfuelhack)
3092  this->warpenergy = this->fuel;
3093  this->warpenergy -= (insys ? jump.insysenergy/bleedfactor : jump.energy)*time;
3094  if (this->warpenergy < 0)
3095  this->warpenergy = 0;
3096  if (WCfuelhack)
3097  this->fuel = this->warpenergy;
3098 }
void Unit::Deselect ( )

Definition at line 1819 of file unit_generic.cpp.

1820 {
1821  selected = false;
1822 }
void Unit::Destroy ( )

Definition at line 5594 of file unit_generic.cpp.

References DestroyMount(), NetServer::sendKill(), SERVER, SIMULATION_ATOM, and VSServer.

5595 {
5596  if (!killed) {
5597  if (hull >= 0)
5598  hull = -1;
5599  for (int beamcount = 0; beamcount < GetNumMounts(); ++beamcount)
5600  DestroyMount( &mounts[beamcount] );
5601  //The server send a kill notification to all concerned clients but not if it is an upgrade
5602  if (SERVER && this->serial) {
5603  VSServer->sendKill( this->serial, this->getStarSystem()->GetZone() );
5604  this->serial = 0;
5605  }
5606  if ( !Explode( false, SIMULATION_ATOM ) )
5607  Kill();
5608  }
5609 }
void Unit::DisableTurretAI ( )

Definition at line 2106 of file unit_generic.cpp.

References aistate, Order::Destroy(), DisableTurretAI(), Order::SetParent(), and UnFire().

Referenced by createObjects(), DisableTurretAI(), FireKeyboard::Execute(), SwitchUnits2(), and Cockpit::Update().

2107 {
2108  turretstatus = 1;
2109  Unit *un;
2110  for (un_iter iter = getSubUnits(); (un = *iter); ++iter) {
2111  if (un->aistate)
2112  un->aistate->Destroy();
2113  un->aistate = new Order; //get 'er ready for enqueueing
2114  un->aistate->SetParent( un );
2115  un->UnFire();
2116  un->DisableTurretAI();
2117  }
2118 }
int Unit::Dock ( Unit unitToDockWith)

Definition at line 5905 of file unit_generic.cpp.

References _Universe, CanDockWithMe(), UnitImages< BOGUS >::clearedunits, NetClient::dockRequest(), Network, pImage, serial, and Universe::whichPlayerStarship().

Referenced by Orders::DockingOps::DockToTarget(), LoadRow(), and TryDock().

5906 {
5907  //Do only if non networking mode or if server (for both Network==NULL)
5908  if (Network == NULL) {
5909  if ( docked&(DOCKED_INSIDE|DOCKED) )
5910  return 0;
5911  std::vector< Unit* >::iterator lookcleared;
5912  if ( ( lookcleared = std::find( utdw->pImage->clearedunits.begin(),
5913  utdw->pImage->clearedunits.end(), this ) ) != utdw->pImage->clearedunits.end() ) {
5914  int whichdockport;
5915  if ( ( whichdockport = utdw->CanDockWithMe( this ) ) != -1 ) {
5916  utdw->pImage->clearedunits.erase( lookcleared );
5917  return ForceDock( utdw, whichdockport );
5918  }
5919  }
5920  return 0;
5921  } else {
5922  //Send a dock request
5923  int playernum = _Universe->whichPlayerStarship( this );
5924  if (playernum >= 0)
5925  Network[playernum].dockRequest( utdw->serial );
5926  }
5927  return 0;
5928 }
char Unit::DockedOrDocking ( ) const
inline

Definition at line 1432 of file unit_generic.h.

References docked.

Referenced by Collide(), UnitUtil::hasDockingUnits(), and StarSystem::JumpTo().

1433  {
1434  return docked;
1435  }
Vector Unit::DownCoordinateLevel ( const Vector v) const

Definition at line 4039 of file unit_generic.cpp.

References TransformNormal().

Referenced by CheckAccessory().

4040 {
4041  Matrix m;
4043  return TransformNormal( m, v );
4044 }
bool Unit::Downgrade ( const Unit downgradeor,
int  mountoffset,
int  subunitoffset,
double &  percentage,
const Unit downgradelimit,
bool  gen_downgrade_list = true 
)

Definition at line 6681 of file unit_generic.cpp.

Referenced by BaseComputer::SellUpgradeOperation::concludeTransaction().

6687 {
6688  return UpAndDownGrade( downgradeor,
6689  NULL,
6690  mountoffset,
6691  subunitoffset,
6692  true,
6693  true,
6694  false,
6695  true,
6696  percentage,
6697  downgradelimit,
6698  false,
6699  gen_downgrade_list );
6700 }
virtual void Unit::Draw ( const Transformation quat = identity_transformation,
const Matrix m = identity_matrix 
)
inlinevirtual
virtual void Unit::DrawNow ( const Matrix m = identity_matrix,
float  lod = 1000000000 
)
inlinevirtual
void Unit::EjectCargo ( unsigned int  index)

Definition at line 7925 of file unit_generic.cpp.

References _Universe, abletodock(), Universe::activeStarSystem(), StarSystem::AddUnit(), aistate, Cargo::content, UnitFactory::createMissile(), UnitFactory::createUnit(), Universe::CurrentCockpit(), StarSystemGent::faction, faction, ForceDock(), UnitUtil::GetCargo(), Cargo::GetCategory(), GetPosition(), getUniqueSerial(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), int, Universe::isPlayerStarship(), Kill(), UniverseUtil::LookupUnitStat(), Cargo::mass, Mass, Cargo::mission, name, Flightgroup::nr_ships, Flightgroup::nr_ships_left, Universe::numPlayers(), UnitUtil::owner(), owner, XMLSupport::parse_bool(), XMLSupport::parse_float(), Position(), PrimeOrders(), q, Cargo::quantity, QVector, randVector(), rSize(), Orders::SelectDockPort(), SERVER, SetAI(), SetAngularVelocity(), SetOrientation(), SetOwner(), Cockpit::SetParent(), SetPosAndCumPos(), SetTurretAI(), SetVelocity(), SwitchUnits(), XMLSupport::tostring(), Transform(), TurretFAW(), VSRandom::uniformInc(), UpgradeInterface(), Vector, Cargo::volume, vs_config, and vsrandom.

Referenced by BaseInterface::Room::Eject::Click(), DropCargo(), DropHalfCargo(), DropOneCargo(), FireKeyboard::Execute(), and Cockpit::Update().

7926 {
7927  Cargo *tmp = NULL;
7928  Cargo ejectedPilot;
7929  Cargo dockedPilot;
7930  string name;
7931  bool isplayer = false;
7932  //if (index==((unsigned int)-1)) { is ejecting normally
7933  //if (index==((unsigned int)-2)) { is ejecting for eject-dock
7934 
7935  Cockpit *cp = NULL;
7936  if ( index == (UINT_MAX-1) ) {
7937  int pilotnum = _Universe->CurrentCockpit();
7938  //this calls the unit's existence, by the way.
7939  name = "return_to_cockpit";
7940  if ( NULL != ( cp = _Universe->isPlayerStarship( this ) ) ) {
7941  isplayer = true;
7942  string playernum = string( "player" )+( (pilotnum == 0) ? string( "" ) : XMLSupport::tostring( pilotnum ) );
7943  }
7944  //we will have to check for this on undock to return to the parent unit!
7945  dockedPilot.content = "return_to_cockpit";
7946  dockedPilot.mass = .1;
7947  dockedPilot.volume = 1;
7948  tmp = &dockedPilot;
7949  }
7950  if (index == UINT_MAX) {
7951  int pilotnum = _Universe->CurrentCockpit();
7952  name = "Pilot";
7953  if ( NULL != ( cp = _Universe->isPlayerStarship( this ) ) ) {
7954  string playernum = string( "player" )+( (pilotnum == 0) ? string( "" ) : XMLSupport::tostring( pilotnum ) );
7955  isplayer = true;
7956  }
7957  ejectedPilot.content = "eject";
7958  ejectedPilot.mass = .1;
7959  ejectedPilot.volume = 1;
7960  tmp = &ejectedPilot;
7961  }
7962  if ( index < numCargo() )
7963  tmp = &GetCargo( index );
7964  static float cargotime = XMLSupport::parse_float( vs_config->getVariable( "physics", "cargo_live_time", "600" ) );
7965  if (tmp) {
7966  string tmpcontent = tmp->content;
7967  if (tmp->mission)
7968  tmpcontent = "Mission_Cargo";
7969  const int ulen = strlen( "upgrades" );
7970  //prevents a number of bad things, incl. impossible speeds and people getting rich on broken stuff
7971  if ( (!tmp->mission) && memcmp( tmp->GetCategory().c_str(), "upgrades", ulen ) == 0 )
7972  tmpcontent = "Space_Salvage";
7973  //this happens if it's a ship
7974  if (tmp->quantity > 0) {
7975  const int sslen = strlen( "starships" );
7976  Unit *cargo = NULL;
7977  if (tmp->GetCategory().length() >= (unsigned int) sslen) {
7978  if ( (!tmp->mission) && memcmp( tmp->GetCategory().c_str(), "starships", sslen ) == 0 ) {
7979  string ans = tmpcontent;
7980  string::size_type blank = ans.find( ".blank" );
7981  if (blank != string::npos)
7982  ans = ans.substr( 0, blank );
7983  Flightgroup *fg = this->getFlightgroup();
7984  int fgsnumber = 0;
7985  if (fg != NULL) {
7986  fgsnumber = fg->nr_ships;
7987  ++(fg->nr_ships);
7988  ++(fg->nr_ships_left);
7989  }
7990  cargo = UnitFactory::createUnit( ans.c_str(), false, faction, "", fg, fgsnumber, NULL, getUniqueSerial() );
7991  cargo->PrimeOrders();
7992  cargo->SetAI( new Orders::AggressiveAI( "default.agg.xml" ) );
7993  cargo->SetTurretAI();
7994  //he's alive!!!!!
7995  }
7996  }
7997  float arot = 0;
7998  static float grot =
7999  XMLSupport::parse_float( vs_config->getVariable( "graphics", "generic_cargo_rotation_speed",
8000  "1" ) )*3.1415926536/180;
8001  if (!cargo) {
8002  static float crot =
8003  XMLSupport::parse_float( vs_config->getVariable( "graphics", "cargo_rotation_speed",
8004  "60" ) )*3.1415926536/180;
8005  static float erot =
8006  XMLSupport::parse_float( vs_config->getVariable( "graphics", "eject_rotation_speed",
8007  "0" ) )*3.1415926536/180;
8008  if (tmpcontent == "eject") {
8009  if (isplayer) {
8010  Flightgroup *fg = this->getFlightgroup();
8011  int fgsnumber = 0;
8012  if (fg != NULL) {
8013  fgsnumber = fg->nr_ships;
8014  ++(fg->nr_ships);
8015  ++(fg->nr_ships_left);
8016  }
8017  cargo = UnitFactory::createUnit( "eject", false, faction, "", fg, fgsnumber, NULL, getUniqueSerial() );
8018  } else {
8019  int fac = FactionUtil::GetUpgradeFaction();
8020  cargo = UnitFactory::createUnit( "eject", false, fac, "", NULL, 0, NULL, getUniqueSerial() );
8021  }
8022  if (owner)
8023  cargo->owner = owner;
8024  else
8025  cargo->owner = this;
8026  arot = erot;
8027  static bool eject_attacks = XMLSupport::parse_bool( vs_config->getVariable( "AI", "eject_attacks", "false" ) );
8028  if (eject_attacks) {
8029  cargo->PrimeOrders();
8030  //generally fraidycat AI
8031  cargo->SetAI( new Orders::AggressiveAI( "default.agg.xml" ) );
8032  }
8033 
8034  //Meat. Docking should happen here
8035  } else if (tmpcontent == "return_to_cockpit") {
8036  if (isplayer) {
8037  Flightgroup *fg = this->getFlightgroup();
8038  int fgsnumber = 0;
8039  if (fg != NULL) {
8040  fgsnumber = fg->nr_ships;
8041  ++(fg->nr_ships);
8042  ++(fg->nr_ships_left);
8043  }
8044  cargo = UnitFactory::createUnit( "return_to_cockpit", false, faction, "", fg, fgsnumber, NULL,
8045  getUniqueSerial() );
8046  if (owner)
8047  cargo->owner = owner;
8048  else
8049  cargo->owner = this;
8050  } else {
8051  int fac = FactionUtil::GetUpgradeFaction();
8052  static float ejectcargotime =
8053  XMLSupport::parse_float( vs_config->getVariable( "physics", "eject_live_time", SERVER ? "200" : "0" ) );
8054  if (cargotime == 0.0) {
8055  cargo = UnitFactory::createUnit( "eject", false, fac, "", NULL, 0, NULL, getUniqueSerial() );
8056  } else {
8057  cargo = UnitFactory::createMissile( "eject",
8058  fac, "",
8059  0,
8060  0,
8061  ejectcargotime,
8062  1,
8063  1,
8064  1,
8065  getUniqueSerial() );
8066  }
8067  }
8068  arot = erot;
8069  cargo->PrimeOrders();
8070  cargo->aistate = NULL;
8071  } else {
8072  string tmpnam = tmpcontent+".cargo";
8073  static std::string nam( "Name" );
8074  float rot = crot;
8075  if (UniverseUtil::LookupUnitStat( tmpnam, "upgrades", nam ).length() == 0) {
8076  tmpnam = "generic_cargo";
8077  rot = grot;
8078  }
8079  int upgrfac = FactionUtil::GetUpgradeFaction();
8080  cargo = UnitFactory::createMissile( tmpnam.c_str(),
8081  upgrfac,
8082  "",
8083  0,
8084  0,
8085  cargotime,
8086  1,
8087  1,
8088  1,
8089  getUniqueSerial()
8090  );
8091  arot = rot;
8092  }
8093  }
8094  if (cargo->name == "LOAD_FAILED") {
8095  cargo->Kill();
8096  cargo = UnitFactory::createMissile( "generic_cargo",
8098  0,
8099  0,
8100  cargotime,
8101  1,
8102  1,
8103  1,
8104  getUniqueSerial() );
8105  arot = grot;
8106  }
8107  Vector rotation( vsrandom.uniformInc( -arot, arot ), vsrandom.uniformInc( -arot, arot ), vsrandom.uniformInc( -arot,
8108  arot ) );
8109  static bool all_rotate_same =
8110  XMLSupport::parse_bool( vs_config->getVariable( "graphics", "cargo_rotates_at_same_speed", "true" ) );
8111  if (all_rotate_same && arot != 0) {
8112  float tmp = rotation.Magnitude();
8113  if (tmp > .001) {
8114  rotation.Scale( 1/tmp );
8115  rotation *= arot;
8116  }
8117  }
8118  if ( 0 && cargo->rSize() >= rSize() ) {
8119  cargo->Kill();
8120  } else {
8121  Vector tmpvel = -Velocity;
8122  if (tmpvel.MagnitudeSquared() < .00001) {
8123  tmpvel = randVector( -rSize(), rSize() ).Cast();
8124  if (tmpvel.MagnitudeSquared() < .00001)
8125  tmpvel = Vector( 1, 1, 1 );
8126  }
8127  tmpvel.Normalize();
8128  if ( (SelectDockPort( this, this ) > -1) ) {
8129  static float eject_cargo_offset =
8130  XMLSupport::parse_float( vs_config->getVariable( "physics", "eject_distance", "20" ) );
8131  QVector loc( Transform( this->GetTransformation(), this->DockingPortLocations()[0].GetPosition().Cast() ) );
8132  //index is always > -1 because it's unsigned. Lets use the correct terms, -1 in Uint is UINT_MAX
8133  loc += tmpvel*1.5*rSize()+randVector( -.5*rSize()+(index == UINT_MAX ? eject_cargo_offset/2 : 0),
8134  .5*rSize()+(index == UINT_MAX ? eject_cargo_offset : 0) );
8135  cargo->SetPosAndCumPos( loc );
8136  Vector p, q, r;
8137  this->GetOrientation( p, q, r );
8138  cargo->SetOrientation( p, q, r );
8139  if (owner)
8140  cargo->owner = owner;
8141  else
8142  cargo->owner = this;
8143  } else {
8144  cargo->SetPosAndCumPos( Position()+tmpvel*1.5*rSize()+randVector( -.5*rSize(), .5*rSize() ) );
8145  cargo->SetAngularVelocity( rotation );
8146  }
8147  static float velmul = XMLSupport::parse_float( vs_config->getVariable( "physics", "eject_cargo_speed", "1" ) );
8148  cargo->SetOwner( this );
8149  cargo->SetVelocity( Velocity*velmul+randVector( -.25, .25 ).Cast() );
8150  cargo->Mass = tmp->mass;
8151  if (name.length() > 0)
8152  cargo->name = name;
8153  else if (tmp)
8154  cargo->name = tmpcontent;
8155  if (cp && _Universe->numPlayers() == 1) {
8156  cargo->SetOwner( NULL );
8157  PrimeOrders();
8158  cargo->SetTurretAI();
8159  cargo->faction = faction;
8160  //changes control to that cockpit
8161  cp->SetParent( cargo, "", "", Position() );
8162  if (tmpcontent == "return_to_cockpit") {
8163  static bool simulate_while_at_base =
8164  XMLSupport::parse_bool( vs_config->getVariable( "physics", "simulate_while_docked", "false" ) );
8165  if ( (simulate_while_at_base) || (_Universe->numPlayers() > 1) )
8166  this->TurretFAW();
8167  //make unit a sitting duck in the mean time
8168  SwitchUnits( NULL, this );
8169  if (owner)
8170  cargo->owner = owner;
8171  else
8172  cargo->owner = this;
8173  PrimeOrders();
8174  cargo->SetOwner( this );
8175  cargo->Position() = this->Position();
8176  cargo->SetPosAndCumPos( this->Position() );
8177  //claims to be docked, stops speed and taking damage etc. but doesn't seem to call the base script
8178  cargo->ForceDock( this, 0 );
8179  abletodock( 3 );
8180  //actually calls the interface, meow. yay!
8181  cargo->UpgradeInterface( this );
8182  if ( (simulate_while_at_base) || (_Universe->numPlayers() > 1) )
8183  this->TurretFAW();
8184  } else {
8185  SwitchUnits( NULL, cargo );
8186  if (owner)
8187  cargo->owner = owner;
8188  else
8189  cargo->owner = this;
8190  } //switching NULL gives "dead" ai to the unit I ejected from, by the way.
8191  }
8192  _Universe->activeStarSystem()->AddUnit( cargo );
8193  if ( (unsigned int) index != ( (unsigned int) -1 ) && (unsigned int) index != ( (unsigned int) -2 ) )
8194  if ( index < pImage->cargo.size() )
8195  RemoveCargo( index, 1, true );
8196  }
8197  }
8198  }
8199 }
void Unit::endElement ( void *  userData,
const XML_Char *  name 
)
static

Definition at line 109 of file unit_xml.cpp.

110 {
111  ( (Unit*) userData )->endElement( name );
112 }
void Unit::endElement ( const std::string &  name)
bool Unit::EndRequestClearance ( Unit dockingunit)

Definition at line 5738 of file unit_generic.cpp.

References UnitImages< BOGUS >::clearedunits, and pImage.

Referenced by DoDockingOps(), and Cockpit::Update().

5739 {
5740  std::vector< Unit* >::iterator lookcleared;
5741  if ( ( lookcleared =
5742  std::find( targ->pImage->clearedunits.begin(), targ->pImage->clearedunits.end(),
5743  this ) ) != targ->pImage->clearedunits.end() ) {
5744  targ->pImage->clearedunits.erase( lookcleared );
5745  return true;
5746  } else {
5747  return false;
5748  }
5749 }
float Unit::EnergyData ( ) const

Definition at line 4735 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_bool(), totalShieldEnergyCapacitance(), and vs_config.

Referenced by GameCockpit::LookupUnitStat(), and Cockpit::Update().

4736 {
4737  static bool max_shield_lowers_capacitance =
4738  XMLSupport::parse_bool( vs_config->getVariable( "physics", "max_shield_lowers_capacitance", "false" ) );
4739  if (max_shield_lowers_capacitance) {
4741  return 0;
4742  return ( (float) energy )/( maxenergy-totalShieldEnergyCapacitance( shield ) );
4743  } else {
4744  return ( (float) energy )/maxenergy;
4745  }
4746 }
float Unit::EnergyRechargeData ( ) const
inline

Definition at line 905 of file unit_generic.h.

References recharge.

Referenced by ZoneMgr::addDamage(), FireKeyboard::Execute(), and showUnitStats().

906  {
907  return recharge;
908  }
void Unit::EnqueueAI ( Order newAI)

Definition at line 1975 of file unit_generic.cpp.

References Order::SetParent().

Referenced by AddUnitToSystem(), createObjects(), UnitUtil::orbit(), Mount::PhysicsAlignedFire(), and SwitchUnits2().

1976 {
1977  newAI->SetParent( this );
1978  if (aistate)
1979  aistate->EnqueueOrder( newAI );
1980  else
1981  aistate = newAI;
1982 }
void Unit::EnqueueAIFirst ( Order newAI)

Definition at line 1984 of file unit_generic.cpp.

References Order::SetParent().

Referenced by ExecuteRequestClearenceKey(), SetTurretAI(), TurretFAW(), and TurretFAW().

1985 {
1986  newAI->SetParent( this );
1987  if (aistate)
1988  aistate->EnqueueOrderFirst( newAI );
1989  else
1990  aistate = newAI;
1991 }
bool Unit::EnqueueLastPythonAIScript ( )

Definition at line 1920 of file unit_generic.cpp.

References PythonClass< SuperClass >::LastPythonClass().

1921 {
1923  if (pyai)
1924  EnqueueAI( pyai );
1925  else if (!aistate)
1926  return false;
1927  return true;
1928 }
void Unit::eraseOrderType ( unsigned int  type)

Definition at line 1902 of file unit_generic.cpp.

1903 {
1904  if (aistate)
1905  aistate->eraseType( type );
1906 }
void Unit::ExecuteAI ( )

Definition at line 1993 of file unit_generic.cpp.

References ExecuteAI(), UnitUtil::getFgSubnumber(), and getFgSubnumber().

Referenced by ExecuteAI(), StarSystem::ExecuteUnitAI(), and StarSystem::UpdateUnitPhysics().

1994 {
1995  if (flightgroup) {
1996  Unit *leader = flightgroup->leader.GetUnit();
1997  //no heirarchy in flight group
1998  if (leader ? (flightgroup->leader_decision > -1) && ( leader->getFgSubnumber() >= getFgSubnumber() ) : true) {
1999  if (!leader)
2001  flightgroup->leader.SetUnit( this );
2002  }
2004  }
2005  if (aistate) aistate->Execute();
2006  if ( !SubUnits.empty() ) {
2007  un_iter iter = getSubUnits();
2008  Unit *un;
2009  while ( (un = *iter) ) {
2010  un->ExecuteAI(); //like dubya
2011  ++iter;
2012  }
2013  }
2014 }
bool Unit::Explode ( bool  draw,
float  timeit 
)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 5583 of file unit_generic.cpp.

Referenced by GameUnit< UnitType >::Explode(), and SelfDestruct().

5584 {
5585  return true;
5586 }
float Unit::ExplodingProgress ( ) const

Definition at line 5588 of file unit_generic.cpp.

References VegaConfig::getVariable(), min(), XMLSupport::parse_float(), and vs_config.

Referenced by Radar::Track::ExplodingProgress().

5589 {
5590  static float debrisTime = XMLSupport::parse_float( vs_config->getVariable( "physics", "debris_time", "500" ) );
5591  return std::min(pImage->timeexplode / debrisTime, 1.0f);
5592 }
float Unit::ExplosionRadius ( )
protectedvirtual

Reimplemented in Missile.

Definition at line 4697 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_float(), and vs_config.

4698 {
4699  static float expsize = XMLSupport::parse_float( vs_config->getVariable( "graphics", "explosion_size", "3" ) );
4700  return expsize*rSize();
4701 }
vector< CargoColor > & Unit::FilterDowngradeList ( std::vector< class CargoColor > &  mylist,
bool  downgrade = true 
)

Definition at line 7784 of file unit_generic.cpp.

References ComputeMinDowngradePercent(), UnitFactory::createUnit(), disable, StarSystemGent::faction, ClassCache< Typ, Key >::getCachedConst(), GetModeFromName(), GetNumMounts(), GetUnitDir(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), name, XMLSupport::parse_bool(), ClassCache< Typ, Key >::setCachedConst(), and vs_config.

Referenced by BaseComputer::loadSellUpgradeControls().

7785 {
7786  const Unit *templ = NULL;
7787  const Unit *downgradelimit = NULL;
7788  static bool staticrem =
7789  XMLSupport::parse_bool( vs_config->getVariable( "general", "remove_impossible_downgrades", "true" ) );
7790  static float MyPercentMin = ComputeMinDowngradePercent();
7791  int upgrfac = FactionUtil::GetUpgradeFaction();
7792  for (unsigned int i = 0; i < mylist.size(); ++i) {
7793  bool removethis = true /*staticrem*/;
7794  int mode = GetModeFromName( mylist[i].cargo.GetContent().c_str() );
7795  if ( mode != 2 || (!downgrade) ) {
7796  const Unit *NewPart = UnitConstCache::getCachedConst( StringIntKey( mylist[i].cargo.GetContent().c_str(), upgrfac ) );
7797  if (!NewPart) {
7799  mylist[i].cargo.GetContent(),
7800  upgrfac ),
7801  UnitFactory::createUnit( mylist[i].cargo.GetContent().c_str(), false,
7802  upgrfac ) );
7803  }
7804  if ( NewPart->name == string( "LOAD_FAILED" ) ) {
7805  const Unit *NewPart =
7806  UnitConstCache::getCachedConst( StringIntKey( mylist[i].cargo.GetContent().c_str(), faction ) );
7807  if (!NewPart) {
7808  NewPart = UnitConstCache::setCachedConst( StringIntKey( mylist[i].cargo.content, faction ),
7809  UnitFactory::createUnit( mylist[i].cargo.GetContent().c_str(),
7810  false, faction ) );
7811  }
7812  }
7813  if ( NewPart->name != string( "LOAD_FAILED" ) ) {
7814  int maxmountcheck = NewPart->GetNumMounts() ? GetNumMounts() : 1;
7815  char *unitdir = GetUnitDir( name.get().c_str() );
7816  string templnam = string( unitdir )+".template";
7817  string limiternam = string( unitdir )+".blank";
7818  if (!downgrade) {
7819  templ = UnitConstCache::getCachedConst( StringIntKey( templnam, faction ) );
7820  if (templ == NULL) {
7821  templ =
7823  faction ),
7824  UnitFactory::createUnit( templnam.c_str(), true, this->faction ) );
7825  }
7826  if ( templ->name == std::string( "LOAD_FAILED" ) )
7827  templ = NULL;
7828  } else {
7829  downgradelimit = UnitConstCache::getCachedConst( StringIntKey( limiternam, faction ) );
7830  if (downgradelimit == NULL) {
7831  downgradelimit = UnitConstCache::setCachedConst( StringIntKey( limiternam,
7832  faction ),
7833  UnitFactory::createUnit( limiternam.c_str(), true,
7834  this->faction ) );
7835  }
7836  if ( downgradelimit->name == std::string( "LOAD_FAILED" ) )
7837  downgradelimit = NULL;
7838  }
7839  free( unitdir );
7840  for (int m = 0; m < maxmountcheck; ++m) {
7841  int s = 0;
7842  for (un_iter ui = getSubUnits(); s == 0 || ( (*ui) != NULL ); ++ui, ++s) {
7843  double percent = 1;
7844  if (downgrade) {
7845  if ( canDowngrade( NewPart, m, s, percent, downgradelimit ) ) {
7846  if (percent > MyPercentMin) {
7847  removethis = false;
7848  break;
7849  }
7850  }
7851  } else if ( canUpgrade( NewPart, m, s, mode, false /*force*/, percent, templ ) ) {
7852  removethis = false;
7853  break;
7854  }
7855  if (*ui == NULL)
7856  break;
7857  }
7858  }
7859  }
7860  } else {
7861  removethis = true;
7862  }
7863  if (removethis) {
7864  if (downgrade && staticrem) {
7865  mylist.erase( mylist.begin()+i );
7866  i--;
7867  } else {
7868  mylist[i].color = disable;
7869  }
7870  }
7871  }
7872  return mylist;
7873 }
vector< CargoColor > & Unit::FilterUpgradeList ( std::vector< class CargoColor > &  mylist)

Definition at line 7875 of file unit_generic.cpp.

References _Universe, Cockpit::credits, disable, VegaConfig::getVariable(), Universe::isPlayerStarship(), XMLSupport::parse_bool(), and vs_config.

Referenced by BaseComputer::loadBuyUpgradeControls().

7876 {
7877  static bool filtercargoprice = XMLSupport::parse_bool( vs_config->getVariable( "cargo", "filter_expensive_cargo", "false" ) );
7878  if (filtercargoprice) {
7879  Cockpit *cp = _Universe->isPlayerStarship( this );
7880  if (cp) {
7881  for (unsigned int i = 0; i < mylist.size(); ++i)
7882  if (mylist[i].cargo.price > cp->credits) {
7883  mylist[i].color = disable;
7884  }
7885  }
7886  }
7887  return FilterDowngradeList( mylist, false );
7888 }
void Unit::Fire ( unsigned int  bitmask,
bool  beams_target_owner = false 
)

Definition at line 1422 of file unit_generic.cpp.

References _Universe, Mount::ACCEPTED, Mount::ACTIVE, Mount::ammo, weapon_info::AUTOTRACKING, Mount::bank, weapon_info::BEAM, NetServer::BroadcastFire(), NetServer::BroadcastUnfire(), Beam::Dissolved(), weapon_info::EnergyRate, ROLES::EVERYTHING_ELSE, Mount::Fire(), ROLES::FIRE_GUNS, ROLES::FIRE_MISSILES, ROLES::FIRE_ONLY_AUTOTRACKERS, Mount::FIRED, NetClient::fireRequest(), getUniqueSerial(), VegaConfig::getVariable(), Mount::REF::gun, index, isMissile(), j, weapon_info::LockTime, Network, Mount::NextMountCloser(), UnitUtil::owner(), XMLSupport::parse_bool(), preEmptiveClientFire(), Mount::PROCESSED, Mount::processed, Beam::Ready(), Mount::ref, Mount::REQUESTED, weapon_info::role_bits, Mount::serial, SERVER, SIMULATION_ATOM, Mount::size, Mount::status, Mount::time_to_lock, weapon_info::type, Mount::type, Mount::UnFire(), vs_config, VSFileSystem::vs_fprintf(), VSServer, and Universe::whichPlayerStarship().

Referenced by Orders::FireAllYouGot::Execute(), Orders::TurretAI::Execute(), FireKeyboard::Execute(), Takeoff(), and TakeoffEveryZig().

1423 {
1424  static bool can_fire_in_spec = XMLSupport::parse_bool( vs_config->getVariable( "physics", "can_fire_in_spec", "false" ) );
1425  static bool can_fire_in_cloak = XMLSupport::parse_bool( vs_config->getVariable( "physics", "can_fire_in_cloak", "false" ) );
1426  static bool verbose_debug = XMLSupport::parse_bool( vs_config->getVariable( "data", "verbose_debug", "false" ) );
1427  if ( (cloaking >= 0 && can_fire_in_cloak == false) || (graphicOptions.InWarp && can_fire_in_spec == false) ) {
1428  UnFire();
1429  return;
1430  }
1431  unsigned int mountssize = mounts.size();
1432  int playernum = _Universe->whichPlayerStarship( this );
1433  vector< int >gunFireRequests;
1434  vector< int >missileFireRequests;
1435  vector< int >serverUnfireRequests;
1436  for (unsigned int counter = 0; counter < mountssize; ++counter) {
1437  unsigned int index = counter;
1438  Mount *i = &mounts[index];
1439  if (i->status != Mount::ACTIVE)
1440  continue;
1441  if (i->bank == true) {
1442  unsigned int best = index;
1443  unsigned int j;
1444  for (j = index+1; j < mountssize; ++j) {
1445  if ( i->NextMountCloser( &mounts[j], this ) ) {
1446  best = j;
1447  if ( SERVER && (mounts[j].processed == Mount::FIRED || mounts[j].processed == Mount::PROCESSED) )
1448  serverUnfireRequests.push_back( j );
1449  i->UnFire();
1450  i = &mounts[j];
1451  } else {
1452  if ( SERVER && (mounts[j].processed == Mount::FIRED || mounts[j].processed == Mount::PROCESSED) )
1453  serverUnfireRequests.push_back( j );
1454  mounts[j].UnFire();
1455  }
1456  if (mounts[j].bank == false) {
1457  ++j;
1458  break;
1459  }
1460  }
1461  counter = j-1; //will increment to the next one
1462  index = best;
1463  }
1464  const bool mis = isMissile( i->type );
1465  const bool locked_on = i->time_to_lock <= 0;
1466  const bool lockable_weapon = i->type->LockTime > 0;
1467  const bool autotracking_gun = (!mis) && 0 != (i->size&weapon_info::AUTOTRACKING) && locked_on;
1468  const bool fire_non_autotrackers = ( 0 == (weapon_type_bitmask&ROLES::FIRE_ONLY_AUTOTRACKERS) );
1469  const bool locked_missile = (mis && locked_on && lockable_weapon);
1470  const bool missile_and_want_to_fire_missiles = ( mis && (weapon_type_bitmask&ROLES::FIRE_MISSILES) );
1471  const bool gun_and_want_to_fire_guns = ( (!mis) && (weapon_type_bitmask&ROLES::FIRE_GUNS) );
1472  if (verbose_debug && missile_and_want_to_fire_missiles && locked_missile)
1473  VSFileSystem::vs_fprintf( stderr, "\n about to fire locked missile \n" );
1474  bool want_to_fire =
1475  (fire_non_autotrackers || autotracking_gun || locked_missile)
1476  && ( (ROLES::EVERYTHING_ELSE&weapon_type_bitmask&i->type->role_bits) || i->type->role_bits == 0 )
1477  && ( (locked_on && missile_and_want_to_fire_missiles) || gun_and_want_to_fire_guns );
1478  if ( (*i).type->type == weapon_info::BEAM ) {
1479  if ( (*i).type->EnergyRate*SIMULATION_ATOM > energy ) {
1480  //On server side send a PACKET TO ALL CLIENT TO NOTIFY UNFIRE
1481  //Including the one who fires to make sure it stops
1482  if ( SERVER && ( (*i).processed == Mount::FIRED || (*i).processed == Mount::PROCESSED ) )
1483  serverUnfireRequests.push_back( index );
1484  //NOT ONLY IN non-networking mode : anyway, the server will tell everyone including us to stop if not already done
1485  (*i).UnFire();
1486  continue;
1487  }
1488  } else
1489  //Only in non-networking mode
1490  if (i->type->EnergyRate > energy) {
1491  if (!want_to_fire) {
1492  if ( SERVER && ( (*i).processed == Mount::FIRED || (*i).processed == Mount::PROCESSED ) )
1493  serverUnfireRequests.push_back( index );
1494  i->UnFire();
1495  }
1496  if (Network == NULL)
1497  continue;
1498  }
1499  if (want_to_fire) {
1500  //If in non-networking mode and mount fire has been accepted or if on server side
1501  if (Network != NULL && (!SERVER) && i->processed != Mount::ACCEPTED && i->processed != Mount::FIRED
1502  && i->processed != Mount::REQUESTED && playernum >= 0 && i->ammo != 0) {
1503  //Request a fire order to the server telling him the serial of the unit and the mount index (nm)
1504  if (mis)
1505  missileFireRequests.push_back( index );
1506  else
1507  gunFireRequests.push_back( index );
1508  //Mark the mount as fire requested
1510  //NETFIXME: REQUESTED was commented out.
1511  }
1512  //projectile and beam weapons should be confirmed by server...not just fired off willy-nilly
1513  if ( Network == NULL || SERVER || i->processed == Mount::ACCEPTED || preEmptiveClientFire( i->type ) ) {
1514  //If we are on server or if the weapon has been accepted for fire we fire
1515  if ( i->Fire( this, owner == NULL ? this : owner, mis, listen_to_owner ) ) {
1516  ObjSerial serid;
1517  if (missile_and_want_to_fire_missiles) {
1518  serid = getUniqueSerial();
1519  i->serial = serid;
1520  } else {
1521  serid = 0;
1522  }
1523  if (SERVER) {
1524  if (serid) {
1525  //One Serial ID per broadcast. Not mush point in optimizing this.
1526  vector< int >indexvec;
1527  indexvec.push_back( index );
1528  VSServer->BroadcastFire( this->serial, indexvec, serid, this->energy,
1529  this->getStarSystem()->GetZone() );
1530  } else {
1531  gunFireRequests.push_back( index );
1532  }
1533  }
1534  //We could only refresh energy on server side or in non-networking mode, on client side it is done with
1535  //info the server sends with ack for fire
1536  //FOR NOW WE TRUST THE CLIENT SINCE THE SERVER CAN REFUSE A FIRE
1537  //if( Network==NULL || SERVER)
1538  if (i->type->type == weapon_info::BEAM) {
1539  if (i->ref.gun)
1540  if ( ( !i->ref.gun->Dissolved() ) || i->ref.gun->Ready() )
1542  } else if ( isMissile( i->type ) ) {
1543  energy -= i->type->EnergyRate;
1544  }
1545  //IF WE REFRESH ENERGY FROM SERVER : Think to send the energy update to the firing client with ACK TO fireRequest
1546  //fire only 1 missile at a time
1547  if (mis) weapon_type_bitmask &= (~ROLES::FIRE_MISSILES);
1548  }
1549  }
1550  }
1551  if ( want_to_fire == false
1553  i->UnFire();
1554  if (SERVER)
1555  serverUnfireRequests.push_back( index );
1556  }
1557  }
1558  if ( !gunFireRequests.empty() ) {
1559  if (SERVER) {
1560  VSServer->BroadcastFire( this->serial, gunFireRequests, 0, this->energy, this->getStarSystem()->GetZone() );
1561  } else {
1562  char mis2 = false;
1563  Network[playernum].fireRequest( this->serial, gunFireRequests, mis2 );
1564  }
1565  }
1566  if ( SERVER && !serverUnfireRequests.empty() )
1567  VSServer->BroadcastUnfire( this->serial, serverUnfireRequests, this->getStarSystem()->GetZone() );
1568  //Client missile requests can be grouped because clients only send a boolean, not a serial.
1569  if ( !SERVER && !missileFireRequests.empty() ) {
1570  char mis2 = true;
1571  Network[playernum].fireRequest( this->serial, missileFireRequests, mis2 );
1572  }
1573 }
void Unit::FireEngines ( const Vector Direction,
float  FuelSpeed,
float  FMass 
)

Fire engine takes a unit vector for direction and how fast the fuel speed and mass coming out are

Definition at line 3206 of file unit_generic.cpp.

References GetElapsedTime(), VegaConfig::getVariable(), XMLSupport::parse_float(), and vs_config.

3207 {
3208  static float fuelpct = XMLSupport::parse_float( vs_config->getVariable( "physics", "FuelUsage", "1" ) );
3209  fuel -= fuelpct*FMass;
3210  if (fuel < 0) {
3211  FMass += fuel;
3212  fuel = 0; //ha ha!
3213  }
3214  NetForce += Direction*( FuelSpeed*FMass/GetElapsedTime() );
3215 }
int Unit::ForceDock ( Unit utdw,
unsigned int  whichdockport 
)

Definition at line 5845 of file unit_generic.cpp.

References _Universe, Universe::AccessCockpit(), active_missions, arrested_list_do_not_dereference, Cockpit::credits, DecreaseWarpEnergy(), docked, UnitImages< BOGUS >::dockedunits, UnitImages< BOGUS >::dockingports, Unit::UnitJump::energy, ExecuteDirector(), faction, UniverseUtil::GetMasterPartList(), Cockpit::GetParent(), VegaConfig::getVariable(), IncreaseWarpEnergy(), UnitUtil::isPlayerStarship(), j, jump, Network, XMLSupport::parse_float(), pImage, SERVER, UpdateMasterPartList(), vs_config, WarpCapData(), and WarpEnergyData().

Referenced by CrashForceDock(), Orders::AutoDocking::DockingState(), DockToSavedBases(), EjectCargo(), and SuperDock().

5846 {
5847  if (utdw->pImage->dockingports.size() <= whichdockport)
5848  return 0;
5849  utdw->pImage->dockingports[whichdockport].Occupy(true);
5850 
5851  utdw->docked |= DOCKING_UNITS;
5852  utdw->pImage->dockedunits.push_back( new DockedUnits( this, whichdockport ) );
5853  //NETFIXME: Broken on server.
5854  if ( (!Network) && (!SERVER) && utdw->pImage->dockingports[whichdockport].IsInside() ) {
5855  RemoveFromSystem();
5856  SetVisible( false );
5857  docked |= DOCKED_INSIDE;
5858  } else {
5859  docked |= DOCKED;
5860  }
5861  pImage->DockedTo.SetUnit( utdw );
5862  computer.set_speed = 0;
5863  if ( this == _Universe->AccessCockpit()->GetParent() )
5864  this->RestoreGodliness();
5866  unsigned int cockpit = UnitUtil::isPlayerStarship( this );
5867 
5868  static float MinimumCapacityToRefuelOnLand =
5869  XMLSupport::parse_float( vs_config->getVariable( "physics", "MinimumWarpCapToRefuelDockeesAutomatically", "0" ) );
5870  float capdata = utdw->WarpCapData();
5871  if ( (capdata >= MinimumCapacityToRefuelOnLand) && ( this->RefillWarpEnergy() ) ) {
5872  if ( cockpit >= 0 && cockpit < _Universe->numPlayers() ) {
5873  static float docking_fee = XMLSupport::parse_float( vs_config->getVariable( "general", "fuel_docking_fee", "0" ) );
5874  _Universe->AccessCockpit( cockpit )->credits -= docking_fee;
5875  }
5876  }
5877  if ( (capdata < MinimumCapacityToRefuelOnLand) && (this->faction == utdw->faction) ) {
5878  if (utdw->WarpEnergyData() > this->WarpEnergyData() && utdw->WarpEnergyData() > this->jump.energy) {
5879  this->IncreaseWarpEnergy( false, this->jump.energy );
5880  utdw->DecreaseWarpEnergy( false, this->jump.energy );
5881  }
5882  if (utdw->WarpEnergyData() < this->WarpEnergyData() && this->WarpEnergyData() > utdw->jump.energy) {
5883  utdw->IncreaseWarpEnergy( false, utdw->jump.energy );
5884  this->DecreaseWarpEnergy( false, utdw->jump.energy );
5885  }
5886  }
5887  if ( cockpit >= 0 && cockpit < _Universe->numPlayers() ) {
5888  static float docking_fee = XMLSupport::parse_float( vs_config->getVariable( "general", "docking_fee", "0" ) );
5889  if (_Universe->AccessCockpit( cockpit )->credits >= docking_fee)
5890  _Universe->AccessCockpit( cockpit )->credits -= docking_fee;
5891  else if (_Universe->AccessCockpit( cockpit )->credits >= 0)
5892  _Universe->AccessCockpit( cockpit )->credits = 0;
5893  }
5894  std::set< Unit* >::iterator arrested = arrested_list_do_not_dereference.find( this );
5895  if ( arrested != arrested_list_do_not_dereference.end() ) {
5896  arrested_list_do_not_dereference.erase( arrested );
5897  //do this for jail time
5898  for (unsigned int j = 0; j < 100000; ++j)
5899  for (unsigned int i = 0; i < active_missions.size(); ++i)
5900  ExecuteDirector();
5901  }
5902  return whichdockport+1;
5903 }
void Unit::FreeDockingPort ( unsigned int  whichport)

Definition at line 5758 of file unit_generic.cpp.

Referenced by BaseInterface::Draw(), and UnDock().

5759 {
5760  if (pImage->dockedunits.size() == 1)
5761  docked &= (~DOCKING_UNITS);
5762  unsigned int whichdock = pImage->dockedunits[i]->whichdock;
5763  pImage->dockingports[whichdock].Occupy(false);
5764  pImage->dockedunits[i]->uc.SetUnit( NULL );
5765  delete pImage->dockedunits[i];
5766  pImage->dockedunits.erase( pImage->dockedunits.begin()+i );
5767 }
float Unit::FShieldData ( ) const

Definition at line 4748 of file unit_generic.cpp.

Referenced by GameCockpit::LookupTargetStat(), GameCockpit::LookupUnitStat(), Orders::AggressiveAI::ProcessLogicItem(), Orders::AggressiveAI::ReCommandWing(), Orders::AggressiveAI::SetParent(), and UpAndDownGrade().

4749 {
4750  switch (shield.number)
4751  {
4752  case 2:
4753  {
4754  if (shield.shield2fb.frontmax != 0)
4755  return shield.shield2fb.front/shield.shield2fb.frontmax;
4756  break;
4757  }
4758  case 4:
4759  {
4760  if (shield.shield4fbrl.frontmax != 0)
4761  return (shield.shield4fbrl.front)/shield.shield4fbrl.frontmax;
4762  break;
4763  }
4764  case 8:
4765  {
4766  if (shield.shield8.frontrighttopmax != 0 || shield.shield8.frontrightbottommax != 0
4767  || shield.shield8.frontlefttopmax != 0 || shield.shield8.frontleftbottommax
4768  != 0) {
4769  return (shield.shield8.frontrighttop+shield.shield8.frontrightbottom+shield.shield8.frontlefttop
4770  +shield.shield8.frontleftbottom)
4771  /(shield.shield8.frontrighttopmax+shield.shield8.frontrightbottommax+shield.shield8.frontlefttopmax
4772  +shield.shield8.frontleftbottommax);
4773  }
4774  break;
4775  }
4776  }
4777  return 0;
4778 }
float Unit::FuelData ( ) const

Definition at line 4721 of file unit_generic.cpp.

Referenced by ZoneMgr::addDamage(), GameCockpit::LookupUnitStat(), Cockpit::SetParent(), and showUnitStats().

4722 {
4723  return fuel;
4724 }
Vector Unit::GetAcceleration ( ) const
inline

Definition at line 1086 of file unit_generic.h.

References SavedAccel.

Referenced by Prediction::InitInterpolation(), ShoveCamBehindUnit(), and ShoveCamBelowUnit().

1087  {
1088  return SavedAccel;
1089  }
const Vector& Unit::GetAngularVelocity ( ) const
inline
const std::string & Unit::getAttackPreference ( ) const

Definition at line 8685 of file unit_generic.cpp.

References ROLES::getRole().

8686 {
8687  return ROLES::getRole( attackPreference() );
8688 }
void Unit::getAverageGunSpeed ( float speed,
float grange,
float mrange 
) const
const Cargo & Unit::GetCargo ( unsigned int  i) const

Definition at line 8323 of file unit_generic.cpp.

8324 {
8325  return pImage->cargo[i];
8326 }
Cargo * Unit::GetCargo ( const std::string &  s,
unsigned int i 
)

Definition at line 8376 of file unit_generic.cpp.

References UnitUtil::GetCargo(), and GetCargo().

8377 {
8378  const Unit *thus = this;
8379  if ( thus->GetCargo( s, i ) )
8380  return &GetCargo( i );
8381  return NULL;
8382 }
const Cargo * Unit::GetCargo ( const std::string &  s,
unsigned int i 
) const

Definition at line 8384 of file unit_generic.cpp.

References Cargo::content, Hashtable< KEY, VALUE, SIZ >::Delete(), Hashtable< KEY, VALUE, SIZ >::Get(), UnitFactory::getMasterPartList(), int, and Hashtable< KEY, VALUE, SIZ >::Put().

8385 {
8386  static Hashtable< string, unsigned int, 2047 >index_cache_table;
8388  if (this == mpl) {
8389  unsigned int *ind = index_cache_table.Get( s );
8390  if (ind) {
8391  if ( *ind < pImage->cargo.size() ) {
8392  Cargo *guess = &pImage->cargo[*ind];
8393  if (guess->content == s) {
8394  i = *ind;
8395  return guess;
8396  }
8397  }
8398  }
8399  Cargo searchfor;
8400  searchfor.content = s;
8401  vector< Cargo >::iterator tmp = std::find( pImage->cargo.begin(), pImage->cargo.end(), searchfor );
8402  if ( tmp == pImage->cargo.end() )
8403  return NULL;
8404  if ( (*tmp).content == searchfor.content ) {
8405  i = ( tmp-pImage->cargo.begin() );
8406  if (this == mpl) {
8407  unsigned int *tmp = new unsigned int;
8408  *tmp = i;
8409  if ( index_cache_table.Get( s ) )
8410  index_cache_table.Delete( s );
8411  //memory leak--should not be reached though, ever
8412  index_cache_table.Put( s, tmp );
8413  }
8414  return &(*tmp);
8415  }
8416  return NULL;
8417  }
8418  Cargo searchfor;
8419  searchfor.content = s;
8420  vector< Cargo >::iterator tmp = ( std::find( pImage->cargo.begin(), pImage->cargo.end(), searchfor ) );
8421  if ( tmp == pImage->cargo.end() )
8422  return NULL;
8423  i = ( tmp-pImage->cargo.begin() );
8424  return &(*tmp);
8425 }
float Unit::getCargoVolume ( void  ) const

Definition at line 8295 of file unit_generic.cpp.

References cargoIsUpgrade().

Referenced by BaseComputer::maxQuantityForPlayer(), and BaseComputer::recalcTitle().

8296 {
8297  float result = 0.0;
8298  for (unsigned int i = 0; i < pImage->cargo.size(); ++i)
8299  if ( !cargoIsUpgrade( pImage->cargo[i] ) )
8300  result += pImage->cargo[i].quantity*pImage->cargo[i].volume;
8301  return result;
8302 }
const std::string & Unit::getCockpit ( ) const

Definition at line 1809 of file unit_generic.cpp.

Referenced by CockpitKeys::Inside(), and SwitchUnits2().

1810 {
1811  return pImage->cockpitImage.get();
1812 }
csOPCODECollider * Unit::getCollideTree ( const Vector scale = Vector( 1,                                                                           1,                                                                           1 ),
const std::vector< struct mesh_polygon > *  = NULL 
)

Definition at line 2045 of file unit_xml.cpp.

References j, meshdata, and nummesh().

Referenced by collideTrees::colTree(), and LoadRow().

2046 {
2047  vector< mesh_polygon >polies;
2048  if (!pol)
2049  for (int j = 0; j < nummesh(); j++)
2050  meshdata[j]->GetPolys( polies );
2051  else
2052  polies = *pol;
2053  if (scale.i != 1 || scale.j != 1 || scale.k != 1) {
2054  for (vector< mesh_polygon >::iterator i = polies.begin(); i != polies.end(); ++i)
2055  for (unsigned int j = 0; j < i->v.size(); ++j) {
2056  i->v[j].i *= scale.i;
2057  i->v[j].j *= scale.j;
2058  i->v[j].k *= scale.k;
2059  }
2060  }
2061  return new csOPCODECollider( polies );
2062 }
const std::string & Unit::getCombatRole ( ) const

Definition at line 8698 of file unit_generic.cpp.

References ROLES::getRole().

8699 {
8700  static unsigned char inert = ROLES::getRole( "INERT" );
8701  unsigned char retA = unitRole();
8702  unsigned char retB = attackPreference();
8703 
8704  //often missions used this to render items either uninteresting or not attacking...so want to prioritize that behavior
8705  if (retA == inert || retB == inert) {
8706  static const std::string INERT("INERT");
8707  return INERT;
8708  }
8709 
8710  return ROLES::getRole( retA );
8711 }
float Unit::GetElasticity ( )

Definition at line 1867 of file unit_generic.cpp.

1868 {
1869  return .5;
1870 }
float Unit::getEmptyCargoVolume ( void  ) const

Definition at line 8285 of file unit_generic.cpp.

Referenced by BaseComputer::maxQuantityForPlayer(), BaseComputer::recalcTitle(), and showUnitStats().

8286 {
8287  return pImage->CargoVolume;
8288 }
float Unit::getEmptyUpgradeVolume ( void  ) const

Definition at line 8290 of file unit_generic.cpp.

Referenced by BaseComputer::recalcTitle(), and showUnitStats().

8291 {
8292  return pImage->UpgradeVolume;
8293 }
const string Unit::getFgID ( )

Definition at line 1575 of file unit_generic.cpp.

References buffer.

1576 {
1577  if (flightgroup != NULL) {
1578  char buffer[32];
1579  sprintf( buffer, "-%d", flightgroup_subnumber );
1580  return flightgroup->name+buffer;
1581  } else {
1582  return fullname;
1583  }
1584 }
const string& Unit::getFilename ( ) const
inline
string Unit::getFullAIDescription ( )

Definition at line 2016 of file unit_generic.cpp.

Referenced by AImissionScript::~AImissionScript().

2017 {
2018  if ( getAIState() )
2019  return getFgID()+":"+getAIState()->createFullOrderDescription( 0 ).c_str();
2020  else
2021  return "no order";
2022 }
float Unit::getHiddenCargoVolume ( void  ) const

Definition at line 8260 of file unit_generic.cpp.

Referenced by CommunicatingAI::UpdateContrabandSearch().

8261 {
8262  return pImage->HiddenCargoVolume;
8263 }
virtual VSSprite* Unit::getHudImage ( ) const
inlinevirtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 541 of file unit_generic.h.

Referenced by buildShipDescription(), and DrawShield().

542  {
543  return NULL;
544  }
float Unit::GetHullPercent ( ) const
inline

Definition at line 1198 of file unit_generic.h.

References hull, and maxhull.

Referenced by GamePlanet::AddFog(), DrawShield(), Orders::AggressiveAI::ProcessLogicItem(), Orders::AggressiveAI::SetParent(), and showUnitStats().

1199  {
1200  return maxhull != 0 ? hull/maxhull : hull;
1201  }
std::string Unit::GetManifest ( unsigned int  i,
Unit scanningUnit,
const Vector original_velocity 
) const

FIXME somehow mangle string

Definition at line 8432 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_float(), and vs_config.

Referenced by CommunicatingAI::UpdateContrabandSearch().

8433 {
8435  string mangled = pImage->cargo[i].content;
8436  static float scramblingmanifest =
8437  XMLSupport::parse_float( vs_config->getVariable( "general", "PercentageSpeedChangeToFaultSearch", ".5" ) );
8438  {
8439  //Keep inside subblock, otherwice MSVC will throw an error while redefining 'i'
8440  bool last = true;
8441  for (string::iterator i = mangled.begin(); i != mangled.end(); ++i) {
8442  if (last)
8443  (*i) = toupper( *i );
8444  last = (*i == ' ' || *i == '_');
8445  }
8446  }
8447  if (CourseDeviation( oldspd, GetVelocity() ) > scramblingmanifest)
8448  for (string::iterator i = mangled.begin(); i != mangled.end(); ++i)
8449  (*i) += (rand()%3-1);
8450  return mangled;
8451 }
float Unit::GetMaxAccelerationInDirectionOf ( const Vector ref,
bool  afterburn 
) const

Definition at line 222 of file unit_generic.cpp.

References Unit::Limits::forward, Unit::Limits::lateral, q, Unit::Limits::retro, Vector, and Unit::Limits::vertical.

223 {
224  Vector p, q, r;
225  GetOrientation( p, q, r );
226  Vector lref( ref*p, ref*q, ref*r );
227  float tp = (lref.i == 0) ? 0 : fabs( Limits().lateral/lref.i );
228  float tq = (lref.j == 0) ? 0 : fabs( Limits().vertical/lref.j );
229  float tr = (lref.k == 0) ? 0 : fabs( ( (lref.k > 0) ? Limits().forward : Limits().retro )/lref.k );
230  float trqmin = (tr < tq) ? tr : tq;
231  float tm = tp < trqmin ? tp : trqmin;
232  return lref.Magnitude()*tm/GetMass();
233 }
double Unit::getMinDis ( const QVector pnt)

Definition at line 5622 of file unit_generic.cpp.

References e, getMinDis(), Transform(), and Vector.

Referenced by getMinDis(), and ClickList::requestShip().

5623 {
5624  float minsofar = 1e+10;
5625  float tmpvar;
5626  int i;
5627  Vector TargetPoint( cumulative_transformation_matrix.getP() );
5628 
5629 #ifdef VARIABLE_LENGTH_PQR
5630  //the scale factor of the current UNIT
5631  float SizeScaleFactor = sqrtf( TargetPoint.Dot( TargetPoint ) );
5632 #endif
5633  for (i = 0; i < nummesh(); ++i) {
5634  TargetPoint = (Transform( cumulative_transformation_matrix, meshdata[i]->Position() ).Cast()-pnt).Cast();
5635  tmpvar = sqrtf( TargetPoint.Dot( TargetPoint ) )-meshdata[i]->rSize()
5636 #ifdef VARIABLE_LENGTH_PQR
5637  *SizeScaleFactor
5638 #endif
5639  ;
5640  if (tmpvar < minsofar)
5641  minsofar = tmpvar;
5642  }
5643  Unit *su;
5644  for (un_kiter ui = viewSubUnits(); (su = *ui); ++ui) {
5645  tmpvar = su->getMinDis( pnt );
5646  if (tmpvar < minsofar)
5647  minsofar = tmpvar;
5648  }
5649  return minsofar;
5650 }
float Unit::GetMoment ( ) const
inline
Nebula* Unit::GetNebula ( ) const
inline

Definition at line 488 of file unit_generic.h.

References nebula.

Referenced by Radar::Sensor::InsideNebula().

489  {
490  return nebula;
491  }
Vector Unit::GetNetAcceleration ( )

Definition at line 212 of file unit_generic.cpp.

References identity_matrix(), InvTransformNormal(), q, and Vector.

213 {
214  Vector p, q, r;
215  GetOrientation( p, q, r );
216  Vector res( NetLocalForce.i*p+NetLocalForce.j*q+NetLocalForce.k*r );
217  if (NetForce.i || NetForce.j || NetForce.k)
219  return res/GetMass();
220 }
void Unit::GetSortedCargoCat ( const std::string &  category,
size_t &  catbegin,
size_t &  catend 
)

Definition at line 8349 of file unit_generic.cpp.

References Cargo::category, BaseUtil::Comp(), and Cargo::content.

Referenced by UniverseUtil::getRandCargo().

8350 {
8351  vector< Cargo >::iterator Begin = pImage->cargo.begin();
8352  vector< Cargo >::iterator End = pImage->cargo.end();
8353  vector< Cargo >::iterator lbound = pImage->cargo.end();
8354  vector< Cargo >::iterator ubound = pImage->cargo.end();
8355 
8356  Cargo beginningtype;
8357  beginningtype.category = cat;
8358  CatCompare Comp;
8359  lbound = std::lower_bound( Begin, End, beginningtype, Comp );
8360  beginningtype.content = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";
8361  ubound = std::upper_bound( Begin, End, beginningtype, Comp );
8362  begin = lbound-Begin;
8363  end = ubound-Begin;
8364 }
StarSystem * Unit::getStarSystem ( )
const StarSystem * Unit::getStarSystem ( ) const

Definition at line 1402 of file unit_generic.cpp.

References _Universe, Universe::activeStarSystem(), Cockpit::activeStarSystem, and Universe::isPlayerStarship().

1403 {
1404  if (activeStarSystem) {
1405  return activeStarSystem;
1406  } else {
1407  Cockpit *cp = _Universe->isPlayerStarship( this );
1408  if (cp)
1409  if (cp->activeStarSystem)
1410  return cp->activeStarSystem;
1411  }
1412  return _Universe->activeStarSystem();
1413 }
un_iter Unit::getSubUnits ( )
enum Unit::tractorHow Unit::getTractorability ( ) const

Definition at line 8932 of file unit_generic.cpp.

References _Universe, VegaConfig::getVariable(), Universe::isPlayerStarship(), and vs_config.

8933 {
8934  static bool tractorability_mask_init = false;
8935  static unsigned char tractorability_mask;
8936  if (!tractorability_mask_init) {
8937  std::string stractorability_mask = vs_config->getVariable( "physics", "PlayerTractorabilityMask", "p" );
8938  if ( !stractorability_mask.empty() ) {
8939  tractorability_mask = tractorImmune;
8940  if (stractorability_mask.find_first_of( "pP" ) != string::npos)
8941  tractorability_mask |= tractorPush;
8942  if (stractorability_mask.find_first_of( "iI" ) != string::npos)
8943  tractorability_mask |= tractorIn;
8944  } else {
8945  tractorability_mask = tractorPush;
8946  }
8947  tractorability_mask_init = true;
8948  }
8949  unsigned char tflags;
8950  if (_Universe->isPlayerStarship( this ) != NULL)
8951  tflags = tractorability_flags&tractorability_mask;
8952 
8953  else
8954  tflags = tractorability_flags;
8955  return (Unit::tractorHow) (tflags);
8956 }
const std::string & Unit::getUnitRole ( ) const

Definition at line 8680 of file unit_generic.cpp.

References ROLES::getRole().

8681 {
8682  return ROLES::getRole( unitRole() );
8683 }
float Unit::getUpgradeVolume ( void  ) const

Definition at line 8304 of file unit_generic.cpp.

References cargoIsUpgrade().

Referenced by BaseComputer::recalcTitle().

8305 {
8306  float result = 0.0;
8307  for (unsigned int i = 0; i < pImage->cargo.size(); ++i)
8308  if ( cargoIsUpgrade( pImage->cargo[i] ) )
8309  result += pImage->cargo[i].quantity*pImage->cargo[i].volume;
8310  return result;
8311 }
Cockpit * Unit::GetVelocityDifficultyMult ( float difficulty) const

Definition at line 3176 of file unit_generic.cpp.

References _Universe, game_data_t::difficulty, UniverseUtil::exp(), g_game, VegaConfig::getVariable(), Universe::isPlayerStarship(), XMLSupport::parse_float(), and vs_config.

Referenced by DistanceWarrantsTravelTo(), DistanceWarrantsWarpTo(), and UnitWrapper::GetVelocityDifficultyMult().

3177 {
3178  difficulty = 1;
3179  Cockpit *player_cockpit = _Universe->isPlayerStarship( this );
3180  if ( (player_cockpit) == NULL ) {
3181  static float exp = XMLSupport::parse_float( vs_config->getVariable( "physics", "difficulty_speed_exponent", ".2" ) );
3182  difficulty = pow( g_game.difficulty, exp );
3183  }
3184  return player_cockpit;
3185 }
float Unit::GetWarpEnergy ( ) const
inline

Definition at line 922 of file unit_generic.h.

References warpenergy.

Referenced by GameCockpit::LookupUnitStat(), showUnitStats(), and TurnJumpOKLightOn().

923  {
924  return warpenergy;
925  }
Vector Unit::GetWarpVelocity ( ) const

Definition at line 169 of file unit_generic.cpp.

References cumulative_velocity, speed, and Vector.

Referenced by DistanceWarrantsWarpTo(), Radar::SphereDisplay::DrawBackground(), InsideCollideTree(), GameCockpit::LookupUnitStat(), rayCollide(), ShoveCamBehindUnit(), ShoveCamBelowUnit(), and WarpMatrixForCollisions().

170 {
171  Vector VelocityRef( 0, 0, 0 );
172  {
173  Unit *vr = const_cast< UnitContainer* > (&computer.velocity_ref)->GetUnit();
174  if (vr)
175  VelocityRef = vr->cumulative_velocity;
176  }
177 
178  //return(cumulative_velocity*graphicOptions.WarpFieldStrength);
179  Vector vel = cumulative_velocity-VelocityRef;
180  float speed = vel.Magnitude();
181  //return vel*graphicOptions.WarpFieldStrength;
182  if (speed > 0) {
183  Vector veldir = vel*(1./speed);
185  float ang = facing.Dot( veldir );
186  float warpfield = graphicOptions.WarpFieldStrength;
187  if (ang < 0) warpfield = 1./warpfield;
188  return ang*facing*speed*(warpfield-1)+vel+VelocityRef;
189  } else {return VelocityRef; }
190 }
bool Unit::hasPendingClearanceRequests ( ) const

Definition at line 5983 of file unit_generic.cpp.

Referenced by UnitUtil::hasDockingUnits().

5984 {
5985  return pImage && (pImage->clearedunits.size() > 0);
5986 }
virtual void Unit::HullDamageSound ( const Vector pnt)
inlinevirtual
void Unit::ImportPartList ( const std::string &  category,
float  price,
float  pricedev,
float  quantity,
float  quantdev 
)

Definition at line 8525 of file unit_generic.cpp.

References c, Cargo::category, float, float_to_int(), UnitUtil::GetCargo(), GetCargo(), GetUnitMasterPartList(), VegaConfig::getVariable(), j, numCargo(), XMLSupport::parse_float(), Cargo::price, Cargo::quantity, and vs_config.

Referenced by ImportCargo().

8526 {
8527  unsigned int numcarg = GetUnitMasterPartList().numCargo();
8528  float minprice = FLT_MAX;
8529  float maxprice = 0;
8530  for (unsigned int j = 0; j < numcarg; ++j)
8531  if (GetUnitMasterPartList().GetCargo( j ).category == category) {
8532  float price = GetUnitMasterPartList().GetCargo( j ).price;
8533  if (price < minprice)
8534  minprice = price;
8535  else if (price > maxprice)
8536  maxprice = price;
8537  }
8538  for (unsigned int i = 0; i < numcarg; ++i) {
8540  if (c.category == category) {
8541  static float aveweight =
8542  fabs( XMLSupport::parse_float( vs_config->getVariable( "cargo", "price_recenter_factor", "0" ) ) );
8543  c.quantity = float_to_int( quantity-quantdev );
8544  float baseprice = c.price;
8545  c.price *= price-pricedev;
8546 
8547  //stupid way
8548  c.quantity += float_to_int( (quantdev*2+1)*( (double) rand() )/( ( (double) RAND_MAX )+1 ) );
8549  c.price += pricedev*2*( (float) rand() )/RAND_MAX;
8550  c.price = fabs( c.price );
8551  c.price = ( c.price+(baseprice*aveweight) )/(aveweight+1);
8552  if (c.quantity <= 0) {
8553  c.quantity = 0;
8554  }
8555  //quantity more than zero
8556  else if (maxprice > minprice+.01) {
8557  float renormprice = (baseprice-minprice)/(maxprice-minprice);
8558  static float maxpricequantadj =
8559  XMLSupport::parse_float( vs_config->getVariable( "cargo", "max_price_quant_adj", "5" ) );
8560  static float minpricequantadj =
8561  XMLSupport::parse_float( vs_config->getVariable( "cargo", "min_price_quant_adj", "1" ) );
8562  static float powah = XMLSupport::parse_float( vs_config->getVariable( "cargo", "price_quant_adj_power", "1" ) );
8563  renormprice = pow( renormprice, powah );
8564  renormprice *= (maxpricequantadj-minpricequantadj);
8565  renormprice += 1;
8566  if (renormprice > .001) {
8567  c.quantity /= float_to_int( renormprice );
8568  if (c.quantity < 1)
8569  c.quantity = 1;
8570  }
8571  }
8572  static float minprice = XMLSupport::parse_float( vs_config->getVariable( "cargo", "min_cargo_price", "0.01" ) );
8573  if (c.price < minprice)
8574  c.price = minprice;
8575  c.quantity = abs( c.quantity );
8576  AddCargo( c, false );
8577  }
8578  }
8579 }
bool Unit::InCorrectStarSystem ( StarSystem active)

Definition at line 126 of file unit_generic.cpp.

Referenced by Orders::AggressiveAI::ProcessCurrentFgDirective().

127 {
128  return active == activeStarSystem;
129 }
void Unit::IncreaseWarpEnergy ( bool  insystem,
float  time = 1.0f 
)

Definition at line 3100 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_bool(), and vs_config.

Referenced by ForceDock().

3101 {
3102  static bool WCfuelhack = XMLSupport::parse_bool( vs_config->getVariable( "physics", "fuel_equals_warp", "false" ) );
3103  if (WCfuelhack)
3104  this->warpenergy = this->fuel;
3105  this->warpenergy += (insys ? jump.insysenergy : jump.energy)*time;
3106  if (this->warpenergy > this->maxwarpenergy)
3107  this->warpenergy = this->maxwarpenergy;
3108  if (WCfuelhack)
3109  this->fuel = this->warpenergy;
3110 }
void Unit::Init ( )

Definition at line 965 of file unit_generic.cpp.

References activeStarSystem, Unit::Limits::afterburn, afterburnenergy, aistate, AngularVelocity, UnitSounds::armor, armor, attack_preference, autopilotactive, Armor::backlefttop, Armor::backrighttop, Unit::Computer::RADARLIM::capability, capship_size, UnitImages< BOGUS >::CargoVolume, UnitSounds::cloak, UnitImages< BOGUS >::cloakenergy, UnitImages< BOGUS >::cloakglass, cloaking, cloakmin, UnitImages< BOGUS >::cloakrate, UnitImages< BOGUS >::cockpit_damage, colTrees, Unit::Computer::combat_mode, UnitImages< BOGUS >::CommFunctionality, UnitImages< BOGUS >::CommFunctionalityMax, computer, corner_max, corner_min, cumulative_transformation, cumulative_transformation_matrix, cumulative_velocity, cur_sim_queue_slot, curr_physical_state, Unit::UnitJump::damage, damages, DEFAULTVIS, Unit::UnitJump::delay, do_subunit_scheduling, docked, Unit::UnitJump::drive, UnitImages< BOGUS >::ecm, Unit::Computer::ecmactive, Shield::efficiency, Unit::UnitJump::energy, energy, UnitSounds::engine, UnitImages< BOGUS >::equipment_volume, UnitSounds::explode, Unit::graphic_options::FaceCamera, UnitImages< BOGUS >::fireControlFunctionality, UnitImages< BOGUS >::fireControlFunctionalityMax, flightgroup, flightgroup_subnumber, float, UnitImages< BOGUS >::forcejump, Unit::Limits::forward, Armor::frontlefttop, Armor::frontrightbottom, Armor::frontrighttop, fuel, ROLES::getRole(), VegaConfig::getVariable(), graphicOptions, HeatSink, UnitImages< BOGUS >::HiddenCargoVolume, UnitSounds::hull, hull, Identity(), identity_transformation(), Unit::Computer::RADARLIM::Capability::IFF_NONE, inertialmode, Unit::UnitJump::insysenergy, invisible, Unit::Computer::itts, UnitSounds::jump, jump, killed, last_processed_sqs, Unit::Limits::lateral, Shield::leak, UnitImages< BOGUS >::LifeSupportFunctionality, UnitImages< BOGUS >::LifeSupportFunctionalityMax, Unit::Limits::limitmin, limits, location, Unit::Computer::RADARLIM::lockcone, Unit::Computer::RADARLIM::locked, Mass, Unit::Computer::max_combat_ab_speed, Unit::Computer::max_combat_speed, Unit::Computer::max_pitch_down, Unit::Computer::max_pitch_up, Unit::Computer::max_roll_left, Unit::Computer::max_roll_right, Unit::Computer::max_yaw_left, Unit::Computer::max_yaw_right, Unit::Computer::RADARLIM::maxcone, maxenergy, maxhull, Unit::Computer::RADARLIM::maxrange, MAXVDUS, maxwarpenergy, Unit::Computer::RADARLIM::mintargetsize, Momentofinertia, Unit::Computer::NavPoint, nebula, NetForce, NetLocalForce, NetLocalTorque, NetTorque, Network, networked, UnitImages< BOGUS >::next_repair_cargo, UnitImages< BOGUS >::next_repair_time, NO_DAMAGE, NOT_DOCKED, NUM_COLLIDE_MAPS, Shield::number, owner, XMLSupport::parse_float(), UnitImages< BOGUS >::pExplosion, UnitImages< BOGUS >::pHudImage, pImage, Unit::Limits::pitch, predicted_priority, prev_physical_state, Unit::Computer::radar, Shield::recharge, recharge, Unit::graphic_options::RecurseIntoSubUnitsOnCollision, UnitImages< BOGUS >::repair_droid, resolveforces, Unit::Limits::retro, Unit::Limits::roll, schedule_priority, scheduleDefault, selected, set_null(), Unit::Computer::set_speed, UnitContainer::SetUnit(), UnitSounds::shield, shield, Shield::shield2fb, shieldtight, sim_atom_multiplier, SIM_QUEUE_SIZE, Unit::Computer::slide_end, Unit::Computer::slide_start, sound, UnitImages< BOGUS >::SPECDriveFunctionality, UnitImages< BOGUS >::SPECDriveFunctionalityMax, specInterdiction, Unit::Limits::structurelimits, Unit::graphic_options::SubUnit, Unit::Computer::threat, Unit::Computer::threatlevel, UnitImages< BOGUS >::timeexplode, Unit::Computer::RADARLIM::trackingactive, Unit::Computer::RADARLIM::trackingcone, turretstatus, ucref, UncheckUnit(), unit_role, UnitImages< BOGUS >::unitwriter, UnitImages< BOGUS >::UpgradeVolume, Vector, Velocity, VelocityReference(), Unit::Limits::vertical, vs_config, Unit::UnitJump::warpDriveRating, warpenergy, Unit::graphic_options::WarpFieldStrength, xml, and Unit::Limits::yaw.

Referenced by Asteroid::Asteroid(), GameAsteroid::GameAsteroid(), GameUnit< UnitType >::GameUnit(), Planet::InitPlanet(), and Unit().

966 {
968  for (unsigned int locind = 0; locind < NUM_COLLIDE_MAPS; ++locind)
969  set_null( location[locind] );
970  specInterdiction = 0;
972  predicted_priority = 1;
974  last_processed_sqs = 0;
975  do_subunit_scheduling = false;
976  if (Network == NULL)
977  this->networked = 0;
978  else
979  this->networked = 1;
980  damages = NO_DAMAGE;
981 
984  inertialmode = false;
985  turretstatus = 0;
986  autopilotactive = false;
987  this->unit_role = this->attack_preference = ROLES::getRole( "INERT" );
988  this->computer.combat_mode = true;
989 #ifdef CONTAINER_DEBUG
990  UncheckUnit( this );
991 #endif
992  static float capsize = XMLSupport::parse_float( vs_config->getVariable( "physics", "capship_size", "500" ) );
993 
994  capship_size = capsize;
995  activeStarSystem = NULL;
996  xml = NULL;
997  docked = NOT_DOCKED;
999  jump.energy = 100;
1000  static float insys_jump_cost = XMLSupport::parse_float( vs_config->getVariable( "physics", "insystem_jump_cost", ".1" ) );
1001  jump.insysenergy = insys_jump_cost*jump.energy;
1002  jump.delay = 5;
1003  jump.damage = 0;
1004  jump.warpDriveRating = 0;
1005  graphicOptions.FaceCamera = false;
1006  jump.drive = -2; //disabled
1007  afterburnenergy = 0;
1008  nebula = NULL;
1009  limits.structurelimits = Vector( 0, 0, 1 );
1010  limits.limitmin = -1;
1011  cloaking = -1;
1012  pImage->repair_droid = 0;
1013  pImage->next_repair_time = -FLT_MAX;
1014  pImage->next_repair_cargo = ~0;
1015  pImage->ecm = 0;
1016  pImage->cloakglass = false;
1017  pImage->CargoVolume = 0;
1018  pImage->UpgradeVolume = 0;
1019  this->HeatSink = 0;
1020 
1021  pImage->unitwriter = NULL;
1022  cloakmin = pImage->cloakglass ? 1 : 0;
1023  pImage->equipment_volume = 0;
1025  pImage->cloakrate = 100;
1026  pImage->cloakenergy = 0;
1027  pImage->forcejump = false;
1028  sound->engine = -1;
1029  sound->armor = -1;
1030  sound->shield = -1;
1031  sound->hull = -1;
1032  sound->explode = -1;
1033  sound->cloak = -1;
1034  sound->jump = -1;
1039  pImage->CommFunctionality = 1.0f;
1040  pImage->CommFunctionalityMax = 1.0f;
1043 
1044  pImage->pHudImage = NULL;
1045 
1046  //Freedom for the masses!!!! //you'll have to justify why setting to this is better.
1047  owner = NULL;
1048  faction = 0;
1049  resolveforces = true;
1050  colTrees = NULL;
1052  corner_min.Set( FLT_MAX, FLT_MAX, FLT_MAX );
1053  corner_max.Set( -FLT_MAX, -FLT_MAX, -FLT_MAX );
1054 
1055  //BUCO! Must add shield tightness back into units.csv for great justice.
1056  static float default_shield_tightness =
1057  XMLSupport::parse_float( vs_config->getVariable( "physics", "default_shield_tightness", "0" ) );
1058  //was 0 // sphere mesh by default, but let's decide on it
1059  shieldtight =
1060  default_shield_tightness;
1061  energy = maxenergy = 1;
1062  warpenergy =
1063  0;
1064  maxwarpenergy =
1065  0;
1066  recharge = 1;
1067  shield.recharge =
1068  shield.leak = 0;
1069  this->shield.efficiency = 1;
1070  shield.shield2fb.front = shield.shield2fb.back = shield.shield2fb.frontmax = shield.shield2fb.backmax =
1074  armor.backlefttop =
1076  armor
1077  .
1078  backrightbottom
1079  =
1080  armor.
1081  frontleftbottom
1082  =
1083  armor
1084  .
1085  backleftbottom
1086  =
1087  0;
1088  hull = 1; //10;
1089  maxhull = 1; //10;
1090  shield.number =
1091  0;
1092 
1093  pImage->pExplosion = NULL;
1094  pImage->timeexplode = 0;
1095  killed = false;
1096  ucref = 0;
1097  aistate = NULL;
1101  Mass = .01;
1102  fuel = 000;
1103 
1104  static Vector myang( XMLSupport::parse_float( vs_config->getVariable( "general", "pitch", "0" ) ), XMLSupport::parse_float(
1105  vs_config->getVariable( "general", "yaw", "0" ) ), XMLSupport::parse_float( vs_config->getVariable(
1106  "general",
1107  "roll",
1108  "0" ) ) );
1109  static float rr = XMLSupport::parse_float( vs_config->getVariable( "graphics", "hud", "radarRange", "20000" ) );
1110  static float minTrackingNum = XMLSupport::parse_float( vs_config->getVariable( "physics",
1111  "autotracking",
1112  ".93" ) ); //DO NOT CHANGE see unit_customize.cpp
1113 
1114  //DO NOT CHANGE see unit_customize.cpp
1115  static float lc = XMLSupport::parse_float( vs_config->getVariable( "physics", "lock_cone", ".8" ) );
1116 
1117  Momentofinertia = .01;
1118  AngularVelocity = myang;
1119  cumulative_velocity = Velocity = Vector( 0, 0, 0 );
1120 
1121  NetTorque = NetLocalTorque = Vector( 0, 0, 0 );
1122  NetForce = Vector( 0, 0, 0 );
1123  NetLocalForce = Vector( 0, 0, 0 );
1124 
1125  selected = false;
1126 
1127  limits.yaw = 2.55;
1128  limits.pitch = 2.55;
1129  limits.roll = 2.55;
1130 
1131  limits.lateral = 2;
1132  limits.vertical = 8;
1133  limits.forward = 2;
1134  limits.afterburn = 5;
1135  limits.retro = 2;
1136  VelocityReference( NULL );
1137  computer.threat.SetUnit( NULL );
1138  computer.threatlevel = 0;
1140  computer.set_speed = 0;
1144 
1147  computer.NavPoint = Vector( 0, 0, 0 );
1148  computer.itts = false;
1149  computer.radar.maxrange = rr;
1150  computer.radar.locked = false;
1151  computer.radar.maxcone = -1;
1152  computer.radar.trackingcone = minTrackingNum;
1154  computer.radar.lockcone = lc;
1157  computer.ecmactive = true;
1158 
1159  flightgroup = NULL;
1161  //No cockpit reference here
1162  if (!pImage->cockpit_damage) {
1163  unsigned int numg = (1+MAXVDUS+UnitImages< void >::NUMGAUGES)*2;
1164  pImage->cockpit_damage = (float*) malloc( (numg)*sizeof (float) );
1165  for (unsigned int damageiterator = 0; damageiterator < numg; ++damageiterator)
1166  pImage->cockpit_damage[damageiterator] = 1;
1167  }
1168 }
void Unit::Init ( const char *  filename,
bool  SubUnit,
int  faction,
std::string  customizedUnit = std::string(""),
Flightgroup flightgroup = NULL,
int  fg_subnumber = 0,
std::string *  netxml = NULL 
)
bool Unit::InRange ( Unit target,
bool  cone = true,
bool  cap = true 
) const
inline
bool Unit::InRange ( Unit target,
double &  mm,
bool  cone,
bool  cap,
bool  lock 
) const

Definition at line 245 of file unit_generic.cpp.

References capship_size, CloakVisible(), getFlightgroup(), isUnit(), Magnitude(), Flightgroup::name, PLANETPTR, Position(), QVector, rSize(), and Vector.

246 {
247  if (this == target || target->CloakVisible() < .8)
248  return false;
249  if (cone && computer.radar.maxcone > -.98) {
250  QVector delta( target->Position()-Position() );
251  mm = delta.Magnitude();
252  if ( (!lock) || ( !(TargetLocked() && computer.target == target) ) ) {
253  double tempmm = mm-target->rSize();
254  if (tempmm > 0.0001)
255  if ( (ToLocalCoordinates( Vector( delta.i, delta.j, delta.k ) ).k/tempmm) < computer.radar.maxcone && cone )
256  return false;
257  }
258  } else {
259  mm = ( target->Position()-Position() ).Magnitude();
260  }
261  //owner==target?!
262  if ( ( ( mm-rSize()-target->rSize() ) > computer.radar.maxrange ) || target->rSize() < computer.radar.mintargetsize ) {
263  Flightgroup *fg = target->getFlightgroup();
264  if ( ( target->rSize() < capship_size || (!cap) ) && (fg == NULL ? true : fg->name != "Base") )
265  return target->isUnit() == PLANETPTR;
266  }
267  return true;
268 }
bool Unit::Inside ( const QVector position,
const float  radius,
Vector normal,
float dist 
)

Definition at line 138 of file unit_collide.cpp.

References isPlanet(), Position(), and querySphere().

Referenced by Collide(), and GameNebula::UpdatePhysics2().

139 {
140  if ( !querySphere( target, radius ) )
141  return false;
142  normal = ( target-Position() ).Cast();
143  ::Normalize( normal );
144  //if its' in the sphre, that's enough
145  if(isPlanet() )
146  return true;
147  return false;
148 }
bool Unit::InsideCollideTree ( Unit smaller,
QVector bigpos,
Vector bigNormal,
QVector smallpos,
Vector smallNormal,
bool  bigasteroid = false,
bool  smallasteroid = false 
)

Definition at line 150 of file unit_collide.cpp.

References a1, csCollisionPair::a1, csCollisionPair::a2, ASTEROIDPTR, csCollisionPair::b1, csCollisionPair::b2, csCollisionPair::c1, csCollisionPair::c2, csOPCODECollider::Collide(), collideTrees::colTree(), colTrees, csVector3::Cross(), cumulative_transformation_matrix, UnitCollection::empty(), csOPCODECollider::GetCollisionPairCount(), csOPCODECollider::GetCollisions(), getSubUnits(), VegaConfig::getVariable(), GetWarpVelocity(), graphicOptions, hull, i, InsideCollideTree(), isUnit(), Magnitude(), csVector3::Normalize(), Matrix::p, XMLSupport::parse_float(), Position(), Unit::graphic_options::RecurseIntoSubUnitsOnCollision, csOPCODECollider::ResetCollisionPairs(), rSize(), csTransform::SetO2TTranslation(), SubUnits, Transform(), TransformNormal(), collideTrees::usingColTree(), vs_config, csVector3::x, Opcode::Point::x, csVector3::y, Opcode::Point::y, csVector3::z, and Opcode::Point::z.

Referenced by Collide(), UnitWrapper::InsideCollideTree(), and InsideCollideTree().

157 {
158  if (smaller->colTrees == NULL || this->colTrees == NULL)
159  return false;
160  if (hull < 0) return false;
161  if (smaller->colTrees->usingColTree() == false || this->colTrees->usingColTree() == false)
162  return false;
164  Unit *bigger = this;
165 
167  csReversibleTransform smalltransform( smaller->cumulative_transformation_matrix );
168  smalltransform.SetO2TTranslation( csVector3( smaller->cumulative_transformation_matrix.p
169  -bigger->cumulative_transformation_matrix.p ) );
170  bigtransform.SetO2TTranslation( csVector3( 0, 0, 0 ) );
171  //we're only gonna lerp the positions for speed here... gahh!
172 
173  // Check for shield collisions here prior to checking for mesh on mesh or ray collisions below.
174  csOPCODECollider *tmpCol = smaller->colTrees->colTree( smaller, bigger->GetWarpVelocity() );
175  if ( tmpCol
176  && ( tmpCol->Collide( *bigger->colTrees->colTree( bigger,
177  smaller->GetWarpVelocity() ), &smalltransform, &bigtransform ) ) ) {
179  unsigned int numHits = csOPCODECollider::GetCollisionPairCount();
180  if (numHits) {
181  smallpos.Set( (mycollide[0].a1.x+mycollide[0].b1.x+mycollide[0].c1.x)/3.0f,
182  (mycollide[0].a1.y+mycollide[0].b1.y+mycollide[0].c1.y)/3.0f,
183  (mycollide[0].a1.z+mycollide[0].b1.z+mycollide[0].c1.z)/3.0f );
184  smallpos = Transform( smaller->cumulative_transformation_matrix, smallpos );
185  bigpos.Set( (mycollide[0].a2.x+mycollide[0].b2.x+mycollide[0].c2.x)/3.0f,
186  (mycollide[0].a2.y+mycollide[0].b2.y+mycollide[0].c2.y)/3.0f,
187  (mycollide[0].a2.z+mycollide[0].b2.z+mycollide[0].c2.z)/3.0f );
188  bigpos = Transform( bigger->cumulative_transformation_matrix, bigpos );
189  csVector3 sn, bn;
190  sn.Cross( mycollide[0].b1-mycollide[0].a1, mycollide[0].c1-mycollide[0].a1 );
191  bn.Cross( mycollide[0].b2-mycollide[0].a2, mycollide[0].c2-mycollide[0].a2 );
192  sn.Normalize();
193  bn.Normalize();
194  smallNormal.Set( sn.x, sn.y, sn.z );
195  bigNormal.Set( bn.x, bn.y, bn.z );
196  smallNormal = TransformNormal( smaller->cumulative_transformation_matrix, smallNormal );
197  bigNormal = TransformNormal( bigger->cumulative_transformation_matrix, bigNormal );
198  return true;
199  }
200  }
201  un_iter i;
202  static float rsizelim = XMLSupport::parse_float( vs_config->getVariable( "physics", "smallest_subunit_to_collide", ".2" ) );
203  clsptr bigtype = bigasteroid ? ASTEROIDPTR : bigger->isUnit();
204  clsptr smalltype = smallasteroid ? ASTEROIDPTR : smaller->isUnit();
205  if ( bigger->SubUnits.empty() == false
206  && (bigger->graphicOptions.RecurseIntoSubUnitsOnCollision == true || bigtype == ASTEROIDPTR) ) {
207  i = bigger->getSubUnits();
208  float rad = smaller->rSize();
209  for (Unit *un; (un = *i); ++i) {
210  float subrad = un->rSize();
211  if ( (bigtype != ASTEROIDPTR) && (subrad/bigger->rSize() < rsizelim) ) {
212  break;
213  }
214  if ( ( un->Position()-smaller->Position() ).Magnitude() <= subrad+rad ) {
215  if ( ( un->InsideCollideTree( smaller, bigpos, bigNormal, smallpos, smallNormal, bigtype == ASTEROIDPTR,
216  smalltype == ASTEROIDPTR ) ) )
217  return true;
218  }
219  }
220  }
221  if ( smaller->SubUnits.empty() == false
222  && (smaller->graphicOptions.RecurseIntoSubUnitsOnCollision == true || smalltype == ASTEROIDPTR) ) {
223  i = smaller->getSubUnits();
224  float rad = bigger->rSize();
225  for (Unit *un; (un = *i); ++i) {
226  float subrad = un->rSize();
227  if ( (smalltype != ASTEROIDPTR) && (subrad/smaller->rSize() < rsizelim) )
228  break;
229  if ( ( un->Position()-bigger->Position() ).Magnitude() <= subrad+rad ) {
230  if ( ( bigger->InsideCollideTree( un, bigpos, bigNormal, smallpos, smallNormal, bigtype == ASTEROIDPTR,
231  smalltype == ASTEROIDPTR ) ) )
232  return true;
233  }
234  }
235  }
236  //FIXME
237  //doesn't check all i*j options of subunits vs subunits
238  return false;
239 }
bool Unit::IsBase ( ) const

Definition at line 7890 of file unit_generic.cpp.

Referenced by Radar::Track::IdentifyType(), and Orders::AggressiveAI::ProcessCurrentFgDirective().

7891 {
7892  return ((flightgroup != NULL) && (flightgroup->name == "Base"));
7893 }
bool Unit::IsCleared ( const Unit dockignunit) const

Definition at line 5978 of file unit_generic.cpp.

Referenced by Orders::AutoDocking::CanDock(), DrawDockingBoxes(), and Cockpit::Update().

5979 {
5980  return std::find( pImage->clearedunits.begin(), pImage->clearedunits.end(), DockingUnit ) != pImage->clearedunits.end();
5981 }
bool Unit::isDocked ( const Unit dockingUnit) const

Definition at line 5988 of file unit_generic.cpp.

References docked.

Referenced by Collide(), DockToSavedBases(), UnDockNow(), and Cockpit::Update().

5989 {
5990  if (!d)
5991  return false;
5992  if ( !( d->docked&(DOCKED_INSIDE|DOCKED) ) )
5993  return false;
5994  for (unsigned int i = 0; i < pImage->dockedunits.size(); ++i) {
5995  Unit *un;
5996  if ( ( un = pImage->dockedunits[i]->uc.GetUnit() ) != NULL )
5997  if (un == d)
5998  return true;
5999  }
6000  return false;
6001 }
bool Unit::isEnemy ( const Unit other) const
inline

Definition at line 1540 of file unit_generic.h.

References getRelation().

Referenced by getNearestTargetUnit().

1541  {
1542  return getRelation( other ) < 0.0;
1543  }
bool Unit::IsExploding ( ) const
inline

Definition at line 890 of file unit_generic.h.

References pImage, and UnitImages< BOGUS >::timeexplode.

Referenced by Radar::Track::IsExploding().

890 { return pImage->timeexplode > 0; }
bool Unit::isFriend ( const Unit other) const
inline

Definition at line 1544 of file unit_generic.h.

References getRelation().

1545  {
1546  return getRelation( other ) > 0.0;
1547  }
bool Unit::isJumppoint ( ) const
inline
bool Unit::isNeutral ( const Unit other) const
inline

Definition at line 1548 of file unit_generic.h.

References getRelation().

1549  {
1550  return getRelation( other ) == 0.0;
1551  }
bool Unit::isStarShip ( ) const
inline

Definition at line 1526 of file unit_generic.h.

References isUnit(), and UNITPTR.

1527  {
1528  return isUnit() == UNITPTR;
1529  }
bool Unit::isTractorable ( enum tractorHow  how = tractorBoth) const

Definition at line 8918 of file unit_generic.cpp.

Referenced by Beam::Collide(), and WriteUnitString().

8919 {
8920  if (how != tractorImmune)
8921  return (getTractorability()&how) == how;
8922 
8923  else
8924  return getTractorability() == tractorImmune;
8925 }
virtual enum clsptr Unit::isUnit ( ) const
inlinevirtual

Reimplemented in Planet, Missile, Building, Nebula, Asteroid, and Enhancement.

Definition at line 1513 of file unit_generic.h.

References UNITPTR.

Referenced by UnitFactory::addBuffer(), StarSystem::AddUnit(), Planet::PlanetIterator::advance(), MissileEffect::ApplyDamage(), ApplyDamage(), AutoPilotToErrorMessage(), ZoneMgr::broadcastDamage(), ZoneMgr::broadcastSnapshots(), buildCargoDescription(), CloseEnoughToNavOrDest(), Bolt::Collide(), Terrain::Collide(), ContinuousTerrain::Collide(), Beam::Collide(), Collide(), compute_light_dot(), createObjects(), DistanceTwoTargets(), DockToSavedBases(), Orders::DockingOps::DockToTarget(), DoSpeech(), Orders::AggressiveAI::ExecuteNoEnemies(), getAtmospheric(), getAutoRSize(), UnitUtil::getPhysicsPriority(), getUnitNameAndFgNoBase(), ZoneMgr::getZoneBuffer(), Radar::Track::IdentifyType(), InRange(), InsideCollideTree(), UnitUtil::isAsteroid(), UnitUtil::isCloseEnoughToDock(), UnitUtil::isDockableUnit(), Orders::FireAt::isJumpablePlanet(), isPlanet(), UnitUtil::isSignificant(), isStarShip(), BaseInterface::Load(), UnitUtil::orbit(), Orders::DockingOps::PerformDockingOperations(), querySphereNoRecurse(), Asteroid::reactToCollision(), Enhancement::reactToCollision(), GamePlanet::reactToCollision(), Missile::reactToCollision(), reactToCollision(), BaseComputer::recalcTitle(), RequestClearence(), UniverseUtil::SafeStarSystemEntrancePoint(), ScoreKill(), Orders::FireAt::ShouldFire(), TargMissile(), TargNear(), TargSig(), TargThreat(), TargUn(), GameUnit< UnitType >::TransferUnitToSystem(), Atmosphere::Update(), Cockpit::Update(), UpdatePhysics(), and GameUnit< UnitType >::UpgradeInterface().

1514  {
1515  return UNITPTR;
1516  }
bool Unit::jumpReactToCollision ( Unit smaller)

Definition at line 3112 of file unit_generic.cpp.

References _Universe, Universe::activeStarSystem(), DeactivateJumpDrive(), Unit::UnitJump::drive, Unit::UnitJump::energy, UnitImages< BOGUS >::forcejump, GetDestinations(), GetJumpStatus(), VegaConfig::getVariable(), graphicOptions, Unit::graphic_options::InWarp, Universe::isPlayerStarship(), StarSystem::JumpTo(), XMLSupport::parse_bool(), pImage, NetServer::sendJump(), SERVER, size, TurnJumpOKLightOn(), vs_config, VSServer, and warpenergy.

3113 {
3114  static bool ai_jump_cheat = XMLSupport::parse_bool( vs_config->getVariable( "AI", "jump_without_energy", "false" ) );
3115  static bool nojumpinSPEC = XMLSupport::parse_bool( vs_config->getVariable( "physics", "noSPECJUMP", "true" ) );
3116  bool SPEC_interference = ( NULL != _Universe->isPlayerStarship( smalle ) ) ? smalle->graphicOptions.InWarp
3117  && nojumpinSPEC : ( NULL != _Universe->isPlayerStarship( this ) ) ? graphicOptions.InWarp
3118  && nojumpinSPEC : false;
3119  //only allow big with small
3120  if ( !GetDestinations().empty() ) {
3121  Cockpit *cp = _Universe->isPlayerStarship( smalle );
3122  if (!SPEC_interference || pImage->forcejump)
3123  TurnJumpOKLightOn( smalle, cp );
3124  else
3125  return false;
3126  //we have a drive
3127  if ( ( !SPEC_interference && ( smalle->GetJumpStatus().drive >= 0
3128  && //we have power
3129  (smalle->warpenergy >= smalle->GetJumpStatus().energy
3130  //or we're being cheap
3131  || (ai_jump_cheat && cp == NULL)
3132  ) ) )
3133  || pImage->forcejump ) {
3134  //or the jump is being forced?
3135  //NOW done in star_system_generic.cpp before TransferUnitToSystem smalle->warpenergy-=smalle->GetJumpStatus().energy;
3136  int dest = smalle->GetJumpStatus().drive;
3137  if (dest < 0)
3138  dest = 0;
3139  smalle->DeactivateJumpDrive();
3140  Unit *jumppoint = this;
3141  if (SERVER)
3142  VSServer->sendJump( smalle, this, GetDestinations()[dest%GetDestinations().size()] );
3143  else
3144  _Universe->activeStarSystem()->JumpTo( smalle, jumppoint, GetDestinations()[dest%GetDestinations().size()] );
3145  return true;
3146  }
3147  return true;
3148  }
3149  if ( !smalle->GetDestinations().empty() ) {
3150  Cockpit *cp = _Universe->isPlayerStarship( this );
3151  if (!SPEC_interference || smalle->pImage->forcejump)
3152  TurnJumpOKLightOn( this, cp );
3153  else
3154  return false;
3155  if ( ( !SPEC_interference && (GetJumpStatus().drive >= 0
3156  && ( warpenergy >= GetJumpStatus().energy || (ai_jump_cheat && cp == NULL) )
3157  ) ) || smalle->pImage->forcejump ) {
3160  Unit *jumppoint = smalle;
3161  if (SERVER) {
3162  VSServer->sendJump( this, smalle,
3163  smalle->GetDestinations()[GetJumpStatus().drive%smalle->GetDestinations().size()] );
3164  } else {
3165  _Universe->activeStarSystem()->JumpTo( this, jumppoint,
3166  smalle->GetDestinations()[GetJumpStatus().drive
3167  %smalle->GetDestinations().size()] );
3168  }
3169  return true;
3170  }
3171  return true;
3172  }
3173  return false;
3174 }
void Unit::Kill ( bool  eraseFromSave = true,
bool  quitting = false 
)

Definition at line 4557 of file unit_generic.cpp.

References _Universe, AUDDeleteSound(), AUDStopPlaying(), float_to_int(), VegaConfig::getVariable(), UnitUtil::isPlayerStarship(), Kill(), MISSILEPTR, Universe::netLock(), Network, XMLSupport::parse_float(), NetServer::sendKill(), SERVER, Unitdeletequeue, vs_config, VSFileSystem::vs_dprintf(), and VSServer.

4558 {
4559  if (this->colTrees)
4560  this->colTrees->Dec(); //might delete
4561  this->colTrees = NULL;
4562  if (this->sound->engine != -1) {
4563  AUDStopPlaying( this->sound->engine );
4564  AUDDeleteSound( this->sound->engine );
4565  }
4566  if (this->sound->explode != -1) {
4567  AUDStopPlaying( this->sound->explode );
4568  AUDDeleteSound( this->sound->explode );
4569  }
4570  if (this->sound->shield != -1) {
4571  AUDStopPlaying( this->sound->shield );
4572  AUDDeleteSound( this->sound->shield );
4573  }
4574  if (this->sound->armor != -1) {
4575  AUDStopPlaying( this->sound->armor );
4576  AUDDeleteSound( this->sound->armor );
4577  }
4578  if (this->sound->hull != -1) {
4579  AUDStopPlaying( this->sound->hull );
4580  AUDDeleteSound( this->sound->hull );
4581  }
4582  if (this->sound->cloak != -1) {
4583  AUDStopPlaying( this->sound->cloak );
4584  AUDDeleteSound( this->sound->cloak );
4585  }
4586  ClearMounts();
4587  if (SERVER && this->serial) {
4588  VSServer->sendKill( this->serial, this->getStarSystem()->GetZone() );
4589  this->serial = 0;
4590  }
4591  if ( docked&(DOCKING_UNITS) ) {
4592  static float survival =
4593  XMLSupport::parse_float( vs_config->getVariable( "physics", "survival_chance_on_base_death", "0.1" ) );
4594  static float player_survival =
4595  XMLSupport::parse_float( vs_config->getVariable( "physics", "player_survival_chance_on_base_death", "1.0" ) );
4596  static int i_survival = float_to_int( (RAND_MAX*survival) );
4597  static int i_player_survival = float_to_int( (RAND_MAX*player_survival) );
4598 
4599  vector< Unit* >dockedun;
4600  unsigned int i;
4601  for (i = 0; i < pImage->dockedunits.size(); ++i) {
4602  Unit *un;
4603  if ( NULL != ( un = pImage->dockedunits[i]->uc.GetUnit() ) )
4604  dockedun.push_back( un );
4605  }
4606  while ( !dockedun.empty() ) {
4607  if (Network) _Universe->netLock( true );
4608  dockedun.back()->UnDock( this );
4609  if (Network) _Universe->netLock( false );
4610  if ( rand() <= (UnitUtil::isPlayerStarship( dockedun.back() ) ? i_player_survival : i_survival) )
4611  dockedun.back()->Kill();
4612  dockedun.pop_back();
4613  }
4614  }
4615  //eraticate everything. naturally (see previous line) we won't erraticate beams erraticated above
4616  if ( !isSubUnit() )
4617  RemoveFromSystem();
4618  killed = true;
4619  computer.target.SetUnit( NULL );
4620 
4621  //God I can't believe this next line cost me 1 GIG of memory until I added it
4622  computer.threat.SetUnit( NULL );
4623  computer.velocity_ref.SetUnit( NULL );
4625  if (aistate) {
4627  aistate->Destroy();
4628  }
4629  aistate = NULL;
4630  Unit *un;
4631  for (un_iter iter = getSubUnits(); (un = *iter); ++iter)
4632  un->Kill();
4633 
4634  if (isUnit() != MISSILEPTR)
4635  VSFileSystem::vs_dprintf( 1, "UNIT HAS DIED: %s %s (file %s)\n", name.get().c_str(),
4636  fullname.c_str(), filename.get().c_str() );
4637 
4638  if (ucref == 0) {
4639  Unitdeletequeue.push_back( this );
4640  if (flightgroup)
4641  if (flightgroup->leader.GetUnit() == this)
4642  flightgroup->leader.SetUnit( NULL );
4643 
4644 #ifdef DESTRUCTDEBUG
4645  VSFileSystem::vs_dprintf( 3, "%s 0x%x - %d\n", name.c_str(), this, Unitdeletequeue.size() );
4646 #endif
4647  }
4648 }
bool Unit::Killed ( )
inline

Definition at line 22 of file unit.h.

References killed, and zapped.

Referenced by UnitCollection::contains(), and UnitContainer::SetUnit().

23  {
24  if (zapped == true)
25  printf( "segfault" );
26  return killed;
27  }
bool Unit::Killed ( ) const
inline

Definition at line 886 of file unit_generic.h.

References killed.

887  {
888  return killed;
889  }
void Unit::LateralThrust ( float  amt)

Definition at line 3505 of file unit_generic.cpp.

References Vector.

3506 {
3507  if (amt > 1.0) amt = 1.0;
3508  if (amt < -1.0) amt = -1.0;
3509  ApplyLocalForce( amt*limits.lateral*Vector( 1, 0, 0 ) );
3510 }
void Unit::leach ( float  XshieldPercent,
float  YrechargePercent,
float  ZenergyPercent 
)

Definition at line 4650 of file unit_generic.cpp.

4651 {
4652  recharge *= damEnRecharge;
4653  shield.recharge *= damShieldRecharge;
4654  switch (shield.number)
4655  {
4656  case 2:
4657  shield.shield2fb.frontmax *= damShield;
4658  shield.shield2fb.backmax *= damShield;
4659  break;
4660  case 4:
4661  shield.shield4fbrl.frontmax *= damShield;
4662  shield.shield4fbrl.backmax *= damShield;
4663  shield.shield4fbrl.leftmax *= damShield;
4664  shield.shield4fbrl.rightmax *= damShield;
4665  break;
4666  case 8:
4667  shield.shield8.frontrighttopmax *= damShield;
4668  shield.shield8.backrighttopmax *= damShield;
4669  shield.shield8.frontlefttopmax *= damShield;
4670  shield.shield8.backlefttopmax *= damShield;
4671  shield.shield8.frontrightbottommax *= damShield;
4672  shield.shield8.backrightbottommax *= damShield;
4673  shield.shield8.frontleftbottommax *= damShield;
4674  shield.shield8.backleftbottommax *= damShield;
4675  break;
4676  }
4677 }
void Unit::LightShields ( const Vector pnt,
const Vector normal,
float  amt,
const GFXColor color 
)

Definition at line 4070 of file unit_generic.cpp.

References mymax(), mymin, and Vector.

4071 {
4072  meshdata.back()->AddDamageFX( pnt, shieldtight ? shieldtight*normal : Vector( 0, 0, 0 ), mymin( 1.0f, mymax( 0.0f,
4073  amt ) ), color );
4074 }
void Unit::LoadAIScript ( const std::string &  aiscript)

Definition at line 1877 of file unit_generic.cpp.

References Mission::addModule(), PythonClass< SuperClass >::Factory(), and mission.

Referenced by Mission::call_unit_launch(), createObjects(), and LoadMission().

1878 {
1879  if (s.find( ".py" ) != string::npos) {
1881  PrimeOrders( ai );
1882  return;
1883  } else {
1884  if (s.length() > 0) {
1885  if (*s.begin() == '_') {
1886  mission->addModule( s.substr( 1 ) );
1887  PrimeOrders( new AImissionScript( s.substr( 1 ) ) );
1888  } else {
1889  if (s == "ikarus") {
1890  PrimeOrders( new Orders::Ikarus() );
1891  } else {
1892  string ai_agg = s+".agg.xml";
1893  PrimeOrders( new Orders::AggressiveAI( ai_agg.c_str() ) );
1894  }
1895  }
1896  } else {
1897  PrimeOrders();
1898  }
1899  }
1900 }
bool Unit::LoadLastPythonAIScript ( )

Definition at line 1908 of file unit_generic.cpp.

References PythonClass< SuperClass >::LastPythonClass().

1909 {
1911  if (pyai) {
1912  PrimeOrders( pyai );
1913  } else if (!aistate) {
1914  PrimeOrders();
1915  return false;
1916  }
1917  return true;
1918 }
void Unit::LoadRow ( class CSVRow row,
std::string  unitMod,
std::string *  netxml = NULL 
)

Definition at line 704 of file unit_csv.cpp.

References AddCarg(), AddDocks(), AddLights(), AddMeshes(), AddMounts(), addRapidMesh(), addShieldMesh(), AddSounds(), AddSubUnits(), Unit::Limits::afterburn, afterburnenergy, afterburntype, Unit::graphic_options::Animating, armor, AssignIf(), AssignIfDeg(), Armor::backleftbottom, Armor::backlefttop, Armor::backrightbottom, Armor::backrighttop, cache_ani(), calculate_extent(), Unit::XML::calculated_role, Unit::Computer::RADARLIM::canlock, Unit::Computer::RADARLIM::capability, UnitImages< BOGUS >::CargoVolume, CheckAccessory(), UnitImages< BOGUS >::cloakenergy, UnitImages< BOGUS >::cloakglass, cloaking, cloakmin, UnitImages< BOGUS >::cloakrate, UnitImages< BOGUS >::cockpit_damage, UnitImages< BOGUS >::CockpitCenter, collideTreesMaxTrees, colTrees, UnitImages< BOGUS >::CommFunctionality, UnitImages< BOGUS >::CommFunctionalityMax, computer, corner_max, corner_min, UniverseUtil::cos(), createVSSprite(), csvRow, Unit::XML::damageiterator, Unit::XML::data, DEF_OPTIMIZER, Unit::UnitJump::delay, deleteVSSprite(), Dock(), Unit::UnitJump::drive, UnitImages< BOGUS >::ecm, Shield::efficiency, Unit::UnitJump::energy, energy, UnitImages< BOGUS >::equipment_volume, UnitImages< BOGUS >::explosion_type, Unit::graphic_options::FaceCamera, faction, UnitImages< BOGUS >::fireControlFunctionality, UnitImages< BOGUS >::fireControlFunctionalityMax, float, UnitImages< BOGUS >::forcejump, Unit::Limits::forward, Armor::frontleftbottom, Armor::frontlefttop, Armor::frontrightbottom, Armor::frontrighttop, fuel, fullname, collideTrees::Get(), getCollideTree(), FactionUtil::GetFaction(), getFlightgroup(), VSFileSystem::GetHashName(), CSVRow::getParent(), Mesh::GetPolys(), VegaConfig::getVariable(), graphicOptions, Unit::XML::hasColTree, HeatSink, UnitImages< BOGUS >::HiddenCargoVolume, HudDamage(), hull, i, Unit::Computer::RADARLIM::Capability::IFF_BUBBLE, Unit::Computer::RADARLIM::Capability::IFF_FRIEND_FOE, Unit::Computer::RADARLIM::Capability::IFF_NONE, Unit::Computer::RADARLIM::Capability::IFF_OBJECT_RECOGNITION, Unit::Computer::RADARLIM::Capability::IFF_PLANE, Unit::Computer::RADARLIM::Capability::IFF_SPHERE, Unit::Computer::RADARLIM::Capability::IFF_THREAT_ASSESSMENT, ImportCargo(), collideTrees::Inc(), INIT_OPTIMIZER, Unit::UnitJump::insysenergy, int, isVSSpriteLoaded(), UnitXML::ITTS, Unit::Computer::itts, jump, Unit::Limits::lateral, Shield::leak, UnitImages< BOGUS >::LifeSupportFunctionality, UnitImages< BOGUS >::LifeSupportFunctionalityMax, limits, LoadCockpit(), LOADROW_OPTIMIZER, Unit::Computer::RADARLIM::lockcone, Mass, Unit::Computer::max_combat_ab_speed, Unit::Computer::max_combat_speed, Unit::Computer::max_pitch_down, Unit::Computer::max_pitch_up, Unit::Computer::max_roll_left, Unit::Computer::max_roll_right, MAX_SHIELD_NUMBER, Unit::Computer::max_yaw_left, Unit::Computer::max_yaw_right, Unit::Computer::RADARLIM::maxcone, maxenergy, maxhull, Unit::Computer::RADARLIM::maxrange, MAXVDUS, maxwarpenergy, Unit::graphic_options::MaxWarpMultiplier, meshdata, Unit::XML::meshes, Unit::graphic_options::MinWarpMultiplier, Momentofinertia, Unit::graphic_options::NoDamageParticles, Unit::graphic_options::NumAnimationPoints, Shield::number, ONE, OPTIM_GET, CSVTable::optimizer_setup, XMLSupport::parse_bool(), XMLSupport::parse_float(), XMLSupport::parse_int(), UnitImages< BOGUS >::pHudImage, pImage, Unit::Limits::pitch, Unit::Computer::radar, Unit::XML::randomstartframe, Unit::XML::randomstartseconds, Shield::range, collideTrees::rapidColliders, Unit::XML::rapidmesh, Unit::XML::rapidmesh_str, Shield::recharge, recharge, Unit::graphic_options::RecurseIntoSubUnitsOnCollision, UnitImages< BOGUS >::repair_droid, Unit::Limits::retro, ShieldFacing::rhomax, ShieldFacing::rhomin, Unit::Limits::roll, rSize(), setAttackPreference(), setAverageGunSpeed(), setTractorability(), setUnitRole(), CSVTable::SetupOptimizer(), Shield::shield, shield, Shield::shield2fb, Shield::shield4fbrl, Shield::shield8, Unit::XML::shieldmesh, Unit::XML::shieldmesh_str, sizeof(), Unit::Computer::slide_end, Unit::Computer::slide_start, UnitImages< BOGUS >::SPECDriveFunctionality, UnitImages< BOGUS >::SPECDriveFunctionalityMax, specInterdiction, stob(), stof(), stoi(), ShieldFacing::thetamax, ShieldFacing::thetamin, XMLSupport::tostring(), Unit::Computer::RADARLIM::trackingcone, tractorImmune, tractorIn, tractorPush, two, Unit::XML::unitlevel, Unit::XML::unitModifications, UnitImages< BOGUS >::unitscale, Unit::XML::unitscale, UpgradeUnit(), UnitImages< BOGUS >::UpgradeVolume, Vector, Unit::Limits::vertical, vs_config, VS_PI, warpenergy, xml, and Unit::Limits::yaw.

705 {
706  CSVTable *table = row.getParent();
707  Unit::XML xml;
708  xml.unitModifications = modification.c_str();
709  xml.randomstartframe = ( (float) rand() )/RAND_MAX;
710  xml.randomstartseconds = 0;
711  xml.calculated_role = false;
712  xml.damageiterator = 0;
713  xml.shieldmesh = NULL;
714  xml.rapidmesh = NULL;
715  xml.hasColTree = true;
716  xml.unitlevel = 0;
717  xml.unitscale = 1;
718  xml.data = xml.shieldmesh = xml.rapidmesh = NULL; //was uninitialized memory
719  string tmpstr;
720  csvRow = row[0];
721  DEF_OPTIMIZER( FaceCamera );
722  DEF_OPTIMIZER( Name );
723  DEF_OPTIMIZER( Hud_image );
724  DEF_OPTIMIZER( Combat_Role ); //legacy only
725  DEF_OPTIMIZER( Unit_Role );
726  DEF_OPTIMIZER( Attack_Preference );
727  DEF_OPTIMIZER( Num_Animation_Stages );
728  DEF_OPTIMIZER( Unit_Scale );
729  DEF_OPTIMIZER( Mesh );
730  DEF_OPTIMIZER( Dock );
731  DEF_OPTIMIZER( Sub_Units );
732  DEF_OPTIMIZER( Mounts );
733  DEF_OPTIMIZER( Hold_Volume );
734  DEF_OPTIMIZER( Hidden_Hold_Volume );
735  DEF_OPTIMIZER( Upgrade_Storage_Volume );
736  DEF_OPTIMIZER( Equipment_Space );
737  DEF_OPTIMIZER( Cargo_Import );
738  DEF_OPTIMIZER( Cargo );
739  DEF_OPTIMIZER( Sounds );
741  DEF_OPTIMIZER( CockpitX );
742  DEF_OPTIMIZER( CockpitY );
743  DEF_OPTIMIZER( CockpitZ );
744  DEF_OPTIMIZER( Mass );
745  DEF_OPTIMIZER( Moment_Of_Inertia );
746  DEF_OPTIMIZER( Fuel_Capacity );
747  DEF_OPTIMIZER( Hull );
748  DEF_OPTIMIZER( Armor_Front_Top_Left );
749  DEF_OPTIMIZER( Armor_Front_Top_Right );
750  DEF_OPTIMIZER( Armor_Back_Top_Left );
751  DEF_OPTIMIZER( Armor_Back_Top_Right );
752  DEF_OPTIMIZER( Armor_Front_Bottom_Left );
753  DEF_OPTIMIZER( Armor_Front_Bottom_Right );
754  DEF_OPTIMIZER( Armor_Back_Bottom_Left );
755  DEF_OPTIMIZER( Armor_Back_Bottom_Right );
756  DEF_OPTIMIZER( Description );
757  DEF_OPTIMIZER( Shield_Front_Top_Left );
758  DEF_OPTIMIZER( Shield_Front_Top_Right );
759  DEF_OPTIMIZER( Shield_Back_Top_Left );
760  DEF_OPTIMIZER( Shield_Back_Top_Right );
761  DEF_OPTIMIZER( Shield_Front_Bottom_Left );
762  DEF_OPTIMIZER( Shield_Front_Bottom_Right );
763  DEF_OPTIMIZER( Shield_Back_Bottom_Left );
764  DEF_OPTIMIZER( Shield_Back_Bottom_Right );
765  DEF_OPTIMIZER( Shield_Leak );
766  DEF_OPTIMIZER( Shield_Recharge );
767  DEF_OPTIMIZER( Shield_Efficiency );
768  DEF_OPTIMIZER( Warp_Capacitor );
769  DEF_OPTIMIZER( Warp_Min_Multiplier );
770  DEF_OPTIMIZER( Warp_Max_Multiplier );
771  DEF_OPTIMIZER( Primary_Capacitor );
772  DEF_OPTIMIZER( Reactor_Recharge );
773  DEF_OPTIMIZER( Jump_Drive_Present );
774  DEF_OPTIMIZER( Jump_Drive_Delay );
775  DEF_OPTIMIZER( Wormhole );
776  DEF_OPTIMIZER( Collide_Subunits );
777  DEF_OPTIMIZER( Outsystem_Jump_Cost );
778  DEF_OPTIMIZER( Warp_Usage_Cost );
779  DEF_OPTIMIZER( Afterburner_Usage_Cost );
780  DEF_OPTIMIZER( Afterburner_Type );
781  DEF_OPTIMIZER( Maneuver_Yaw );
782  DEF_OPTIMIZER( Maneuver_Pitch );
783  DEF_OPTIMIZER( Maneuver_Roll );
784  DEF_OPTIMIZER( Yaw_Governor );
785  DEF_OPTIMIZER( Yaw_Governor_Right );
786  DEF_OPTIMIZER( Yaw_Governor_Left );
787  DEF_OPTIMIZER( Pitch_Governor );
788  DEF_OPTIMIZER( Pitch_Governor_Up );
789  DEF_OPTIMIZER( Pitch_Governor_Down );
790  DEF_OPTIMIZER( Roll_Governor );
791  DEF_OPTIMIZER( Roll_Governor_Right );
792  DEF_OPTIMIZER( Roll_Governor_Left );
793  DEF_OPTIMIZER( Afterburner_Accel );
794  DEF_OPTIMIZER( Forward_Accel );
795  DEF_OPTIMIZER( Retro_Accel );
796  DEF_OPTIMIZER( Left_Accel );
797  DEF_OPTIMIZER( Right_Accel );
798  DEF_OPTIMIZER( Top_Accel );
799  DEF_OPTIMIZER( Bottom_Accel );
800  DEF_OPTIMIZER( Default_Speed_Governor );
801  DEF_OPTIMIZER( Afterburner_Speed_Governor );
802  DEF_OPTIMIZER( ITTS );
803  DEF_OPTIMIZER( Can_Lock );
804  DEF_OPTIMIZER( Radar_Color );
805  DEF_OPTIMIZER( Radar_Range );
806  DEF_OPTIMIZER( Max_Cone );
807  DEF_OPTIMIZER( Tracking_Cone );
808  DEF_OPTIMIZER( Lock_Cone );
809  DEF_OPTIMIZER( Cloak_Min );
810  DEF_OPTIMIZER( Cloak_Glass );
811  DEF_OPTIMIZER( Can_Cloak );
812  DEF_OPTIMIZER( Cloak_Rate );
813  DEF_OPTIMIZER( Cloak_Energy );
814  DEF_OPTIMIZER( Repair_Droid );
815  DEF_OPTIMIZER( ECM_Rating );
816  DEF_OPTIMIZER( Heat_Sink_Rating );
817  DEF_OPTIMIZER( Hud_Functionality );
818  DEF_OPTIMIZER( Max_Hud_Functionality );
819  DEF_OPTIMIZER( Lifesupport_Functionality );
820  DEF_OPTIMIZER( Max_Lifesupport_Functionality );
821  DEF_OPTIMIZER( Comm_Functionality );
822  DEF_OPTIMIZER( Max_Comm_Functionality );
823  DEF_OPTIMIZER( FireControl_Functionality );
824  DEF_OPTIMIZER( Max_FireControl_Functionality );
825  DEF_OPTIMIZER( SPECDrive_Functionality );
826  DEF_OPTIMIZER( Max_SPECDrive_Functionality );
827  DEF_OPTIMIZER( Slide_Start );
828  DEF_OPTIMIZER( Slide_End );
829  DEF_OPTIMIZER( Upgrades );
830  DEF_OPTIMIZER( Tractorability );
831  DEF_OPTIMIZER( Explosion );
832  DEF_OPTIMIZER( Light );
833  DEF_OPTIMIZER( Shield_Mesh );
834  DEF_OPTIMIZER( Rapid_Mesh );
835  DEF_OPTIMIZER( Use_Rapid );
836  DEF_OPTIMIZER( NoDamageParticles );
837  DEF_OPTIMIZER( Spec_Interdiction );
838  if (table && !table->optimizer_setup) {
839  static std::vector< std::string >keys;
840  static bool optimizer_keys_init = false;
841  if (!optimizer_keys_init) {
842  optimizer_keys_init = true;
843  printf( "Initializing optimizer\n" );
844  INIT_OPTIMIZER( keys, Name );
845  INIT_OPTIMIZER( keys, Hud_image );
846  INIT_OPTIMIZER( keys, FaceCamera );
847  INIT_OPTIMIZER( keys, Combat_Role ); //legacy only
848  INIT_OPTIMIZER( keys, Unit_Role );
849  INIT_OPTIMIZER( keys, Attack_Preference );
850  INIT_OPTIMIZER( keys, Num_Animation_Stages );
851  INIT_OPTIMIZER( keys, Unit_Scale );
852  INIT_OPTIMIZER( keys, Mesh );
853  INIT_OPTIMIZER( keys, Dock );
854  INIT_OPTIMIZER( keys, Sub_Units );
855  INIT_OPTIMIZER( keys, Mounts );
856  INIT_OPTIMIZER( keys, Hold_Volume );
857  INIT_OPTIMIZER( keys, Hidden_Hold_Volume );
858  INIT_OPTIMIZER( keys, Upgrade_Storage_Volume );
859  INIT_OPTIMIZER( keys, Equipment_Space );
860  INIT_OPTIMIZER( keys, Cargo_Import );
861  INIT_OPTIMIZER( keys, Cargo );
862  INIT_OPTIMIZER( keys, Sounds );
863  INIT_OPTIMIZER( keys, Cockpit );
864  INIT_OPTIMIZER( keys, CockpitX );
865  INIT_OPTIMIZER( keys, CockpitY );
866  INIT_OPTIMIZER( keys, CockpitZ );
867  INIT_OPTIMIZER( keys, Mass );
868  INIT_OPTIMIZER( keys, Moment_Of_Inertia );
869  INIT_OPTIMIZER( keys, Fuel_Capacity );
870  INIT_OPTIMIZER( keys, Hull );
871  INIT_OPTIMIZER( keys, Armor_Front_Top_Left );
872  INIT_OPTIMIZER( keys, Armor_Front_Top_Right );
873  INIT_OPTIMIZER( keys, Armor_Back_Top_Left );
874  INIT_OPTIMIZER( keys, Armor_Back_Top_Right );
875  INIT_OPTIMIZER( keys, Armor_Front_Bottom_Left );
876  INIT_OPTIMIZER( keys, Armor_Front_Bottom_Right );
877  INIT_OPTIMIZER( keys, Armor_Back_Bottom_Left );
878  INIT_OPTIMIZER( keys, Armor_Back_Bottom_Right );
879  INIT_OPTIMIZER( keys, Description );
880  INIT_OPTIMIZER( keys, Shield_Front_Top_Left );
881  INIT_OPTIMIZER( keys, Shield_Front_Top_Right );
882  INIT_OPTIMIZER( keys, Shield_Back_Top_Left );
883  INIT_OPTIMIZER( keys, Shield_Back_Top_Right );
884  INIT_OPTIMIZER( keys, Shield_Front_Bottom_Left );
885  INIT_OPTIMIZER( keys, Shield_Front_Bottom_Right );
886  INIT_OPTIMIZER( keys, Shield_Back_Bottom_Left );
887  INIT_OPTIMIZER( keys, Shield_Back_Bottom_Right );
888  INIT_OPTIMIZER( keys, Shield_Leak );
889  INIT_OPTIMIZER( keys, Shield_Recharge );
890  INIT_OPTIMIZER( keys, Shield_Efficiency );
891  INIT_OPTIMIZER( keys, Warp_Capacitor );
892  INIT_OPTIMIZER( keys, Warp_Min_Multiplier );
893  INIT_OPTIMIZER( keys, Warp_Max_Multiplier );
894  INIT_OPTIMIZER( keys, Primary_Capacitor );
895  INIT_OPTIMIZER( keys, Reactor_Recharge );
896  INIT_OPTIMIZER( keys, Jump_Drive_Present );
897  INIT_OPTIMIZER( keys, Jump_Drive_Delay );
898  INIT_OPTIMIZER( keys, Wormhole );
899  INIT_OPTIMIZER( keys, Collide_Subunits );
900  INIT_OPTIMIZER( keys, Outsystem_Jump_Cost );
901  INIT_OPTIMIZER( keys, Warp_Usage_Cost );
902  INIT_OPTIMIZER( keys, Afterburner_Usage_Cost );
903  INIT_OPTIMIZER( keys, Afterburner_Type );
904  INIT_OPTIMIZER( keys, Maneuver_Yaw );
905  INIT_OPTIMIZER( keys, Maneuver_Pitch );
906  INIT_OPTIMIZER( keys, Maneuver_Roll );
907  INIT_OPTIMIZER( keys, Yaw_Governor );
908  INIT_OPTIMIZER( keys, Yaw_Governor_Right );
909  INIT_OPTIMIZER( keys, Yaw_Governor_Left );
910  INIT_OPTIMIZER( keys, Pitch_Governor );
911  INIT_OPTIMIZER( keys, Pitch_Governor_Up );
912  INIT_OPTIMIZER( keys, Pitch_Governor_Down );
913  INIT_OPTIMIZER( keys, Roll_Governor );
914  INIT_OPTIMIZER( keys, Roll_Governor_Right );
915  INIT_OPTIMIZER( keys, Roll_Governor_Left );
916  INIT_OPTIMIZER( keys, Afterburner_Accel );
917  INIT_OPTIMIZER( keys, Forward_Accel );
918  INIT_OPTIMIZER( keys, Retro_Accel );
919  INIT_OPTIMIZER( keys, Left_Accel );
920  INIT_OPTIMIZER( keys, Right_Accel );
921  INIT_OPTIMIZER( keys, Top_Accel );
922  INIT_OPTIMIZER( keys, Bottom_Accel );
923  INIT_OPTIMIZER( keys, Default_Speed_Governor );
924  INIT_OPTIMIZER( keys, Afterburner_Speed_Governor );
925  INIT_OPTIMIZER( keys, ITTS );
926  INIT_OPTIMIZER( keys, Can_Lock );
927  INIT_OPTIMIZER( keys, Radar_Color );
928  INIT_OPTIMIZER( keys, Radar_Range );
929  INIT_OPTIMIZER( keys, Max_Cone );
930  INIT_OPTIMIZER( keys, Tracking_Cone );
931  INIT_OPTIMIZER( keys, Lock_Cone );
932  INIT_OPTIMIZER( keys, Cloak_Min );
933  INIT_OPTIMIZER( keys, Cloak_Glass );
934  INIT_OPTIMIZER( keys, Can_Cloak );
935  INIT_OPTIMIZER( keys, Cloak_Rate );
936  INIT_OPTIMIZER( keys, Cloak_Energy );
937  INIT_OPTIMIZER( keys, Repair_Droid );
938  INIT_OPTIMIZER( keys, ECM_Rating );
939  INIT_OPTIMIZER( keys, Heat_Sink_Rating );
940  INIT_OPTIMIZER( keys, Hud_Functionality );
941  INIT_OPTIMIZER( keys, Max_Hud_Functionality );
942  INIT_OPTIMIZER( keys, Lifesupport_Functionality );
943  INIT_OPTIMIZER( keys, Max_Lifesupport_Functionality );
944  INIT_OPTIMIZER( keys, Comm_Functionality );
945  INIT_OPTIMIZER( keys, Max_Comm_Functionality );
946  INIT_OPTIMIZER( keys, FireControl_Functionality );
947  INIT_OPTIMIZER( keys, Max_FireControl_Functionality );
948  INIT_OPTIMIZER( keys, SPECDrive_Functionality );
949  INIT_OPTIMIZER( keys, Max_SPECDrive_Functionality );
950  INIT_OPTIMIZER( keys, Slide_Start );
951  INIT_OPTIMIZER( keys, Slide_End );
952  INIT_OPTIMIZER( keys, Upgrades );
953  INIT_OPTIMIZER( keys, Tractorability );
954  INIT_OPTIMIZER( keys, Explosion );
955  INIT_OPTIMIZER( keys, Light );
956  INIT_OPTIMIZER( keys, Shield_Mesh );
957  INIT_OPTIMIZER( keys, Rapid_Mesh );
958  INIT_OPTIMIZER( keys, Use_Rapid );
959  INIT_OPTIMIZER( keys, NoDamageParticles );
960  INIT_OPTIMIZER( keys, Spec_Interdiction );
961  }
962  table->SetupOptimizer( keys, LOADROW_OPTIMIZER );
963  }
964  //begin the geometry (and things that depend on stats)
965  fullname = OPTIM_GET( row, table, Name );
966  if ( ( tmpstr = OPTIM_GET( row, table, Hud_image ) ).length() != 0 ) {
967  std::string fac = FactionUtil::GetFaction( faction );
968  fac += "_";
969  fac += tmpstr;
970  pImage->pHudImage = createVSSprite( fac.c_str() );
971  if ( !isVSSpriteLoaded( pImage->pHudImage ) ) {
973  pImage->pHudImage = createVSSprite( tmpstr.c_str() );
974  }
975  }
976  if ( ( tmpstr = OPTIM_GET( row, table, FaceCamera ) ).length() != 0 )
978  std::string llegacy_combat_role( OPTIM_GET( row, table, Combat_Role ) );
979  std::string lunit_role( OPTIM_GET( row, table, Unit_Role ) );
980  std::string lattack_preference( OPTIM_GET( row, table, Attack_Preference ) );
981  if (lunit_role.length() == 0)
982  this->setUnitRole( llegacy_combat_role );
983  else
984  this->setUnitRole( lunit_role );
985  if (lattack_preference.length() == 0)
986  this->setAttackPreference( llegacy_combat_role );
987  else
988  this->setAttackPreference( lattack_preference );
989  graphicOptions.NumAnimationPoints = stoi( OPTIM_GET( row, table, Num_Animation_Stages ), 0 );
990  graphicOptions.NoDamageParticles = stoi( OPTIM_GET( row, table, NoDamageParticles ), 0 );
993  xml.unitscale = stof( OPTIM_GET( row, table, Unit_Scale ), 1 );
994  if (!xml.unitscale) xml.unitscale = 1;
995  pImage->unitscale = xml.unitscale;
997  table,
998  Mesh ), faction,
999  getFlightgroup() );
1000  AddDocks( this, xml, OPTIM_GET( row, table, Dock ) );
1001  AddSubUnits( this, xml, OPTIM_GET( row, table, Sub_Units ), faction, modification );
1002 
1003  meshdata = xml.meshes;
1004  meshdata.push_back( NULL );
1005  corner_min = Vector( FLT_MAX, FLT_MAX, FLT_MAX );
1006  corner_max = Vector( -FLT_MAX, -FLT_MAX, -FLT_MAX );
1007  calculate_extent( false );
1008  AddMounts( this, xml, OPTIM_GET( row, table, Mounts ) );
1009  this->pImage->CargoVolume = ::stof( OPTIM_GET( row, table, Hold_Volume ) );
1010  this->pImage->HiddenCargoVolume = ::stof( OPTIM_GET( row, table, Hidden_Hold_Volume ) );
1011  this->pImage->UpgradeVolume = ::stof( OPTIM_GET( row, table, Upgrade_Storage_Volume ) );
1012  this->pImage->equipment_volume = ::stof( OPTIM_GET( row, table, Equipment_Space ) );
1013  ImportCargo( this, OPTIM_GET( row, table, Cargo_Import ) ); //if this changes change planet_generic.cpp
1014  AddCarg( this, OPTIM_GET( row, table, Cargo ) );
1015  AddSounds( this, OPTIM_GET( row, table, Sounds ) );
1016  LoadCockpit( this, OPTIM_GET( row, table, Cockpit ) );
1017  pImage->CockpitCenter.i = ::stof( OPTIM_GET( row, table, CockpitX ) )*xml.unitscale;
1018  pImage->CockpitCenter.j = ::stof( OPTIM_GET( row, table, CockpitY ) )*xml.unitscale;
1019  pImage->CockpitCenter.k = ::stof( OPTIM_GET( row, table, CockpitZ ) )*xml.unitscale;
1020  Mass = stof( OPTIM_GET( row, table, Mass ), 1.0 );
1021  Momentofinertia = stof( OPTIM_GET( row, table, Moment_Of_Inertia ), 1.0 );
1022  fuel = ::stof( OPTIM_GET( row, table, Fuel_Capacity ) );
1023  hull = maxhull = ::stof( OPTIM_GET( row, table, Hull ) );
1024  specInterdiction = ::stof( OPTIM_GET( row, table, Spec_Interdiction ) );
1025  armor.frontlefttop = ::stof( OPTIM_GET( row, table, Armor_Front_Top_Left ) );
1026  armor.frontrighttop = ::stof( OPTIM_GET( row, table, Armor_Front_Top_Right ) );
1027  armor.backlefttop = ::stof( OPTIM_GET( row, table, Armor_Back_Top_Left ) );
1028  armor.backrighttop = ::stof( OPTIM_GET( row, table, Armor_Back_Top_Right ) );
1029  armor.frontleftbottom = ::stof( OPTIM_GET( row, table, Armor_Front_Bottom_Left ) );
1030  armor.frontrightbottom = ::stof( OPTIM_GET( row, table, Armor_Front_Bottom_Right ) );
1031  armor.backleftbottom = ::stof( OPTIM_GET( row, table, Armor_Back_Bottom_Left ) );
1032  armor.backrightbottom = ::stof( OPTIM_GET( row, table, Armor_Back_Bottom_Right ) );
1033  int shieldcount = 0;
1034  Shield two;
1035  Shield four;
1036  Shield eight;
1037  memset( &two, 0, sizeof (Shield) );
1038  memset( &four, 0, sizeof (Shield) );
1039  memset( &eight, 0, sizeof (Shield) );
1040  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Front_Top_Right ),
1041  two.shield2fb.front, four.shield4fbrl.front, eight.shield8.frontrighttop );
1042  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Front_Top_Left ),
1043  two.shield2fb.front, four.shield4fbrl.front, eight.shield8.frontlefttop );
1044  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Back_Top_Left ),
1045  two.shield2fb.back, four.shield4fbrl.back, eight.shield8.backlefttop );
1046  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Back_Top_Right ),
1047  two.shield2fb.back, four.shield4fbrl.back, eight.shield8.backrighttop );
1048  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Front_Bottom_Left ),
1049  two.shield2fb.front, four.shield4fbrl.left, eight.shield8.frontleftbottom );
1050  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Front_Bottom_Right ),
1051  two.shield2fb.front, four.shield4fbrl.right, eight.shield8.frontrightbottom );
1052  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Back_Bottom_Left ),
1053  two.shield2fb.back, four.shield4fbrl.left, eight.shield8.backleftbottom );
1054  shieldcount += AssignIf( OPTIM_GET( row, table, Shield_Back_Bottom_Right ),
1055  two.shield2fb.back, four.shield4fbrl.right, eight.shield8.backrightbottom );
1056  two.shield2fb.frontmax = two.shield2fb.front;
1057  two.shield2fb.backmax = two.shield2fb.back;
1058  four.shield4fbrl.frontmax = four.shield4fbrl.front;
1059  four.shield4fbrl.backmax = four.shield4fbrl.back;
1060  four.shield4fbrl.rightmax = four.shield4fbrl.right;
1061  four.shield4fbrl.leftmax = four.shield4fbrl.left;
1062  eight.shield8.frontlefttopmax = eight.shield8.frontlefttop;
1063  eight.shield8.frontrighttopmax = eight.shield8.frontrighttop;
1064  eight.shield8.backrighttopmax = eight.shield8.backrighttop;
1065  eight.shield8.backlefttopmax = eight.shield8.backlefttop;
1066  eight.shield8.frontleftbottommax = eight.shield8.frontleftbottom;
1067  eight.shield8.frontrightbottommax = eight.shield8.frontrightbottom;
1068  eight.shield8.backrightbottommax = eight.shield8.backrightbottom;
1069  eight.shield8.backleftbottommax = eight.shield8.backleftbottom;
1070  float r45 = VS_PI/4;
1071  float r90 = VS_PI/2;
1072  float r135 = 3*VS_PI/4;
1073  float r180 = VS_PI;
1074  float r225 = 5*VS_PI/4;
1075  float r270 = 3*VS_PI/2;
1076  float r315 = 7*VS_PI/4;
1077  float r360 = 2*VS_PI;
1078  int iter;
1079  if (shieldcount > MAX_SHIELD_NUMBER)
1080  shieldcount = MAX_SHIELD_NUMBER;
1081  memset( shield.range, 0, sizeof (shield.range) );
1082  if (shieldcount == 8) {
1083  shield.number = 8;
1084  shield.shield.cur[0] = shield.shield.max[0] = eight.shield8.frontlefttopmax;
1085  shield.range[0].thetamin = 0;
1086  shield.range[0].thetamax = r90;
1087  shield.range[0].rhomin = 0;
1088  shield.range[0].rhomax = r90;
1089 
1090  shield.shield.cur[1] = shield.shield.max[1] = eight.shield8.backlefttopmax;
1091  shield.range[1].thetamin = r90;
1092  shield.range[1].thetamax = r180;
1093  shield.range[1].rhomin = 0;
1094  shield.range[1].rhomax = r90;
1095 
1096  shield.shield.cur[2] = shield.shield.max[2] = eight.shield8.frontrighttopmax;
1097  shield.range[2].thetamin = r270;
1098  shield.range[2].thetamax = r360;
1099  shield.range[2].rhomin = 0;
1100  shield.range[2].rhomax = r90;
1101 
1102  shield.shield.cur[3] = shield.shield.max[3] = eight.shield8.backrighttopmax;
1103  shield.range[3].thetamin = r180;
1104  shield.range[3].thetamax = r270;
1105  shield.range[3].rhomin = 0;
1106  shield.range[3].rhomax = r90;
1107 
1108  shield.shield.cur[4] = shield.shield.max[4] = eight.shield8.frontleftbottommax;
1109  shield.range[4].thetamin = 0;
1110  shield.range[4].thetamax = r90;
1111  shield.range[4].rhomin = -r90;
1112  shield.range[4].rhomax = 0;
1113 
1114  shield.shield.cur[5] = shield.shield.max[5] = eight.shield8.backleftbottommax;
1115  shield.range[5].thetamin = r90;
1116  shield.range[5].thetamax = r180;
1117  shield.range[5].rhomin = -r90;
1118  shield.range[5].rhomax = 0;
1119 
1120  shield.shield.cur[6] = shield.shield.max[6] = eight.shield8.frontrightbottommax;
1121  shield.range[6].thetamin = r270;
1122  shield.range[6].thetamax = r360;
1123  shield.range[6].rhomin = -r90;
1124  shield.range[6].rhomax = 0;
1125 
1126  shield.shield.cur[7] = shield.shield.max[7] = eight.shield8.backrightbottommax;
1127  shield.range[7].thetamin = r180;
1128  shield.range[7].thetamax = r270;
1129  shield.range[7].rhomin = -r90;
1130  shield.range[7].rhomax = 0;
1131  } else if (shieldcount == 4) {
1132  shield.number = 4;
1133 
1134  shield.shield.cur[0] = shield.shield.max[0] = four.shield4fbrl.frontmax;
1135  shield.range[0].thetamin = r315;
1136  shield.range[0].thetamax = r360+r45;
1137  shield.range[0].rhomin = -r90;
1138  shield.range[0].rhomax = r90;
1139 
1140  shield.shield.cur[1] = shield.shield.max[1] = four.shield4fbrl.backmax;
1141  shield.range[1].thetamin = r135;
1142  shield.range[1].thetamax = r225;
1143  shield.range[1].rhomin = -r90;
1144  shield.range[1].rhomax = r90;
1145 
1146  shield.shield.cur[2] = shield.shield.max[2] = four.shield4fbrl.rightmax;
1147  shield.range[2].thetamin = r225;
1148  shield.range[2].thetamax = r315;
1149  shield.range[2].rhomin = -r90;
1150  shield.range[2].rhomax = r90;
1151 
1152  shield.shield.cur[3] = shield.shield.max[3] = four.shield4fbrl.leftmax;
1153  shield.range[3].thetamin = r45;
1154  shield.range[3].thetamax = r225;
1155  shield.range[3].rhomin = -r90;
1156  shield.range[3].rhomax = r90;
1157  } else if (shieldcount == 2) {
1158  shield.number = 2;
1159 
1160  shield.shield.cur[0] = shield.shield.max[0] = four.shield2fb.frontmax;
1161  shield.range[0].thetamin = r270;
1162  shield.range[0].thetamax = r360+r90;
1163  shield.range[0].rhomin = -r90;
1164  shield.range[0].rhomax = r90;
1165 
1166  shield.shield.cur[1] = shield.shield.max[1] = four.shield2fb.backmax;
1167  shield.range[1].thetamin = r90;
1168  shield.range[1].thetamax = r270;
1169  shield.range[1].rhomin = -r90;
1170  shield.range[1].rhomax = r90;
1171  } else {
1172  //No shields
1173  shield.number = 0;
1174  }
1175  for (iter = 0; iter < shieldcount; ++iter) {
1176  std::string shieldname = "Shield_"+XMLSupport::tostring( iter );
1177  AssignIfDeg( row[shieldname+"_Min_Theta"], shield.range[iter].thetamin );
1178  AssignIfDeg( row[shieldname+"_Max_Theta"], shield.range[iter].thetamax );
1179  AssignIfDeg( row[shieldname+"_Min_Rho"], shield.range[iter].rhomin );
1180  AssignIfDeg( row[shieldname+"_Max_Rho"], shield.range[iter].rhomax );
1181  }
1182  shield.leak = (char) (::stof( OPTIM_GET( row, table, Shield_Leak ) )*100.0);
1183  shield.recharge = ::stof( OPTIM_GET( row, table, Shield_Recharge ) );
1184  shield.efficiency = ::stof( OPTIM_GET( row, table, Shield_Efficiency ), 1.0 );
1185 
1186  static bool WCfuelhack = XMLSupport::parse_bool( vs_config->getVariable( "physics", "fuel_equals_warp", "false" ) );
1187  maxwarpenergy = warpenergy = ::stof( OPTIM_GET( row, table, Warp_Capacitor ) );
1188 
1189  graphicOptions.MinWarpMultiplier = ::stof( OPTIM_GET( row, table, Warp_Min_Multiplier ), 1.0 );
1190  graphicOptions.MaxWarpMultiplier = ::stof( OPTIM_GET( row, table, Warp_Max_Multiplier ), 1.0 );
1191 
1192  maxenergy = energy = ::stof( OPTIM_GET( row, table, Primary_Capacitor ) );
1193  recharge = ::stof( OPTIM_GET( row, table, Reactor_Recharge ) );
1194  jump.drive = XMLSupport::parse_bool( OPTIM_GET( row, table, Jump_Drive_Present ) ) ? -1 : -2;
1195  jump.delay = ::stoi( OPTIM_GET( row, table, Jump_Drive_Delay ) );
1196  pImage->forcejump = XMLSupport::parse_bool( OPTIM_GET( row, table, Wormhole ) );
1198  table,
1199  Collide_Subunits ),
1200  graphicOptions.RecurseIntoSubUnitsOnCollision ? true : false ) ? 1
1201  : 0;
1202  jump.energy = ::stof( OPTIM_GET( row, table, Outsystem_Jump_Cost ) );
1203  jump.insysenergy = ::stof( OPTIM_GET( row, table, Warp_Usage_Cost ) );
1204  if (WCfuelhack) fuel = warpenergy = warpenergy+jump.energy*0.1f; //this is required to make sure we don't trigger the "globally out of fuel" if we use all warp charges -- save some afterburner for later!!!
1205  afterburnenergy = ::stof( OPTIM_GET( row, table, Afterburner_Usage_Cost ), 32767 );
1206  afterburntype = ::stoi( OPTIM_GET( row, table, Afterburner_Type ) ); //type 1 == "use fuel", type 0 == "use reactor energy", type 2 ==(hopefully) "use jump fuel" 3: NO AFTERBURNER
1207  limits.yaw = ::stof( OPTIM_GET( row, table, Maneuver_Yaw ) )*VS_PI/180.;
1208  limits.pitch = ::stof( OPTIM_GET( row, table, Maneuver_Pitch ) )*VS_PI/180.;
1209  limits.roll = ::stof( OPTIM_GET( row, table, Maneuver_Roll ) )*VS_PI/180.;
1210  {
1211  std::string t, tn, tp;
1212  t = OPTIM_GET( row, table, Yaw_Governor );
1213  tn = OPTIM_GET( row, table, Yaw_Governor_Right );
1214  tp = OPTIM_GET( row, table, Yaw_Governor_Left );
1215  computer.max_yaw_right = ::stof( tn.length() > 0 ? tn : t )*VS_PI/180.;
1216  computer.max_yaw_left = ::stof( tp.length() > 0 ? tp : t )*VS_PI/180.;
1217  t = OPTIM_GET( row, table, Pitch_Governor );
1218  tn = OPTIM_GET( row, table, Pitch_Governor_Up );
1219  tp = OPTIM_GET( row, table, Pitch_Governor_Down );
1220  computer.max_pitch_up = ::stof( tn.length() > 0 ? tn : t )*VS_PI/180.;
1221  computer.max_pitch_down = ::stof( tp.length() > 0 ? tp : t )*VS_PI/180.;
1222  t = OPTIM_GET( row, table, Roll_Governor );
1223  tn = OPTIM_GET( row, table, Roll_Governor_Right );
1224  tp = OPTIM_GET( row, table, Roll_Governor_Left );
1225  computer.max_roll_right = ::stof( tn.length() > 0 ? tn : t )*VS_PI/180.;
1226  computer.max_roll_left = ::stof( tp.length() > 0 ? tp : t )*VS_PI/180.;
1227  }
1228  static float game_accel = XMLSupport::parse_float( vs_config->getVariable( "physics", "game_accel", "1" ) );
1229  static float game_speed = XMLSupport::parse_float( vs_config->getVariable( "physics", "game_speed", "1" ) );
1230  limits.afterburn = ::stof( OPTIM_GET( row, table, Afterburner_Accel ) )*game_accel*game_speed;
1231  limits.forward = ::stof( OPTIM_GET( row, table, Forward_Accel ) )*game_accel*game_speed;
1232  limits.retro = ::stof( OPTIM_GET( row, table, Retro_Accel ) )*game_accel*game_speed;
1233  limits.lateral = .5
1234  *( ::stof( OPTIM_GET( row, table,
1235  Left_Accel ) )+::stof( OPTIM_GET( row, table, Right_Accel ) ) )*game_accel*game_speed;
1236  limits.vertical = .5
1237  *( ::stof( OPTIM_GET( row, table,
1238  Top_Accel ) )+::stof( OPTIM_GET( row, table, Bottom_Accel ) ) )*game_accel*game_speed;
1239  computer.max_combat_speed = ::stof( OPTIM_GET( row, table, Default_Speed_Governor ) )*game_speed;
1240  computer.max_combat_ab_speed = ::stof( OPTIM_GET( row, table, Afterburner_Speed_Governor ) )*game_speed;
1241  computer.itts = stob( OPTIM_GET( row, table, ITTS ), true );
1242  computer.radar.canlock = stob( OPTIM_GET( row, table, Can_Lock ), true );
1243  {
1244  // The Radar_Color column in the units.csv has been changed from a
1245  // boolean value to a string. The boolean values are supported for
1246  // backwardscompatibility.
1247  // When we save this setting, it is simply converted from an integer
1248  // number to a string, and we need to support this as well.
1249  std::string iffval = OPTIM_GET( row, table, Radar_Color );
1250  if ((iffval.empty()) || (iffval == "FALSE") || (iffval == "0"))
1251  {
1253  }
1254  else if ((iffval == "TRUE") || (iffval == "1"))
1255  {
1259  }
1260  else if (iffval == "THREAT")
1261  {
1266  }
1267  else if (iffval == "BUBBLE_THREAT")
1268  {
1274  }
1275  else if (iffval == "PLANE")
1276  {
1280  }
1281  else if (iffval == "PLANE_THREAT")
1282  {
1288  }
1289  else
1290  {
1291  unsigned int value = stoi(iffval, 0);
1292  if (value == 0)
1293  {
1294  // Unknown value
1295  assert(false);
1297  }
1298  else
1299  {
1300  computer.radar.capability = value;
1301  }
1302  }
1303  }
1304  computer.radar.maxrange = stof( OPTIM_GET( row, table, Radar_Range ), FLT_MAX );
1305  computer.radar.maxcone = cos( stof( OPTIM_GET( row, table, Max_Cone ), 180 )*VS_PI/180 );
1306  computer.radar.trackingcone = cos( stof( OPTIM_GET( row, table, Tracking_Cone ), 180 )*VS_PI/180 );
1307  computer.radar.lockcone = cos( stof( OPTIM_GET( row, table, Lock_Cone ), 180 )*VS_PI/180 );
1308  cloakmin = (int) (::stof( OPTIM_GET( row, table, Cloak_Min ) )*2147483136);
1309  if (cloakmin < 0) cloakmin = 0;
1310  pImage->cloakglass = XMLSupport::parse_bool( OPTIM_GET( row, table, Cloak_Glass ) );
1311  if ( (cloakmin&0x1) && !pImage->cloakglass )
1312  cloakmin -= 1;
1313  if ( (cloakmin&0x1) == 0 && pImage->cloakglass )
1314  cloakmin += 1;
1315  if ( !XMLSupport::parse_bool( OPTIM_GET( row, table, Can_Cloak ) ) )
1316  cloaking = -1;
1317  else
1318  cloaking = (int) (-2147483647)-1;
1319  pImage->cloakrate = (int) ( 2147483136.*::stof( OPTIM_GET( row, table, Cloak_Rate ) ) ); //short fix
1320  pImage->cloakenergy = ::stof( OPTIM_GET( row, table, Cloak_Energy ) );
1321  pImage->repair_droid = ::stoi( OPTIM_GET( row, table, Repair_Droid ) );
1322  pImage->ecm = ::stoi( OPTIM_GET( row, table, ECM_Rating ) );
1323 
1324  this->HeatSink = ::stof( OPTIM_GET( row, table, Heat_Sink_Rating ) );
1325  if (pImage->ecm < 0) pImage->ecm *= -1;
1326  if (pImage->cockpit_damage) {
1327  HudDamage( pImage->cockpit_damage, OPTIM_GET( row, table, Hud_Functionality ) );
1328  HudDamage( pImage->cockpit_damage+1+MAXVDUS+UnitImages< void >::NUMGAUGES, OPTIM_GET( row, table, Max_Hud_Functionality ) );
1329  }
1330  pImage->LifeSupportFunctionality = ::stof( OPTIM_GET( row, table, Lifesupport_Functionality ) );
1331  pImage->LifeSupportFunctionalityMax = ::stof( OPTIM_GET( row, table, Max_Lifesupport_Functionality ) );
1332  pImage->CommFunctionality = ::stof( OPTIM_GET( row, table, Comm_Functionality ) );
1333  pImage->CommFunctionalityMax = ::stof( OPTIM_GET( row, table, Max_Comm_Functionality ) );
1334  pImage->fireControlFunctionality = ::stof( OPTIM_GET( row, table, FireControl_Functionality ) );
1335  pImage->fireControlFunctionalityMax = ::stof( OPTIM_GET( row, table, Max_FireControl_Functionality ) );
1336  pImage->SPECDriveFunctionality = ::stof( OPTIM_GET( row, table, SPECDrive_Functionality ) );
1337  pImage->SPECDriveFunctionalityMax = ::stof( OPTIM_GET( row, table, Max_SPECDrive_Functionality ) );
1338  computer.slide_start = ::stoi( OPTIM_GET( row, table, Slide_Start ) );
1339  computer.slide_end = ::stoi( OPTIM_GET( row, table, Slide_End ) );
1340  UpgradeUnit( this, OPTIM_GET( row, table, Upgrades ) );
1341  {
1342  std::string tractorability = OPTIM_GET( row, table, Tractorability );
1343  unsigned char tflags;
1344  if ( !tractorability.empty() ) {
1345  tflags = tractorImmune;
1346  if (tractorability.find_first_of( "pP" ) != string::npos)
1347  tflags |= tractorPush;
1348  if (tractorability.find_first_of( "iI" ) != string::npos)
1349  tflags |= tractorIn;
1350  } else {tflags = tractorPush; } setTractorability( (enum tractorHow) tflags );
1351  }
1352  this->pImage->explosion_type = OPTIM_GET( row, table, Explosion );
1353  if ( pImage->explosion_type.get().length() ) {
1355  } else {
1356  static std::string expani = vs_config->getVariable( "graphics", "explosion_animation", "explosion_orange.ani" );
1357  cache_ani( expani );
1358  }
1359  AddLights( this, xml, OPTIM_GET( row, table, Light ) );
1360  xml.shieldmesh_str = OPTIM_GET( row, table, Shield_Mesh );
1361  if ( xml.shieldmesh_str.length() ) {
1362  addShieldMesh( &xml, xml.shieldmesh_str.c_str(), xml.unitscale, faction, getFlightgroup() );
1363  meshdata.back() = xml.shieldmesh;
1364  } else {
1365  static int shieldstacks = XMLSupport::parse_int( vs_config->getVariable( "graphics", "shield_detail", "16" ) );
1366  static std::string shieldtex = vs_config->getVariable( "graphics", "shield_texture", "shield.bmp" );
1367  static std::string shieldtechnique = vs_config->getVariable( "graphics", "shield_technique", "" );
1368  meshdata.back() = new SphereMesh( rSize(), shieldstacks, shieldstacks, shieldtex.c_str(), shieldtechnique, NULL, false, ONE, ONE );
1369  }
1370  meshdata.back()->EnableSpecialFX();
1371  //Begin the Pow-w-w-war Zone Collide Tree Generation
1372  {
1373  xml.rapidmesh_str = OPTIM_GET( row, table, Rapid_Mesh );
1374  vector< mesh_polygon >polies;
1375 
1376  std::string collideTreeHash = VSFileSystem::GetHashName( modification+"#"+row[0] );
1377  this->colTrees = collideTrees::Get( collideTreeHash );
1378  if (this->colTrees)
1379  this->colTrees->Inc();
1380  csOPCODECollider *colShield = NULL;
1381  string tmpname = row[0]; //key
1382  if (!this->colTrees) {
1383  string val;
1384  xml.hasColTree = 1;
1385  if ( ( val = OPTIM_GET( row, table, Use_Rapid ) ).length() )
1386  xml.hasColTree = XMLSupport::parse_bool( val );
1387  if (xml.shieldmesh) {
1388  if ( meshdata.back() ) {
1389  meshdata.back()->GetPolys( polies );
1390  colShield = new csOPCODECollider( polies );
1391  }
1392  }
1393  if ( xml.rapidmesh_str.length() )
1394  addRapidMesh( &xml, xml.rapidmesh_str.c_str(), xml.unitscale, faction, getFlightgroup() );
1395  else
1396  xml.rapidmesh = NULL;
1397  polies.clear();
1398  if (xml.rapidmesh)
1399  xml.rapidmesh->GetPolys( polies );
1400  csOPCODECollider *csrc = NULL;
1401  if (xml.hasColTree) {
1402  csrc = getCollideTree( Vector( 1, 1, 1 ),
1403  xml.rapidmesh
1404  ? &polies : NULL );
1405  }
1406  this->colTrees = new collideTrees( collideTreeHash,
1407  csrc,
1408  colShield );
1409  if (xml.rapidmesh && xml.hasColTree) {
1410  //if we have a special rapid mesh we need to generate things now
1411  for (unsigned int i = 1; i < collideTreesMaxTrees; ++i)
1412  if (!this->colTrees->rapidColliders[i]) {
1413  unsigned int which = 1<<i;
1414  this->colTrees->rapidColliders[i] =
1415  getCollideTree( Vector( 1, 1, which ),
1416  &polies );
1417  }
1418  }
1419  if (xml.rapidmesh) {
1420  delete xml.rapidmesh;
1421  xml.rapidmesh = NULL;
1422  }
1423  }
1424  }
1425  CheckAccessory( this ); //turns on the ceerazy rotation for any accessories
1426  this->setAverageGunSpeed();
1427 }
void Unit::LoadXML ( const char *  filename,
const char *  unitModifications = "",
std::string *  xmlbuffer = NULL 
)
void Unit::LoadXML ( VSFileSystem::VSFile f,
const char *  unitModifications = "",
std::string *  xmlbuffer = NULL 
)
Vector Unit::LocalCoordinates ( Unit un) const
inline

Definition at line 871 of file unit_generic.h.

References Position(), and ToLocalCoordinates().

Referenced by Mount::NextMountCloser(), and Radar::Track::Track().

872  {
873  return ToLocalCoordinates( ( un->Position()-Position() ).Cast() );
874  }
int Unit::LockMissile ( ) const

Definition at line 5561 of file unit_generic.cpp.

References Mount::ACTIVE, and isMissile().

5562 {
5563  bool missilelock = false;
5564  bool dumblock = false;
5565  for (int i = 0; i < GetNumMounts(); ++i) {
5566  if ( mounts[i].status == Mount::ACTIVE && mounts[i].type->LockTime > 0 && mounts[i].time_to_lock <= 0
5567  && isMissile( mounts[i].type ) )
5568  missilelock = true;
5569  else if (mounts[i].status == Mount::ACTIVE && mounts[i].type->LockTime == 0 && isMissile( mounts[i].type )
5570  && mounts[i].time_to_lock <= 0)
5571  dumblock = true;
5572  }
5573  return missilelock ? 1 : (dumblock ? -1 : 0);
5574 }
void Unit::LockTarget ( bool  myboo)

Definition at line 5275 of file unit_generic.cpp.

References UnitUtil::isSignificant().

Referenced by FireKeyboard::Execute().

5276 {
5277  computer.radar.locked = myboo;
5278  if ( myboo && computer.radar.canlock == false && false == UnitUtil::isSignificant( Target() ) )
5279  computer.radar.locked = false;
5280 }
void Unit::LongitudinalThrust ( float  amt)

Definition at line 3519 of file unit_generic.cpp.

References Vector.

3520 {
3521  if (amt > 1.0) amt = 1.0;
3522  if (amt < -1.0) amt = -1.0;
3523  ApplyLocalForce( amt*limits.forward*Vector( 0, 0, 1 ) );
3524 }
float Unit::LShieldData ( ) const

Definition at line 4812 of file unit_generic.cpp.

Referenced by GameCockpit::LookupTargetStat(), GameCockpit::LookupUnitStat(), Orders::AggressiveAI::ProcessLogicItem(), Orders::AggressiveAI::SetParent(), and UpAndDownGrade().

4813 {
4814  switch (shield.number)
4815  {
4816  case 2:
4817  return 0; //no data, captain
4818 
4819  case 4:
4820  {
4821  if (shield.shield4fbrl.leftmax != 0)
4822  return (shield.shield4fbrl.left)/shield.shield4fbrl.leftmax;
4823  break;
4824  }
4825  case 8:
4826  {
4827  if (shield.shield8.backlefttopmax != 0 || shield.shield8.backleftbottommax != 0
4828  || shield.shield8.frontlefttopmax != 0 || shield.shield8.frontleftbottommax
4829  != 0) {
4830  return (shield.shield8.backlefttop+shield.shield8.backleftbottom+shield.shield8.frontlefttop
4831  +shield.shield8.frontleftbottom)
4832  /(shield.shield8.backlefttopmax+shield.shield8.backleftbottommax+shield.shield8.frontlefttopmax
4833  +shield.shield8.frontleftbottommax);
4834  }
4835  break;
4836  }
4837  }
4838  return 0;
4839 }
Unit * Unit::makeMasterPartList ( )
static

Definition at line 1793 of file unit_csv.cpp.

References AddCargo(), UnitImages< BOGUS >::cargo, Cargo::category, VSFileSystem::VSFile::Close(), Cargo::content, Cargo::description, GetCargo(), GetImageInformation(), VSFileSystem::VSFile::GetRoot(), VegaConfig::getVariable(), i, Cargo::mass, name, VSFileSystem::Ok, VSFileSystem::VSFile::OpenReadOnly(), Cargo::price, Cargo::quantity, stof(), stoi(), Unit(), VSFileSystem::UnknownFile, UpdateMasterPartList(), Cargo::volume, and vs_config.

Referenced by UnitFactory::getMasterPartList().

1794 {
1795  static std::string mpl = vs_config->getVariable( "data", "master_part_list", "master_part_list" );
1796  Unit *ret = new Unit();
1797  ret->name = "master_part_list";
1798  VSFileSystem::VSFile mplf;
1800  unsigned int i;
1801  if (err <= VSFileSystem::Ok) {
1802  CSVTable table( mplf, mplf.GetRoot() );
1803  mplf.Close();
1804  vsUMap< std::string, int >::const_iterator it;
1805  for (it = table.rows.begin(); it != table.rows.end(); ++it) {
1806  CSVRow row( &table, it->second );
1807  Cargo carg;
1808  carg.content = row["file"];
1809  carg.category = row["categoryname"];
1810  carg.volume = stof( row["volume"], 1 );
1811  carg.mass = stof( row["mass"], 1 );
1812  carg.quantity = 1;
1813  carg.price = stoi( row["price"], 1 );
1814  carg.description = row["description"];
1815  ret->GetImageInformation().cargo.push_back( carg );
1816  }
1817  }
1818  UpdateMasterPartList( ret );
1819  if ( !ret->GetCargo( "Pilot", i ) ) //required items
1820  ret->AddCargo( Cargo( "Pilot", "Contraband", 800, 1, .01, 1, 1.0, 1.0 ), true );
1821  if ( !ret->GetCargo( "Hitchhiker", i ) )
1822  ret->AddCargo( Cargo( "Hitchhiker", "Passengers", 42, 1, .01, 5.0, 1.0, 1.0 ), true );
1823  if ( !ret->GetCargo( "Slaves", i ) )
1824  ret->AddCargo( Cargo( "Slaves", "Contraband", 800, 1, .01, 1, 1, 1 ), true );
1825  return ret;
1826 }
std::string Unit::massSerializer ( const struct XMLType input,
void *  mythis 
)
staticprotected

Definition at line 8581 of file unit_generic.cpp.

References UnitImages< BOGUS >::cargo, VegaConfig::getVariable(), Mass, XMLSupport::parse_bool(), pImage, XMLSupport::tostring(), and vs_config.

8582 {
8583  Unit *un = (Unit*) mythis;
8584  float mass = un->Mass;
8585  static bool usemass = XMLSupport::parse_bool( vs_config->getVariable( "physics", "use_cargo_mass", "true" ) );
8586  for (unsigned int i = 0; i < un->pImage->cargo.size(); ++i)
8587  if (un->pImage->cargo[i].quantity > 0)
8588  if (usemass)
8589  mass -= un->pImage->cargo[i].mass*un->pImage->cargo[i].quantity;
8590  return XMLSupport::tostring( (float) mass );
8591 }
float Unit::MaxEnergyData ( ) const
inline

Definition at line 911 of file unit_generic.h.

References maxenergy.

Referenced by ZoneMgr::addDamage(), and showUnitStats().

912  {
913  return maxenergy;
914  }
float Unit::MaxShieldVal ( ) const
protected

Definition at line 3622 of file unit_generic.cpp.

Referenced by RepairUpgrade().

3623 {
3624  float maxshield = 0;
3625  switch (shield.number)
3626  {
3627  case 2:
3628  maxshield = .5*(shield.shield2fb.frontmax+shield.shield2fb.backmax);
3629  break;
3630  case 4:
3631  maxshield = .25
3632  *(shield.shield4fbrl.frontmax+shield.shield4fbrl.backmax+shield.shield4fbrl.leftmax
3633  +shield.shield4fbrl.rightmax);
3634  break;
3635  case 8:
3636  maxshield = .125
3637  *(shield.shield8.frontrighttopmax+shield.shield8.backrighttopmax+shield.shield8.frontlefttopmax
3638  +shield.shield8.backlefttopmax+shield.shield8.frontrightbottommax+shield.shield8.backrightbottommax
3639  +shield.shield8.frontleftbottommax+shield.shield8.backleftbottommax);
3640  break;
3641  }
3642  return maxshield;
3643 }
Vector Unit::MaxThrust ( const Vector thrust)

Definition at line 3400 of file unit_generic.cpp.

References copysign(), and Vector.

3401 {
3402  //amt1 is a normal
3403  return amt1*(Vector( copysign( limits.lateral, amt1.i ),
3404  copysign( limits.vertical, amt1.j ),
3405  amt1.k > 0 ? limits.forward : -limits.retro )*amt1);
3406 }
Vector Unit::MaxTorque ( const Vector torque)

Definition at line 3267 of file unit_generic.cpp.

References copysign(), and Vector.

3268 {
3269  //torque is a normal
3270  return torque*(Vector( copysign( limits.pitch, torque.i ),
3271  copysign( limits.yaw, torque.j ),
3272  copysign( limits.roll, torque.k ) )*torque);
3273 }
Vector Unit::MountPercentOperational ( int  whichmount)

Definition at line 7547 of file unit_generic.cpp.

References Mount::ACTIVE, Mount::INACTIVE, Mount::UNCHOSEN, and Vector.

7548 {
7549  if ( whichmount < 0 || (unsigned int) whichmount >= mounts.size() ) return Vector( -1, -1, -1 );
7550  return Vector( mounts[whichmount].functionality,
7551  mounts[whichmount].maxfunctionality,
7552  ( (mounts[whichmount].status == Mount::ACTIVE || mounts[whichmount].status
7553  == Mount::INACTIVE) ? 0.0 : (Mount::UNCHOSEN ? 2.0 : 1.0) ) );
7554 }
std::string Unit::mountSerializer ( const struct XMLType input,
void *  mythis 
)
staticprotected

Definition at line 8621 of file unit_generic.cpp.

References Mount::ACTIVE, GetNumMounts(), Matrix::getQ(), Matrix::getR(), XMLType::wordlength::hardint, Mount::INACTIVE, lookupMountSize(), mounts, Matrix::p, XMLSupport::parse_float(), XMLType::str, tostring(), XMLSupport::tostring(), and XMLType::w.

8622 {
8623  Unit *un = (Unit*) mythis;
8624  int i = input.w.hardint;
8625  if (un->GetNumMounts() > i) {
8626  string result( lookupMountSize( un->mounts[i].size ) );
8627  if (un->mounts[i].status == Mount::INACTIVE || un->mounts[i].status == Mount::ACTIVE)
8628  result += string( "\" weapon=\"" )+(un->mounts[i].type->weapon_name);
8629  if (un->mounts[i].ammo != -1)
8630  result += string( "\" ammo=\"" )+XMLSupport::tostring( un->mounts[i].ammo );
8631  if (un->mounts[i].volume != -1)
8632  result += string( "\" volume=\"" )+XMLSupport::tostring( un->mounts[i].volume );
8633  result += string( "\" xyscale=\"" )+XMLSupport::tostring( un->mounts[i].xyscale )+string( "\" zscale=\"" )
8634  +XMLSupport::tostring( un->mounts[i].zscale );
8635  Matrix m;
8636  Transformation( un->mounts[i].GetMountOrientation(), un->mounts[i].GetMountLocation().Cast() ).to_matrix( m );
8637  result += string( "\" x=\"" )+tostring( (float) ( m.p.i/parse_float( input.str ) ) );
8638  result += string( "\" y=\"" )+tostring( (float) ( m.p.j/parse_float( input.str ) ) );
8639  result += string( "\" z=\"" )+tostring( (float) ( m.p.k/parse_float( input.str ) ) );
8640 
8641  result += string( "\" qi=\"" )+tostring( m.getQ().i );
8642  result += string( "\" qj=\"" )+tostring( m.getQ().j );
8643  result += string( "\" qk=\"" )+tostring( m.getQ().k );
8644 
8645  result += string( "\" ri=\"" )+tostring( m.getR().i );
8646  result += string( "\" rj=\"" )+tostring( m.getR().j );
8647  result += string( "\" rk=\"" )+tostring( m.getR().k );
8648  return result;
8649  } else {
8650  return string( "" );
8651  }
8652 }
virtual int Unit::nummesh ( ) const
inlinevirtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 507 of file unit_generic.h.

References meshdata.

Referenced by getCollideTree(), querySphere(), and querySphereNoRecurse().

508  {
509  return ( (int) meshdata.size() )-1;
510  }
Unit& Unit::operator= ( const Unit )
protected
void Unit::PerformDockingOperations ( )

CHOOSE NEW MISSION

force him in a box...err where he is

Definition at line 5795 of file unit_generic.cpp.

References _Universe, Universe::AccessCockpit(), AngularVelocity, curr_physical_state, Cockpit::GetParent(), HoldPositionWithRespectTo(), NetForce, NetLocalForce, NetLocalTorque, NetTorque, prev_physical_state, UpgradeInterface(), Vector, and Velocity.

5796 {
5797  for (unsigned int i = 0; i < pImage->dockedunits.size(); ++i) {
5798  Unit *un;
5799  if ( ( un = pImage->dockedunits[i]->uc.GetUnit() ) == NULL ) {
5800  FreeDockingPort( i );
5801  i--;
5802  continue;
5803  }
5806  un->NetForce = Vector( 0, 0, 0 );
5807  un->NetLocalForce = Vector( 0, 0, 0 );
5808  un->NetTorque = Vector( 0, 0, 0 );
5809  un->NetLocalTorque = Vector( 0, 0, 0 );
5810  un->AngularVelocity = Vector( 0, 0, 0 );
5811  un->Velocity = Vector( 0, 0, 0 );
5812  if ( un == _Universe->AccessCockpit()->GetParent() ) {
5814  for (unsigned int i = 0; i < pImage->clearedunits.size(); ++i)
5815  //this is a hack because we don't have an interface to say "I want to buy a ship" this does it if you press shift-c in the base
5816  if (pImage->clearedunits[i] == un) {
5817  pImage->clearedunits.erase( pImage->clearedunits.begin()+i );
5818  un->UpgradeInterface( this );
5819  }
5820  }
5821  //now we know the unit's still alive... what do we do to him *G*
5823  }
5824 }
void Unit::PitchTorque ( float  amt)

Definition at line 3534 of file unit_generic.cpp.

References Vector.

3535 {
3536  if (amt > limits.pitch) amt = limits.pitch;
3537  else if (amt < -limits.pitch)
3538  amt = -limits.pitch;
3539  ApplyLocalTorque( amt*Vector( 1, 0, 0 ) );
3540 }
QVector Unit::Position ( ) const
inline

Definition at line 938 of file unit_generic.h.

References cumulative_transformation, and Transformation::position.

Referenced by ActuallyWarpTo(), AddUnitToSystem(), AdjustMatrix(), Orders::AggressiveAI::AfterburnerJumpTurnTowards(), AfterburnerSlide(), AfterburnTurnAway(), AfterburnVeerAndTurnAway(), aim_assist(), AllUnitsCloseAndEngage(), MissileEffect::ApplyDamage(), AutoPilotToErrorMessage(), buyShip(), CalculateNearestWarpUnit(), CanDockWithMe(), CanFaceTarget(), Orders::FireAt::ChangeLocalDirection(), ChooseNearNavPoint(), CloseEnoughToNavOrDest(), Terrain::Collide(), ContinuousTerrain::Collide(), Beam::Collide(), Collide(), compute_light_dot(), CrashForceDock(), DealPossibleJumpDamage(), Mission::DirectorShipDestroyed(), Missile::Discharge(), DistanceTwoTargets(), GameCockpit::DoAutoLanding(), dockingdistance(), DockToSavedBases(), Orders::DockingOps::DockToTarget(), GameStarSystem::DoJumpingLeaveSightAndSound(), WarpTrail::Draw(), GameStarSystem::Draw(), VDU::Draw(), GameCockpit::Draw(), GameStarSystem::DrawJumpStars(), EjectCargo(), Orders::TurretAI::Execute(), Orders::MoveToParent::Execute(), Orders::ChangeHeading::Execute(), Orders::FaceTarget::Execute(), Orders::AutoLongHaul::Execute(), Orders::FaceTargetITTS::Execute(), Orders::FaceDirection::Execute(), Orders::LoopAround::Execute(), Orders::LoopAroundAgro::Execute(), Orders::FacePerpendicular::Execute(), Orders::AggressiveAI::ExecuteNoEnemies(), GameUnit< UnitType >::Explode(), FaceCamTarget(), FaceTarget(), anonymous_namespace{autodocking.cpp}::FindDockingPort(), getAtmospheric(), UnitUtil::getDistance(), getNearestTarget(), getNearestTargetUnit(), UnitUtil::getPhysicsPriority(), CommunicatingAI::GetRandomUnit(), GetThreat(), NetClient::inGame(), InRange(), Inside(), InsideCollideTree(), StarSystem::JumpTo(), LoadMission(), LocalCoordinates(), GameCockpit::LookupUnitStat(), Orders::DockingOps::Movement(), MoveTo(), Nearby(), Orders::DockingOps::PerformDockingOperations(), Priority(), Orders::AggressiveAI::ProcessCurrentFgDirective(), Orders::AggressiveAI::ProcessLogicItem(), querySphere(), querySphereNoRecurse(), rayCollide(), GamePlanet::reactToCollision(), reactToCollision(), RealPosition(), SelectDockPort(), SetupVAndTargetV(), GameCockpit::SetupViewPort(), SheltonSlide(), ShoveCamBehindUnit(), ShoveCamBelowUnit(), SkilledABSlide(), TargFront(), GameUnit< UnitType >::Thrust(), GameUnit< UnitType >::TransferUnitToSystem(), TurnAway(), Orders::DockingOps::Undock(), Cockpit::Update(), UpdatePhysics(), GameMissile::UpdatePhysics2(), Missile::UpdatePhysics2(), VectorThrustHelper(), WarpToP(), GameUniverse::WriteSaveGame(), and WriteUnitString().

939  {
941  }
QVector Unit::PositionITTS ( const QVector firingposit,
Vector  firingvelocity,
float  gunspeed,
bool  smooth_itts 
) const

Definition at line 1667 of file unit_generic.cpp.

References game_data_t::difficulty, g_game, QVector, and speed.

Referenced by AdjustMatrix(), cosAngleFromMountTo(), cosAngleTo(), and Orders::FaceTargetITTS::Execute().

1668 {
1669  if (speed == FLT_MAX)
1670  return this->Position();
1671  float difficultyscale = 1;
1672  if (g_game.difficulty < .99)
1673  GetVelocityDifficultyMult( difficultyscale );
1674  velocity = (cumulative_velocity.Scale( difficultyscale )-velocity);
1675  QVector posit( this->Position()-absposit );
1676  QVector curguess( posit );
1677  for (unsigned int i = 0; i < 3; ++i) {
1678  float time = 0;
1679  if (speed > 0.001)
1680  time = curguess.Magnitude()/speed;
1681  if (steady_itts)
1682  //** jay
1683  curguess = posit+GetVelocity().Cast().Scale( time );
1684  else
1685  curguess = posit+velocity.Scale( time ).Cast();
1686  }
1687  return curguess+absposit;
1688 }
float Unit::PriceCargo ( const std::string &  s)

Definition at line 7761 of file unit_generic.cpp.

References Cargo::content, UnitFactory::getMasterPartList(), VegaConfig::getVariable(), XMLSupport::parse_float(), PriceCargo(), and vs_config.

Referenced by BaseComputer::SellUpgradeOperation::concludeTransaction(), BaseComputer::configureUpgradeCommitControls(), PriceCargo(), RepairUpgradeCargo(), SellCargo(), and BaseComputer::updateTransactionControlsForSelection().

7762 {
7763  Cargo tmp;
7764  tmp.content = s;
7765  vector< Cargo >::iterator mycargo = std::find( pImage->cargo.begin(), pImage->cargo.end(), tmp );
7766  if ( mycargo == pImage->cargo.end() ) {
7768  if (this != mpl) {
7769  return mpl->PriceCargo( s );
7770  } else {
7771  static float spacejunk = parse_float( vs_config->getVariable( "cargo", "space_junk_price", "10" ) );
7772  return spacejunk;
7773  }
7774  }
7775  float price;
7776  price = (*mycargo).price;
7777  return price;
7778 }
void Unit::PrimeOrders ( )

Definition at line 1942 of file unit_generic.cpp.

References Order::SetParent().

Referenced by NetClient::AddClientObject(), Arrested(), Mission::call_unit_launch(), EjectCargo(), Orders::AggressiveAI::ExecuteNoEnemies(), UnitUtil::orbit(), UnitUtil::performDockingOperations(), SwitchUnits(), SwitchUnits2(), and SwitchUnitsTurret().

1943 {
1944  if (aistate) {
1945  aistate->Destroy();
1946  aistate = NULL;
1947  }
1948  aistate = new Order; //get 'er ready for enqueueing
1949  aistate->SetParent( this );
1950 }
void Unit::PrimeOrders ( Order newAI)

Definition at line 1930 of file unit_generic.cpp.

References Order::SetParent().

1931 {
1932  if (newAI) {
1933  if (aistate)
1934  aistate->Destroy();
1935  aistate = newAI;
1936  newAI->SetParent( this );
1937  } else {
1938  PrimeOrders();
1939  }
1940 }
void Unit::PrimeOrdersLaunched ( )

Definition at line 1952 of file unit_generic.cpp.

References Vector.

1953 {
1954  if (aistate) {
1955  aistate->Destroy();
1956  aistate = NULL;
1957  }
1958  Vector vec( 0, 0, 10000 );
1959  aistate = new ExecuteFor( new Orders::MatchVelocity( this->ClampVelocity( vec, true ), Vector( 0,
1960  0,
1961  0 ), true, true,
1962  false ), 4.0f );
1963  aistate->SetParent( this );
1964 }
void Unit::ProcessDeleteQueue ( )
static

might modify unitdeletequeue

Definition at line 4870 of file unit_generic.cpp.

References Unitdeletequeue, and VSFileSystem::vs_fprintf().

Referenced by StarSystem::Update().

4871 {
4872  while ( !Unitdeletequeue.empty() ) {
4873 #ifdef DESTRUCTDEBUG
4874  VSFileSystem::vs_fprintf( stderr, "Eliminatin' 0x%x - %d", Unitdeletequeue.back(), Unitdeletequeue.size() );
4875  fflush( stderr );
4876  VSFileSystem::vs_fprintf( stderr, "Eliminatin' %s\n", Unitdeletequeue.back()->name.c_str() );
4877 #endif
4878 #ifdef DESTRUCTDEBUG
4879  if ( Unitdeletequeue.back()->isSubUnit() )
4880  VSFileSystem::vs_fprintf( stderr, "Subunit Deleting (related to double dipping)" );
4881 #endif
4882  Unit *mydeleter = Unitdeletequeue.back();
4883  Unitdeletequeue.pop_back();
4884  delete mydeleter;
4885 
4886 #ifdef DESTRUCTDEBUG
4887  VSFileSystem::vs_fprintf( stderr, "Completed %d\n", Unitdeletequeue.size() );
4888  fflush( stderr );
4889 #endif
4890  }
4891 }
bool Unit::queryFrustum ( double  frustum[6][4]) const
inline

Definition at line 1380 of file unit_generic.h.

1381  {
1382  return false;
1383  }
bool Unit::querySphere ( const QVector pnt,
float  err 
) const

Definition at line 406 of file unit_collide.cpp.

References UnitCollection::constFastIterator(), cumulative_transformation_matrix, UnitCollection::empty(), Matrix::getP(), graphicOptions, i, isPlanet(), meshdata, nummesh(), Matrix::p, Position(), radial_size, Unit::graphic_options::RecurseIntoSubUnitsOnCollision, UniverseUtil::sqrt(), SubUnits, Transform(), and Vector.

Referenced by Inside(), GameMissile::UpdatePhysics2(), and Missile::UpdatePhysics2().

407 {
408  int i;
410 
411  Vector TargetPoint( tmpo->getP() );
412 #ifdef VARIABLE_LENGTH_PQR
413  //adjust the ship radius by the scale of local coordinates
414  double SizeScaleFactor = sqrt( TargetPoint.Dot( TargetPoint ) );
415 #endif
416  if ( nummesh() < 1 && isPlanet() ) {
417  TargetPoint = (tmpo->p-pnt).Cast();
418  if (TargetPoint.Dot( TargetPoint )
419  < err*err
421 #ifdef VARIABLE_LENGTH_PQR
422  *SizeScaleFactor*SizeScaleFactor
423 #endif
424  +
425 #ifdef VARIABLE_LENGTH_PQR
426  SizeScaleFactor*
427 #endif
428  2.0f*err*radial_size
429  )
430  return true;
431  } else {
432  for (i = 0; i < nummesh(); i++) {
433  TargetPoint = (Transform( *tmpo, meshdata[i]->Position().Cast() )-pnt).Cast();
434  if (TargetPoint.Dot( TargetPoint )
435  < err*err
436  +meshdata[i]->rSize()*meshdata[i]->rSize()
437 #ifdef VARIABLE_LENGTH_PQR
438  *SizeScaleFactor*SizeScaleFactor
439 #endif
440  +
441 #ifdef VARIABLE_LENGTH_PQR
442  SizeScaleFactor*
443 #endif
444  2.0f*err*meshdata[i]->rSize()
445  )
446  return true;
447  }
448  }
450  if ( !SubUnits.empty() ) {
452  for (const Unit *un; (un = *i); ++i)
453  if ( (un)->querySphere( pnt, err ) )
454  return true;
455  }
456  }
457  return false;
458 }
float Unit::querySphere ( const QVector start,
const QVector end,
float  my_unit_radius = 0 
) const

Definition at line 460 of file unit_collide.cpp.

References UnitCollection::constFastIterator(), UnitCollection::empty(), i, querySphereNoRecurse(), and SubUnits.

461 {
462  if ( !SubUnits.empty() ) {
464  for (const Unit *un; (un = *i); ++i) {
465  float tmp;
466  if ( ( tmp = un->querySphere( start, end, min_radius ) ) != 0 )
467  return tmp;
468  }
469  }
470  return querySphereNoRecurse( start, end, min_radius );
471 }
float Unit::querySphereClickList ( const QVector st,
const QVector dir,
float  err 
) const

Definition at line 5655 of file unit_generic.cpp.

References Matrix::getP(), k, perplines, querySphereClickList(), QVector, Transform(), and Vector.

Referenced by querySphereClickList().

5656 {
5657  int i;
5658  float retval = 0;
5659  float adjretval = 0;
5661 
5662  Vector TargetPoint( tmpo->getP() );
5663  for (i = 0; i < nummesh(); ++i) {
5664  TargetPoint = Transform( *tmpo, meshdata[i]->Position() );
5665  Vector origPoint = TargetPoint;
5666 
5667  perplines.push_back( TargetPoint );
5668  //find distance away from the line now :-)
5669  //find scale factor of end on start to get line.
5670  QVector tst = TargetPoint.Cast()-st;
5671  float k = tst.Dot( dir );
5672  TargetPoint = ( tst-k*(dir) ).Cast();
5673  perplines.push_back( origPoint-TargetPoint );
5674  if (TargetPoint.Dot( TargetPoint )
5675  < err*err
5676  +meshdata[i]->rSize()*meshdata[i]->rSize()+2*err*meshdata[i]->rSize()
5677  ) {
5678  if (retval == 0) {
5679  retval = k;
5680  adjretval = k;
5681  if (adjretval < 0) {
5682  adjretval += meshdata[i]->rSize();
5683  if (adjretval > 0)
5684  adjretval = .001;
5685  }
5686  } else {
5687  if ( retval > 0 && k < retval && k > -meshdata[i]->rSize() ) {
5688  retval = k;
5689  adjretval = k;
5690  if (adjretval < 0) {
5691  adjretval += meshdata[i]->rSize();
5692  if (adjretval > 0)
5693  adjretval = .001;
5694  }
5695  }
5696  if (retval < 0 && k+meshdata[i]->rSize() > retval) {
5697  retval = k;
5698  adjretval = k+meshdata[i]->rSize();
5699  if (adjretval > 0)
5700  //THRESHOLD;
5701  adjretval = .001;
5702  }
5703  }
5704  }
5705  }
5706  const Unit *su;
5707  for (un_kiter ui = viewSubUnits(); (su = *ui); ++ui) {
5708  float tmp = su->querySphereClickList( st, dir, err );
5709  if (tmp == 0)
5710  continue;
5711  if (retval == 0) {
5712  retval = tmp;
5713  } else {
5714  if (adjretval > 0 && tmp < adjretval) {
5715  retval = tmp;
5716  adjretval = tmp;
5717  }
5718  if (adjretval < 0 && tmp > adjretval) {
5719  retval = tmp;
5720  adjretval = tmp;
5721  }
5722  }
5723  }
5724  return adjretval;
5725 }
virtual bool Unit::querySphereClickList ( int  ,
int  ,
float  err,
Camera activeCam 
)
inlinevirtual

Queries the bounding sphere with a duo of mouse coordinates that project to the center of a ship and compare with a sphere...pretty fast queries the sphere for weapons (world space point) Only in Unit class

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 1391 of file unit_generic.h.

1392  {
1393  return false;
1394  }
float Unit::querySphereNoRecurse ( const QVector start,
const QVector end,
float  my_unit_radius = 0 
) const

Definition at line 474 of file unit_collide.cpp.

References a, b, c, cumulative_transformation_matrix, i, isUnit(), Magnitude(), meshdata, nummesh(), PLANETPTR, Position(), QVector, rSize(), UniverseUtil::sqrt(), start, and Transform().

Referenced by querySphere(), and rayCollide().

475 {
476  int i;
477  double tmp;
478  for (i = 0; i < nummesh(); i++) {
479  if ( ( meshdata[i]->Position().Magnitude() > this->rSize() ) || ( meshdata[i]->rSize() > 30+this->rSize() ) )
480  continue;
481  if (isUnit() == PLANETPTR && i > 0)
482  break;
483  double a, b, c;
485 
486  QVector dir = end-start; //now start and end are based on mesh's position
487  c = st.Dot( st );
488  double temp1 = ( min_radius+meshdata[i]->rSize() );
489  //if (st.MagnitudeSquared()<temp1*temp1) //UNCOMMENT if you want inside sphere to count...otherwise...
490  //return 1.0e-6;
491  if (min_radius != -FLT_MAX)
492  c = c-temp1*temp1;
493  else
494  c = temp1;
495 #ifdef VARIABLE_LENGTH_PQR
496  c *= SizeScaleFactor*SizeScaleFactor;
497 #endif
498  b = 2.0f*( dir.Dot( st ) );
499  a = dir.Dot( dir );
500  //b^2-4ac
501  if (min_radius != -FLT_MAX)
502  c = b*b-4.0f*a*c;
503  else
504  c = FLT_MAX;
505  if (c < 0 || a == 0)
506  continue;
507  a *= 2.0f;
508 
509  tmp = ( -b+sqrt( c ) )/a;
510  c = ( -b-sqrt( c ) )/a;
511  if (tmp > 0 && tmp <= 1)
512  return (c > 0 && c < tmp) ? c : tmp;
513  else if (c > 0 && c <= 1)
514  return c;
515  }
516  return 0.0f;
517 }
Unit * Unit::rayCollide ( const QVector st,
const QVector end,
Vector normal,
float distance 
)

Definition at line 346 of file unit_collide.cpp.

References collideTrees::colTree(), colTrees, cumulative_transformation_matrix, UnitCollection::empty(), f, UnitCollection::fastIterator(), VegaConfig::getVariable(), GetWarpVelocity(), globQuerySphere(), graphicOptions, i, InvTransform(), Magnitude(), Matrix::p, XMLSupport::parse_bool(), Position(), querySphereNoRecurse(), QVector, csOPCODECollider::rayCollide(), rayCollide(), Unit::graphic_options::RecurseIntoSubUnitsOnCollision, rSize(), start, SubUnits, Vector, vs_config, and VSFileSystem::vs_dprintf().

Referenced by Bolt::Collide(), Beam::Collide(), and rayCollide().

347 {
348  Unit *tmp;
349  float rad = this->rSize();
351  if ( ( tmp = *SubUnits.fastIterator() ) )
352  rad += tmp->rSize();
354  return NULL;
356  if ( !SubUnits.empty() ) {
358  for (Unit *un; (un = *i); ++i)
359  if ( ( tmp = un->rayCollide( start, end, norm, distance) ) != 0 )
360  return tmp;
361  }
362  }
365  static bool sphere_test = XMLSupport::parse_bool( vs_config->getVariable( "physics", "sphere_collision", "true" ) );
366  distance = querySphereNoRecurse( start, end );
367  if (distance > 0.0f || (this->colTrees&&this->colTrees->colTree( this, this->GetWarpVelocity() )&&!sphere_test)) {
368  Vector coord;
369  /* Set up points and ray to send to ray collider. */
370  Opcode::Point rayOrigin(st.i,st.j,st.k);
371  Opcode::Point rayDirection(ed.i,ed.j,ed.k);
372  Opcode::Ray boltbeam(rayOrigin,rayDirection);
373  if(this->colTrees){
374  // Retrieve the correct scale'd collider from the unit's collide tree.
375  csOPCODECollider *tmpCol = this->colTrees->colTree( this, this->GetWarpVelocity() );
376  QVector del(end-start);
377  //Normalize(del);
378  norm = ((start+del*distance)-Position()).Cast();
379  Normalize(norm);
380  //RAY COLLIDE does not yet set normal, use that of the sphere center to current loc
381  if (tmpCol==NULL) {
382 
383  return this;
384  }
385  if(tmpCol->rayCollide(boltbeam,norm,distance)){
386  // compute real distance
387  distance = (end-start).Magnitude() * distance;
388 
389  // NOTE: Here is where we need to retrieve the point on the ray that we collided with the mesh, and set it to end, create the normal and set distance
390  VSFileSystem::vs_dprintf(3,"Beam collide with %p, distance %f\n",this,distance);
391  return(this);
392  }
393  } else {//no col trees = a sphere
394  // compute real distance
395  distance = (end-start).Magnitude() * distance;
396 
397  VSFileSystem::vs_dprintf(3,"Beam collide with %p, distance %f\n",this,distance);
398  return(this);
399  }
400  } else {
401  return (NULL);
402  }
403  return(NULL);
404 }
void Unit::reactToCollision ( Unit smaller,
const QVector biglocation,
const Vector bignormal,
const QVector smalllocation,
const Vector smallnormal,
float  dist 
)
virtual

Reimplemented in Planet, Missile, GameMissile, Nebula, Enhancement, and Asteroid.

Definition at line 388 of file unit_generic.cpp.

References _Universe, Universe::AccessCamera(), ApplyDamage(), ApplyForce(), ApplyTorque(), UniverseUtil::cos(), CrashForceDock(), e, ENHANCEMENTPTR, f, StarSystemGent::faction, faction, float, Unit::Limits::forward, GetAngularVelocity(), UnitUtil::getFlightgroupName(), GetMass(), getNewTime(), Camera::GetPosition(), Camera::GetR(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), GetVelocity(), Matrix::InvertRotationInto(), Universe::isPlayerStarship(), isUnit(), Unit::Limits::lateral, limits, m1, MakeNonColinearVector(), MISSILEPTR, Network, Orthogonize(), UnitUtil::owner(), owner, XMLSupport::parse_bool(), XMLSupport::parse_float(), Unit::Limits::pitch, Position(), radial_size, reactToCollision(), Unit::Limits::retro, Unit::Limits::roll, sim_atom_multiplier, SIMULATION_ATOM, Cockpit::TimeOfLastCollision, Transform(), FactionUtil::upgradefac, Vector, Unit::Limits::vertical, vs_config, and Unit::Limits::yaw.

Referenced by Collide(), Asteroid::reactToCollision(), Missile::reactToCollision(), Planet::reactToCollision(), and reactToCollision().

394 {
395  clsptr smltyp = smalle->isUnit();
396  if (smltyp == ENHANCEMENTPTR || smltyp == MISSILEPTR) {
397  if (isUnit() != ENHANCEMENTPTR && isUnit() != MISSILEPTR) {
398  smalle->reactToCollision( this, smalllocation, smallnormal, biglocation, bignormal, dist );
399  return;
400  }
401  }
402  static bool crash_dock_unit = XMLSupport::parse_bool( vs_config->getVariable( "physics", "unit_collision_docks", "false" ) );
403  if (crash_dock_unit) {
404  Unit *dockingun = smalle;
405  Unit *thus = this;
406  if ( _Universe->isPlayerStarship( this ) ) {
407  thus = smalle;
408  dockingun = this;
409  }
410  if ( _Universe->isPlayerStarship( dockingun ) ) {
411  if (UnitUtil::getFlightgroupName( thus ) == "Base") {
412  static bool crash_dock_hangar =
413  XMLSupport::parse_bool( vs_config->getVariable( "physics", "only_hangar_collision_docks", "false" ) );
414  if ( CrashForceDock( thus, smalle, !crash_dock_hangar ) )
415  return;
416  }
417  }
418  }
419  //don't bounce if you can Juuuuuuuuuuuuuump
420  if ( !jumpReactToCollision( smalle ) ) {
421  static float kilojoules_per_damage =
422  XMLSupport::parse_float( vs_config->getVariable( "physics", "kilojoules_per_unit_damage", "5400" ) );
423  static float collision_scale_factor =
424  XMLSupport::parse_float( vs_config->getVariable( "physics", "collision_damage_scale", "1.0" ) );
425  static float inelastic_scale = XMLSupport::parse_float( vs_config->getVariable( "physics", "inelastic_scale", ".8" ) );
426  static float mintime =
427  XMLSupport::parse_float( vs_config->getVariable( "physics", "minimum_time_between_recorded_player_collisions", "0.1" ) );
428  float m1 = smalle->GetMass(), m2 = GetMass();
429  if (m1 < 1e-6f || m2 < 1e-6f) {
430  if (m1 <= 0) m1 = 0.0f;
431  if (m2 <= 0) m2 = 0.0f;
432  m1 += 1.0e-7f;
433  m2 += 1.0e-7f;
434  }
435  //Compute linear velocity of points of impact by taking into account angular velocities
436  Vector small_velocity = smalle->GetVelocity()-smalle->GetAngularVelocity().Cross( smalllocation-smalle->Position() );
437  Vector big_velocity = GetVelocity()-GetAngularVelocity().Cross( biglocation-Position() );
438  //Compute reference frame conversions to align along force normals (newZ)(currently using bignormal
439  // - will experiment to see if both are needed for sufficient approximation)
440  Vector orthoz = ( (m2*bignormal)-(m1*smallnormal) ).Normalize();
441  Vector orthox = MakeNonColinearVector( orthoz );
442  Vector orthoy( 0, 0, 0 );
443  //need z and non-colinear x to compute new basis trio. destroys x,y, preserves z.
444  Orthogonize( orthox, orthoy, orthoz );
445  //transform matrix from normal aligned space
446  Matrix fromNewRef( orthox, orthoy, orthoz );
447  Matrix toNewRef = fromNewRef;
448  //transform matrix to normal aligned space
449  fromNewRef.InvertRotationInto( toNewRef );
450  Vector small_velocity_aligned = Transform( toNewRef, small_velocity );
451  Vector big_velocity_aligned = Transform( toNewRef, big_velocity );
452  //Compute elastic and inelastic terminal velocities (point object approximation)
453  //doesn't need aligning (I think)
454  Vector Inelastic_vf = ( m1/(m1+m2) )*small_velocity+( m2/(m1+m2) )*big_velocity;
455  //compute along aligned dimension, then return to previous reference frame
456  small_velocity_aligned.k = (small_velocity_aligned.k*(m1-m2)/(m1+m2)+( 2.0f*m2/(m1+m2) )*big_velocity_aligned.k);
457  big_velocity_aligned.k = (big_velocity_aligned.k*(m2-m1)/(m1+m2)+( 2.0f*m1/(m1+m2) )*small_velocity_aligned.k);
458  Vector SmallerElastic_vf = Transform( fromNewRef, small_velocity_aligned );
459  Vector ThisElastic_vf = Transform( fromNewRef, big_velocity_aligned );
460  //HACK ALERT:
461  //following code referencing minvel and time between collisions attempts
462  //to alleviate ping-pong problems due to collisions being detected
463  //after the player has penetrated the hull of another vessel because of discretization of time.
464  //this should eventually be replaced by instead figuring out where
465  //the point of collision should have occurred, and moving the vessels to the
466  //actual collision location before applying forces
467  Cockpit *thcp = _Universe->isPlayerStarship( this );
468  Cockpit *smcp = _Universe->isPlayerStarship( smalle );
469  bool isnotplayerorhasbeenmintime = true;
470  //Need to incorporate normals of colliding polygons somehow, without overiding directions of travel.
471  //We'll use the point object approximation for the magnitude of damage, and then apply the force along the appropriate normals
472  //ThisElastic_vf=((ThisElastic_vf.Magnitude()>minvel||!thcp)?ThisElastic_vf.Magnitude():minvel)*smallnormal;
473  //SmallerElastic_vf=((SmallerElastic_vf.Magnitude()>minvel||!smcp)?SmallerElastic_vf.Magnitude():minvel)*bignormal;
474  Vector ThisFinalVelocity = inelastic_scale*Inelastic_vf+(1.0f-inelastic_scale)*ThisElastic_vf;
475  Vector SmallerFinalVelocity = inelastic_scale*Inelastic_vf+(1.0f-inelastic_scale)*SmallerElastic_vf;
476  //float LargeKE = (0.5)*m2*GetVelocity().MagnitudeSquared();
477  //float SmallKE = (0.5)*m1*smalle->GetVelocity().MagnitudeSquared();
478  //float FinalInelasticKE = Inelastic_vf.MagnitudeSquared()*(0.5)*(m1+m2);
479  //float InelasticDeltaKE = LargeKE +SmallKE - FinalInelasticKE;
480  //1/2Mass*deltavfromnoenergyloss^2
481  float LargeDeltaE = (0.5f)*m2*(ThisFinalVelocity-ThisElastic_vf).MagnitudeSquared();
482  //1/2Mass*deltavfromnoenergyloss^2
483  float SmallDeltaE = (0.5f)*m1*(SmallerFinalVelocity-SmallerElastic_vf).MagnitudeSquared();
484  //Damage distribution (NOTE: currently arbitrary - no known good model for calculating how much energy object endures as a result of the collision)
485  float large_damage = (0.25f*SmallDeltaE+0.75f*LargeDeltaE)/kilojoules_per_damage*collision_scale_factor;
486  float small_damage = (0.25f*LargeDeltaE+0.75f*SmallDeltaE)/kilojoules_per_damage*collision_scale_factor;
487  //Vector ThisDesiredVelocity = ThisElastic_vf*(1-inelastic_scale/2)+Inelastic_vf*inelastic_scale/2;
488  //Vector SmallerDesiredVelocity = SmallerElastic_vf*(1-inelastic_scale)+Inelastic_vf*inelastic_scale;
489  //FIXME need to resolve 2 problems -
490  //1) SIMULATION_ATOM for small != SIMULATION_ATOM for large (below smforce line should mostly address this)
491  //2) Double counting due to collision occurring for each object in a different physics frame.
492  Vector smforce =
493  (SmallerFinalVelocity
494  -small_velocity)*smalle->GetMass()
495  /( SIMULATION_ATOM*( (float) smalle->sim_atom_multiplier )/( (float) this->sim_atom_multiplier ) );
496  Vector thisforce = (ThisFinalVelocity-big_velocity)*GetMass()/SIMULATION_ATOM;
497  if (thcp) {
498  if ( (getNewTime()-thcp->TimeOfLastCollision) > mintime )
500  else
501  isnotplayerorhasbeenmintime = false;
502  }
503  if (smcp) {
504  if ( (getNewTime()-smcp->TimeOfLastCollision) > mintime )
506  else
507  isnotplayerorhasbeenmintime = false;
508  }
509  if (Network != NULL) {
510  //Only player units can move in network mode.
511  if (thcp)
512  this->ApplyForce( thisforce-smforce );
513  else if (smcp)
514  smalle->ApplyForce( smforce-thisforce );
515  } else {
516  //Collision force caps primarily for AI-AI collisions. Once the AIs get a real collision avoidance system, we can
517  // turn damage for AI-AI collisions back on, and then we can remove these caps.
518  static float maxTorqueMultiplier =
519  XMLSupport::parse_float( vs_config->getVariable( "physics", "maxCollisionTorqueMultiplier", ".67" ) ); //value, in seconds of desired maximum recovery time
520  static float maxForceMultiplier =
521  XMLSupport::parse_float( vs_config->getVariable( "physics", "maxCollisionForceMultiplier", "5" ) ); //value, in seconds of desired maximum recovery time
522  if ( (smalle->isUnit() != MISSILEPTR) && isnotplayerorhasbeenmintime ) {
523  //for torque... smalllocation -- approximation hack of MR^2 for rotational inertia (moment of inertia currently just M)
524  Vector torque = smforce/(smalle->radial_size*smalle->radial_size);
525  Vector force = smforce-torque;
526 
527  float maxForce = maxForceMultiplier*(smalle->limits.forward+smalle->limits.retro
528  +smalle->limits.lateral+smalle->limits.vertical);
529  float maxTorque = maxTorqueMultiplier*(smalle->limits.yaw
530  +smalle->limits.pitch+smalle->limits.roll);
531  //Convert from frames to seconds, so that the specified value is meaningful
532  maxForce = maxForce/(smalle->sim_atom_multiplier*SIMULATION_ATOM);
533  maxTorque = maxTorque/(smalle->sim_atom_multiplier*SIMULATION_ATOM);
534  float tMag = torque.Magnitude();
535  float fMag = force.Magnitude();
536  if (tMag > maxTorque)
537  torque *= (maxTorque/tMag);
538  if (fMag > maxForce)
539  force *= (maxForce/fMag);
540  smalle->ApplyTorque( torque, smalllocation );
541  smalle->ApplyForce( force-torque );
542  }
543  if ( (this->isUnit() != MISSILEPTR) && isnotplayerorhasbeenmintime ) {
544  //for torque ... biglocation -- approximation hack of MR^2 for rotational inertia
545  Vector torque = thisforce/(radial_size*radial_size);
546  Vector force = thisforce-torque;
547  float maxForce = maxForceMultiplier*(limits.forward+limits.retro
549  float maxTorque = maxTorqueMultiplier*(limits.yaw+limits.pitch+limits.roll);
550  //Convert from frames to seconds, so that the specified value is meaningful
551  maxForce = maxForce/(this->sim_atom_multiplier*SIMULATION_ATOM);
552  maxTorque = maxTorque/(this->sim_atom_multiplier*SIMULATION_ATOM);
553  float tMag = torque.Magnitude();
554  float fMag = force.Magnitude();
555  if (tMag > maxTorque)
556  torque *= (maxTorque/tMag);
557  if (fMag > maxForce)
558  force *= (maxForce/fMag);
559  this->ApplyTorque( torque, biglocation );
560  this->ApplyForce( force-torque );
561  }
562  }
563  static int upgradefac =
564  XMLSupport::parse_bool( vs_config->getVariable( "physics", "cargo_deals_collide_damage",
565  "false" ) ) ? -1 : FactionUtil::GetUpgradeFaction();
566  bool dealdamage = true;
567  if ( _Universe->AccessCamera() ) {
568  Vector smalldelta = ( _Universe->AccessCamera()->GetPosition()-smalle->Position() ).Cast();
569  float smallmag = smalldelta.Magnitude();
570  Vector thisdelta = ( _Universe->AccessCamera()->GetPosition()-this->Position() ).Cast();
571  float thismag = thisdelta.Magnitude();
572  static float collision_hack_distance =
573  XMLSupport::parse_float( vs_config->getVariable( "physics", "collision_avoidance_hack_distance", "10000" ) );
574  static float front_collision_hack_distance =
575  XMLSupport::parse_float( vs_config->getVariable( "physics", "front_collision_avoidance_hack_distance", "200000" ) );
576  if (thcp == NULL && smcp == NULL) {
577  if (smallmag > collision_hack_distance+this->rSize() && thismag > collision_hack_distance) {
578  static float front_collision_hack_angle =
579  cos( 3.1415926536f
581  "front_collision_avoidance_hack_angle",
582  "40" ) )/180.0f );
583  if (smalldelta.Dot( _Universe->AccessCamera()->GetR() ) < smallmag*front_collision_hack_angle
584  && thisdelta.Dot( _Universe->AccessCamera()->GetR() ) < thismag*front_collision_hack_angle) {
585  if (smallmag > front_collision_hack_distance+this->rSize() && thismag > front_collision_hack_distance)
586  dealdamage = false;
587  } else {
588  dealdamage = false;
589  }
590  }
591  }
592  }
593  if ( !_Universe->isPlayerStarship( this ) && !_Universe->isPlayerStarship( smalle ) ) {
594  if (this->isUnit() != MISSILEPTR && smalle->isUnit() != MISSILEPTR) {
595  static bool collisionDamageToAI =
596  XMLSupport::parse_bool( vs_config->getVariable( "physics", "collisionDamageToAI", "false" ) );
597  if (!collisionDamageToAI)
598  //HACK: Stupid AI ships always crash into each other.
599  dealdamage = false;
600  }
601  }
602  if (dealdamage) {
603  if (faction != upgradefac) {
604  smalle->ApplyDamage( biglocation.Cast(), bignormal, small_damage, smalle, GFXColor( 1,
605  1,
606  1,
607  2 ), this->owner
608  != NULL ? this->owner : this );
609  }
610  if (smalle->faction != upgradefac) {
611  this->ApplyDamage( smalllocation.Cast(), smallnormal, large_damage, this, GFXColor( 1,
612  1,
613  1,
614  2 ), smalle->owner
615  != NULL ? smalle->owner : smalle );
616  }
617  }
618  }
619 }
bool Unit::ReduceToTemplate ( )

Definition at line 7528 of file unit_generic.cpp.

References makeFinalBlankUpgrade(), and name.

Referenced by UnitUtil::RecomputeUnitUpgrades().

7529 {
7530  vector< Cargo >savedCargo;
7531  savedCargo.swap( pImage->cargo );
7532  vector< Mount >savedWeap;
7533  savedWeap.swap( mounts );
7534  const Unit *temprate = makeFinalBlankUpgrade( name, faction );
7535  bool success = false;
7536  double pct = 0;
7537  if ( temprate && temprate->name != string( "LOAD_FAILED" ) ) {
7538  success = Upgrade( temprate, -1, -1, 0, true, pct, NULL, true );
7539  if (pct > 0)
7540  success = true;
7541  }
7542  savedCargo.swap( pImage->cargo );
7543  savedWeap.swap( mounts );
7544  return success;
7545 }
void Unit::Ref ( )
inline

Definition at line 29 of file unit.h.

References ucref, and zapped.

Referenced by UnitCollection::append(), UnitCollection::insert(), UnitCollection::insert_unique(), UnitCollection::prepend(), and UnitContainer::SetUnit().

30  {
31  if (zapped == true)
32  printf( "segfault" );
33  ucref += 1;
34  }
void Unit::Ref ( )
bool Unit::RefillWarpEnergy ( )

Definition at line 5827 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_bool(), and vs_config.

Referenced by Orders::DockingOps::DockToTarget().

5828 {
5829  static bool WCfuelhack = XMLSupport::parse_bool( vs_config->getVariable( "physics", "fuel_equals_warp", "false" ) );
5830  if (WCfuelhack)
5831  this->warpenergy = this->fuel;
5832  float tmp = this->maxwarpenergy;
5833  if (tmp < this->jump.energy)
5834  tmp = this->jump.energy;
5835  if (tmp > this->warpenergy) {
5836  this->warpenergy = tmp;
5837  if (WCfuelhack)
5838  this->fuel = this->warpenergy;
5839  return true;
5840  }
5841  return false;
5842 }
void Unit::RegenShields ( )
protected

Definition at line 3652 of file unit_generic.cpp.

References _Universe, applyto(), game_data_t::difficulty, FINITE, fprintf, g_game, VegaConfig::getVariable(), UniverseUtil::IOmessage(), Universe::isPlayerStarship(), XMLSupport::parse_bool(), XMLSupport::parse_float(), SIMULATION_ATOM, totalShieldEnergyCapacitance(), vs_config, and WARPENERGYMULTIPLIER().

3653 {
3654  static bool shields_in_spec = XMLSupport::parse_bool( vs_config->getVariable( "physics", "shields_in_spec", "false" ) );
3655  static float shieldenergycap =
3656  XMLSupport::parse_float( vs_config->getVariable( "physics", "shield_energy_capacitance", ".2" ) );
3657  static bool energy_before_shield =
3658  XMLSupport::parse_bool( vs_config->getVariable( "physics", "engine_energy_priority", "true" ) );
3659  static bool apply_difficulty_shields =
3660  XMLSupport::parse_bool( vs_config->getVariable( "physics", "difficulty_based_shield_recharge", "true" ) );
3661  static float shield_maintenance_cost =
3662  XMLSupport::parse_float( vs_config->getVariable( "physics", "shield_maintenance_charge", ".25" ) );
3663  static bool shields_require_power =
3664  XMLSupport::parse_bool( vs_config->getVariable( "physics", "shields_require_passive_recharge_maintenance", "true" ) );
3665  static float discharge_per_second =
3666  XMLSupport::parse_float( vs_config->getVariable( "physics", "speeding_discharge", ".25" ) );
3667  //approx
3668  const float dischargerate = (1-(1-discharge_per_second)*SIMULATION_ATOM);
3669  static float min_shield_discharge =
3670  XMLSupport::parse_float( vs_config->getVariable( "physics", "min_shield_speeding_discharge", ".1" ) );
3671  static float low_power_mode =
3672  XMLSupport::parse_float( vs_config->getVariable( "physics", "low_power_mode_energy", "10" ) );
3673  static float max_shield_lowers_recharge =
3674  XMLSupport::parse_float( vs_config->getVariable( "physics", "max_shield_recharge_drain", "0" ) );
3675  static bool max_shield_lowers_capacitance =
3676  XMLSupport::parse_bool( vs_config->getVariable( "physics", "max_shield_lowers_capacitance", "false" ) );
3677  static bool reactor_uses_fuel =
3678  XMLSupport::parse_bool( vs_config->getVariable( "physics", "reactor_uses_fuel", "false" ) );
3679  static float reactor_idle_efficiency =
3680  XMLSupport::parse_float( vs_config->getVariable( "physics", "reactor_idle_efficiency", "0.98" ) );
3681  static float VSD = XMLSupport::parse_float( vs_config->getVariable( "physics", "VSD_MJ_yield", "5.4" ) );
3682  //Fuel Mass in metric tons expended per generation of 100MJ
3683  static float FMEC_factor = XMLSupport::parse_float( vs_config->getVariable( "physics", "FMEC_factor", "0.000000008" ) );
3684  int rechargesh = 1; //used ... oddly
3685  float maxshield = totalShieldEnergyCapacitance( shield );
3686  bool velocity_discharge = false;
3687  float rec = 0;
3688  float precharge = energy;
3689  //Reactor energy
3690  if (!energy_before_shield)
3691  RechargeEnergy();
3692  //Shield energy drain
3693  if (shield.number) {
3694  //GAHHH reactor in units of 100MJ, shields in units of VSD=5.4MJ to make 1MJ of shield use 1/shieldenergycap MJ
3695  if (shields_in_spec || !graphicOptions.InWarp) {
3696  energy -= shield.recharge*VSD
3697  /( 100
3698  *(shield.efficiency ? shield.efficiency : 1) )/shieldenergycap*shield.number*shield_maintenance_cost
3699  *SIMULATION_ATOM*( (apply_difficulty_shields) ? g_game.difficulty : 1 );
3700  if (energy < 0) {
3701  velocity_discharge = true;
3702  energy = 0;
3703  }
3704  }
3705  rec =
3706  (velocity_discharge) ? 0 : ( (shield.recharge*VSD/100*SIMULATION_ATOM*shield.number/shieldenergycap)
3707  > energy ) ? (energy*shieldenergycap*100/VSD
3709  if (apply_difficulty_shields) {
3710  if ( !_Universe->isPlayerStarship( this ) )
3711  rec *= g_game.difficulty;
3712  else
3713  rec *= g_game.difficulty;
3714  }
3715  if (graphicOptions.InWarp && !shields_in_spec) {
3716  rec = 0;
3717  velocity_discharge = true;
3718  }
3719  if (GetNebula() != NULL) {
3720  static float nebshields =
3721  XMLSupport::parse_float( vs_config->getVariable( "physics", "nebula_shield_recharge", ".5" ) );
3722  rec *= nebshields;
3723  }
3724  }
3725  //ECM energy drain
3726  if (computer.ecmactive) {
3727  static float ecmadj = XMLSupport::parse_float( vs_config->getVariable( "physics", "ecm_energy_cost", ".05" ) );
3728  float sim_atom_ecm = ecmadj*pImage->ecm*SIMULATION_ATOM;
3729  if (energy > sim_atom_ecm)
3730  energy -= sim_atom_ecm;
3731  else
3732  energy = 0;
3733  }
3734  //Shield regeneration
3735  switch (shield.number)
3736  {
3737  case 2:
3738  shield.shield2fb.front += rec;
3739  shield.shield2fb.back += rec;
3740  if (shield.shield2fb.front > shield.shield2fb.frontmax)
3741  shield.shield2fb.front = shield.shield2fb.frontmax;
3742  else
3743  rechargesh = 0;
3744  if (shield.shield2fb.back > shield.shield2fb.backmax)
3745  shield.shield2fb.back = shield.shield2fb.backmax;
3746 
3747  else
3748  rechargesh = 0;
3749  if (velocity_discharge) {
3750  if (shield.shield2fb.back > min_shield_discharge*shield.shield2fb.backmax)
3751  shield.shield2fb.back *= dischargerate;
3752  if (shield.shield2fb.front > min_shield_discharge*shield.shield2fb.frontmax)
3753  shield.shield2fb.front *= dischargerate;
3754  }
3755  rec = rec*2/shieldenergycap*VSD/100;
3756  break;
3757  case 4:
3758  rechargesh =
3759  applyto( shield.shield4fbrl.front, shield.shield4fbrl.frontmax,
3760  rec )*( applyto( shield.shield4fbrl.back, shield.shield4fbrl.backmax, rec ) )*applyto(
3761  shield.shield4fbrl.right,
3763  rightmax,
3764  rec )*applyto(
3765  shield.shield4fbrl.left,
3766  shield.shield4fbrl.leftmax,
3767  rec );
3768  if (velocity_discharge) {
3769  if (shield.shield4fbrl.front > min_shield_discharge*shield.shield4fbrl.frontmax)
3770  shield.shield4fbrl.front *= dischargerate;
3771  if (shield.shield4fbrl.left > min_shield_discharge*shield.shield4fbrl.leftmax)
3772  shield.shield4fbrl.left *= dischargerate;
3773  if (shield.shield4fbrl.back > min_shield_discharge*shield.shield4fbrl.backmax)
3774  shield.shield4fbrl.back *= dischargerate;
3775  if (shield.shield4fbrl.right > min_shield_discharge*shield.shield4fbrl.rightmax)
3776  shield.shield4fbrl.right *= dischargerate;
3777  }
3778  rec = rec*4/shieldenergycap*VSD/100;
3779  break;
3780  case 8:
3781  rechargesh =
3782  applyto( shield.shield8.frontrighttop, shield.shield8.frontrighttopmax,
3783  rec )*( applyto( shield.shield8.backrighttop, shield.shield8.backrighttopmax, rec ) )*applyto(
3784  shield.shield8.frontlefttop,
3785  shield.shield8.frontlefttopmax,
3786  rec )*applyto( shield.shield8.backlefttop, shield.shield8.backlefttopmax, rec )*applyto(
3787  shield.shield8.frontrightbottom,
3788  shield.shield8.
3789  frontrightbottommax,
3790  rec )
3791  *( applyto( shield.shield8.backrightbottom, shield.shield8.backrightbottommax, rec ) )*applyto(
3792  shield.shield8.frontleftbottom,
3793  shield.shield8.frontleftbottommax,
3794  rec )*applyto( shield.shield8.backleftbottom, shield.shield8.backleftbottommax, rec );
3795  if (velocity_discharge) {
3796  if (shield.shield8.frontrighttop > min_shield_discharge*shield.shield8.frontrighttopmax)
3797  shield.shield8.frontrighttop *= dischargerate;
3798  if (shield.shield8.frontlefttop > min_shield_discharge*shield.shield8.frontlefttopmax)
3799  shield.shield8.frontlefttop *= dischargerate;
3800  if (shield.shield8.backrighttop > min_shield_discharge*shield.shield8.backrighttopmax)
3801  shield.shield8.backrighttop *= dischargerate;
3802  if (shield.shield8.backlefttop > min_shield_discharge*shield.shield8.backlefttopmax)
3803  shield.shield8.backlefttop *= dischargerate;
3804  if (shield.shield8.frontrightbottom > min_shield_discharge*shield.shield8.frontrightbottommax)
3805  shield.shield8.frontrightbottom *= dischargerate;
3806  if (shield.shield8.frontleftbottom > min_shield_discharge*shield.shield8.frontleftbottommax)
3807  shield.shield8.frontleftbottom *= dischargerate;
3808  if (shield.shield8.backrightbottom > min_shield_discharge*shield.shield8.backrightbottommax)
3809  shield.shield8.backrightbottom *= dischargerate;
3810  if (shield.shield8.backleftbottom > min_shield_discharge*shield.shield8.backleftbottommax)
3811  shield.shield8.backleftbottom *= dischargerate;
3812  }
3813  rec = rec*8/shieldenergycap*VSD/100;
3814  break;
3815  }
3816  if (shield.number) {
3817  if (rechargesh == 0)
3818  energy -= rec;
3819  if (shields_require_power)
3820  maxshield = 0;
3821  if (max_shield_lowers_recharge)
3822  energy -= max_shield_lowers_recharge*SIMULATION_ATOM*maxshield*VSD
3823  /( 100*(shield.efficiency ? shield.efficiency : 1) );
3824  if (!max_shield_lowers_capacitance)
3825  maxshield = 0;
3826  }
3827  //Reactor energy
3828  if (energy_before_shield)
3829  RechargeEnergy();
3830  //Final energy computations
3831  float menergy = maxenergy;
3832  if ( shield.number && (menergy-maxshield < low_power_mode) ) {
3833  menergy = maxshield+low_power_mode;
3834  if ( _Universe->isPlayerStarship( this ) ) {
3835  if (rand() < .00005*RAND_MAX) {
3837  0,
3838  " game",
3839  "all",
3840  "**Warning** Power Supply Overdrawn: downgrade shield or purchase reactor capacitance!" );
3841  }
3842  }
3843  }
3844  if (graphicOptions.InWarp) {
3845  //FIXME FIXME FIXME
3846  static float bleedfactor = XMLSupport::parse_float( vs_config->getVariable( "physics", "warpbleed", "20" ) );
3847  float bleed = jump.insysenergy/bleedfactor*SIMULATION_ATOM;
3848  if (warpenergy > bleed) {
3849  warpenergy -= bleed;
3850  } else {
3851  graphicOptions.InWarp = 0;
3853  }
3854  }
3855  float excessenergy = 0;
3856  //NOTE: !shield.number => maxshield==0
3857  if (menergy > maxshield) {
3858  //allow warp caps to absorb xtra power
3859  if (energy > menergy-maxshield) {
3860  excessenergy = energy-(menergy-maxshield);
3861  energy = menergy-maxshield;
3862  if (excessenergy > 0) {
3863  warpenergy = warpenergy+WARPENERGYMULTIPLIER( this )*excessenergy;
3864  float mwe = maxwarpenergy;
3865  if (mwe < jump.energy && mwe == 0)
3866  mwe = jump.energy;
3867  if (warpenergy > mwe) {
3868  excessenergy = (warpenergy-mwe)/WARPENERGYMULTIPLIER( this );
3869  warpenergy = mwe;
3870  }
3871  }
3872  }
3873  } else {
3874  energy = 0;
3875  }
3876  excessenergy = (excessenergy > precharge) ? excessenergy-precharge : 0;
3877  if (reactor_uses_fuel) {
3878  static float min_reactor_efficiency =
3879  XMLSupport::parse_float( vs_config->getVariable( "physics", "min_reactor_efficiency", ".00001" ) );
3880  fuel -= FMEC_factor
3881  *( ( recharge*SIMULATION_ATOM
3882  -(reactor_idle_efficiency
3883  *excessenergy) )/( min_reactor_efficiency+( pImage->LifeSupportFunctionality*(1-min_reactor_efficiency) ) ) );
3884  if (fuel < 0) fuel = 0;
3885  if ( !FINITE( fuel ) ) {
3886  fprintf( stderr, "Fuel is nan C\n" );
3887  fuel = 0;
3888  }
3889  }
3890  energy = energy < 0 ? 0 : energy;
3891 }
int Unit::RemoveCargo ( unsigned int  i,
int  quantity,
bool  eraseZero = true 
)

Definition at line 8201 of file unit_generic.cpp.

References _Universe, NetServer::BroadcastCargoUpgrade(), NetClient::cargoRequest(), fprintf, Cargo::GetContent(), VegaConfig::getVariable(), Cargo::mass, Cargo::mission, Universe::netLocked(), Network, XMLSupport::parse_bool(), Cargo::price, Cargo::quantity, SERVER, Cargo::volume, vs_config, VSServer, and Universe::whichPlayerStarship().

Referenced by Arrested(), BuyCargo(), buyShip(), BaseComputer::BuyUpgradeOperation::concludeTransaction(), UnitUtil::decrementCargo(), eliminateZeroCargo(), Enslave(), makeBlankUpgrade(), UnitUtil::removeCargo(), BaseComputer::sellSelectedCargo(), and UpdateMasterPartList().

8202 {
8203  if ( !( i < pImage->cargo.size() ) ) {
8204  fprintf( stderr, "(previously) FATAL problem...removing cargo that is past the end of array bounds." );
8205  return 0;
8206  }
8207  Cargo *carg = &(pImage->cargo[i]);
8208  if (quantity > carg->quantity)
8209  quantity = carg->quantity;
8210  if ( Network && !_Universe->netLocked() ) {
8211  int playernum = _Universe->whichPlayerStarship( this );
8212  if (playernum >= 0)
8213  Network[playernum].cargoRequest( 0, this->serial, carg->GetContent(), quantity, 0, 0 );
8214  else
8215  return 0;
8216  return 0;
8217  }
8218  static bool usemass = XMLSupport::parse_bool( vs_config->getVariable( "physics", "use_cargo_mass", "true" ) );
8219  if (usemass)
8220  Mass -= quantity*carg->mass;
8221  if ( SERVER && !_Universe->netLocked() && getStarSystem() ) {
8222  VSServer->BroadcastCargoUpgrade( this->serial, 0, this->serial, carg->GetContent(),
8223  carg->price, carg->mass, carg->volume, carg->mission,
8224  quantity, 0, 0, getStarSystem()->GetZone() );
8225  }
8226  carg->quantity -= quantity;
8227  if (carg->quantity <= 0 && eraseZero)
8228  pImage->cargo.erase( pImage->cargo.begin()+i );
8229  return quantity;
8230 }
void Unit::RemoveFromSystem ( )

Definition at line 27 of file unit_collide.cpp.

References _Universe, Universe::activeStarSystem(), activeStarSystem, weapon_info::BEAM, CollideArray::begin(), CollideArray::checkSet(), StarSystem::collidemap, CollideArray::end(), CollideArray::erase(), GetNumMounts(), VegaConfig::getVariable(), i, is_null(), j, location, mounts, NUM_COLLIDE_MAPS, XMLSupport::parse_bool(), set_null(), and vs_config.

Referenced by SelfDestruct().

28 {
29  for (unsigned int locind = 0; locind < NUM_COLLIDE_MAPS; ++locind)
30  if ( !is_null( this->location[locind] ) ) {
31  if (activeStarSystem == NULL) {
32  printf( "NONFATAL NULL activeStarSystem detected...please fix\n" );
34  }
35  static bool collidemap_sanity_check =
36  XMLSupport::parse_bool( vs_config->getVariable( "physics", "collidemap_sanity_check", "false" ) );
37  if (collidemap_sanity_check) {
38  if (0) {
41 
42  bool found = false;
43  for (i = activeStarSystem->collidemap[locind]->begin();
44  i != activeStarSystem->collidemap[locind]->end(); ++i) {
45  if (i == this->location[locind]) {
46  printf( "hussah %d\n", *i == *this->location[locind] );
47  found = true;
48  }
49  if (**i < **j) {
50  printf( "(%f %f %f) and (%f %f %f) %f < %f %d!!!",
51  (**i).GetPosition().i,
52  (**i).GetPosition().j,
53  (**i).GetPosition().k,
54  (**j).GetPosition().i,
55  (**j).GetPosition().j,
56  (**j).GetPosition().k,
57  (**i).GetPosition().MagnitudeSquared(),
58  (**j).GetPosition().MagnitudeSquared(),
59  (**i).GetPosition().MagnitudeSquared()
60  < (**j).GetPosition().MagnitudeSquared() );
61  }
62  j = i;
63  }
64  printf( "fin %d %d ", *(int*) &i, found );
66  assert( 0 );
67  }
68  }
69  activeStarSystem->collidemap[locind]->erase( this->location[locind] );
70  set_null( this->location[locind] );
71  }
72  for (int j = 0; j < GetNumMounts(); ++j)
73  if (mounts[j].type->type == weapon_info::BEAM)
74  if (mounts[j].ref.gun)
75  mounts[j].ref.gun->RemoveFromSystem( true );
76  activeStarSystem = NULL;
77 }
void Unit::Repair ( )

Definition at line 8837 of file unit_generic.cpp.

References Cargo::category, Cargo::content, DamagedCategory, UnitCollection::empty(), VSRandom::genrand_int31(), UnitUtil::GetCargo(), Cargo::GetCategory(), Cargo::GetContent(), UniverseUtil::GetGameTime(), GetNumMounts(), getUnitFromUpgradeName(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), makeTemplateUpgrade(), MAXVDUS, name, XMLSupport::parse_float(), UnitUtil::PercentOperational(), REPAIRINTEGRATED, SIMULATION_ATOM, SubUnits, vs_config, VSFileSystem::vs_fprintf(), and vsrandom.

8838 {
8839  static float repairtime = XMLSupport::parse_float( vs_config->getVariable( "physics", "RepairDroidTime", "180" ) );
8840  static float checktime = XMLSupport::parse_float( vs_config->getVariable( "physics", "RepairDroidCheckTime", "5" ) );
8841  if ( (repairtime <= 0) || (checktime <= 0) ) return;
8842  if (pImage->repair_droid > 0) {
8844  unsigned int numcargo = numCargo();
8845  if (numcargo > 0) {
8846  if ( pImage->next_repair_cargo >= numCargo() )
8848  Cargo *carg = &GetCargo( pImage->next_repair_cargo );
8849  float percentoperational = 1;
8850  if ( carg->GetCategory().find( "upgrades/" ) == 0
8851  && carg->GetCategory().find( DamagedCategory ) != 0
8852  && carg->GetContent().find( "add_" ) != 0
8853  && carg->GetContent().find( "mult_" ) != 0
8854  && ( ( percentoperational =
8855  UnitUtil::PercentOperational( this, carg->content, carg->category, true ) ) < 1.f ) ) {
8856  if (pImage->next_repair_time == -FLT_MAX) {
8857  pImage->next_repair_time = UniverseUtil::GetGameTime()+repairtime*(1-percentoperational)/pImage->repair_droid;
8858  } else {
8859  //ACtually fix the cargo here
8860  static int upfac = FactionUtil::GetUpgradeFaction();
8861  const Unit *up = getUnitFromUpgradeName( carg->content, upfac );
8862  static std::string loadfailed( "LOAD_FAILED" );
8863  if (up->name == loadfailed) {
8864  printf( "Bug: Load failed cargo encountered: report to hellcatv@hotmail.com\n" );
8865  } else {
8866  double percentage = 0;
8867  //don't want to repair these things
8868  if (up->SubUnits.empty() && up->GetNumMounts() == 0) {
8869  this->Upgrade( up, 0, 0, 0, true, percentage, makeTemplateUpgrade( this->name,
8870  this->faction ), false,
8871  false );
8872  if (percentage == 0) {
8874  stderr, "Failed repair for unit %s, cargo item %d: %s (%s) - please report error\n",
8875  name.get().c_str(), pImage->next_repair_cargo, carg->GetContent().c_str(),
8876  carg->GetCategory().c_str() );
8877  }
8878  }
8879  }
8880  pImage->next_repair_time = -FLT_MAX;
8882  }
8883  } else {
8885  }
8886  }
8887  }
8888  float ammt_repair = SIMULATION_ATOM/repairtime*pImage->repair_droid;
8893  unsigned int numg = (1+UnitImages< void >::NUMGAUGES+MAXVDUS);
8894  unsigned int which = vsrandom.genrand_int31()%numg;
8895  static float hud_repair_quantity = XMLSupport::parse_float( vs_config->getVariable( "physics", "hud_repair_unit", ".25" ) );
8896  //total damage
8897  if (pImage->cockpit_damage[which] < pImage->cockpit_damage[which+numg]) {
8898  pImage->cockpit_damage[which] += hud_repair_quantity;
8899  if (pImage->cockpit_damage[which] > pImage->cockpit_damage[which+numg])
8900  //total damage
8901  pImage->cockpit_damage[which] = pImage->cockpit_damage[which+numg];
8902  }
8903  if ( mounts.size() ) {
8904  static float mount_repair_quantity =
8905  XMLSupport::parse_float( vs_config->getVariable( "physics", "mount_repair_unit", ".25" ) );
8906  unsigned int i = vsrandom.genrand_int31()%mounts.size();
8907  if (mounts[i].functionality < mounts[i].maxfunctionality) {
8908  mounts[i].functionality += mount_repair_quantity;
8909  if (mounts[i].functionality > mounts[i].maxfunctionality)
8910  mounts[i].functionality = mounts[i].maxfunctionality;
8911  }
8912  }
8913  }
8914 }
int Unit::RepairCost ( )

Definition at line 7556 of file unit_generic.cpp.

References DamagedCategory, UnitUtil::GetCargo(), and Cargo::GetCategory().

Referenced by BasicRepair(), BaseComputer::loadBuyUpgradeControls(), and BaseComputer::updateTransactionControlsForSelection().

7557 {
7558  int cost = 1;
7559  unsigned int i;
7560  for (i = 0; i < (1+MAXVDUS+UnitImages< void >::NUMGAUGES)*2; ++i)
7561  if (pImage->cockpit_damage[i] < 1)
7562  ++cost;
7564  ++cost;
7566  ++cost;
7567  if (pImage->SPECDriveFunctionality < 1)
7568  ++cost;
7570  ++cost;
7571  if (pImage->CommFunctionality < 1)
7572  ++cost;
7573  if (pImage->CommFunctionalityMax < 1)
7574  ++cost;
7576  ++cost;
7578  ++cost;
7579  for (i = 0; i < numCargo(); ++i)
7580  if (GetCargo( i ).GetCategory().find( DamagedCategory ) == 0)
7581  ++cost;
7582  return cost;
7583 }
int Unit::RepairUpgrade ( )

Definition at line 7585 of file unit_generic.cpp.

References Cargo::category, UnitImages< BOGUS >::cockpit_damage, UnitImages< BOGUS >::CommFunctionality, UnitImages< BOGUS >::CommFunctionalityMax, DamagedCategory, StarSystemGent::faction, UnitImages< BOGUS >::fireControlFunctionality, UnitImages< BOGUS >::fireControlFunctionalityMax, UnitUtil::GetCargo(), Cargo::GetCategory(), UnitFactory::getMasterPartList(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), UnitImages< BOGUS >::LifeSupportFunctionality, UnitImages< BOGUS >::LifeSupportFunctionalityMax, loadUnitByCache(), makeFinalBlankUpgrade(), makeTemplateUpgrade(), maxenergy, MaxShieldVal(), name, XMLSupport::parse_bool(), Shield::recharge, recharge, shield, UnitImages< BOGUS >::SPECDriveFunctionality, UnitImages< BOGUS >::SPECDriveFunctionalityMax, and vs_config.

Referenced by BasicRepair(), and UnitUtil::repair().

7586 {
7587  vector< Cargo >savedCargo;
7588  savedCargo.swap( pImage->cargo );
7589  vector< Mount >savedWeap;
7590  savedWeap.swap( mounts );
7591  int upfac = FactionUtil::GetUpgradeFaction();
7592  const Unit *temprate = makeFinalBlankUpgrade( name, faction );
7593  int success = 0;
7594  double pct = 0;
7595  if ( temprate && temprate->name != string( "LOAD_FAILED" ) ) {
7596  success = Upgrade( temprate, -1, -1, 0, false, pct, NULL, false ) ? 1 : 0;
7597  if (pct > 0)
7598  success = 1;
7599  }
7600  savedCargo.swap( pImage->cargo );
7601  savedWeap.swap( mounts );
7603  for (int i = 0; i < (1+MAXVDUS+UnitImages< void >::NUMGAUGES)*2; ++i)
7604  if (im->cockpit_damage[i] < 1) {
7605  im->cockpit_damage[i] = 1;
7606  success += 1;
7607  pct = 1;
7608  }
7609  if (im->fireControlFunctionality < 1) {
7610  im->fireControlFunctionality = 1;
7611  pct = 1;
7612  success += 1;
7613  }
7614  if (im->fireControlFunctionalityMax < 1) {
7616  pct = 1;
7617  success += 1;
7618  }
7619  if (im->SPECDriveFunctionality < 1) {
7620  im->SPECDriveFunctionality = 1;
7621  pct = 1;
7622  success += 1;
7623  }
7624  if (im->SPECDriveFunctionalityMax < 1) {
7625  im->SPECDriveFunctionalityMax = 1;
7626  pct = 1;
7627  success += 1;
7628  }
7629  if (im->CommFunctionality < 1) {
7630  im->CommFunctionality = 1;
7631  pct = 1;
7632  success += 1;
7633  }
7634  if (im->CommFunctionalityMax < 1) {
7635  im->CommFunctionalityMax = 1;
7636  pct = 1;
7637  success += 1;
7638  }
7639  if (im->LifeSupportFunctionality < 1) {
7640  im->LifeSupportFunctionality = 1;
7641  pct = 1;
7642  success += 1;
7643  }
7644  if (im->LifeSupportFunctionalityMax < 1) {
7646  pct = 1;
7647  success += 1;
7648  }
7649  damages = NO_DAMAGE;
7650  bool ret = success && pct > 0;
7651  static bool ComponentBasedUpgrades =
7652  XMLSupport::parse_bool( vs_config->getVariable( "physics", "component_based_upgrades", "false" ) );
7653  if (ComponentBasedUpgrades) {
7654  for (unsigned int i = 0; i < numCargo(); ++i)
7655  if (GetCargo( i ).GetCategory().find( DamagedCategory ) == 0) {
7656  ++success;
7657  static int damlen = strlen( DamagedCategory );
7658  GetCargo( i ).category = "upgrades/"+GetCargo( i ).GetCategory().substr( damlen );
7659  }
7660  } else if (ret) {
7661  const Unit *maxrecharge = makeTemplateUpgrade( name.get()+".template", faction );
7662 
7664  for (unsigned int i = 0; i < mpl->numCargo(); ++i)
7665  if (mpl->GetCargo( i ).GetCategory().find( "upgrades" ) == 0) {
7666  const Unit *up = loadUnitByCache( mpl->GetCargo( i ).content, upfac );
7667  //now we analyzify up!
7668  if (up->MaxShieldVal() == MaxShieldVal() && up->shield.recharge > shield.recharge) {
7670  if (maxrecharge)
7671  if (shield.recharge > maxrecharge->shield.recharge)
7672  shield.recharge = maxrecharge->shield.recharge;
7673  }
7674  if (up->maxenergy == maxenergy && up->recharge > recharge) {
7675  recharge = up->recharge;
7676  if (recharge > maxrecharge->recharge)
7677  recharge = maxrecharge->recharge;
7678  }
7679  }
7680  }
7681  return success;
7682 }
bool Unit::RepairUpgradeCargo ( Cargo item,
Unit baseUnit,
float credits 
)

Definition at line 7692 of file unit_generic.cpp.

References c, Cargo::category, Cargo::content, DamagedCategory, Mount::DESTROYED, UnitUtil::GetCargo(), Cargo::GetCategory(), Cargo::GetContent(), GetNumMounts(), getUnitFromUpgradeName(), Mount::INACTIVE, isWeapon(), makeTemplateUpgrade(), mounts, UnitUtil::PercentOperational(), Cargo::price, PriceCargo(), RepairPrice(), Mount::type, UnitUtil::upgrade(), and weapon_info::weapon_name.

Referenced by BaseComputer::fixUpgrade().

7693 {
7694  assert( (item!=NULL) |! "Unit::RepairUpgradeCargo got a null item." ); //added by chuck_starchaser
7695  double itemPrice = baseUnit ? baseUnit->PriceCargo( item->content ) : item->price;
7696  if ( isWeapon( item->category ) ) {
7697  const Unit *upgrade = getUnitFromUpgradeName( item->content, this->faction );
7698  if ( upgrade->GetNumMounts() ) {
7699  double price = itemPrice; //RepairPrice probably won't work for mounts.
7700  if ( !credits || price <= (*credits) ) {
7701  if (credits) (*credits) -= price;
7702  const Mount *mnt = &upgrade->mounts[0];
7703  unsigned int nummounts = this->GetNumMounts();
7704  bool complete = false;
7705  for (unsigned int i = 0; i < nummounts; ++i)
7706  if (mnt->type->weapon_name == this->mounts[i].type->weapon_name) {
7707  if (this->mounts[i].status == Mount::DESTROYED) {
7708  this->mounts[i].status = Mount::INACTIVE;
7709  complete = true;
7710  }
7711  if (this->mounts[i].functionality < 1.0f) {
7712  this->mounts[i].functionality = 1.0f;
7713  complete = true;
7714  }
7715  if (this->mounts[i].maxfunctionality < 1.0f) {
7716  this->mounts[i].maxfunctionality = 1.0f;
7717  complete = true;
7718  }
7719  if (complete) break;
7720  }
7721  return complete;
7722  }
7723  }
7724  return false;
7725  } else {
7726  Cargo sold;
7727  bool notadditive = (item->GetContent().find( "add_" ) != 0 && item->GetContent().find( "mult_" ) != 0);
7728  if (notadditive || item->GetCategory().find( DamagedCategory ) == 0) {
7729  Cargo itemCopy = *item; //Copy this because we reload master list before we need it.
7730  const Unit *un = getUnitFromUpgradeName( item->content, this->faction );
7731  if (un) {
7732  double percentage = UnitUtil::PercentOperational( this, item->content, item->category, false );
7733  double price = RepairPrice( percentage, itemPrice );
7734  if ( !credits || price <= (*credits) ) {
7735  if (credits)
7736  (*credits) -= price;
7737  if (notadditive)
7738  this->Upgrade( un, 0, 0, 0, true, percentage, makeTemplateUpgrade( this->name, this->faction ) );
7739  if (item->GetCategory().find( DamagedCategory ) == 0) {
7740  unsigned int where;
7741  Cargo *c = this->GetCargo( item->content, where );
7742  if (c)
7743  c->category = "upgrades/"+c->GetCategory().substr( strlen( DamagedCategory ) );
7744  }
7745  return true;
7746  }
7747  }
7748  }
7749  }
7750  return false;
7751 }
bool Unit::RequestClearance ( Unit dockingunit)

Definition at line 5751 of file unit_generic.cpp.

Referenced by DoDockingOps(), ExecuteRequestClearenceKey(), Order::ProcessCommunicationMessages(), and Orders::DockingOps::RequestClearence().

5752 {
5753  if ( std::find( pImage->clearedunits.begin(), pImage->clearedunits.end(), dockingunit ) == pImage->clearedunits.end() )
5754  pImage->clearedunits.push_back( dockingunit );
5755  return true;
5756 }
void Unit::RequestPhysics ( )

Definition at line 8958 of file unit_generic.cpp.

Referenced by DockToSavedBases().

8959 {
8960  //Request ASAP physics
8961  if ( getStarSystem() )
8963 }
void Unit::ResetThreatLevel ( )
inline
Vector Unit::ResolveForces ( const Transformation trans,
const Matrix transmat 
)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 3893 of file unit_generic.cpp.

References _Universe, active_missions, UniverseUtil::cacheAnimation(), FINITE, VegaConfig::getVariable(), UniverseUtil::getVariable(), InvTransformNormal(), Universe::isPlayerStarship(), XMLSupport::parse_float(), UniverseUtil::playAnimationGrow(), q, RealPosition(), SIMULATION_ATOM, v, Vector, vs_config, and VSFileSystem::vs_fprintf().

Referenced by GameUnit< UnitType >::ResolveForces().

3894 {
3895  //First, save theoretical instantaneous acceleration (not time-quantized) for GetAcceleration()
3897 
3898  Vector p, q, r;
3899  GetOrientation( p, q, r );
3900  Vector temp1( NetLocalTorque.i*p+NetLocalTorque.j*q+NetLocalTorque.k*r );
3901  if (NetTorque.i || NetTorque.j || NetTorque.k)
3902  temp1 += InvTransformNormal( transmat, NetTorque );
3903  if ( GetMoment() )
3904  temp1 = temp1/GetMoment();
3905  else
3906  VSFileSystem::vs_fprintf( stderr, "zero moment of inertia %s\n", name.get().c_str() );
3907  Vector temp( temp1*SIMULATION_ATOM );
3908  AngularVelocity += temp;
3909  static float maxplayerrotationrate =
3910  XMLSupport::parse_float( vs_config->getVariable( "physics", "maxplayerrot", "24" ) );
3911  static float maxnonplayerrotationrate = XMLSupport::parse_float( vs_config->getVariable( "physics", "maxNPCrot", "360" ) );
3912  float caprate;
3913  if ( _Universe->isPlayerStarship( this ) ) //clamp to avoid vomit-comet effects
3914  caprate = maxplayerrotationrate;
3915  else
3916  caprate = maxnonplayerrotationrate;
3917  if (AngularVelocity.MagnitudeSquared() > caprate*caprate)
3918  AngularVelocity = AngularVelocity.Normalize()*caprate;
3919  //acceleration
3920  Vector temp2 = (NetLocalForce.i*p+NetLocalForce.j*q+NetLocalForce.k*r);
3921  if ( !( FINITE( NetForce.i ) && FINITE( NetForce.j ) && FINITE( NetForce.k ) ) )
3922  cout<<"NetForce skrewed";
3923  if (NetForce.i || NetForce.j || NetForce.k)
3924  temp2 += InvTransformNormal( transmat, NetForce );
3925  temp2 = temp2/GetMass();
3926  temp = temp2*SIMULATION_ATOM;
3927  if ( !( FINITE( temp2.i ) && FINITE( temp2.j ) && FINITE( temp2.k ) ) )
3928  cout<<"NetForce transform skrewed";
3929  float oldmagsquared = Velocity.MagnitudeSquared();
3930  Velocity += temp;
3931  //}
3932 
3933  float newmagsquared = Velocity.MagnitudeSquared();
3934  static float warpstretchcutoff =
3935  XMLSupport::parse_float( vs_config->getVariable( "graphics", "warp_stretch_cutoff",
3936  "500000" ) )*XMLSupport::parse_float(
3937  vs_config->getVariable( "physics", "game_speed", "1" ) );
3938  static float warpstretchoutcutoff =
3939  XMLSupport::parse_float( vs_config->getVariable( "graphics", "warp_stretch_decel_cutoff",
3940  "500000" ) )
3941  *XMLSupport::parse_float( vs_config->getVariable( "physics", "game_speed", "1" ) );
3942  static float cutsqr = warpstretchcutoff*warpstretchcutoff;
3943  static float outcutsqr = warpstretchoutcutoff*warpstretchoutcutoff;
3944  bool oldbig = oldmagsquared > cutsqr;
3945  bool newbig = newmagsquared > cutsqr;
3946  bool oldoutbig = oldmagsquared > outcutsqr;
3947  bool newoutbig = newmagsquared > outcutsqr;
3948  if ( (newbig && !oldbig) || (oldoutbig && !newoutbig) ) {
3949  static string insys_jump_ani = vs_config->getVariable( "graphics", "insys_jump_animation", "warp.ani" );
3950  static bool docache = true;
3951  if (docache) {
3952  UniverseUtil::cacheAnimation( insys_jump_ani );
3953  docache = false;
3954  }
3955  Vector v( GetVelocity() );
3956  v.Normalize();
3957  Vector p, q, r;
3958  GetOrientation( p, q, r );
3959  static float sec =
3960  XMLSupport::parse_float( vs_config->getVariable( "graphics", "insys_jump_ani_second_ahead",
3961  "4" ) )
3962  /( XMLSupport::parse_float( vs_config->getVariable( "physics", "game_speed",
3963  "1" ) )
3964  *XMLSupport::parse_float( vs_config->getVariable( "physics", "game_accel", "1" ) ) );
3965  static float endsec =
3966  XMLSupport::parse_float( vs_config->getVariable( "graphics", "insys_jump_ani_second_ahead_end",
3967  ".03" ) )
3968  /( XMLSupport::parse_float( vs_config->getVariable( "physics", "game_speed",
3969  "1" ) )
3970  *XMLSupport::parse_float( vs_config->getVariable( "physics", "game_accel", "1" ) ) );
3971  float tmpsec = oldbig ? endsec : sec;
3972  UniverseUtil::playAnimationGrow( insys_jump_ani, RealPosition( this ).Cast()+Velocity*tmpsec+v*rSize(), rSize()*8, 1 );
3973  }
3974  static float air_res_coef = XMLSupport::parse_float( active_missions[0]->getVariable( "air_resistance", "0" ) );
3975  static float lateral_air_res_coef = XMLSupport::parse_float( active_missions[0]->getVariable( "lateral_air_resistance", "0" ) );
3976  if (air_res_coef || lateral_air_res_coef) {
3977  float velmag = Velocity.Magnitude();
3978  Vector AirResistance = Velocity
3979  *( air_res_coef*velmag/GetMass() )*(corner_max.i-corner_min.i)*(corner_max.j-corner_min.j);
3980  if (AirResistance.Magnitude() > velmag) {
3981  Velocity.Set( 0, 0, 0 );
3982  } else {
3983  Velocity = Velocity-AirResistance;
3984  if (lateral_air_res_coef) {
3985  Vector p, q, r;
3986  GetOrientation( p, q, r );
3987  Vector lateralVel = p*Velocity.Dot( p )+q*Velocity.Dot( q );
3988  AirResistance = lateralVel
3989  *( lateral_air_res_coef*velmag
3991  if ( AirResistance.Magnitude() > lateralVel.Magnitude() )
3992  Velocity = r*Velocity.Dot( r );
3993  else
3994  Velocity = Velocity-AirResistance;
3995  }
3996  }
3997  }
3999 
4000  return temp2;
4001 }
void Unit::RestoreGodliness ( )

Definition at line 285 of file unit_generic.cpp.

References _Universe, Universe::AccessCockpit(), and Cockpit::RestoreGodliness().

286 {
288 }
void Unit::ReTargetFg ( int  which_target = 0)

Definition at line 2045 of file unit_generic.cpp.

References _Universe, Universe::activeStarSystem(), UnitCollection::createIterator(), and StarSystem::getUnitList().

2046 {
2047 #if 0
2048  StarSystem *ssystem = _Universe->activeStarSystem();
2049  UnitCollection *unitlist = ssystem->getUnitList();
2050  un_iter uiter = unitlist->createIterator();
2051 
2052  GameUnit *found_target = NULL;
2053  int found_attackers = 1000;
2054  for (GameUnit *other_unit = NULL; other_unit = *uiter; ++uiter) {
2055  string other_fgid = other_unit->getFgID();
2056  if ( other_unit->matchesFg( target_fgid[which_target] ) ) {
2057  //the other unit matches our primary target
2058 
2059  int num_attackers = other_unit->getNumAttackers();
2060  if (num_attackers < found_attackers) {
2061  //there's less ships attacking this target than the previous one
2062  found_target = other_unit;
2063  found_attackers = num_attackers;
2064  setTarget( found_target );
2065  }
2066  }
2067  }
2068  if (found_target == NULL) {
2069  //we haven't found a target yet, search again
2070  if (which_target <= 1)
2071  ReTargetFg( which_target+1 );
2072  else
2073  //we can't find any target
2074  setTarget( NULL );
2075  }
2076 #endif
2077 }
void Unit::RollTorque ( float  amt)

Definition at line 3542 of file unit_generic.cpp.

References Vector.

3543 {
3544  if (amt > limits.roll) amt = limits.roll;
3545  else if (amt < -limits.roll)
3546  amt = -limits.roll;
3547  ApplyLocalTorque( amt*Vector( 0, 0, 1 ) );
3548 }
void Unit::Rotate ( const Vector axis)

Definition at line 3187 of file unit_generic.cpp.

References UniverseUtil::cos(), Matrix::getR(), and identity_quaternion().

3188 {
3189  double theta = axis.Magnitude();
3190  double ootheta = 0;
3191  if (theta == 0) return;
3192  ootheta = 1/theta;
3193  float s = cos( theta*.5 );
3194  Quaternion rot = Quaternion( s, axis*(sinf( theta*.5 )*ootheta) );
3195  if (theta < 0.0001)
3196  rot = identity_quaternion;
3198  if (limits.limitmin > -1) {
3199  Matrix mat;
3201  if (limits.structurelimits.Dot( mat.getR() ) < limits.limitmin)
3203  }
3204 }
float Unit::RShieldData ( ) const

Definition at line 4841 of file unit_generic.cpp.

Referenced by GameCockpit::LookupTargetStat(), GameCockpit::LookupUnitStat(), Orders::AggressiveAI::ProcessLogicItem(), Orders::AggressiveAI::ReCommandWing(), Orders::AggressiveAI::SetParent(), and UpAndDownGrade().

4842 {
4843  switch (shield.number)
4844  {
4845  case 2:
4846  return 0; //don't react to stuff we have no data on
4847 
4848  case 4:
4849  {
4850  if (shield.shield4fbrl.rightmax != 0)
4851  return (shield.shield4fbrl.right)/shield.shield4fbrl.rightmax;
4852  break;
4853  }
4854  case 8:
4855  {
4856  if (shield.shield8.backrighttopmax != 0 || shield.shield8.backrightbottommax != 0
4857  || shield.shield8.frontrighttopmax != 0 || shield.shield8.frontrightbottommax
4858  != 0) {
4859  return (shield.shield8.backrighttop+shield.shield8.backrightbottom+shield.shield8.frontrighttop
4860  +shield.shield8.frontrightbottom)
4861  /(shield.shield8.backrighttopmax+shield.shield8.backrightbottommax+shield.shield8.frontrighttopmax
4862  +shield.shield8.frontrightbottommax);
4863  }
4864  break;
4865  }
4866  }
4867  return 0;
4868 }
float Unit::rSize ( ) const
inline

Definition at line 932 of file unit_generic.h.

References radial_size.

Referenced by Radar::CollectRadarTracks::acquire(), Planet::AddSpaceElevator(), MissileEffect::ApplyDamage(), GameCockpit::Autopilot(), AutoPilotToErrorMessage(), AutoSafeEntrancePoint(), CalculateNearestWarpUnit(), Mission::call_unit_launch(), CanDockWithMe(), ChooseNearNavPoint(), CloseEnoughToNavOrDest(), Collidable::Collidable(), Terrain::Collide(), ContinuousTerrain::Collide(), Beam::Collide(), Collide(), collideTrees::colTree(), cosAngleFromMountTo(), cosAngleTo(), CrashForceDock(), createObjects(), DistanceTwoTargets(), GameCockpit::DoAutoLanding(), dockingdistance(), DockToSavedBases(), Orders::DockingOps::DockToTarget(), GameStarSystem::DoJumpingComeSightAndSound(), GameStarSystem::DoJumpingLeaveSightAndSound(), WarpTrail::Draw(), GameStarSystem::Draw(), BaseInterface::Room::BaseShip::Draw(), GameStarSystem::DrawJumpStars(), EjectCargo(), Orders::TurretAI::Execute(), PlanetaryOrbit::Execute(), Orders::AutoLongHaul::Execute(), Orders::FaceDirection::Execute(), Orders::LoopAround::Execute(), Orders::LoopAroundAgro::Execute(), Orders::AggressiveAI::ExecuteNoEnemies(), anonymous_namespace{autodocking.cpp}::FindDockingPort(), anonymous_namespace{autodocking.cpp}::FindWaypoint(), getAtmospheric(), getAutoRSize(), UnitUtil::getDistance(), UnitUtil::getPhysicsPriority(), CommunicatingAI::GetRandomUnit(), UnitUtil::getSignificantDistance(), Radar::Track::GetSize(), InRange(), InsideCollideTree(), LaunchOneParticle(), LoadMission(), LoadRow(), GameCockpit::LookupUnitStat(), Orders::AggressiveAI::ProcessCurrentFgDirective(), Orders::AggressiveAI::ProcessLogicItem(), querySphereNoRecurse(), rayCollide(), UniverseUtil::SafeStarSystemEntrancePoint(), ShoveCamBehindUnit(), ShoveCamBelowUnit(), TargFront(), GameUnit< UnitType >::TransferUnitToSystem(), Orders::DockingOps::Undock(), Cockpit::Update(), GameNebula::UpdatePhysics2(), GameMissile::UpdatePhysics2(), Missile::UpdatePhysics2(), UpgradeSubUnitsWithFactory(), WarpMatrixForCollisions(), and WarpToP().

933  {
934  return radial_size;
935  }
void Unit::Select ( )

Definition at line 1814 of file unit_generic.cpp.

1815 {
1816  selected = true;
1817 }
void Unit::SelectAllWeapon ( bool  Missile)

Definition at line 5365 of file unit_generic.cpp.

References Mount::DESTROYED, and weapon_info::SPECIAL.

Referenced by Takeoff(), and TakeoffEveryZig().

5366 {
5367  for (int i = 0; i < GetNumMounts(); ++i)
5368  if (mounts[i].status < Mount::DESTROYED)
5369  if (mounts[i].type->size != weapon_info::SPECIAL)
5370  mounts[i].Activate( Missile );
5371 }
bool Unit::SellCargo ( unsigned int  i,
int  quantity,
float creds,
Cargo carg,
Unit buyer 
)

Definition at line 8453 of file unit_generic.cpp.

References _Universe, AddCargo(), CanAddCargo(), Universe::netLocked(), Network, Cargo::price, PriceCargo(), Cargo::quantity, NetServer::sendCredits(), SERVER, and VSServer.

Referenced by BaseComputer::sellSelectedCargo(), and BaseComputer::sellUpgrade().

8454 {
8455  if (i < 0 || i >= pImage->cargo.size() || !buyer->CanAddCargo( pImage->cargo[i] ) || Mass < pImage->cargo[i].mass)
8456  return false;
8457  carg = pImage->cargo[i];
8458  if (quantity > pImage->cargo[i].quantity)
8459  quantity = pImage->cargo[i].quantity;
8460  carg.price = buyer->PriceCargo( pImage->cargo[i].content );
8461  if ( !Network || _Universe->netLocked() )
8462  //Don't give cash back until server acknowledges purchase.
8463  creds += quantity*carg.price;
8464  if ( SERVER && !_Universe->netLocked() )
8465  VSServer->sendCredits( serial, creds );
8466  carg.quantity = quantity;
8467  buyer->AddCargo( carg );
8468 
8469  RemoveCargo( i, quantity );
8470  return true;
8471 }
bool Unit::SellCargo ( const std::string &  s,
int  quantity,
float creds,
Cargo carg,
Unit buyer 
)

Definition at line 8473 of file unit_generic.cpp.

References Cargo::content.

8474 {
8475  Cargo tmp;
8476  tmp.content = s;
8477  vector< Cargo >::iterator mycargo = std::find( pImage->cargo.begin(), pImage->cargo.end(), tmp );
8478  if ( mycargo == pImage->cargo.end() )
8479  return false;
8480  return SellCargo( mycargo-pImage->cargo.begin(), quantity, creds, carg, buyer );
8481 }
void Unit::SetAfterBurn ( float  aft)

Definition at line 149 of file unit_generic.cpp.

150 {
151  afterburnenergy = aft;
152 }
void Unit::SetAI ( Order newAI)

Definition at line 1966 of file unit_generic.cpp.

References Order::SetParent().

Referenced by EjectCargo(), Planet::InitPlanet(), GamePlanet::Kill(), Planet::Kill(), and SwitchUnits().

1967 {
1968  newAI->SetParent( this );
1969  if (aistate)
1970  aistate->ReplaceOrder( newAI );
1971  else
1972  aistate = newAI;
1973 }
void Unit::SetAllVisible ( bool  isvis)

Definition at line 1851 of file unit_generic.cpp.

1852 {
1853  if (vis)
1854  invisible &= (~INVISUNIT);
1855  else
1856  invisible |= INVISUNIT;
1857 }
void Unit::SetAngularVelocity ( const Vector v)
void Unit::setAttackPreference ( const std::string &  s)

Definition at line 8675 of file unit_generic.cpp.

References ROLES::getRole().

Referenced by LoadRow().

8676 {
8678 }
void Unit::setAverageGunSpeed ( )

Definition at line 1628 of file unit_generic.cpp.

References Mount::ACTIVE, weapon_info::BEAM, Mount::INACTIVE, isMissile(), and speed.

Referenced by LoadRow(), and Mount::ReplaceMounts().

1629 {
1630  float mrange = -1;
1631  float grange = -1;
1632  float speed = -1;
1633  bool beam = true;
1634  if ( GetNumMounts() ) {
1635  grange = 0;
1636  speed = 0;
1637  mrange = 0;
1638  int nummt = 0;
1639  //this breaks the name, but... it _is_ more useful.
1640  for (int i = 0; i < GetNumMounts(); ++i)
1641  if (mounts[i].status == Mount::ACTIVE || mounts[i].status == Mount::INACTIVE) {
1642  if (isMissile( mounts[i].type ) == false) {
1643  if (mounts[i].type->Range > grange)
1644  grange = mounts[i].type->Range;
1645  if (mounts[i].status == Mount::ACTIVE) {
1646  speed += mounts[i].type->Speed;
1647  ++nummt;
1648  beam &= (mounts[i].type->type == weapon_info::BEAM);
1649  }
1650  } else if ( isMissile( mounts[i].type ) ) {
1651  if (mounts[i].type->Range > mrange)
1652  mrange = mounts[i].type->Range;
1653  }
1654  }
1655  if (nummt) {
1656  if (beam)
1657  speed = FLT_MAX;
1658  else
1659  speed = speed/nummt;
1660  }
1661  }
1662  this->missilerange = mrange;
1663  this->gunrange = grange;
1664  this->gunspeed = speed;
1665 }
void Unit::SetCollisionParent ( Unit name)

Definition at line 5611 of file unit_generic.cpp.

References SetCollisionParent().

Referenced by SetCollisionParent().

5612 {
5613  assert( 0 ); //deprecated... many less collisions with subunits out of the table
5614 #if 0
5615  for (int i = 0; i < numsubunit; ++i) {
5616  subunits[i]->CollideInfo.object.u = name;
5617  subunits[i]->SetCollisionParent( name );
5618  }
5619 #endif
5620 }
void Unit::setCombatRole ( const std::string &  s)

Definition at line 8691 of file unit_generic.cpp.

References ROLES::getRole().

8692 {
8693  unitRole( ROLES::getRole( s ) );
8695 }
void Unit::SetCurPosition ( const QVector pos)
inline

Sets the cumulative transformation matrix's position...for setting up to be out in the middle of nowhere.

Definition at line 954 of file unit_generic.h.

References curr_physical_state, and Transformation::position.

Referenced by PlanetaryOrbit::Execute(), StarSystem::ProcessPendingJumps(), Cockpit::Update(), and GameBuilding::UpdatePhysics2().

955  {
957  }
void Unit::SetEnergyRecharge ( float  enrech)

Definition at line 159 of file unit_generic.cpp.

160 {
161  recharge = enrech;
162 }
void Unit::setFaceCamera ( )

Definition at line 98 of file unit_generic.cpp.

Referenced by GamePlanet::AddFog().

99 {
101 }
void Unit::SetFaction ( int  faction)

Definition at line 1586 of file unit_generic.cpp.

References StarSystemGent::faction.

Referenced by UnitUtil::setFactionIndex(), UnitUtil::setFactionName(), and UpgradeSubUnitsWithFactory().

1587 {
1588  this->faction = faction;
1589  for (un_iter ui = getSubUnits(); (*ui) != NULL; ++ui)
1590  (*ui)->SetFaction( faction );
1591 }
void Unit::SetFg ( Flightgroup fg,
int  fg_snumber 
)

Definition at line 1599 of file unit_generic.cpp.

Referenced by FireKeyboard::JoinFg(), Orders::AggressiveAI::ProcessCurrentFgDirective(), and UnitUtil::switchFg().

1600 {
1601  flightgroup = fg;
1602  flightgroup_subnumber = fg_subnumber;
1603 }
void Unit::SetFuel ( float  f)

Definition at line 154 of file unit_generic.cpp.

155 {
156  fuel = f;
157 }
void Unit::setFullname ( std::string  name)
inline

Definition at line 1498 of file unit_generic.h.

References fullname, and name.

Referenced by Planet::beginElement(), and Planet::InitPlanet().

1499  {
1500  fullname = name;
1501  }
void Unit::SetGlowVisible ( bool  isvis)

Definition at line 1859 of file unit_generic.cpp.

Referenced by FireKeyboard::Execute().

1860 {
1861  if (vis)
1862  invisible &= (~INVISGLOW);
1863  else
1864  invisible |= INVISGLOW;
1865 }
void Unit::SetMaxEnergy ( float  maxen)

Definition at line 164 of file unit_generic.cpp.

165 {
166  maxenergy = maxen;
167 }
void Unit::SetNebula ( Nebula neb)

Definition at line 113 of file unit_generic.cpp.

References SetNebula().

Referenced by Nebula::reactToCollision(), SetNebula(), and StarSystem::Update().

114 {
115  nebula = neb;
116  if ( !SubUnits.empty() ) {
117  un_fiter iter = SubUnits.fastIterator();
118  Unit *un;
119  while ( (un = *iter) ) {
120  un->SetNebula( neb );
121  ++iter;
122  }
123  }
124 }
void Unit::SetNetworkMode ( bool  mode = true)

Definition at line 79 of file unit_generic.cpp.

References UniverseUtil::networked().

Referenced by NetClient::AddClientObject(), and createObjects().

80 {
81  networked = mode;
82 }
void Unit::SetOrientation ( QVector  q,
QVector  r 
)

Definition at line 4003 of file unit_generic.cpp.

References Quaternion::from_vectors(), and QVector.

Referenced by Planet::AddSpaceElevator(), EjectCargo(), Orders::ChangeHeading::Execute(), and FaceTarget().

4004 {
4005  q.Normalize();
4006  r.Normalize();
4007  QVector p;
4008  CrossProduct( q, r, p );
4009  CrossProduct( r, p, q );
4010  curr_physical_state.orientation = Quaternion::from_vectors( p.Cast(), q.Cast(), r.Cast() );
4011 }
void Unit::SetOrientation ( Quaternion  Q)

Definition at line 4021 of file unit_generic.cpp.

4022 {
4024 }
void Unit::SetOrientation ( QVector  p,
QVector  q,
QVector  r 
)

Definition at line 4013 of file unit_generic.cpp.

References Quaternion::from_vectors().

4014 {
4015  q.Normalize();
4016  r.Normalize();
4017  p.Normalize();
4018  curr_physical_state.orientation = Quaternion::from_vectors( p.Cast(), q.Cast(), r.Cast() );
4019 }
void Unit::SetPosition ( const QVector pos)
void Unit::SetRecursiveOwner ( Unit target)

Definition at line 5553 of file unit_generic.cpp.

References UnitUtil::owner(), and SetRecursiveOwner().

Referenced by Planet::AddSpaceElevator(), Planet::InitPlanet(), SetRecursiveOwner(), and UpgradeSubUnitsWithFactory().

5554 {
5555  owner = target;
5556  Unit *su;
5557  for (un_iter iter = getSubUnits(); (su = *iter); ++iter)
5558  su->SetRecursiveOwner( target );
5559 }
void Unit::SetResolveForces ( bool  ys)

Definition at line 1594 of file unit_generic.cpp.

Referenced by PlanetaryOrbit::Execute(), PlanetaryOrbit::PlanetaryOrbit(), and PlanetaryOrbit::~PlanetaryOrbit().

1595 {
1596  resolveforces = ys;
1597 }
void Unit::setTargetFg ( std::string  primary,
std::string  secondary = std::string(),
std::string  tertiary = std::string() 
)

Definition at line 2036 of file unit_generic.cpp.

References primary, and secondary.

2037 {
2038  target_fgid[0] = primary;
2039  target_fgid[1] = secondary;
2040  target_fgid[2] = tertiary;
2041 
2042  ReTargetFg( 0 );
2043 }
void Unit::setTractorability ( enum tractorHow  how)

Definition at line 8927 of file unit_generic.cpp.

Referenced by LoadRow().

8928 {
8929  tractorability_flags = how;
8930 }
void Unit::SetTurretAI ( )

Definition at line 2079 of file unit_generic.cpp.

References aistate, CheckAccessory(), Order::Destroy(), EnqueueAIFirst(), VegaConfig::getVariable(), XMLSupport::parse_bool(), Order::SetParent(), SetTurretAI(), and vs_config.

Referenced by AddUnitToSystem(), Mission::call_unit_launch(), createObjects(), EjectCargo(), FireKeyboard::Execute(), Planet::InitPlanet(), LoadMission(), UnitUtil::orbit(), Mount::PhysicsAlignedFire(), Orders::AggressiveAI::ProcessCurrentFgDirective(), SetTurretAI(), SwitchUnits2(), Cockpit::Update(), and UnitUtil::upgrade().

2080 {
2081  turretstatus = 2;
2082  static bool talkinturrets = XMLSupport::parse_bool( vs_config->getVariable( "AI", "independent_turrets", "false" ) );
2083  if (talkinturrets) {
2084  Unit *un;
2085  for (un_iter iter = getSubUnits(); (un = *iter); ++iter) {
2086  if ( !CheckAccessory( un ) ) {
2087  un->EnqueueAIFirst( new Orders::FireAt( 15.0f ) );
2088  un->EnqueueAIFirst( new Orders::FaceTarget( false, 3 ) );
2089  }
2090  un->SetTurretAI();
2091  }
2092  } else {
2093  Unit *un;
2094  for (un_iter iter = getSubUnits(); (un = *iter); ++iter) {
2095  if ( !CheckAccessory( un ) ) {
2096  if (un->aistate)
2097  un->aistate->Destroy();
2098  un->aistate = ( new Orders::TurretAI() );
2099  un->aistate->SetParent( un );
2100  }
2101  un->SetTurretAI();
2102  }
2103  }
2104 }
void Unit::setUnitRole ( const std::string &  s)

Definition at line 8670 of file unit_generic.cpp.

References ROLES::getRole().

Referenced by LoadRow().

8671 {
8672  unitRole( ROLES::getRole( s ) );
8673 }
void Unit::SetVelocity ( const Vector v)
void Unit::SetVisible ( bool  isvis)

Definition at line 1843 of file unit_generic.cpp.

Referenced by GameCockpit::SetupViewPort(), and SwitchUnits().

1844 {
1845  if (vis)
1846  invisible &= (~INVISCAMERA);
1847  else
1849 }
float Unit::ShieldRechargeData ( ) const
inline

Definition at line 915 of file unit_generic.h.

References Shield::recharge, and shield.

916  {
917  return shield.recharge;
918  }
std::string Unit::shieldSerializer ( const struct XMLType input,
void *  mythis 
)
staticprotected

Definition at line 8593 of file unit_generic.cpp.

References Shield::number, shield, Shield::shield2fb, Shield::shield4fbrl, Shield::shield8, and tostring().

8594 {
8595  Unit *un = (Unit*) mythis;
8596  switch (un->shield.number)
8597  {
8598  case 2:
8599  return tostring( un->shield.shield2fb.frontmax )+string( "\" back=\"" )+tostring( un->shield.shield2fb.backmax );
8600 
8601  case 8:
8602  return string( "\" frontrighttop=\"" )+tostring( un->shield.shield8.frontrighttop )+string( "\" backrighttop=\"" )
8603  +tostring( un->shield.shield8.backrighttop )+string( "\" frontlefttop=\"" )+tostring(
8604  un->shield.shield8.frontlefttop )
8605  +string( "\" backlefttop=\"" )+tostring( un->shield.shield8.backlefttop )+string( "\" frontrightbottom=\"" )
8606  +tostring(
8607  un->shield.shield8.frontrightbottom )+string( "\" backrightbottom=\"" )+tostring(
8608  un->shield.shield8.backrightbottom )
8609  +string( "\" frontleftbottom=\"" )+tostring( un->shield.shield8.frontleftbottom )+string( "\" backleftbottom=\"" )
8610  +tostring( un->shield.shield8.backleftbottom );
8611 
8612  case 4:
8613  default:
8614  return tostring( un->shield.shield4fbrl.frontmax )+string( "\" back=\"" )+tostring( un->shield.shield4fbrl.backmax )
8615  +string( "\" left=\"" )+tostring( un->shield.shield4fbrl.leftmax )+string( "\" right=\"" )+tostring(
8616  un->shield.shield4fbrl.rightmax );
8617  }
8618  return string( "" );
8619 }
bool Unit::ShieldUp ( const Vector pnt) const
protected

Definition at line 5184 of file unit_generic.cpp.

References VegaConfig::getVariable(), XMLSupport::parse_float(), and vs_config.

5185 {
5186  const int shieldmin = 5;
5187  static float nebshields = XMLSupport::parse_float( vs_config->getVariable( "physics", "nebula_shield_recharge", ".5" ) );
5188  if (nebula != NULL || nebshields > 0)
5189  return false;
5190  switch (shield.number)
5191  {
5192  case 2:
5193  return ( (pnt.k > 0) ? (shield.shield2fb.front) : (shield.shield2fb.back) ) > shieldmin;
5194  case 8:
5195  if (pnt.i > 0) {
5196  if (pnt.j > 0) {
5197  if (pnt.k > 0)
5198  return shield.shield8.frontlefttop > shieldmin;
5199  else
5200  return shield.shield8.backlefttop > shieldmin;
5201  } else {
5202  if (pnt.k > 0)
5203  return shield.shield8.frontleftbottom > shieldmin;
5204  else
5205  return shield.shield8.backleftbottom > shieldmin;
5206  }
5207  } else {
5208  if (pnt.j > 0) {
5209  if (pnt.k > 0)
5210  return shield.shield8.frontrighttop > shieldmin;
5211  else
5212  return shield.shield8.backrighttop > shieldmin;
5213  } else {
5214  if (pnt.k > 0)
5215  return shield.shield8.frontrightbottom > shieldmin;
5216  else
5217  return shield.shield8.backrightbottom > shieldmin;
5218  }
5219  }
5220  break;
5221  case 4:
5222  if ( fabs( pnt.k ) > fabs( pnt.i ) ) {
5223  if (pnt.k > 0)
5224  return shield.shield4fbrl.front > shieldmin;
5225  else
5226  return shield.shield4fbrl.back > shieldmin;
5227  } else {
5228  if (pnt.i > 0)
5229  return shield.shield4fbrl.left > shieldmin;
5230  else
5231  return shield.shield4fbrl.right > shieldmin;
5232  }
5233  return false;
5234 
5235  default:
5236  return false;
5237  }
5238 }
void Unit::SortCargo ( )
protected

Definition at line 8713 of file unit_generic.cpp.

References UnitImages< BOGUS >::cargo, and pImage.

Referenced by cargoSerializer().

8714 {
8715  Unit *un = this;
8716  std::sort( un->pImage->cargo.begin(), un->pImage->cargo.end() );
8717  for (unsigned int i = 0; i+1 < un->pImage->cargo.size(); ++i)
8718  if (un->pImage->cargo[i].content == un->pImage->cargo[i+1].content) {
8719  float tmpmass = un->pImage->cargo[i].quantity*un->pImage->cargo[i].mass
8720  +un->pImage->cargo[i+1].quantity*un->pImage->cargo[i+1].mass;
8721  float tmpvolume = un->pImage->cargo[i].quantity*un->pImage->cargo[i].volume
8722  +un->pImage->cargo[i+1].quantity*un->pImage->cargo[i+1].volume;
8723  un->pImage->cargo[i].quantity += un->pImage->cargo[i+1].quantity;
8724  if (un->pImage->cargo[i].quantity) {
8725  tmpmass /= un->pImage->cargo[i].quantity;
8726  tmpvolume /= un->pImage->cargo[i].quantity;
8727  }
8728  un->pImage->cargo[i].volume = tmpvolume;
8729  un->pImage->cargo[i].mission = (un->pImage->cargo[i].mission || un->pImage->cargo[i+1].mission);
8730  un->pImage->cargo[i].mass = tmpmass;
8731  //group up similar ones
8732  un->pImage->cargo.erase( un->pImage->cargo.begin()+(i+1) );
8733  i--;
8734  }
8735 }
virtual void Unit::Split ( int  level)
inlinevirtual
vector< Mesh * > Unit::StealMeshes ( )

Definition at line 1330 of file unit_generic.cpp.

Referenced by Briefing::Ship::Ship().

1331 {
1332  vector< Mesh* >ret;
1333 
1334  Mesh *shield = meshdata.empty() ? NULL : meshdata.back();
1335  for (int i = 0; i < nummesh(); ++i)
1336  ret.push_back( meshdata[i] );
1337  meshdata.clear();
1338  meshdata.push_back( shield );
1339 
1340  return ret;
1341 }
std::string Unit::subunitSerializer ( const struct XMLType input,
void *  mythis 
)
staticprotected

Definition at line 8654 of file unit_generic.cpp.

References XMLSerializer::getName(), getSubUnits(), XMLType::wordlength::hardint, index, name, pImage, UnitImages< BOGUS >::unitwriter, and XMLType::w.

8655 {
8656  Unit *un = (Unit*) mythis;
8657  int index = input.w.hardint;
8658  Unit *su;
8659  int i = 0;
8660  for (un_iter ui = un->getSubUnits(); (su = *ui); ++ui, ++i) {
8661  if (i == index) {
8662  if (su->pImage->unitwriter)
8663  return su->pImage->unitwriter->getName();
8664  return su->name;
8665  }
8666  }
8667  return string( "destroyed_blank" );
8668 }
void Unit::SwitchCombatFlightMode ( )

Definition at line 3330 of file unit_generic.cpp.

Referenced by FlyByKeyboard::Execute().

3331 {
3332  if (computer.combat_mode)
3333  computer.combat_mode = false;
3334  else
3335  computer.combat_mode = true;
3336 }
Unit * Unit::Target ( )

Definition at line 270 of file unit_generic.cpp.

Referenced by Radar::CollectRadarTracks::acquire(), CommunicatingAI::AdjustRelationTo(), Pilot::adjustSpecificRelationship(), AfterburnTurnAway(), AfterburnVeerAndTurnAway(), AllUnitsCloseAndEngage(), Arrested(), TurretBin::AssignTargets(), Order::AttachOrder(), ZoneMgr::broadcastSnapshots(), Mission::call_unit_launch(), ChooseSubTargets(), Orders::FireAt::ChooseTargets(), ChooseTargets(), DockedScript(), DoDockingOps(), GameStarSystem::Draw(), GameUnit< UnitType >::Draw(), GameCockpit::Draw(), NavigationSystem::DrawSystem(), Orders::TurretAI::Execute(), Orders::Ikarus::Execute(), Orders::AggressiveAI::Execute(), Orders::FireAt::Execute(), FlyByKeyboard::Execute(), Orders::FaceTarget::Execute(), Orders::AutoLongHaul::Execute(), FireKeyboard::Execute(), Orders::FaceTargetITTS::Execute(), Orders::LoopAround::Execute(), Orders::LoopAroundAgro::Execute(), Orders::FacePerpendicular::Execute(), FlyTo::Execute(), Orders::AggressiveAI::ExecuteNoEnemies(), FaceTarget(), Radar::Sensor::FindTracksInRange(), FireBitmask(), ForceChangeTarget(), getAutoRSize(), getNearestTargetUnit(), UnitUtil::getPhysicsPriority(), CommunicatingAI::GetRandomUnit(), UnitWrapper::GetTarget(), GameCockpit::getTargetLabel(), GetThreat(), Radar::Track::HasLock(), HelpOut(), Radar::Sensor::IsTracking(), FireKeyboard::JoinFg(), KickstopBase(), LeadMe(), GameCockpit::LookupUnitStat(), MoveTo(), Mount::NextMountCloser(), Mount::PhysicsAlignedFire(), Priority(), Orders::AggressiveAI::ProcessCurrentFgDirective(), Orders::AggressiveAI::ProcessLogicItem(), Orders::FireAt::PursueTarget(), RequestClearence(), CommunicatingAI::selectCommunicationMessageMood(), NetClient::sendPosition(), Orders::AutoLongHaul::SetParent(), UnitWrapper::SetTarget(), GameCockpit::setTargetLabel(), SetupVAndTargetV(), GameCockpit::SetupViewPort(), Orders::FireAt::ShouldFire(), Orders::AggressiveAI::SignalChosenTarget(), SwitchUnits(), Target(), UniverseUtil::TargetEachOther(), TargetTurret(), TargIncomingMissile(), TargThreat(), GameUnit< UnitType >::TransferUnitToSystem(), TurnAway(), Cockpit::Update(), Cockpit::updateAttackers(), UpdatePhysics(), GameMissile::UpdatePhysics2(), Missile::UpdatePhysics2(), UpdateSubunitPhysics(), and VectorThrustHelper().

271 {
272  return computer.target.GetUnit();
273 }
void Unit::Target ( Unit targ)

Definition at line 5282 of file unit_generic.cpp.

References _Universe, Universe::activeStarSystem(), activeStarSystem, NetServer::BroadcastTarget(), UnitCollection::constIterator(), GetDestinations(), StarSystem::getFileName(), GetSerial(), getStarSystem(), StarSystem::getUnitList(), Universe::isPlayerStarship(), SERVER, Target(), VSServer, and WarpPursuit().

5283 {
5284  if (targ == this)
5285  return;
5286  ObjSerial oldtarg = 0;
5287  if ( computer.target.GetUnit() )
5288  oldtarg = computer.target.GetUnit()->GetSerial();
5289  if ( !( activeStarSystem == NULL || activeStarSystem == _Universe->activeStarSystem() ) ) {
5290  if (SERVER && computer.target.GetUnit() != NULL)
5291  VSServer->BroadcastTarget( GetSerial(), oldtarg, 0, this->getStarSystem()->GetZone() );
5292  computer.target.SetUnit( NULL );
5293  return;
5294  }
5295  if (targ) {
5296  if (targ->activeStarSystem == _Universe->activeStarSystem() || targ->activeStarSystem == NULL) {
5297  if ( targ != Unit::Target() ) {
5298  for (int i = 0; i < GetNumMounts(); ++i)
5299  mounts[i].time_to_lock = mounts[i].type->LockTime;
5300  if (SERVER && computer.target.GetUnit() != targ)
5301  VSServer->BroadcastTarget( GetSerial(), oldtarg, targ->GetSerial(), this->getStarSystem()->GetZone() );
5302  computer.target.SetUnit( targ );
5303  LockTarget( false );
5304  }
5305  } else {
5306  if (jump.drive != -1) {
5307  bool found = false;
5308  Unit *u;
5309  for (un_kiter i = _Universe->activeStarSystem()->getUnitList().constIterator(); (u = *i) != NULL; ++i)
5310  if ( !u->GetDestinations().empty() ) {
5311  if ( std::find( u->GetDestinations().begin(), u->GetDestinations().end(),
5312  targ->activeStarSystem->getFileName() ) != u->GetDestinations().end() ) {
5313  Target( u );
5314  ActivateJumpDrive( 0 );
5315  found = true;
5316  }
5317  }
5318  if ( !found && !_Universe->isPlayerStarship( this ) )
5320  } else {
5321  if (SERVER && computer.target.GetUnit() != NULL)
5322  VSServer->BroadcastTarget( GetSerial(), oldtarg, 0, this->getStarSystem()->GetZone() );
5323  computer.target.SetUnit( NULL );
5324  }
5325  }
5326  } else {
5327  if (SERVER && computer.target.GetUnit() != NULL)
5328  VSServer->BroadcastTarget( GetSerial(), oldtarg, 0, this->getStarSystem()->GetZone() );
5329  computer.target.SetUnit( NULL );
5330  }
5331 }
bool Unit::TargetLocked ( ) const
inline

Definition at line 1172 of file unit_generic.h.

References computer, Unit::Computer::RADARLIM::locked, and Unit::Computer::radar.

Referenced by FireKeyboard::Execute(), and Radar::Track::HasWeaponLock().

1173  {
1174  return computer.radar.locked;
1175  }
void Unit::TargetTurret ( Unit targ)

Definition at line 5246 of file unit_generic.cpp.

References Target(), and TargetTurret().

Referenced by CommunicatingAI::AdjustRelationTo(), AllUnitsCloseAndEngage(), TurretBin::AssignTargets(), FireKeyboard::Execute(), Mount::PhysicsAlignedFire(), Orders::AggressiveAI::ProcessCurrentFgDirective(), TargetTurret(), and Missile::UpdatePhysics2().

5247 {
5248  if ( !SubUnits.empty() ) {
5249  Unit *su;
5250  bool inrange = (targ != NULL) ? InRange( targ ) : true;
5251  if (inrange) {
5252  for (un_iter iter = getSubUnits(); (su = *iter); ++iter) {
5253  su->Target( targ );
5254  su->TargetTurret( targ );
5255  }
5256  }
5257  }
5258 }
void Unit::Threaten ( Unit targ,
float  danger 
)

Definition at line 1798 of file unit_generic.cpp.

References owner, and PARANOIA.

Referenced by GameCockpit::Draw(), Orders::FireAt::ShouldFire(), and GameUnit< UnitType >::TransferUnitToSystem().

1799 {
1800  if (!targ) {
1801  computer.threatlevel = danger;
1802  computer.threat.SetUnit( NULL );
1803  } else if (targ->owner != this && this->owner != targ && danger > PARANOIA && danger > computer.threatlevel) {
1804  computer.threat.SetUnit( targ );
1805  computer.threatlevel = danger;
1806  }
1807 }
void Unit::Thrust ( const Vector amt,
bool  afterburn = false 
)
virtual
void Unit::ToggleWeapon ( bool  Missile,
bool  forward = true 
)
Vector Unit::ToLocalCoordinates ( const Vector v) const

Definition at line 4048 of file unit_generic.cpp.

References MM, and Vector.

Referenced by VDU::Draw(), GameCockpit::Draw(), Orders::MoveToParent::Execute(), Orders::MatchAngularVelocity::Execute(), Orders::ChangeHeading::Execute(), LocalCoordinates(), and TargFront().

4049 {
4050  //Matrix m;
4051  //062201: not a cumulative transformation...in prev unit space curr_physical_state.to_matrix(m);
4052  return Vector( v.i*MM( 0, 0 )+v.j*MM( 1, 0 )+v.k*MM( 2, 0 ),
4053  v.i*MM( 0, 1 )+v.j*MM( 1, 1 )+v.k*MM( 2, 1 ),
4054  v.i*MM( 0, 2 )+v.j*MM( 1, 2 )+v.k*MM( 2, 2 ) );
4055 }
Vector Unit::ToWorldCoordinates ( const Vector v) const

Definition at line 4059 of file unit_generic.cpp.

References TransformNormal().

Referenced by Orders::FireAt::ChangeLocalDirection().

4060 {
4062 }
float Unit::TrackingGuns ( bool missileLock)

Definition at line 1615 of file unit_generic.cpp.

References Mount::ACTIVE, weapon_info::AUTOTRACKING, and size.

1616 {
1617  float trackingcone = 0;
1618  missilelock = false;
1619  for (int i = 0; i < GetNumMounts(); ++i) {
1620  if ( mounts[i].status == Mount::ACTIVE && (mounts[i].size&weapon_info::AUTOTRACKING) )
1621  trackingcone = computer.radar.trackingcone;
1622  if (mounts[i].status == Mount::ACTIVE && mounts[i].type->LockTime > 0 && mounts[i].time_to_lock <= 0)
1623  missilelock = true;
1624  }
1625  return trackingcone;
1626 }
bool Unit::TransferUnitToSystem ( StarSystem NewSystem)
virtual

Definition at line 8789 of file unit_generic.cpp.

References _Universe, Cockpit::activeStarSystem, StarSystem::AddUnit(), StarSystem::getFileName(), Universe::isPlayerStarship(), Cockpit::visitSystem(), and VSFileSystem::vs_fprintf().

Referenced by StarSystem::ProcessPendingJumps(), and GameUnit< UnitType >::TransferUnitToSystem().

8790 {
8791  if ( getStarSystem()->RemoveUnit( this ) ) {
8792  this->RemoveFromSystem();
8793  this->Target( NULL );
8794  Current->AddUnit( this );
8795 
8796  Cockpit *an_active_cockpit = _Universe->isPlayerStarship( this );
8797  if (an_active_cockpit != NULL) {
8798  an_active_cockpit->activeStarSystem = Current;
8799  an_active_cockpit->visitSystem( Current->getFileName() );
8800  }
8801  activeStarSystem = Current;
8802  return true;
8803  } else {
8804  VSFileSystem::vs_fprintf( stderr, "Fatal Error: cannot remove starship from critical system" );
8805  }
8806  return false;
8807 }
bool Unit::TransferUnitToSystem ( unsigned int  whichJumpQueue,
class StarSystem *&  previouslyActiveStarSystem,
bool  DoSightAndSound 
)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 131 of file unit_generic.cpp.

134 {
135  return false;
136 }
void Unit::TurretFAW ( )

Definition at line 7907 of file unit_generic.cpp.

References CheckAccessory(), EnqueueAIFirst(), and TurretFAW().

Referenced by FireKeyboard::Execute(), Mount::PhysicsAlignedFire(), Orders::AggressiveAI::ProcessCurrentFgDirective(), and TurretFAW().

7908 {
7909  turretstatus = 3;
7910  Unit *un;
7911  for (un_iter iter = getSubUnits(); (un = *iter); ++iter) {
7912  if ( !CheckAccessory( un ) ) {
7913  un->EnqueueAIFirst( new Orders::FireAt( 15.0f ) );
7914  un->EnqueueAIFirst( new Orders::FaceTarget( false, 3 ) );
7915  }
7916  un->TurretFAW();
7917  }
7918 }
bool Unit::UnDock ( Unit unitToDockWith)

Definition at line 6006 of file unit_generic.cpp.

References _Universe, Universe::AccessCockpit(), UniverseUtil::asin(), Universe::CurrentCockpit(), UnitImages< BOGUS >::dockedunits, faction, FreeDockingPort(), VegaConfig::getVariable(), Universe::netLocked(), Network, Cockpit::OnDockEnd(), UnitUtil::owner(), XMLSupport::parse_bool(), XMLSupport::parse_float(), PI, pImage, q, RealPosition(), Rotate(), serial, SERVER, turretcontrol, NetClient::undockRequest(), Vector, Velocity, vs_config, VSFileSystem::vs_dprintf(), and Universe::whichPlayerStarship().

Referenced by buyShip(), BaseInterface::Room::Launch::Click(), BaseInterface::Room::Eject::Click(), Orders::DockingOps::PerformDockingOperations(), and UnDockNow().

6007 {
6008  unsigned int i = 0;
6009  if (this->name == "return_to_cockpit") {
6010  if (this->faction == utdw->faction)
6011  this->owner = utdw;
6012  else
6013  this->owner = NULL;
6014  }
6015  VSFileSystem::vs_dprintf(3,"Asking to undock\n");
6016  if ( Network != NULL && !SERVER && !_Universe->netLocked() ) {
6017  cerr<<"Sending an undock notification"<<endl;
6018  int playernum = _Universe->whichPlayerStarship( this );
6019  if (playernum >= 0)
6020  Network[playernum].undockRequest( utdw->serial );
6021  }
6022  for (i = 0; i < utdw->pImage->dockedunits.size(); ++i)
6023  if (utdw->pImage->dockedunits[i]->uc.GetUnit() == this) {
6024  utdw->FreeDockingPort( i );
6025  i--;
6026  SetVisible( true );
6027  docked &= ( ~(DOCKED_INSIDE|DOCKED) );
6028  pImage->DockedTo.SetUnit( NULL );
6029  Velocity = utdw->Velocity;
6030  static float launch_speed = XMLSupport::parse_float( vs_config->getVariable( "physics", "launch_speed", "-1" ) );
6031  static bool auto_turn_towards =
6032  XMLSupport::parse_bool( vs_config->getVariable( "physics", "undock_turn_away", "true" ) );
6033  if (Network || SERVER) {
6034  auto_turn_towards = false;
6035  launch_speed = -1;
6036  }
6037  if (launch_speed > 0)
6038  computer.set_speed = launch_speed;
6039  if (auto_turn_towards) {
6040  for (int i = 0; i < 3; ++i) {
6041  Vector methem( RealPosition( this )-RealPosition( utdw ).Cast() );
6042  methem.Normalize();
6043  Vector p, q, r;
6044  GetOrientation( p, q, r );
6045  p = methem.Cross( r );
6046  float theta = p.Magnitude();
6047  if (theta*theta > .00001) {
6048  p *= (asin( theta )/theta);
6049  Rotate( p );
6050  GetOrientation( p, q, r );
6051  }
6052  if (r.Dot( methem ) < 0)
6053  Rotate( p*(PI/theta) );
6054  }
6055  }
6056  if (name == "return_to_cockpit" || this->name == "return_to_cockpit") {
6057  while ( turretcontrol.size() <= _Universe->CurrentCockpit() )
6058  turretcontrol.push_back( 0 );
6060  }
6061  // Send notification that a ship has undocked from a station
6062  _Universe->AccessCockpit()->OnDockEnd(utdw, this);
6063  return true;
6064  }
6065  return false;
6066 }
void Unit::UnFire ( )

Definition at line 5388 of file unit_generic.cpp.

References _Universe, Mount::ACTIVE, NetServer::BroadcastUnfire(), Network, SERVER, UnFire(), Mount::UNFIRED, NetClient::unfireRequest(), VSServer, and Universe::whichPlayerStarship().

Referenced by DisableTurretAI(), Orders::TurretAI::Execute(), FireKeyboard::Execute(), Takeoff(), TakeoffEveryZig(), and UnFire().

5389 {
5390  if (this->GetNumMounts() == 0) {
5391  Unit *tur = NULL;
5392  for (un_iter i = this->getSubUnits(); (tur = *i) != NULL; ++i)
5393  tur->UnFire();
5394  } else {
5395  int playernum = _Universe->whichPlayerStarship( this );
5396  vector< int >unFireRequests;
5397  for (int i = 0; i < GetNumMounts(); ++i) {
5398  if (mounts[i].status != Mount::ACTIVE)
5399  continue;
5400  if ( ( SERVER || (Network && playernum >= 0) ) && mounts[i].processed != Mount::UNFIRED )
5401  unFireRequests.push_back( i );
5402  mounts[i].UnFire(); //turns off beams;
5403  }
5404  if ( !unFireRequests.empty() ) {
5405  if (SERVER)
5406  VSServer->BroadcastUnfire( this->serial, unFireRequests, this->getStarSystem()->GetZone() );
5407  else
5408  Network[playernum].unfireRequest( this->serial, unFireRequests );
5409  }
5410  }
5411 }
unsigned Unit::unitRole ( ) const
inline
void Unit::unitRole ( unsigned char  c)

Definition at line 108 of file unit_generic.cpp.

References c.

109 {
110  unit_role = c;
111 }
void Unit::UnRef ( )
inline

Definition at line 35 of file unit.h.

References killed, ucref, and zapped.

Referenced by UnitContainer::SetUnit(), and UnitContainer::~UnitContainer().

36  {
37  if (zapped == true)
38  printf( "segfault" );
39  ucref -= 1;
40  if (ucref == 0 && killed)
41  zapped = true;
42  }
void Unit::UnRef ( )
bool Unit::UpAndDownGrade ( const Unit up,
const Unit templ,
int  mountoffset,
int  subunitoffset,
bool  touchme,
bool  downgrade,
int  additive,
bool  forcetransaction,
double &  percentage,
const Unit downgrade_min,
bool  force_change_on_nothing,
bool  gen_downgrade_list 
)

Definition at line 6923 of file unit_generic.cpp.

References _Universe, a, accelStarHandler, Universe::activeStarSystem(), AddToDowngradeMap(), AddUp(), Unit::Limits::afterburn, afterburnenergy, afterburntype, AGreaterB(), angleStarHandler, armor, b, Armor::backleftbottom, Armor::backlefttop, Armor::backrightbottom, Armor::backrighttop, NetServer::BroadcastCargoUpgrade(), BShieldData(), c, Unit::Computer::RADARLIM::canlock, Unit::Computer::RADARLIM::capability, UnitImages< BOGUS >::cargo, NetClient::cargoRequest(), UnitImages< BOGUS >::CargoVolume, cell_has_recursive_data(), UnitImages< BOGUS >::cloakenergy, UnitImages< BOGUS >::cloakglass, cloaking, cloakmin, UnitImages< BOGUS >::cloakrate, UnitImages< BOGUS >::cockpit_damage, UnitImages< BOGUS >::CommFunctionality, UnitImages< BOGUS >::CommFunctionalityMax, computeAdderPercent(), computeDowngradePercent(), ComputeMinDowngradePercent(), computeMultPercent(), computePercent(), computer, UnitCollection::createIterator(), UnitFactory::createServerSideUnit(), d, Unit::UnitJump::damage, Unit::UnitJump::delay, Unit::UnitJump::drive, UnitImages< BOGUS >::ecm, Shield::efficiency, Unit::UnitJump::energy, UnitImages< BOGUS >::equipment_volume, faction, UnitImages< BOGUS >::fireControlFunctionality, UnitImages< BOGUS >::fireControlFunctionalityMax, float, Unit::Limits::forward, Armor::frontleftbottom, Armor::frontlefttop, Armor::frontrightbottom, Armor::frontrighttop, FShieldData(), fuel, GCCBugCheckFloat(), Universe::getNumActiveStarSystem(), GetsB(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), graphicOptions, StarSystem::gravitationalUnits(), GreaterZero(), HeatSink, UnitImages< BOGUS >::HiddenCargoVolume, hull, Unit::UnitJump::insysenergy, Unit::Computer::itts, jump, Unit::Limits::lateral, Shield::leak, UnitImages< BOGUS >::LifeSupportFunctionality, UnitImages< BOGUS >::LifeSupportFunctionalityMax, limits, Unit::Computer::RADARLIM::lockcone, LShieldData(), Mass, Unit::Computer::max_combat_ab_speed, Unit::Computer::max_combat_speed, Unit::Computer::max_pitch_down, Unit::Computer::max_pitch_up, Unit::Computer::max_roll_left, Unit::Computer::max_roll_right, Unit::Computer::max_yaw_left, Unit::Computer::max_yaw_right, Unit::Computer::RADARLIM::maxcone, maxenergy, Unit::Computer::RADARLIM::maxrange, MAXVDUS, maxwarpenergy, Unit::graphic_options::MaxWarpMultiplier, Unit::graphic_options::MinWarpMultiplier, Momentofinertia, MultUp(), name, Universe::netLocked(), Network, Shield::number, XMLSupport::parse_bool(), XMLSupport::parse_float(), pImage, Unit::Limits::pitch, UnitCollection::prepend(), Unit::Computer::radar, Shield::recharge, recharge, UnitImages< BOGUS >::repair_droid, Unit::Limits::retro, Unit::Limits::roll, RShieldData(), SERVER, shield, Shield::shield2fb, Shield::shield4fbrl, Shield::shield8, UnitImages< BOGUS >::SPECDriveFunctionality, UnitImages< BOGUS >::SPECDriveFunctionalityMax, specInterdiction, speedStarHandler, STDUPGRADE, STDUPGRADE_SPECIFY_DEFAULTS, STDUPGRADECLAMP, SubtractUp(), Unit::Computer::RADARLIM::trackingcone, UpgradeBoolval(), UPGRADEOK, UnitImages< BOGUS >::UpgradeVolume, Unit::Limits::vertical, vs_config, VSServer, Universe::whichPlayerStarship(), and Unit::Limits::yaw.

6935 {
6936  percentage = 0;
6937  if (Network && !_Universe->netLocked() && touchme) {
6938  int playernum = _Universe->whichPlayerStarship( this );
6939  if (playernum >= 0) {
6940  ObjSerial buySerial = downgrade ? 0 : serial,
6941  sellSerial = downgrade ? serial : 0;
6942  Network[playernum].cargoRequest( buySerial, sellSerial,
6943  up->name, 0, mountoffset, subunitoffset );
6944  }
6945  return false;
6946  }
6947  if ( SERVER && touchme && !_Universe->netLocked() && getStarSystem() ) {
6948  //Server may not go here if it wants to send an atomic upgrade message.
6949  ObjSerial buySerial = downgrade ? 0 : serial,
6950  sellSerial = downgrade ? serial : 0;
6951  VSServer->BroadcastCargoUpgrade( serial, buySerial, sellSerial,
6952  up->name, 0, 0, 0, false, 0,
6953  mountoffset, subunitoffset, getStarSystem()->GetZone() );
6954  }
6955  static bool csv_cell_null_check = XMLSupport::parse_bool( vs_config->getVariable( "data", "empty_cell_check", "true" ) );
6956  int numave = 0;
6957  bool cancompletefully = true;
6958  bool can_be_redeemed = false;
6959  bool needs_redemption = false;
6960  if (mountoffset >= 0)
6961  cancompletefully = UpgradeMounts( up, mountoffset, touchme, downgrade, numave, templ, percentage );
6962  bool cancompletefully1 = true;
6963  if (subunitoffset >= 0)
6964  cancompletefully1 = UpgradeSubUnits( up, subunitoffset, touchme, downgrade, numave, percentage );
6965  cancompletefully = cancompletefully && cancompletefully1;
6966  adder Adder;
6967  comparer Comparer;
6968  percenter Percenter;
6969  vsUMap< int, DoubleName >tempdownmap;
6970  if (cancompletefully && cancompletefully1 && downgrade)
6971  if (percentage > 0)
6972  AddToDowngradeMap( up->name, 1, curdowngrademapoffset++, tempdownmap );
6973  float tmax_speed = up->computer.max_combat_speed;
6974  float tmax_ab_speed = up->computer.max_combat_ab_speed;
6975  float tmax_yaw_right = up->computer.max_yaw_right;
6976  float tmax_yaw_left = up->computer.max_yaw_left;
6977  float tmax_pitch_up = up->computer.max_pitch_up;
6978  float tmax_pitch_down = up->computer.max_pitch_down;
6979  float tmax_roll_right = up->computer.max_roll_right;
6980  float tmax_roll_left = up->computer.max_roll_left;
6981  float tlimits_yaw = up->limits.yaw;
6982  float tlimits_roll = up->limits.roll;
6983  float tlimits_pitch = up->limits.pitch;
6984  float tlimits_lateral = up->limits.lateral;
6985  float tlimits_vertical = up->limits.vertical;
6986  float tlimits_forward = up->limits.forward;
6987  float tlimits_retro = up->limits.retro;
6988  float tlimits_afterburn = up->limits.afterburn;
6989  if (downgrade) {
6990  Adder = &SubtractUp;
6991  Percenter = &computeDowngradePercent;
6992  Comparer = &GreaterZero;
6993  } else {
6994  if (additive == 1) {
6995  Adder = &AddUp;
6996  Percenter = &computeAdderPercent;
6997  } else if (additive == 2) {
6998  Adder = &MultUp;
6999  Percenter = &computeMultPercent;
7000  tmax_speed = XMLSupport::parse_float( speedStarHandler( XMLType( &tmax_speed ), NULL ) );
7001  tmax_ab_speed = XMLSupport::parse_float( speedStarHandler( XMLType( &tmax_ab_speed ), NULL ) );
7002  tmax_yaw_right = XMLSupport::parse_float( angleStarHandler( XMLType( &tmax_yaw_right ), NULL ) );
7003  tmax_yaw_left = XMLSupport::parse_float( angleStarHandler( XMLType( &tmax_yaw_left ), NULL ) );
7004  tmax_pitch_up = XMLSupport::parse_float( angleStarHandler( XMLType( &tmax_pitch_up ), NULL ) );
7005  tmax_pitch_down = XMLSupport::parse_float( angleStarHandler( XMLType( &tmax_pitch_down ), NULL ) );
7006  tmax_roll_right = XMLSupport::parse_float( angleStarHandler( XMLType( &tmax_roll_right ), NULL ) );
7007  tmax_roll_left = XMLSupport::parse_float( angleStarHandler( XMLType( &tmax_roll_left ), NULL ) );
7008  tlimits_yaw = XMLSupport::parse_float( angleStarHandler( XMLType( &tlimits_yaw ), NULL ) );
7009  tlimits_pitch = XMLSupport::parse_float( angleStarHandler( XMLType( &tlimits_pitch ), NULL ) );
7010  tlimits_roll = XMLSupport::parse_float( angleStarHandler( XMLType( &tlimits_roll ), NULL ) );
7011  tlimits_forward = XMLSupport::parse_float( accelStarHandler( XMLType( &tlimits_forward ), NULL ) );
7012  tlimits_retro = XMLSupport::parse_float( accelStarHandler( XMLType( &tlimits_retro ), NULL ) );
7013  tlimits_lateral = XMLSupport::parse_float( accelStarHandler( XMLType( &tlimits_lateral ), NULL ) );
7014  tlimits_vertical = XMLSupport::parse_float( accelStarHandler( XMLType( &tlimits_vertical ), NULL ) );
7015  tlimits_afterburn = XMLSupport::parse_float( accelStarHandler( XMLType( &tlimits_afterburn ), NULL ) );
7016  } else {
7017  Adder = &GetsB;
7018  Percenter = &computePercent;
7019  }
7020  Comparer = AGreaterB;
7021  }
7022  double resultdoub;
7023  int retval = 0; //"= 0" added by chuck_starchaser to shut off a warning about its possibly being used uninitialized
7024  double temppercent;
7025  static Unit *blankship = NULL;
7026  static bool initblankship = false;
7027  if (!initblankship) {
7028  blankship = this;
7029  initblankship = true;
7030  blankship = UnitFactory::createServerSideUnit( "upgrading_dummy_unit", true, FactionUtil::GetUpgradeFaction() );
7031  }
7032  //set up vars for "LookupUnitStat" to check for empty cells
7033  string upgrade_name = up->name;
7034  //Check SPEC stuff
7035  if ( !csv_cell_null_check || force_change_on_nothing
7036  || cell_has_recursive_data( upgrade_name, up->faction,
7037  "Spec_Interdiction|Warp_Min_Multiplier|Warp_Max_Multiplier" ) ) {
7038  if ( !csv_cell_null_check || force_change_on_nothing
7039  || cell_has_recursive_data( upgrade_name, up->faction, "Spec_Interdiction" ) ) {
7040  bool upneg = up->specInterdiction < 0;
7041  bool interdictionUnits = specInterdiction > 0;
7043  STDUPGRADE( specInterdiction, fabs( up->specInterdiction ), upneg ? fabs(
7044  templ->specInterdiction ) : templ->specInterdiction, 0 );
7045  if (upneg)
7047  if ( interdictionUnits != (specInterdiction > 0) ) {
7050  if (ss) {
7051  Unit *un;
7052  for (un_iter i = ss->gravitationalUnits().createIterator(); (un = *i); ++i)
7053  if (un == this) {
7054  i.remove();
7055  //NOTE: I think we can only be in here once
7056  break;
7057  }
7058  if (!interdictionUnits)
7059  //will interdict
7060  ss->gravitationalUnits().prepend( this );
7061  }
7062  }
7063  }
7064  if ( !csv_cell_null_check || force_change_on_nothing
7065  || cell_has_recursive_data( upgrade_name, up->faction, "Warp_Min_Multiplier" ) ) {
7069  1 );
7070  }
7071  if ( !csv_cell_null_check || force_change_on_nothing
7072  || cell_has_recursive_data( upgrade_name, up->faction, "Warp_Max_Multiplier" ) ) {
7076  1 );
7077  }
7078  }
7079  //Check jump and jump/SPEC stuff
7080  if ( !csv_cell_null_check || force_change_on_nothing
7081  || cell_has_recursive_data( upgrade_name, up->faction,
7082  "Warp_Capacitor|Warp_Usage_Cost" ) ) {
7083  if ( !csv_cell_null_check || force_change_on_nothing
7084  || cell_has_recursive_data( upgrade_name, up->faction, "Warp_Capacitor" ) )
7086  if ( !csv_cell_null_check || force_change_on_nothing
7087  || cell_has_recursive_data( upgrade_name, up->faction, "Warp_Usage_Cost" ) )
7089 
7090 // for when we'll need more than one jump drive upgrade (Elite Strike?)
7091  if ( !csv_cell_null_check || force_change_on_nothing
7092  || cell_has_recursive_data( upgrade_name, up->faction, "Outsystem_Jump_Cost" ) )
7093  STDUPGRADE( jump.energy, up->jump.energy, templ->jump.energy, 0 );
7094  if ( !csv_cell_null_check || force_change_on_nothing
7095  || cell_has_recursive_data( upgrade_name, up->faction, "Jump_Drive_Delay" ) )
7096  STDUPGRADE( jump.delay, up->jump.delay, templ->jump.delay, 0 );
7097 
7098  }
7099 
7100 
7101  if ( !csv_cell_null_check || force_change_on_nothing
7102  || cell_has_recursive_data( upgrade_name, up->faction, "Armor_Front_Top_Right" ) ) {
7111  }
7112  float tmp = shield.recharge;
7113  if ( !csv_cell_null_check || force_change_on_nothing
7114  || cell_has_recursive_data( upgrade_name, up->faction, "Shield_Recharge" ) )
7116  bool upgradedrecharge = (tmp != shield.recharge);
7117  if ( !csv_cell_null_check || force_change_on_nothing || cell_has_recursive_data( upgrade_name, up->faction, "Hull" ) )
7118  STDUPGRADE( hull, up->hull, templ->hull, 0 );
7119  if ( (maxhull < hull) && (hull != 0) )
7120  maxhull = hull;
7121  if ( !csv_cell_null_check || force_change_on_nothing
7122  || cell_has_recursive_data( upgrade_name, up->faction, "Reactor_Recharge" ) )
7123  STDUPGRADE( recharge, up->recharge, templ->recharge, 0 );
7124  static bool unittable = XMLSupport::parse_bool( vs_config->getVariable( "physics", "UnitTable", "false" ) );
7125  //Uncommon fields (capacities... rates... etc...)
7126  if ( !csv_cell_null_check || force_change_on_nothing
7127  || cell_has_recursive_data( upgrade_name, up->faction,
7128  "Heat_Sink_Rating|Repair_Droid|Hold_Volume|Upgrade_Storage_Volume|Equipment_Space|Hidden_Hold_Volume|ECM_Rating|Primary_Capacitor|Warp_Capacitor" ) )
7129  {
7130  if ( !csv_cell_null_check || force_change_on_nothing
7131  || cell_has_recursive_data( upgrade_name, up->faction, "Heat_Sink_Rating" ) )
7132  STDUPGRADE( HeatSink, up->HeatSink, templ->HeatSink, 0 );
7133  if ( !csv_cell_null_check || force_change_on_nothing
7134  || cell_has_recursive_data( upgrade_name, up->faction, "Repair_Droid" ) )
7136  if ( !csv_cell_null_check || force_change_on_nothing
7137  || cell_has_recursive_data( upgrade_name, up->faction, "Hold_Volume" ) )
7139  if ( !csv_cell_null_check || force_change_on_nothing
7140  || cell_has_recursive_data( upgrade_name, up->faction, "Upgrade_Storage_Volume" ) )
7142  if ( !csv_cell_null_check || force_change_on_nothing
7143  || cell_has_recursive_data( upgrade_name, up->faction, "Equipment_Space" ) )
7145  if ( !csv_cell_null_check || force_change_on_nothing
7146  || cell_has_recursive_data( upgrade_name, up->faction, "Hidden_Hold_Volume" ) )
7148  if ( !csv_cell_null_check || force_change_on_nothing
7149  || cell_has_recursive_data( upgrade_name, up->faction, "ECM_Rating" ) )
7150  STDUPGRADE( pImage->ecm, up->pImage->ecm, templ->pImage->ecm, 0 ); //ecm is unsigned --chuck_starchaser
7151  if ( !csv_cell_null_check || force_change_on_nothing
7152  || cell_has_recursive_data( upgrade_name, up->faction, "Primary_Capacitor" ) )
7153  STDUPGRADE( maxenergy, up->maxenergy, templ->maxenergy, 0 );
7154  }
7155  //Maneuvering stuff
7156  if ( !csv_cell_null_check || force_change_on_nothing
7157  || cell_has_recursive_data( upgrade_name, up->faction,
7158  "Maneuver_Yaw|Maneuver_Pitch|Maneuver_Roll|Left_Accel|Top_Accel|Retro_Accel|Forward_Accel|Afterburner_Accel|Default_Speed_Governor|Afterburner_Speed_Governor|Yaw_Governor|Pitch_Governor|Roll_Speed_Governor" ) )
7159  {
7160  if ( !csv_cell_null_check || force_change_on_nothing
7161  || cell_has_recursive_data( upgrade_name, up->faction, "Maneuver_Yaw" ) )
7162  STDUPGRADE( limits.yaw, tlimits_yaw, templ->limits.yaw, 0 );
7163  if ( !csv_cell_null_check || force_change_on_nothing
7164  || cell_has_recursive_data( upgrade_name, up->faction, "Maneuver_Pitch" ) )
7165  STDUPGRADE( limits.pitch, tlimits_pitch, templ->limits.pitch, 0 );
7166  if ( !csv_cell_null_check || force_change_on_nothing
7167  || cell_has_recursive_data( upgrade_name, up->faction, "Maneuver_Roll" ) )
7168  STDUPGRADE( limits.roll, tlimits_roll, templ->limits.roll, 0 );
7169  if ( !csv_cell_null_check || force_change_on_nothing
7170  || cell_has_recursive_data( upgrade_name, up->faction, "Left_Accel" ) )
7171  STDUPGRADE( limits.lateral, tlimits_lateral, templ->limits.lateral, 0 );
7172  if ( !csv_cell_null_check || force_change_on_nothing || cell_has_recursive_data( upgrade_name, up->faction, "Top_Accel" ) )
7173  STDUPGRADE( limits.vertical, tlimits_vertical, templ->limits.vertical, 0 );
7174  if ( !csv_cell_null_check || force_change_on_nothing
7175  || cell_has_recursive_data( upgrade_name, up->faction, "Retro_Accel" ) )
7176  STDUPGRADE( limits.retro, tlimits_retro, templ->limits.retro, 0 );
7177  if ( !csv_cell_null_check || force_change_on_nothing
7178  || cell_has_recursive_data( upgrade_name, up->faction, "Forward_Accel" ) )
7179  STDUPGRADE( limits.forward, tlimits_forward, templ->limits.forward, 0 );
7180  if ( !csv_cell_null_check || force_change_on_nothing
7181  || cell_has_recursive_data( upgrade_name, up->faction, "Afterburner_Accel" ) )
7182  STDUPGRADE( limits.afterburn, tlimits_afterburn, templ->limits.afterburn, 0 );
7183  if ( !csv_cell_null_check || force_change_on_nothing
7184  || cell_has_recursive_data( upgrade_name, up->faction, "Fuel_Capacity" ) )
7185  STDUPGRADE( fuel, up->fuel, templ->fuel, 0 );
7186  if ( !csv_cell_null_check || force_change_on_nothing
7187  || cell_has_recursive_data( upgrade_name, up->faction, "Default_Speed_Governor" ) )
7188  STDUPGRADE( computer.max_combat_speed, tmax_speed, templ->computer.max_combat_speed, 0 );
7189  if ( !csv_cell_null_check || force_change_on_nothing
7190  || cell_has_recursive_data( upgrade_name, up->faction, "Afterburner_Speed_Governor" ) )
7192  if ( !csv_cell_null_check || force_change_on_nothing
7193  || cell_has_recursive_data( upgrade_name, up->faction, "Yaw_Governor" ) ) {
7194  STDUPGRADE( computer.max_yaw_right, tmax_yaw_right, templ->computer.max_yaw_right, 0 );
7195  STDUPGRADE( computer.max_yaw_left, tmax_yaw_left, templ->computer.max_yaw_left, 0 );
7196  }
7197  if ( !csv_cell_null_check || force_change_on_nothing
7198  || cell_has_recursive_data( upgrade_name, up->faction, "Pitch_Governor" ) ) {
7199  STDUPGRADE( computer.max_pitch_down, tmax_pitch_down, templ->computer.max_pitch_down, 0 );
7200  STDUPGRADE( computer.max_pitch_up, tmax_pitch_up, templ->computer.max_pitch_up, 0 );
7201  }
7202  if ( !csv_cell_null_check || force_change_on_nothing
7203  || cell_has_recursive_data( upgrade_name, up->faction, "Roll_Speed_Governor" ) ) {
7204  STDUPGRADE( computer.max_roll_left, tmax_roll_left, templ->computer.max_roll_left, 0 );
7205  STDUPGRADE( computer.max_roll_right, tmax_roll_right, templ->computer.max_roll_right, 0 );
7206  }
7207  }
7208  //FIXME - do cell lookup later here
7209  static bool UpgradeCockpitDamage =
7210  XMLSupport::parse_bool( vs_config->getVariable( "physics", "upgrade_cockpit_damage", "false" ) );
7211  if (UpgradeCockpitDamage) {
7214  (unittable ? 0 : 1) );
7217  (unittable ? 0 : 1) );
7219  (unittable ? 0 : 1) );
7222  (unittable ? 0 : 1) );
7224  (unittable ? 0 : 1) );
7226  (unittable ? 0 : 1) );
7229  (unittable ? 0 : 1) );
7232  (unittable ? 0 : 1) );
7233  unsigned int upgrmax = (UnitImages< void >::NUMGAUGES+1+MAXVDUS)*2;
7234  for (unsigned int upgr = 0; upgr < upgrmax; upgr++)
7235  STDUPGRADE( pImage->cockpit_damage[upgr], up->pImage->cockpit_damage[upgr], templ->pImage->cockpit_damage[upgr],
7236  (unittable ? 0 : 1) );
7237  for (unsigned int upgr = 0; upgr < upgrmax; ++upgr)
7239  }
7240  bool upgradedshield = false;
7241  if ( !csv_cell_null_check || force_change_on_nothing
7242  || cell_has_recursive_data( upgrade_name, up->faction, "Shield_Front_Top_Right" ) ) {
7243  if (shield.number == up->shield.number) {
7244  float a, b, c, d;
7245  float aa, bb, cc, dd;
7246  switch (shield.number)
7247  {
7248  case 2:
7249  a = shield.shield2fb.frontmax;
7250  b = shield.shield2fb.backmax;
7251  STDUPGRADE( shield.shield2fb.frontmax, up->shield.shield2fb.frontmax, templ->shield.shield2fb.frontmax, 0 );
7252  STDUPGRADE( shield.shield2fb.backmax, up->shield.shield2fb.backmax, templ->shield.shield2fb.backmax, 0 );
7253  if (shield.shield2fb.frontmax != a) shield.shield2fb.front = shield.shield2fb.frontmax;
7254  if (shield.shield2fb.backmax != b) shield.shield2fb.back = shield.shield2fb.backmax;
7255  break;
7256  case 4:
7257  a = shield.shield4fbrl.frontmax;
7258  b = shield.shield4fbrl.backmax;
7259  c = shield.shield4fbrl.leftmax;
7260  d = shield.shield4fbrl.rightmax;
7261  STDUPGRADE( shield.shield4fbrl.frontmax, up->shield.shield4fbrl.frontmax, templ->shield.shield4fbrl.frontmax, 0 );
7262  STDUPGRADE( shield.shield4fbrl.backmax, up->shield.shield4fbrl.backmax, templ->shield.shield4fbrl.backmax, 0 );
7263  STDUPGRADE( shield.shield4fbrl.leftmax, up->shield.shield4fbrl.leftmax, templ->shield.shield4fbrl.leftmax, 0 );
7264  STDUPGRADE( shield.shield4fbrl.rightmax, up->shield.shield4fbrl.rightmax, templ->shield.shield4fbrl.rightmax, 0 );
7265  if (a != shield.shield4fbrl.frontmax) shield.shield4fbrl.front = shield.shield4fbrl.frontmax;
7266  if (b != shield.shield4fbrl.backmax) shield.shield4fbrl.back = shield.shield4fbrl.backmax;
7267  if (c != shield.shield4fbrl.leftmax) shield.shield4fbrl.left = shield.shield4fbrl.leftmax;
7268  if (d != shield.shield4fbrl.rightmax) shield.shield4fbrl.right = shield.shield4fbrl.rightmax;
7269  break;
7270  case 8:
7271  a = shield.shield8.frontrighttopmax;
7272  b = shield.shield8.backrighttopmax;
7273  c = shield.shield8.frontlefttopmax;
7274  d = shield.shield8.backlefttopmax;
7275  aa = shield.shield8.frontrightbottommax;
7276  bb = shield.shield8.backrightbottommax;
7277  cc = shield.shield8.frontleftbottommax;
7278  dd = shield.shield8.backleftbottommax;
7279  STDUPGRADE( shield.shield8.frontrighttopmax,
7280  up->shield.shield8.frontrighttopmax,
7281  templ->shield.shield8.frontrighttopmax,
7282  0 );
7283  STDUPGRADE( shield.shield8.backrighttopmax,
7284  up->shield.shield8.backrighttopmax,
7285  templ->shield.shield8.backrighttopmax,
7286  0 );
7287  STDUPGRADE( shield.shield8.frontlefttopmax,
7288  up->shield.shield8.frontlefttopmax,
7289  templ->shield.shield8.frontlefttopmax,
7290  0 );
7291  STDUPGRADE( shield.shield8.backlefttopmax,
7292  up->shield.shield8.backlefttopmax,
7293  templ->shield.shield8.backlefttopmax,
7294  0 );
7295  STDUPGRADE( shield.shield8.frontrightbottommax,
7296  up->shield.shield8.frontrightbottommax,
7297  templ->shield.shield8.frontrightbottommax,
7298  0 );
7299  STDUPGRADE( shield.shield8.backrightbottommax,
7300  up->shield.shield8.backrightbottommax,
7301  templ->shield.shield8.backrightbottommax,
7302  0 );
7303  STDUPGRADE( shield.shield8.frontleftbottommax,
7304  up->shield.shield8.frontleftbottommax,
7305  templ->shield.shield8.frontleftbottommax,
7306  0 );
7307  STDUPGRADE( shield.shield8.backleftbottommax,
7308  up->shield.shield8.backleftbottommax,
7309  templ->shield.shield8.backleftbottommax,
7310  0 );
7311  if (a != shield.shield8.frontrighttopmax) shield.shield8.frontrighttop = shield.shield8.frontrighttopmax;
7312  if (b != shield.shield8.backrighttopmax) shield.shield8.backrighttop = shield.shield8.backrighttopmax;
7313  if (c != shield.shield8.frontlefttopmax) shield.shield8.frontlefttop = shield.shield8.frontlefttopmax;
7314  if (d != shield.shield8.backlefttopmax) shield.shield8.backlefttop = shield.shield8.backlefttopmax;
7315  if (aa != shield.shield8.frontrightbottommax)
7316  shield.shield8.frontrightbottom =
7317  shield.shield8.frontrightbottommax;
7318  if (bb != shield.shield8.backrightbottommax)
7319  shield.shield8.backrightbottom =
7320  shield.shield8.backrightbottommax;
7321  if (cc != shield.shield8.frontleftbottommax)
7322  shield.shield8.frontleftbottom =
7323  shield.shield8.frontleftbottommax;
7324  if (dd != shield.shield8.backleftbottommax) shield.shield8.backleftbottom = shield.shield8.backleftbottommax;
7325  break;
7326  }
7327  if (touchme && retval == UPGRADEOK)
7328  upgradedshield = true;
7329  } else if (up->FShieldData() > 0 || up->RShieldData() > 0 || up->LShieldData() > 0 || up->BShieldData() > 0) {
7330  cancompletefully = false;
7331  }
7332  }
7333  if (upgradedshield || upgradedrecharge) {
7334  if (up->shield.efficiency) {
7336  if (templ)
7337  if (shield.efficiency > templ->shield.efficiency)
7339  }
7340  }
7341  if ( !csv_cell_null_check || force_change_on_nothing
7342  || cell_has_recursive_data( upgrade_name, up->faction, "Shield_Leak" ) ) {
7343  double myleak = 100-shield.leak;
7344  double upleak = 100-up->shield.leak;
7345  double templeak = 100-(templ != NULL ? templ->shield.leak : 0);
7346  bool ccf = cancompletefully;
7347  STDUPGRADE_SPECIFY_DEFAULTS( myleak, upleak, templeak, 0, 100, 100, false, shield.leak );
7348  if (touchme && myleak <= 100 && myleak >= 0) shield.leak = (char) 100-myleak;
7349  cancompletefully = ccf;
7350  }
7351  //DO NOT CHANGE see unit_customize.cpp
7352  static float lc = XMLSupport::parse_float( vs_config->getVariable( "physics", "lock_cone", ".8" ) );
7353  //DO NOT CHANGE! see unit.cpp:258
7354  static float tc = XMLSupport::parse_float( vs_config->getVariable( "physics", "autotracking", ".93" ) );
7355  static bool use_template_maxrange =
7356  XMLSupport::parse_bool( vs_config->getVariable( "physics", "use_upgrade_template_maxrange", "true" ) );
7357  //Radar stuff
7358  if ( !csv_cell_null_check || force_change_on_nothing
7359  || cell_has_recursive_data( upgrade_name, up->faction,
7360  "Radar_Range|Radar_Color|ITTS|Can_Lock|Max_Cone|Lock_Cone|Tracking_Cone" ) ) {
7361  if ( !csv_cell_null_check || force_change_on_nothing
7362  || cell_has_recursive_data( upgrade_name, up->faction, "Radar_Range" ) ) {
7364  up->computer.radar.maxrange,
7365  use_template_maxrange ? templ->computer.radar.maxrange : FLT_MAX,
7366  0 );
7367  }
7368  if ( !csv_cell_null_check || force_change_on_nothing
7369  || cell_has_recursive_data( upgrade_name, up->faction, "Radar_Color" ) )
7371  if ( !csv_cell_null_check || force_change_on_nothing
7372  || cell_has_recursive_data( upgrade_name, up->faction, "ITTS" ) ) {
7374  up->computer.itts,
7375  touchme,
7376  downgrade,
7377  numave,
7378  percentage,
7379  force_change_on_nothing );
7380  }
7381  if ( !csv_cell_null_check || force_change_on_nothing
7382  || cell_has_recursive_data( upgrade_name, up->faction, "Can_Lock" ) ) {
7384  up->computer.radar.canlock,
7385  touchme,
7386  downgrade,
7387  numave,
7388  percentage,
7389  force_change_on_nothing );
7390  }
7391  //Do the two reversed ones below
7392  bool ccf = cancompletefully;
7393  if ( !csv_cell_null_check || force_change_on_nothing
7394  || cell_has_recursive_data( upgrade_name, up->faction, "Max_Cone" ) ) {
7395  double myleak = 1-computer.radar.maxcone;
7396  double upleak = 1-up->computer.radar.maxcone;
7397  double templeak = 1-(templ != NULL ? templ->computer.radar.maxcone : -1);
7398  STDUPGRADE_SPECIFY_DEFAULTS( myleak, upleak, templeak, 0, 0, 0, false, computer.radar.maxcone );
7399  if (touchme) computer.radar.maxcone = 1-myleak;
7400  }
7401  if (up->computer.radar.lockcone != lc) {
7402  double myleak = 1-computer.radar.lockcone;
7403  double upleak = 1-up->computer.radar.lockcone;
7404  double templeak = 1-(templ != NULL ? templ->computer.radar.lockcone : -1);
7405  if (templeak == 1-lc)
7406  templeak = 2;
7407  if ( !csv_cell_null_check || force_change_on_nothing
7408  || cell_has_recursive_data( upgrade_name, up->faction, "Lock_Cone" ) ) {
7409  STDUPGRADE_SPECIFY_DEFAULTS( myleak, upleak, templeak, 0, 0, 0, false, computer.radar.lockcone );
7410  if (touchme) computer.radar.lockcone = 1-myleak;
7411  }
7412  }
7413  if (up->computer.radar.trackingcone != tc) {
7414  double myleak = 1-computer.radar.trackingcone;
7415  double upleak = 1-up->computer.radar.trackingcone;
7416  double templeak = 1-(templ != NULL ? templ->computer.radar.trackingcone : -1);
7417  if (templeak == 1-tc)
7418  templeak = 2;
7419  if ( !csv_cell_null_check || force_change_on_nothing
7420  || cell_has_recursive_data( upgrade_name, up->faction, "Tracking_Cone" ) ) {
7421  STDUPGRADE_SPECIFY_DEFAULTS( myleak, upleak, templeak, 0, 0, 0, false, computer.radar.trackingcone );
7422  if (touchme) computer.radar.trackingcone = 1-myleak;
7423  }
7424  }
7425  cancompletefully = ccf;
7426  }
7427  //NO CLUE FOR BELOW
7428  if (downgrade) {
7429  if (jump.drive >= -1 && up->jump.drive >= -1) {
7430  if (touchme) jump.drive = -2;
7431  ++numave;
7432  percentage += .5*( (float) (100-jump.damage) )/(101-up->jump.damage);
7433  if (gen_downgrade_list)
7434  AddToDowngradeMap( up->name, up->jump.drive, ( (char*) &this->jump.drive )-( (char*) this ), tempdownmap );
7435  }
7436  if (cloaking != -1 && up->cloaking != -1) {
7437  if (touchme) cloaking = -1;
7438  ++numave;
7439  ++percentage;
7440  if (gen_downgrade_list)
7441  AddToDowngradeMap( up->name, up->cloaking, ( (char*) &this->cloaking )-( (char*) this ), tempdownmap );
7442  }
7443  //NOTE: Afterburner type 2 (jmp)
7444  //NOTE: Afterburner type 1 (gas)
7445  //NOTE: Afterburner type 0 (pwr)
7446  if (afterburnenergy < 32767 && afterburnenergy <= up->afterburnenergy && up->afterburnenergy != 32767
7447  && up->afterburnenergy != 0) {
7448  if (touchme) afterburnenergy = 32767, afterburntype = 0;
7449  ++numave;
7450  ++percentage;
7451  if (gen_downgrade_list) {
7452  AddToDowngradeMap( up->name,
7453  up->afterburntype,
7454  ( (char*) &this->afterburnenergy )-( (char*) this ),
7455  tempdownmap );
7456  }
7457  }
7458  } else {
7459  //we are upgrading!
7460  if (touchme) {
7461  for (unsigned int i = 0; i < up->pImage->cargo.size(); ++i)
7462  if ( CanAddCargo( up->pImage->cargo[i] ) )
7463  AddCargo( up->pImage->cargo[i], false );
7464  }
7465  if ( (cloaking == -1 && up->cloaking != -1) || force_change_on_nothing ) {
7466  if (touchme) {
7467  cloaking = up->cloaking;
7468  cloakmin = up->cloakmin;
7469  pImage->cloakrate = up->pImage->cloakrate;
7472  }
7473  ++numave;
7474  } else if (cloaking != -1 && up->cloaking != -1) {
7475  cancompletefully = false;
7476  }
7477  //NOTE: Afterburner type 2 (jmp)
7478  //NOTE: Afterburner type 1 (gas)
7479  //NOTE: Afterburner type 0 (pwr)
7480  if ( ( ( afterburnenergy > up->afterburnenergy
7481  || (afterburntype != up->afterburntype && up->afterburnenergy != 32767) )
7482  && up->afterburnenergy > 0 ) || force_change_on_nothing ) {
7483  ++numave;
7484  if (touchme) afterburnenergy = up->afterburnenergy, afterburntype = up->afterburntype;
7485  } else if (afterburnenergy <= up->afterburnenergy && afterburnenergy >= 0 && up->afterburnenergy > 0
7486  && up->afterburnenergy < 32767) {
7487  cancompletefully = false;
7488  }
7489  if ( (jump.drive == -2 && up->jump.drive >= -1) || force_change_on_nothing ) {
7490  if (touchme) {
7491  jump.drive = up->jump.drive;
7492  jump.damage = 0;
7493  }
7494  ++numave;
7495  } else if (jump.drive >= -1 && up->jump.drive >= -1) {
7496  cancompletefully = false;
7497  }
7498  }
7499  if (needs_redemption)
7500  if (!can_be_redeemed)
7501  cancompletefully = false;
7502  if (0 == numave) //Doesn't upgrade anything -- JS_NUDGE -- may want to revisit this later
7503  percentage = 1.0;
7504  if (numave)
7505  percentage = percentage/numave;
7506  if (0 && touchme && up->Mass && numave) {
7507  float multiplyer = ( (downgrade) ? -1 : 1 );
7508  Mass += multiplyer*percentage*up->Mass;
7509  if ( Mass < (templ ? templ->Mass : .000000001) )
7510  Mass = (templ ? templ->Mass : .000000001);
7511  Momentofinertia += multiplyer*percentage*up->Momentofinertia;
7512  if ( Momentofinertia < (templ ? templ->Momentofinertia : 0.00000001) )
7513  Momentofinertia = (templ ? templ->Momentofinertia : 0.00000001);
7514  }
7515  if (gen_downgrade_list) {
7516  float MyPercentMin = ComputeMinDowngradePercent();
7517  if (downgrade && percentage > MyPercentMin)
7518  for (vsUMap< int, DoubleName >::iterator i = tempdownmap.begin(); i != tempdownmap.end(); ++i)
7519  downgrademap[(*i).first] = (*i).second;
7520  }
7521  return cancompletefully;
7522 }
Vector Unit::UpCoordinateLevel ( const Vector v) const

Definition at line 4028 of file unit_generic.cpp.

References MM, and Vector.

Referenced by Orders::MoveToParent::Execute(), Orders::MatchAngularVelocity::Execute(), Orders::ChangeHeading::Execute(), and Orders::AggressiveAI::ExecuteNoEnemies().

4029 {
4030  Matrix m;
4032  return Vector( v.i*MM( 0, 0 )+v.j*MM( 1, 0 )+v.k*MM( 2, 0 ),
4033  v.i*MM( 0, 1 )+v.j*MM( 1, 1 )+v.k*MM( 2, 1 ),
4034  v.i*MM( 0, 2 )+v.j*MM( 1, 2 )+v.k*MM( 2, 2 ) );
4035 }
void Unit::UpdateCollideQueue ( StarSystem ss,
CollideMap::iterator  hint[NUM_COLLIDE_MAPS] 
)

Definition at line 79 of file unit_collide.cpp.

References activeStarSystem, StarSystem::collidemap, CollideArray::insert(), is_null(), isSubUnit(), location, and NUM_COLLIDE_MAPS.

Referenced by Mission::call_unit_launch(), and Mount::PhysicsAlignedFire().

80 {
81  if (activeStarSystem == NULL)
82  activeStarSystem = ss;
83 
84  else
85  assert( activeStarSystem == ss );
86  for (unsigned int locind = 0; locind < NUM_COLLIDE_MAPS; ++locind)
87  if ( is_null( location[locind] ) ) {
88  assert( !isSubUnit() );
89  if ( !isSubUnit() )
90  location[locind] = ss->collidemap[locind]->insert( Collidable( this ), hint[locind] );
91  }
92 }
virtual void Unit::UpdateHudMatrix ( int  whichcam)
inlinevirtual
void Unit::UpdatePhysics ( const Transformation trans,
const Matrix transmat,
const Vector CumulativeVelocity,
bool  ResolveLast,
UnitCollection uc,
Unit superunit 
)

Definition at line 2200 of file unit_generic.cpp.

References _Universe, Mount::ACTIVE, Universe::activeStarSystem(), AUDAdjustSound(), AUDCreateSoundWAV(), AUDIsPlaying(), AUDStartPlaying(), AUDStopPlaying(), weapon_info::AUTOTRACKING, weapon_info::BEAM, CloseEnoughToAutotrack(), Transformation::Compose(), weapon_info::EnergyRate, Mount::FIRED, StarSystem::getCurrentSimFrame(), StarSystem::getFileName(), Cockpit::GetNavSelectedSystem(), UnitUtil::getSignificantDistance(), FactionUtil::GetUpgradeFaction(), VegaConfig::getVariable(), howFarToJump(), Mount::INACTIVE, int, InvTransform(), is_null(), Universe::isPlayerStarship(), isUnit(), StarSystem::JumpTo(), location, m1, UniverseUtil::musicMute(), NearestSystem(), Network, NUM_COLLIDE_MAPS, UnitUtil::owner(), XMLSupport::parse_bool(), XMLSupport::parse_float(), PLANETPTR, Position(), SERVER, SetShieldZero(), SIM_QUEUE_SIZE, SIMULATION_ATOM, size, weapon_info::SPECIALMISSILE, t1(), Target(), Transformation::to_matrix(), weapon_info::type, Mount::UNFIRED, UNIT_BOLT, UpdatePhysics(), Vector, and vs_config.

Referenced by UpdatePhysics(), UpdateSubunitPhysics(), and StarSystem::UpdateUnitPhysics().

2206 {
2207  static float VELOCITY_MAX = XMLSupport::parse_float( vs_config->getVariable( "physics", "velocity_max", "10000" ) );
2208  static float SPACE_DRAG = XMLSupport::parse_float( vs_config->getVariable( "physics", "unit_space_drag", "0.000000" ) );
2209  static float EXTRA_CARGO_SPACE_DRAG =
2210  XMLSupport::parse_float( vs_config->getVariable( "physics", "extra_space_drag_for_cargo", "0.005" ) );
2211 
2212  //Save information about when this happened
2213  unsigned int cur_sim_frame = _Universe->activeStarSystem()->getCurrentSimFrame();
2214  //Well, wasn't skipped actually, but...
2215  this->last_processed_sqs = cur_sim_frame;
2216  this->cur_sim_queue_slot = (cur_sim_frame+this->sim_atom_multiplier)%SIM_QUEUE_SIZE;
2217  if (maxhull < 0) {
2218  this->Explode( true, 0 );
2219  }
2220  Transformation old_physical_state = curr_physical_state;
2221  if (docked&DOCKING_UNITS)
2223  Repair();
2224  if (fuel < 0)
2225  fuel = 0;
2226  if (cloaking >= cloakmin) {
2227  static bool warp_energy_for_cloak =
2228  XMLSupport::parse_bool( vs_config->getVariable( "physics", "warp_energy_for_cloak", "true" ) );
2229  if ( pImage->cloakenergy*SIMULATION_ATOM > (warp_energy_for_cloak ? warpenergy : energy) ) {
2230  Cloak( false ); //Decloak
2231  } else {
2232  SetShieldZero( this );
2233  if (pImage->cloakrate > 0 || cloaking == cloakmin) {
2234  if (warp_energy_for_cloak)
2236  else
2237  energy -= (SIMULATION_ATOM*pImage->cloakenergy);
2238  }
2239  if (cloaking > cloakmin) {
2241  //short fix
2242  if ( (cloaking == (2147483647)
2243  && pImage->cloakrate > 0) || (cloaking == cloakmin+1 && pImage->cloakrate < 0) )
2245  //short fix
2247  if (cloaking <= cloakmin && pImage->cloakrate > 0)
2248  cloaking = cloakmin;
2249  if (cloaking < 0 && pImage->cloakrate < 0) {
2250  cloaking = -2147483647-1;
2251  }
2252  }
2253  }
2254  }
2255  //Only on server or non-networking
2256  //Do it everywhere -- "interpolation" for client-side.
2257  //if( SERVER || Network==NULL)
2258  RegenShields();
2259  if (lastframe) {
2260  if ( !( docked&(DOCKED|DOCKED_INSIDE) ) )
2261  //the AIscript should take care
2263 #ifdef FIX_TERRAIN
2264  if (planet) {
2265  if (!planet->dirty)
2266  SetPlanetOrbitData( NULL );
2267  else
2268  planet->pps = planet->cps;
2269  }
2270 #endif
2271  }
2272  if (resolveforces) {
2273  //clamp velocity
2274  net_accel = ResolveForces( trans, transmat );
2275  if (Velocity.i > VELOCITY_MAX)
2276  Velocity.i = VELOCITY_MAX;
2277 
2278  else if (Velocity.i < -VELOCITY_MAX)
2279  Velocity.i = -VELOCITY_MAX;
2280  if (Velocity.j > VELOCITY_MAX)
2281  Velocity.j = VELOCITY_MAX;
2282 
2283  else if (Velocity.j < -VELOCITY_MAX)
2284  Velocity.j = -VELOCITY_MAX;
2285  if (Velocity.k > VELOCITY_MAX)
2286  Velocity.k = VELOCITY_MAX;
2287 
2288  else if (Velocity.k < -VELOCITY_MAX)
2289  Velocity.k = -VELOCITY_MAX;
2290  }
2291  float difficulty;
2292  Cockpit *player_cockpit = GetVelocityDifficultyMult( difficulty );
2293 
2294  this->UpdatePhysics2( trans, old_physical_state, net_accel, difficulty, transmat, cum_vel, lastframe, uc );
2295  if (EXTRA_CARGO_SPACE_DRAG > 0) {
2296  int upgfac = FactionUtil::GetUpgradeFaction();
2297  if ( (this->faction == upgfac) || (this->name == "eject") || (this->name == "Pilot") )
2298  Velocity = Velocity*(1-EXTRA_CARGO_SPACE_DRAG);
2299  }
2300  if (SPACE_DRAG > 0)
2301  Velocity = Velocity*(1-SPACE_DRAG);
2302  float dist_sqr_to_target = FLT_MAX;
2303  Unit *target = Unit::Target();
2304  bool increase_locking = false;
2305  if (target && cloaking < 0 /*-1 or -32768*/) {
2306  if (target->isUnit() != PLANETPTR) {
2307  Vector TargetPos( InvTransform( cumulative_transformation_matrix, ( target->Position() ) ).Cast() );
2308  dist_sqr_to_target = TargetPos.MagnitudeSquared();
2309  TargetPos.Normalize();
2310  if (TargetPos.k > computer.radar.lockcone)
2311  increase_locking = true;
2312  }
2313  /* Update the velocity reference to the nearer significant unit/planet. */
2315  Unit *nextVelRef = activeStarSystem->nextSignificantUnit();
2316  if (nextVelRef) {
2317  if ( computer.velocity_ref.GetUnit() ) {
2319  double next_dist = UnitUtil::getSignificantDistance( this, nextVelRef );
2320  if (next_dist < dist)
2321  computer.velocity_ref = nextVelRef;
2322  } else {
2323  computer.velocity_ref = nextVelRef;
2324  }
2325  }
2326  }
2327  }
2328  static string LockingSoundName = vs_config->getVariable( "unitaudio", "locking", "locking.wav" );
2329  //enables spiffy wc2 torpedo music, default to normal though
2330  static string LockingSoundTorpName = vs_config->getVariable( "unitaudio", "locking_torp", "locking.wav" );
2331  static int LockingSound = AUDCreateSoundWAV( LockingSoundName, true );
2332  static int LockingSoundTorp = AUDCreateSoundWAV( LockingSoundTorpName, true );
2333 
2334  bool locking = false;
2335  bool touched = false;
2336  for (int i = 0; (int) i < GetNumMounts(); ++i) {
2337  if ( ( (SERVER
2338  && mounts[i].status
2339  == Mount::INACTIVE) || mounts[i].status == Mount::ACTIVE ) && cloaking < 0 && mounts[i].ammo != 0 ) {
2340  if (player_cockpit)
2341  touched = true;
2342  if ( increase_locking && (dist_sqr_to_target < mounts[i].type->Range*mounts[i].type->Range) ) {
2343  mounts[i].time_to_lock -= SIMULATION_ATOM;
2344  static bool ai_lock_cheat = XMLSupport::parse_bool( vs_config->getVariable( "physics", "ai_lock_cheat", "true" ) );
2345  if (!player_cockpit) {
2346  if (ai_lock_cheat)
2347  mounts[i].time_to_lock = -1;
2348  } else {
2349  int LockingPlay = LockingSound;
2350 
2351  //enables spiffy wc2 torpedo music, default to normal though
2352  static bool LockTrumpsMusic =
2353  XMLSupport::parse_bool( vs_config->getVariable( "unitaudio", "locking_trumps_music", "false" ) );
2354  //enables spiffy wc2 torpedo music, default to normal though
2355  static bool TorpLockTrumpsMusic =
2356  XMLSupport::parse_bool( vs_config->getVariable( "unitaudio", "locking_torp_trumps_music", "false" ) );
2357  if (mounts[i].type->LockTime > 0) {
2358  static string LockedSoundName = vs_config->getVariable( "unitaudio", "locked", "locked.wav" );
2359  static int LockedSound = AUDCreateSoundWAV( LockedSoundName, false );
2360  if (mounts[i].type->size == weapon_info::SPECIALMISSILE)
2361  LockingPlay = LockingSoundTorp;
2362 
2363  else
2364  LockingPlay = LockingSound;
2365  if (mounts[i].time_to_lock > -SIMULATION_ATOM && mounts[i].time_to_lock <= 0) {
2366  if ( !AUDIsPlaying( LockedSound ) ) {
2367  UniverseUtil::musicMute( false );
2368  AUDStartPlaying( LockedSound );
2369  AUDStopPlaying( LockingSound );
2370  AUDStopPlaying( LockingSoundTorp );
2371  }
2372  AUDAdjustSound( LockedSound, Position(), GetVelocity() );
2373  } else if (mounts[i].time_to_lock > 0) {
2374  locking = true;
2375  if ( !AUDIsPlaying( LockingPlay ) ) {
2376  if (LockingPlay == LockingSoundTorp)
2377  UniverseUtil::musicMute( TorpLockTrumpsMusic );
2378 
2379  else
2380  UniverseUtil::musicMute( LockTrumpsMusic );
2381  AUDStartPlaying( LockingSound );
2382  }
2383  AUDAdjustSound( LockingSound, Position(), GetVelocity() );
2384  }
2385  }
2386  }
2387  } else if (mounts[i].ammo != 0) {
2388  mounts[i].time_to_lock = mounts[i].type->LockTime;
2389  }
2390  } else if (mounts[i].ammo != 0) {
2391  mounts[i].time_to_lock = mounts[i].type->LockTime;
2392  }
2393  if (mounts[i].type->type == weapon_info::BEAM) {
2394  if (mounts[i].ref.gun) {
2395  static bool must_lock_to_autotrack =
2396  XMLSupport::parse_bool( vs_config->getVariable( "physics", "must_lock_to_autotrack", "true" ) );
2397  Unit *autotarg =
2398  ( (mounts[i].size&weapon_info::AUTOTRACKING)
2399  && (mounts[i].time_to_lock <= 0)
2400  && (player_cockpit == NULL || TargetLocked() || !must_lock_to_autotrack)
2401  && (computer.radar.trackingactive) ) ? target : NULL;
2402  float trackingcone = computer.radar.trackingcone;
2403  if ( CloseEnoughToAutotrack( this, target, trackingcone ) ) {
2404  if (autotarg)
2405  if (computer.radar.trackingcone < trackingcone)
2406  trackingcone = computer.radar.trackingcone;
2407  autotarg = target;
2408  }
2409  mounts[i].ref.gun->UpdatePhysics( cumulative_transformation,
2411  autotarg,
2412  trackingcone,
2413  target,
2414  (HeatSink ? HeatSink : 1.0f)*mounts[i].functionality,
2415  this,
2416  superunit );
2417  }
2418  } else {
2419  mounts[i].ref.refire += SIMULATION_ATOM*(HeatSink ? HeatSink : 1.0f)*mounts[i].functionality;
2420  }
2421  if (mounts[i].processed == Mount::FIRED) {
2423  Matrix m1;
2424  t1 = prev_physical_state; //a hack that will not work on turrets
2425  t1.Compose( trans, transmat );
2426  t1.to_matrix( m1 );
2427  int autotrack = 0;
2428  static bool must_lock_to_autotrack =
2429  XMLSupport::parse_bool( vs_config->getVariable( "physics", "must_lock_to_autotrack", "true" ) );
2430  if ( ( 0 != (mounts[i].size&weapon_info::AUTOTRACKING) )
2432  && ( (Network != NULL && !SERVER)
2433  || player_cockpit == NULL
2434  || TargetLocked()
2435  || !must_lock_to_autotrack ) )
2436  autotrack = computer.itts ? 2 : 1;
2437  float trackingcone = computer.radar.trackingcone;
2438  if ( CloseEnoughToAutotrack( this, target, trackingcone ) ) {
2439  if (autotrack)
2440  if (trackingcone > computer.radar.trackingcone)
2441  trackingcone = computer.radar.trackingcone;
2442  autotrack = 2;
2443  }
2445  for (unsigned int locind = 0; locind < Unit::NUM_COLLIDE_MAPS; ++locind)
2446  hint[locind] =
2447  ( !is_null( superunit->location[locind] ) ) ? superunit->location[locind] : _Universe->activeStarSystem()->
2448  collidemap[locind]->begin();
2449  if ( !mounts[i].PhysicsAlignedFire( this, t1, m1, cumulative_velocity,
2450  (!isSubUnit() || owner == NULL) ? this : owner, target, autotrack,
2451  trackingcone,
2452  hint ) ) {
2453  const weapon_info *typ = mounts[i].type;
2454  energy += typ->EnergyRate*(typ->type == weapon_info::BEAM ? SIMULATION_ATOM : 1);
2455  }
2456  } else if ( mounts[i].processed == Mount::UNFIRED || mounts[i].ref.refire > 2*mounts[i].type->Refire() ) {
2457  mounts[i].processed = Mount::UNFIRED;
2458  mounts[i].PhysicsAlignedUnfire();
2459  }
2460  }
2461  if (locking == false && touched == true) {
2462  if ( AUDIsPlaying( LockingSound ) ) {
2463  UniverseUtil::musicMute( false );
2464  AUDStopPlaying( LockingSound );
2465  }
2466  if ( AUDIsPlaying( LockingSoundTorp ) ) {
2467  UniverseUtil::musicMute( false );
2468  AUDStopPlaying( LockingSoundTorp );
2469  }
2470  }
2471  bool dead = true;
2472 
2476  lastframe,
2477  uc,
2478  superunit );
2479  //can a unit get to another system without jumping?.
2480  static bool warp_is_interstellar =
2481  XMLSupport::parse_bool( vs_config->getVariable( "physics", "warp_is_interstellar", "false" ) );
2482  if ( warp_is_interstellar
2483  && ( curr_physical_state.position.MagnitudeSquared() > howFarToJump()*howFarToJump() && !isSubUnit() ) ) {
2484  static bool direct = XMLSupport::parse_bool( vs_config->getVariable( "physics", "direct_interstellar_journey", "true" ) );
2485  bool jumpDirect = false;
2486  if (direct) {
2487  Cockpit *cp = _Universe->isPlayerStarship( this );
2488  if (NULL != cp) {
2489  std::string sys = cp->GetNavSelectedSystem();
2490  if ( !sys.empty() ) {
2491  jumpDirect = true;
2492  _Universe->activeStarSystem()->JumpTo( this, NULL, sys, true, true );
2493  }
2494  }
2495  }
2496  if (!jumpDirect) {
2497  _Universe->activeStarSystem()->JumpTo( this, NULL,
2499  curr_physical_state.position ), true, true );
2500  }
2501  }
2502 //Really kill the unit only in non-networking or on server side
2503  if (hull < 0) {
2504  dead &= (pImage->pExplosion == NULL);
2505  if (dead)
2506  Kill();
2507  } else
2508  if ( !isSubUnit() ) {
2509  for (unsigned int locind = 0; locind < Unit::NUM_COLLIDE_MAPS; ++locind) {
2510  if ( is_null( this->location[locind] ) )
2511  this->getStarSystem()->collidemap[locind]->insert( Collidable( this ) );
2512  else if (locind == Unit::UNIT_BOLT)
2513  //that update will propagate with the flatten
2514  this->getStarSystem()->collidemap[Unit::UNIT_BOLT]->changeKey( this->location[locind], Collidable( this ) );
2515  }
2516  }
2517 }
void Unit::UpdatePhysics2 ( const Transformation trans,
const Transformation old_physical_state,
const Vector accel,
float  difficulty,
const Matrix transmat,
const Vector CumulativeVelocity,
bool  ResolveLast,
UnitCollection uc = NULL 
)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, GameUnit< Nebula >, Missile, GameMissile, Nebula, Building, GameBuilding, GameAsteroid, and GameNebula.

Definition at line 2765 of file unit_generic.cpp.

References _Universe, Universe::isPlayerStarship(), Network, Rotate(), SERVER, SIMULATION_ATOM, and TransformNormal().

Referenced by Building::UpdatePhysics2(), Nebula::UpdatePhysics2(), and Missile::UpdatePhysics2().

2773 {
2774  Cockpit *cp = _Universe->isPlayerStarship( this );
2775  //Only in non-networking OR networking && is a player OR SERVER && not a player
2776  if ( (Network == NULL && !SERVER) || (Network != NULL && cp && !SERVER) || (SERVER) )
2779  //SERVERSIDE ONLY : If it is not a player, it is a unit controlled by server so compute changes
2780  if (SERVER) {
2781  AddVelocity( difficulty );
2782 
2784  cumulative_transformation.Compose( trans, transmat );
2786  cumulative_velocity = TransformNormal( transmat, Velocity )+cum_vel;
2787  }
2788 }
void Unit::UpdateSubunitPhysics ( const Transformation trans,
const Matrix transmat,
const Vector CumulativeVelocity,
bool  ResolveLast,
UnitCollection uc,
Unit superunit 
)
virtual

Definition at line 2519 of file unit_generic.cpp.

References _Universe, Universe::activeStarSystem(), cur_sim_queue_slot, float, StarSystem::getCurrentSimFrame(), UnitUtil::getPhysicsPriority(), last_processed_sqs, sim_atom_multiplier, SIM_QUEUE_SIZE, and SIMULATION_ATOM.

2525 {
2526  if ( !SubUnits.empty() ) {
2527  Unit *su;
2528  float backup = SIMULATION_ATOM;
2529  float basesimatom = (this->sim_atom_multiplier ? backup/(float) this->sim_atom_multiplier : backup);
2530  unsigned int cur_sim_frame = _Universe->activeStarSystem()->getCurrentSimFrame();
2531  for (un_iter iter = getSubUnits(); (su = *iter); ++iter)
2532  if (this->sim_atom_multiplier && su->sim_atom_multiplier) {
2533  //This ugly thing detects skipped frames.
2534  //This shouldn't happen during normal execution, as the interpolation will not be correct
2535  //when outside the expected range (that is, if the target queue slot is skipped).
2536  //BUT... this allows easy subunit simulation scattering by initializing cur_sim_frame
2537  //with random data.
2538  //Normal crossing
2539  if ( ( (su->last_processed_sqs < su->cur_sim_queue_slot) && (cur_sim_frame >= su->cur_sim_queue_slot) )
2540  //Full round trip
2541  || (su->last_processed_sqs == cur_sim_frame)
2542  //Incomplete round trip - but including target frame
2543  || ( (su->last_processed_sqs > cur_sim_frame)
2544  && ( (su->cur_sim_queue_slot <= cur_sim_frame) || (su->last_processed_sqs < su->cur_sim_queue_slot) ) )
2545  ) {
2546  if (do_subunit_scheduling) {
2547  int priority = UnitUtil::getPhysicsPriority( su );
2548  //Add some scattering
2549  priority = (priority+rand()%priority)/2;
2550  if (priority < 1) priority = 1;
2551  su->sim_atom_multiplier = this->sim_atom_multiplier*priority;
2554  if (su->sim_atom_multiplier < this->sim_atom_multiplier)
2556  } else {
2558  }
2559  SIMULATION_ATOM = basesimatom*(float) su->sim_atom_multiplier;
2564  lastframe,
2565  uc,
2566  superunit );
2567  }
2568  }
2569  SIMULATION_ATOM = backup;
2570  }
2571 }
void Unit::UpdateSubunitPhysics ( Unit subunit,
const Transformation trans,
const Matrix transmat,
const Vector CumulativeVelocity,
bool  ResolveLast,
UnitCollection uc,
Unit superunit 
)
virtual

Definition at line 2573 of file unit_generic.cpp.

References cloaking, int, Target(), and UpdatePhysics().

2580 {
2584  lastframe,
2585  uc,
2586  superunit );
2587  //short fix
2588  subunit->cloaking = (unsigned int) cloaking;
2589  if (hull < 0) {
2590  subunit->Target( NULL );
2591  UnFire(); //don't want to go off shooting while your body's splitting everywhere
2592  }
2593 }
bool Unit::Upgrade ( const Unit upgrador,
int  mountoffset,
int  subunitoffset,
int  additive,
bool  force,
double &  percentage,
const Unit templ = NULL,
bool  force_change_on_nothing = false,
bool  gen_downgrade_list = true 
)

Definition at line 6636 of file unit_generic.cpp.

Referenced by BaseComputer::buyUpgrade(), BaseComputer::BuyUpgradeOperation::concludeTransaction(), Enhancement::reactToCollision(), UnitUtil::RecomputeUnitUpgrades(), UnitUtil::upgrade(), GameUnit< UnitType >::Upgrade(), and Upgrade().

6645 {
6646  return UpAndDownGrade( upgrador,
6647  templ,
6648  mountoffset,
6649  subunitoffset,
6650  true,
6651  false,
6652  additive,
6653  force,
6654  percentage,
6655  this,
6656  force_change_on_nothing,
6657  gen_downgrade_list );
6658 }
double Unit::Upgrade ( const std::string &  file,
int  mountoffset,
int  subunitoffset,
bool  force,
bool  loop_through_mounts 
)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 6730 of file unit_generic.cpp.

References UnitFactory::createUnit(), StarSystemGent::faction, ClassCache< Typ, Key >::getCachedConst(), UnitUtil::GetCargo(), GetModeFromName(), GetUnitDir(), FactionUtil::GetUpgradeFaction(), Cargo::installed, name, ClassCache< Typ, Key >::setCachedConst(), Upgrade(), and FactionUtil::upgradefac.

6731 {
6732 #if 0
6733  if (shield.number == 2)
6734  printf( "shields before %s %f %f", file.c_str(), shield.fb[2], shield.fb[3] );
6735  else
6736  printf( "shields before %s %d %d", file.c_str(), shield.fbrl.frontmax, shield.fbrl.backmax );
6737 #endif
6739  const Unit *up = UnitConstCache::getCachedConst( StringIntKey( file, upgradefac ) );
6740  if (!up)
6741  up = UnitConstCache::setCachedConst( StringIntKey( file, upgradefac ),
6742  UnitFactory::createUnit( file.c_str(), true, upgradefac ) );
6743  unsigned int cargonum;
6744  Cargo *cargo = GetCargo(file, cargonum);
6745  if (cargo)
6746  cargo->installed = true;
6747  char *unitdir = GetUnitDir( this->name.get().c_str() );
6748  string templnam = string( unitdir )+".template";
6749  const Unit *templ = UnitConstCache::getCachedConst( StringIntKey( templnam, this->faction ) );
6750  if (templ == NULL) {
6751  templ =
6753  this->faction ),
6754  UnitFactory::createUnit( templnam.c_str(), true, this->faction ) );
6755  }
6756  free( unitdir );
6757  double percentage = 0;
6758  if (up->name != "LOAD_FAILED") {
6759  for (int i = 0; percentage == 0; ++i) {
6760  if ( !this->Unit::Upgrade( up, mountoffset+i, subunitoffset+i,
6761  GetModeFromName( file.c_str() ), force, percentage,
6762  ( (templ->name == "LOAD_FAILED") ? NULL : templ ),
6763  false, false ) )
6764  percentage = 0;
6765  if (!loop_through_mounts || ( i+1 >= this->GetNumMounts() ) || percentage > 0)
6766  break;
6767  }
6768  }
6769 #if 0
6770  if (shield.number == 2)
6771  printf( "shields before %s %f %f", file.c_str(), shield.fb[2], shield.fb[3] );
6772  else
6773  printf( "shields before %s %d %d", file.c_str(), shield.fbrl.frontmax, shield.fbrl.backmax );
6774 #endif
6775 
6776  return percentage;
6777 }
virtual void Unit::UpgradeInterface ( Unit base)
inlinevirtual
bool Unit::UpgradeMounts ( const Unit up,
int  subunitoffset,
bool  touchme,
bool  downgrade,
int numave,
const Unit templ,
double &  percentage 
)

go through all guns

search for right mount to remove starting from j. this is the right name

calculate scrap value (if damaged)

deactivate weapon

deactivate weapon

go through all guns

Definition at line 6332 of file unit_generic.cpp.

References Mount::ACTIVE, Mount::ammo, weapon_info::CAPSHIPHEAVYMISSILE, weapon_info::CAPSHIPLIGHTMISSILE, Mount::DESTROYED, GetNumMounts(), VegaConfig::getVariable(), weapon_info::HEAVYMISSILE, Mount::INACTIVE, int, j, k, weapon_info::LIGHTMISSILE, weapon_info::MEDIUMMISSILE, mounts, name, XMLSupport::parse_bool(), weapon_info::SPECIALMISSILE, Mount::type, Mount::UNCHOSEN, volume, weapon_info::volume, and vs_config.

6339 {
6340  int j;
6341  int i;
6342  bool cancompletefully = true;
6343  for (i = 0, j = mountoffset; i < up->GetNumMounts() && i < GetNumMounts() /*i should be GetNumMounts(), s'ok*/; ++i, ++j)
6344  //only mess with this if the upgrador has active mounts
6345  if (up->mounts[i].status == Mount::ACTIVE || up->mounts[i].status == Mount::INACTIVE) {
6346  //make sure since we're offsetting the starting we don't overrun the mounts
6347  bool isammo = ( string::npos != string( up->name ).find( "_ammo" ) ); //is this ammo for a weapon rather than an actual weapon
6348  bool ismissiletype =
6349  ( 0
6350  != ( up->mounts[i].type->size
6354 
6355  int jmod = j%GetNumMounts();
6356  if (!downgrade) {
6357  //if we wish to add guns instead of remove
6358  if (up->mounts[i].type->weapon_name.find( "_UPGRADE" ) == string::npos) {
6359  //check for capability increase rather than actual weapon upgrade
6360  //only look at this mount if it can fit in the rack
6361  if ( (unsigned int) (up->mounts[i].type->size) == (up->mounts[i].type->size&mounts[jmod].size) ) {
6362  if (up->mounts[i].type->weapon_name != mounts[jmod].type->weapon_name || mounts[jmod].status
6363  == Mount::DESTROYED || mounts[jmod].status == Mount::UNCHOSEN) {
6364  //If missile, can upgrade directly, if other type of ammo, needs actual gun to be present.
6365  if (isammo && !ismissiletype) {
6366  cancompletefully = false;
6367  } else {
6368  ++numave; //ok now we can compute percentage of used parts
6369  Mount upmount( up->mounts[i] );
6370  if (templ) {
6371  if (templ->GetNumMounts() > jmod) {
6372  if (templ->mounts[jmod].volume != -1)
6373  if (upmount.ammo*upmount.type->volume > templ->mounts[jmod].volume)
6374  upmount.ammo = (int) ( (templ->mounts[jmod].volume+1)/upmount.type->volume );
6375  }
6376  }
6377  //compute here
6378  percentage += mounts[jmod].Percentage( &upmount );
6379  //if we wish to modify the mounts
6380  if (touchme)
6381  //switch this mount with the upgrador mount
6382  mounts[jmod].ReplaceMounts( this, &upmount );
6383  }
6384  } else {
6385  if (isammo && up->mounts[i].type->weapon_name == mounts[jmod].type->weapon_name) {
6386  //if is ammo and is same weapon type
6387  int tmpammo = mounts[jmod].ammo;
6388  if (mounts[jmod].ammo != -1 && up->mounts[i].ammo != -1) {
6389  tmpammo += up->mounts[i].ammo;
6390  if (templ) {
6391  if (templ->GetNumMounts() > jmod) {
6392  if (templ->mounts[jmod].volume != -1) {
6393  if (templ->mounts[jmod].volume < mounts[jmod].type->volume*tmpammo) {
6394  tmpammo =
6395  (int) floor( .125
6396  +( (0
6397  +templ->mounts[jmod].volume)
6398  /mounts[jmod].type->volume ) );
6399  }
6400  }
6401  }
6402  }
6403  if (tmpammo*mounts[jmod].type->volume > mounts[jmod].volume)
6404  tmpammo = (int) floor( .125+( (0+mounts[jmod].volume)/mounts[jmod].type->volume ) );
6405  if (tmpammo > mounts[jmod].ammo) {
6406  cancompletefully = true;
6407  if (touchme)
6408  mounts[jmod].ammo = tmpammo;
6409  } else {
6410  cancompletefully = false;
6411  }
6412  }
6413  } else {
6414  cancompletefully = false;
6415  }
6416  }
6417  } else {
6418  //since we cannot fit the mount in the slot we cannot complete fully
6419  cancompletefully = false;
6420  }
6421  } else {
6422  unsigned int siz = 0;
6423  siz = ~siz;
6424  if (templ)
6425  if (templ->GetNumMounts() > jmod)
6426  siz = templ->mounts[jmod].size;
6427  if ( ( (siz&up->mounts[i].size)|mounts[jmod].size ) != mounts[jmod].size ) {
6428  if (touchme)
6429  mounts[jmod].size |= up->mounts[i].size;
6430  ++numave;
6431  ++percentage;
6432  } else {
6433  cancompletefully = false;
6434  }
6435  //we need to |= the mount type
6436  }
6437  } //DOWNGRADE
6438  else {
6439  if (up->mounts[i].type->weapon_name != "MOUNT_UPGRADE") {
6440  bool found = false; //we haven't found a matching gun to remove
6442  for (unsigned int k = 0; k < (unsigned int) GetNumMounts(); ++k) {
6443  //we want to start with bias
6444  int jkmod = (jmod+k)%GetNumMounts();
6445  if (Mount::UNCHOSEN == mounts[jkmod].status)
6446  //can't sell weapon that's already been sold/removed
6447  continue;
6449  if (strcasecmp( mounts[jkmod].type->weapon_name.c_str(),
6450  up->mounts[i].type->weapon_name.c_str() ) == 0) {
6451  //we got one, but check if we're trying to sell non-existent ammo
6452  if (isammo && mounts[jkmod].ammo <= 0)
6453  //whether it's gun ammo or a missile, you can't remove ammo from an infinite source, and you can't remove ammo if there isn't any
6454  continue;
6455  else
6456  found = true;
6458  percentage += mounts[jkmod].Percentage( &up->mounts[i] );
6459  //if we modify
6460  if (touchme) {
6461  //if downgrading ammo based upgrade, checks for infinite ammo
6462  if (isammo && up->mounts[i].ammo && up->mounts[i].ammo != -1 && mounts[jkmod].ammo != -1) {
6463  //remove upgrade-worth, else remove remaining
6464  mounts[jkmod].ammo -=
6465  (mounts[jkmod].ammo >= up->mounts[i].ammo) ? up->mounts[i].ammo : mounts[jkmod].ammo;
6466  //if none left
6467  if (!mounts[jkmod].ammo) {
6469  if (ismissiletype)
6470  mounts[jkmod].status = Mount::UNCHOSEN;
6471  }
6472  } else {
6474  mounts[jkmod].status = Mount::UNCHOSEN;
6475  mounts[jkmod].ammo = -1; //remove all ammo
6476  }
6477  }
6478  break;
6479  }
6480  }
6481  if (!found)
6482  //we did not find a matching weapon to remove
6483  cancompletefully = false;
6484  } else {
6485  bool found = false;
6486  static bool downmount =
6487  XMLSupport::parse_bool( vs_config->getVariable( "physics", "can_downgrade_mount_upgrades", "false" ) );
6488  if (downmount) {
6490  for (unsigned int k = 0; k < (unsigned int) GetNumMounts(); ++k) {
6491  //we want to start with bias
6492  int jkmod = (jmod+k)%GetNumMounts();
6493  if ( (up->mounts[i].size&mounts[jkmod].size) == (up->mounts[i].size) ) {
6494  if (touchme)
6495  mounts[jkmod].size &= (~up->mounts[i].size);
6496  ++percentage;
6497  ++numave;
6498  found = true;
6499  }
6500  }
6501  }
6502  if (!found)
6503  cancompletefully = false;
6504  }
6505  }
6506  }
6507  if ( i < up->GetNumMounts() )
6508  cancompletefully = false; //if we didn't reach the last mount that we wished to upgrade, we did not fully complete
6509 
6510  return cancompletefully;
6511 }
bool Unit::UpgradeSubUnits ( const Unit up,
int  subunitoffset,
bool  touchme,
bool  downgrade,
int numave,
double &  percentage 
)
virtual

Reimplemented in GameUnit< Enhancement >, GameUnit< Asteroid >, GameUnit< Unit >, GameUnit< Missile >, GameUnit< Building >, and GameUnit< Nebula >.

Definition at line 6518 of file unit_generic.cpp.

References CreateGenericTurret().

6519 {
6520  return UpgradeSubUnitsWithFactory( up, subunitoffset, touchme, downgrade, numave, percentage, &CreateGenericTurret );
6521 }
bool Unit::UpgradeSubUnitsWithFactory ( const Unit up,
int  subunitoffset,
bool  touchme,
bool  downgrade,
int numave,
double &  percentage,
Unit *(*)(std::string s, int faction createupgradesubunit 
)

set the turrets to the offset

Definition at line 6523 of file unit_generic.cpp.

References Unit::Limits::afterburn, UnitFactory::createUnit(), curr_physical_state, faction, Unit::Limits::forward, getTurretSize(), j, Kill(), Unit::Limits::lateral, limits, name, pImage, Unit::Limits::pitch, UnitCollection::UnitIterator::preinsert(), prev_physical_state, UnitCollection::UnitIterator::remove(), Unit::Limits::retro, Unit::Limits::roll, rSize(), SetFaction(), XMLSerializer::setName(), SetRecursiveOwner(), UnitImages< BOGUS >::unitwriter, viewSubUnits(), and Unit::Limits::yaw.

6527 {
6528  bool cancompletefully = true;
6529  int j;
6530  std::string turSize;
6531  un_iter ui;
6532  bool found = false;
6533  for (j = 0, ui = getSubUnits(); (*ui) != NULL && j < subunitoffset; ++ui, ++j) {}
6534  un_kiter upturrets;
6535  Unit *giveAway;
6536 
6537  giveAway = *ui;
6538  if (giveAway == NULL)
6539  return true;
6540  bool hasAnyTurrets = false;
6541  turSize = getTurretSize( giveAway->name );
6542  //begin goign through other unit's turrets
6543  for (upturrets = up->viewSubUnits(); ( (*upturrets) != NULL ) && ( (*ui) != NULL ); ++ui, ++upturrets) {
6544  hasAnyTurrets = true;
6545  const Unit *addtome;
6546 
6547  addtome = *upturrets; //set pointers
6548 
6549  bool foundthis = false;
6550  //if the new turret has any size at all
6551  if ( turSize == getTurretSize( addtome->name ) && addtome->rSize() && ( turSize+"_blank" != addtome->name.get() ) ) {
6552  if (!downgrade || addtome->name == giveAway->name) {
6553  found = true;
6554  foundthis = true;
6555  ++numave; //add it
6556  //add up percentage equal to ratio of sizes
6557  percentage += ( giveAway->rSize()/addtome->rSize() );
6558  }
6559  }
6560  if (foundthis) {
6561  if (touchme) {
6562  //if we wish to modify,
6563  Transformation addToMeCur = giveAway->curr_physical_state;
6564  Transformation addToMePrev = giveAway->prev_physical_state;
6565  giveAway->Kill(); //risky??
6566  ui.remove(); //remove the turret from the first unit
6567  //if we are upgrading swap them
6568  if (!downgrade) {
6569  Unit *addToMeNew = (*createupgradesubunit)(addtome->name, addtome->faction);
6570  addToMeNew->curr_physical_state = addToMeCur;
6571  addToMeNew->SetFaction( faction );
6572  addToMeNew->prev_physical_state = addToMePrev;
6573  //add unit to your ship
6574  ui.preinsert( addToMeNew );
6575  //set recursive owner
6576  addToMeNew->SetRecursiveOwner( this );
6577  } else {
6578  Unit *un; //make garbage unit
6579  //NOT 100% SURE A GENERIC UNIT CAN FIT (WAS GAME UNIT CREATION)
6580  //give a default do-nothing unit
6581  ui.preinsert( un = UnitFactory::createUnit( "upgrading_dummy_unit", true, faction ) );
6582  //WHAT?!?!?!?! 102302 ui.preinsert (un=new Unit(0));//give a default do-nothing unit
6583  un->SetFaction( faction );
6584  un->curr_physical_state = addToMeCur;
6585  un->prev_physical_state = addToMePrev;
6586  un->limits.yaw = 0;
6587  un->limits.pitch = 0;
6588  un->limits.roll = 0;
6589  un->limits.lateral = un->limits.retro = un->limits.forward = un->limits.afterburn = 0.0;
6590 
6591  un->name = turSize+"_blank";
6592  if (un->pImage->unitwriter != NULL)
6593  un->pImage->unitwriter->setName( un->name );
6594  un->SetRecursiveOwner( this );
6595  }
6596  }
6597  }
6598  }
6599  if (!found)
6600  return !hasAnyTurrets;
6601  if ( (*upturrets) != NULL )
6602  return false;
6603  return cancompletefully;
6604 }
Unit * Unit::VelocityReference ( )
void Unit::VelocityReference ( Unit targ)

Definition at line 5333 of file unit_generic.cpp.

5334 {
5335  computer.force_velocity_ref = !!targ;
5336  computer.velocity_ref.SetUnit( targ );
5337 }
void Unit::VerticalThrust ( float  amt)

Definition at line 3512 of file unit_generic.cpp.

References Vector.

3513 {
3514  if (amt > 1.0) amt = 1.0;
3515  if (amt < -1.0) amt = -1.0;
3516  ApplyLocalForce( amt*limits.vertical*Vector( 0, 1, 0 ) );
3517 }
const Computer& Unit::ViewComputerData ( ) const
inline

Definition at line 711 of file unit_generic.h.

References computer.

Referenced by UnitUtil::maxAfterburnerSpeed(), UnitUtil::maxSpeed(), and showUnitStats().

712  {
713  return computer;
714  }
un_kiter Unit::viewSubUnits ( ) const
float Unit::WarpCapData ( ) const

Definition at line 4716 of file unit_generic.cpp.

Referenced by Orders::DockingOps::DockToTarget(), ForceDock(), Planet::InitPlanet(), and showUnitStats().

4717 {
4718  return maxwarpenergy;
4719 }
float Unit::WarpEnergyData ( ) const

Definition at line 4726 of file unit_generic.cpp.

References float.

Referenced by ActuallyWarpTo(), ForceDock(), and GameCockpit::LookupUnitStat().

4727 {
4728  if (maxwarpenergy > 0)
4729  return ( (float) warpenergy )/( (float) maxwarpenergy );
4730  if (jump.energy > 0)
4731  return ( (float) warpenergy )/( (float) jump.energy );
4732  return 0.0f;
4733 }
void Unit::WriteUnit ( const char *  modificationname = "")

Definition at line 1446 of file unit_csv.cpp.

References VSFileSystem::VSFile::Close(), VSFileSystem::CreateDirectoryHome(), csvRow, f, fprintf, VSFileSystem::VSFile::GetFullPath(), getSubUnits(), VegaConfig::getVariable(), name, VSFileSystem::Ok, VSFileSystem::VSFile::OpenCreateWrite(), XMLSupport::parse_bool(), pImage, VSFileSystem::savedunitpath, VSFileSystem::UnitFile, UnitImages< BOGUS >::unitwriter, vs_config, XMLSerializer::Write(), VSFileSystem::VSFile::Write(), and WriteUnitString().

Referenced by GameUniverse::WriteSaveGame(), and WriteSaveGame().

1447 {
1448  static bool UNITTAB = XMLSupport::parse_bool( vs_config->getVariable( "physics", "UnitTable", "false" ) );
1449  if (UNITTAB) {
1450  bool bad = false;
1451  if (!modifications) bad = true;
1452  if (!bad)
1453  if ( !strlen( modifications ) )
1454  bad = true;
1455  if (bad) {
1456  fprintf( stderr, "Cannot Write out unit file %s %s that has no filename\n", name.get().c_str(), csvRow.get().c_str() );
1457  return;
1458  }
1459  std::string savedir = modifications;
1461  VSFile f;
1462  VSError err = f.OpenCreateWrite( savedir+"/"+name+".csv", UnitFile );
1463  if (err > Ok) {
1464  fprintf( stderr, "!!! ERROR : Writing saved unit file : %s\n", f.GetFullPath().c_str() );
1465  return;
1466  }
1467  std::string towrite = WriteUnitString();
1468  f.Write( towrite.c_str(), towrite.length() );
1469  f.Close();
1470  } else {
1471  if (pImage->unitwriter)
1472  pImage->unitwriter->Write( modifications );
1473  for (un_iter ui = getSubUnits(); (*ui) != NULL; ++ui)
1474  (*ui)->WriteUnit( modifications );
1475  }
1476 }
string Unit::WriteUnitString ( )

Definition at line 1512 of file unit_csv.cpp.

References UniverseUtil::acos(), Unit::Limits::afterburn, afterburnenergy, afterburntype, armor, Armor::backleftbottom, Armor::backlefttop, Armor::backrightbottom, Armor::backrighttop, c, Unit::Computer::RADARLIM::canlock, Unit::Computer::RADARLIM::capability, UnitImages< BOGUS >::CargoVolume, UnitImages< BOGUS >::cloakenergy, UnitImages< BOGUS >::cloakglass, cloaking, cloakmin, UnitImages< BOGUS >::cloakrate, UnitImages< BOGUS >::CommFunctionality, UnitImages< BOGUS >::CommFunctionalityMax, computer, csvRow, Unit::UnitJump::delay, Mount::DESTROYED, Unit::UnitJump::drive, UnitImages< BOGUS >::ecm, Shield::efficiency, Unit::UnitJump::energy, UnitImages< BOGUS >::equipment_volume, filename, UnitImages< BOGUS >::fireControlFunctionality, UnitImages< BOGUS >::fireControlFunctionalityMax, UnitImages< BOGUS >::forcejump, Unit::Limits::forward, fprintf, Armor::frontleftbottom, Armor::frontlefttop, Armor::frontrightbottom, Armor::frontrighttop, fuel, fullname, Cargo::functionality, GetCargo(), Cargo::GetCategory(), Cargo::GetContent(), CSVRow::getKey(), Matrix::getQ(), Matrix::getR(), GetSubUnits(), getSubUnits(), VegaConfig::getVariable(), graphicOptions, HeatSink, UnitImages< BOGUS >::HiddenCargoVolume, hull, i, Cargo::installed, Unit::UnitJump::insysenergy, isTractorable(), Unit::Computer::itts, j, jump, k, Unit::Limits::lateral, Shield::leak, UnitImages< BOGUS >::LifeSupportFunctionality, UnitImages< BOGUS >::LifeSupportFunctionalityMax, limits, Unit::Computer::RADARLIM::lockcone, lookupMountSize(), mapToStringVec(), Cargo::mass, Mass, Unit::Computer::max_combat_ab_speed, Unit::Computer::max_combat_speed, Unit::Computer::max_pitch_down, Unit::Computer::max_pitch_up, Unit::Computer::max_roll_left, Unit::Computer::max_roll_right, Unit::Computer::max_yaw_left, Unit::Computer::max_yaw_right, Unit::Computer::RADARLIM::maxcone, maxenergy, Cargo::maxfunctionality, Unit::Computer::RADARLIM::maxrange, maxwarpenergy, Unit::graphic_options::MaxWarpMultiplier, Unit::graphic_options::MinWarpMultiplier, Cargo::mission, Momentofinertia, mounts, name, Shield::number, numCargo(), Matrix::p, XMLSupport::parse_bool(), XMLSupport::parse_float(), pImage, Unit::Limits::pitch, Position(), Cargo::price, Cargo::quantity, Unit::Computer::radar, Shield::recharge, recharge, UnitImages< BOGUS >::repair_droid, Unit::Limits::retro, Unit::Limits::roll, shield, Shield::shield2fb, Shield::shield4fbrl, Shield::shield8, size, CSVRow::size(), Unit::Computer::slide_end, Unit::Computer::slide_start, UnitImages< BOGUS >::SPECDriveFunctionality, UnitImages< BOGUS >::SPECDriveFunctionalityMax, specInterdiction, stof(), Transformation::to_matrix(), tos(), XMLSupport::tostring(), Unit::Computer::RADARLIM::trackingcone, tractorIn, tractorPush, Mount::UNCHOSEN, unitTables, UnitImages< BOGUS >::unitwriter, UnitImages< BOGUS >::UpgradeVolume, Unit::Limits::vertical, volume, Cargo::volume, vs_config, VS_PI, writeCSV(), WriteHudDamage(), WriteHudDamageFunc(), XMLSerializer::WriteString(), and Unit::Limits::yaw.

Referenced by NavigationSystem::DrawShip(), SaveNetUtil::GetSaveStrings(), BaseComputer::showShipStats(), and WriteUnit().

1513 {
1514  static bool UNITTAB = XMLSupport::parse_bool( vs_config->getVariable( "physics", "UnitTable", "false" ) );
1515  string ret = "";
1516  if (UNITTAB) {
1517  //this is the fillin part
1518  //fixme
1519  for (int i = unitTables.size()-1; i >= 0; --i) {
1520  unsigned int where;
1521  string val;
1522  if ( unitTables[i]->RowExists( csvRow, where ) ) {
1523  CSVRow row( unitTables[i], where );
1524  vsUMap< string, string >unit;
1525  for (unsigned int jj = 0; jj < row.size(); ++jj)
1526  if (jj != 0)
1527  unit[row.getKey( jj )] = row[jj];
1528  //mutable things
1529  unit["Equipment_Space"] = XMLSupport::tostring( pImage->equipment_volume );
1530  unit["Hold_Volume"] = XMLSupport::tostring( pImage->CargoVolume );
1531  unit["Hidden_Hold_Volume"] = XMLSupport::tostring( pImage->HiddenCargoVolume );
1532  unit["Upgrade_Storage_Volume"] = XMLSupport::tostring( pImage->UpgradeVolume );
1533  string mountstr;
1534  double unitScale = stof( unit["Unit_Scale"], 1 );
1535  {
1536  //mounts
1537  for (unsigned int j = 0; j < mounts.size(); ++j) {
1538  char mnt[1024];
1539  Matrix m;
1540  Transformation tr( mounts[j].GetMountOrientation(),
1541  mounts[j].GetMountLocation().Cast() );
1542  tr.to_matrix( m );
1543  string printedname = mounts[j].type->weapon_name;
1544  if (mounts[j].status == Mount::DESTROYED || mounts[j].status == Mount::UNCHOSEN)
1545  printedname = "";
1546  mountstr += "{"+printedname+";"+XMLSupport::tostring( mounts[j].ammo )+";"+XMLSupport::tostring(
1547  mounts[j].volume )+";"+lookupMountSize( mounts[j].size );
1548  sprintf( mnt, ";%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf}",
1549  m.p.i/unitScale,
1550  m.p.j/unitScale,
1551  m.p.k/unitScale,
1552  (double) mounts[j].xyscale/unitScale,
1553  (double) mounts[j].zscale/unitScale,
1554  (double) m.getR().i,
1555  (double) m.getR().j,
1556  (double) m.getR().k,
1557  (double) m.getQ().i,
1558  (double) m.getQ().j,
1559  (double) m.getQ().k,
1560  (double) mounts[j].functionality,
1561  (double) mounts[j].maxfunctionality
1562  );
1563  mountstr += mnt;
1564  }
1565  unit["Mounts"] = mountstr;
1566  }
1567  {
1568  //subunits
1569  vector< SubUnitStruct >subunits = GetSubUnits( unit["Sub_Units"] );
1570  if ( subunits.size() ) {
1571  unsigned int k = 0;
1572  Unit *subun;
1573  for (; k < subunits.size(); ++k)
1574  subunits[k].filename = "destroyed_blank";
1575  k = 0;
1576  for (un_iter su = this->getSubUnits(); ( subun = (*su) ) != NULL; ++su, ++k) {
1577  unsigned int j = k;
1578  for (; j < subunits.size(); ++j)
1579  if ( (subun->Position()-subunits[j].pos).MagnitudeSquared() < .00000001 )
1580  //we've got a hit
1581  break;
1582  if ( j >= subunits.size() ) j = k;
1583  if ( j < subunits.size() )
1584  subunits[j].filename = subun->name;
1585  }
1586  string str;
1587  for (k = 0; k < subunits.size(); ++k) {
1588  char tmp[1024];
1589  sprintf( tmp, ";%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf;%lf}",
1590  subunits[k].pos.i,
1591  subunits[k].pos.j,
1592  subunits[k].pos.k,
1593  subunits[k].R.i,
1594  subunits[k].R.j,
1595  subunits[k].R.k,
1596  subunits[k].Q.i,
1597  subunits[k].Q.j,
1598  subunits[k].Q.k,
1599  ( (double) acos( subunits[k].restricted )*180./VS_PI ) );
1600  str += "{"+subunits[k].filename+tmp;
1601  }
1602  unit["Sub_Units"] = str;
1603  }
1604  }
1605  {
1606  string carg;
1607  for (unsigned int i = 0; i < numCargo(); ++i) {
1608  Cargo *c = &GetCargo( i );
1609  char tmp[2048];
1610  sprintf( tmp, ";%f;%d;%f;%f;%f;%f;;%s;%s}",
1611  c->price,
1612  c->quantity,
1613  c->mass,
1614  c->volume,
1615  c->functionality,
1616  c->maxfunctionality,
1617  c->mission ? "true" : "false",
1618  c->installed ? "true" : "false"
1619  );
1620  carg += "{"+c->GetContent()+";"+c->GetCategory()+tmp;
1621  }
1622  unit["Cargo"] = carg;
1623  }
1624  unit["Mass"] = tos( Mass );
1625  unit["Moment_Of_Inertia"] = tos( Momentofinertia );
1626  unit["Fuel_Capacity"] = tos( fuel );
1627  unit["Hull"] = tos( hull );
1628  unit["Spec_Interdiction"] = tos( specInterdiction );
1629  unit["Armor_Front_Top_Left"] = tos( armor.frontlefttop );
1630  unit["Armor_Front_Top_Right"] = tos( armor.frontrighttop );
1631  unit["Armor_Back_Top_Left"] = tos( armor.backlefttop );
1632  unit["Armor_Back_Top_Right"] = tos( armor.backrighttop );
1633  unit["Armor_Front_Bottom_Left"] = tos( armor.frontleftbottom );
1634  unit["Armor_Front_Bottom_Right"] = tos( armor.frontrightbottom );
1635  unit["Armor_Back_Bottom_Left"] = tos( armor.backleftbottom );
1636  unit["Armor_Back_Bottom_Right"] = tos( armor.backrightbottom );
1637  {
1638  unit["Shield_Front_Top_Right"] = "";
1639  unit["Shield_Front_Top_Left"] = "";
1640  unit["Shield_Back_Top_Right"] = "";
1641  unit["Shield_Back_Top_Left"] = "";
1642  unit["Shield_Front_Bottom_Right"] = "";
1643  unit["Shield_Front_Bottom_Left"] = "";
1644  unit["Shield_Back_Bottom_Right"] = "";
1645  unit["Shield_Back_Bottom_Left"] = "";
1646  switch (shield.number)
1647  {
1648  case 8:
1649  unit["Shield_Front_Top_Right"] = tos( shield.shield8.frontrighttopmax );
1650  unit["Shield_Front_Top_Left"] = tos( shield.shield8.frontlefttopmax );
1651  unit["Shield_Back_Top_Right"] = tos( shield.shield8.backrighttopmax );
1652  unit["Shield_Back_Top_Left"] = tos( shield.shield8.backlefttopmax );
1653  unit["Shield_Front_Bottom_Right"] = tos( shield.shield8.frontrightbottommax );
1654  unit["Shield_Front_Bottom_Left"] = tos( shield.shield8.frontleftbottommax );
1655  unit["Shield_Back_Bottom_Right"] = tos( shield.shield8.backrightbottommax );
1656  unit["Shield_Back_Bottom_Left"] = tos( shield.shield8.backleftbottommax );
1657  break;
1658  case 4:
1659  unit["Shield_Front_Top_Right"] = tos( shield.shield4fbrl.frontmax );
1660  unit["Shield_Back_Top_Right"] = tos( shield.shield4fbrl.backmax );
1661  unit["Shield_Front_Bottom_Right"] = tos( shield.shield4fbrl.rightmax );
1662  unit["Shield_Front_Bottom_Left"] = tos( shield.shield4fbrl.leftmax );
1663  break;
1664  case 2:
1665  unit["Shield_Front_Top_Right"] = tos( shield.shield2fb.frontmax );
1666  unit["Shield_Back_Top_Right"] = tos( shield.shield2fb.backmax );
1667  break;
1668  //NOTE: otherwise, no shields
1669  }
1670  }
1671  unit["Shield_Leak"] = tos( shield.leak/100.0 );
1672  unit["Shield_Recharge"] = tos( shield.recharge );
1673  unit["Shield_Efficiency"] = tos( shield.efficiency );
1674  unit["Warp_Capacitor"] = tos( maxwarpenergy );
1675  unit["Warp_Min_Multiplier"] = tos( graphicOptions.MinWarpMultiplier );
1676  unit["Warp_Max_Multiplier"] = tos( graphicOptions.MaxWarpMultiplier );
1677  unit["Primary_Capacitor"] = tos( maxenergy );
1678  unit["Reactor_Recharge"] = tos( recharge );
1679  unit["Jump_Drive_Present"] = tos( jump.drive >= -1 );
1680  unit["Jump_Drive_Delay"] = tos( jump.delay );
1681  unit["Wormhole"] = tos( pImage->forcejump != 0 );
1682  unit["Outsystem_Jump_Cost"] = tos( jump.energy );
1683  unit["Warp_Usage_Cost"] = tos( jump.insysenergy );
1684  unit["Afterburner_Usage_Cost"] = tos( afterburnenergy );
1685  unit["Afterburner_Type"] = tos( afterburntype );
1686  unit["Maneuver_Yaw"] = tos( limits.yaw*180/(VS_PI) );
1687  unit["Maneuver_Pitch"] = tos( limits.pitch*180/(VS_PI) );
1688  unit["Maneuver_Roll"] = tos( limits.roll*180/(VS_PI) );
1689  unit["Yaw_Governor_Right"] = tos( computer.max_yaw_right*180/VS_PI );
1690  unit["Yaw_Governor_Left"] = tos( computer.max_yaw_left*180/VS_PI );
1691  unit["Pitch_Governor_Up"] = tos( computer.max_pitch_up*180/VS_PI );
1692  unit["Pitch_Governor_Down"] = tos( computer.max_pitch_down*180/VS_PI );
1693  unit["Roll_Governor_Right"] = tos( computer.max_roll_right*180/VS_PI );
1694  unit["Roll_Governor_Left"] = tos( computer.max_roll_left*180/VS_PI );
1695  static float game_accel = XMLSupport::parse_float( vs_config->getVariable( "physics", "game_accel", "1" ) );
1696  static float game_speed = XMLSupport::parse_float( vs_config->getVariable( "physics", "game_speed", "1" ) );
1697  unit["Afterburner_Accel"] = tos( limits.afterburn/(game_accel*game_speed) );
1698  unit["Forward_Accel"] = tos( limits.forward/(game_accel*game_speed) );
1699  unit["Retro_Accel"] = tos( limits.retro/(game_accel*game_speed) );
1700  unit["Left_Accel"] = unit["Right_Accel"] = tos( limits.lateral/(game_accel*game_speed) );
1701  unit["Bottom_Accel"] = unit["Top_Accel"] = tos( limits.vertical/(game_accel*game_speed) );
1702  unit["Default_Speed_Governor"] = tos( computer.max_combat_speed/game_speed );
1703  unit["Afterburner_Speed_Governor"] = tos( computer.max_combat_ab_speed/game_speed );
1704  unit["ITTS"] = tos( computer.itts );
1705  unit["Can_Lock"] = tos( computer.radar.canlock );
1706  unit["Radar_Color"] = tos( computer.radar.capability );
1707  unit["Radar_Range"] = tos( computer.radar.maxrange );
1708  unit["Tracking_Cone"] = tos( acos( computer.radar.trackingcone )*180./VS_PI );
1709  unit["Max_Cone"] = tos( acos( computer.radar.maxcone )*180./VS_PI );
1710  unit["Lock_Cone"] = tos( acos( computer.radar.lockcone )*180./VS_PI );
1711  unit["Cloak_Min"] = tos( cloakmin/2147483136. );
1712  unit["Can_Cloak"] = tos( cloaking != -1 );
1713  unit["Cloak_Rate"] = tos( fabs( pImage->cloakrate/2147483136. ) );
1714  unit["Cloak_Energy"] = tos( pImage->cloakenergy );
1715  unit["Cloak_Glass"] = tos( pImage->cloakglass );
1716  unit["Repair_Droid"] = tos( pImage->repair_droid );
1717  unit["ECM_Rating"] = tos( pImage->ecm > 0 ? pImage->ecm : -pImage->ecm );
1718  unit["Hud_Functionality"] = WriteHudDamage( this );
1719  unit["Max_Hud_Functionality"] = WriteHudDamageFunc( this );
1720  unit["Heat_Sink_Rating"] = tos( this->HeatSink );
1721  unit["Lifesupport_Functionality"] = tos( pImage->LifeSupportFunctionality );
1722  unit["Max_Lifesupport_Functionality"] = tos( pImage->LifeSupportFunctionalityMax );
1723  unit["Comm_Functionality"] = tos( pImage->CommFunctionality );
1724  unit["Max_Comm_Functionality"] = tos( pImage->CommFunctionalityMax );
1725  unit["Comm_Functionality"] = tos( pImage->CommFunctionality );
1726  unit["Max_Comm_Functionality"] = tos( pImage->CommFunctionalityMax );
1727  unit["FireControl_Functionality"] = tos( pImage->fireControlFunctionality );
1728  unit["Max_FireControl_Functionality"] = tos( pImage->fireControlFunctionalityMax );
1729  unit["SPECDrive_Functionality"] = tos( pImage->SPECDriveFunctionality );
1730  unit["Max_SPECDrive_Functionality"] = tos( pImage->SPECDriveFunctionalityMax );
1731  unit["Slide_Start"] = tos( computer.slide_start );
1732  unit["Slide_End"] = tos( computer.slide_end );
1733  unit["Cargo_Import"] = unit["Upgrades"] = ""; //make sure those are empty
1734  {
1735  std::string trac;
1736  if ( isTractorable( tractorPush ) ) trac += "p";
1737  if ( isTractorable( tractorIn ) ) trac += "i";
1738  if ( trac.empty() ) trac = "-";
1739  unit["Tractorability"] = trac;
1740  }
1741  vector< string >keys, values;
1742  keys.push_back( "Key" );
1743  values.push_back( csvRow ); //key has to come first
1744  mapToStringVec( unit, keys, values );
1745  return writeCSV( keys, values );
1746  }
1747  }
1748  fprintf( stderr, "Failed to locate base mesh for %s %s %s\n", csvRow.get().c_str(), name.get().c_str(), fullname.c_str() );
1749  } else {
1750  if (pImage->unitwriter)
1751  ret = pImage->unitwriter->WriteString();
1752  for (un_iter ui = getSubUnits(); (*ui) != NULL; ++ui)
1753  ret = ret+( (*ui)->WriteUnitString() );
1754  }
1755  return ret;
1756 }
void Unit::YawTorque ( float  amt)

Definition at line 3526 of file unit_generic.cpp.

References Vector.

3527 {
3528  if (amt > limits.yaw) amt = limits.yaw;
3529  else if (amt < -limits.yaw)
3530  amt = -limits.yaw;
3531  ApplyLocalTorque( amt*Vector( 0, 1, 0 ) );
3532 }

Friends And Related Function Documentation

friend class ContinuousTerrain
friend

Definition at line 479 of file unit_generic.h.

friend class Mount
friend

Definition at line 442 of file unit_generic.h.

friend class PlanetaryOrbit
friend

Definition at line 478 of file unit_generic.h.

friend class UnitFactory
friend

Definition at line 279 of file unit_generic.h.

friend class UpgradingInfo
friend

Definition at line 483 of file unit_generic.h.

friend class VDU
friend

Definition at line 481 of file unit_generic.h.

Member Data Documentation

float Unit::afterburnenergy
protected

Definition at line 813 of file unit_generic.h.

Referenced by AfterburnData(), Init(), LoadRow(), UpAndDownGrade(), and WriteUnitString().

int Unit::afterburntype
protected

Definition at line 814 of file unit_generic.h.

Referenced by LoadRow(), UpAndDownGrade(), and WriteUnitString().

unsigned char Unit::attack_preference
protected

Definition at line 474 of file unit_generic.h.

Referenced by attackPreference(), and Init().

Vector Unit::corner_max

Definition at line 870 of file unit_generic.h.

Referenced by calculate_extent(), Init(), LoadRow(), and Planet::Planet().

Vector Unit::corner_min

Definition at line 870 of file unit_generic.h.

Referenced by calculate_extent(), Init(), LoadRow(), and Planet::Planet().

StringPool::Reference Unit::csvRow
protected

Definition at line 227 of file unit_generic.h.

Referenced by LoadRow(), WriteUnit(), and WriteUnitString().

unsigned int Unit::cur_sim_queue_slot
unsigned short Unit::damages
bool Unit::do_subunit_scheduling

Definition at line 779 of file unit_generic.h.

Referenced by Init(), and RecursiveSetSchedule().

unsigned char Unit::docked
float Unit::energy

Definition at line 1143 of file unit_generic.h.

Referenced by ZoneMgr::addPosition(), Init(), LoadRow(), and Mount::PhysicsAlignedFire().

int Unit::faction

Definition at line 1460 of file unit_generic.h.

Referenced by UnitFactory::addAsteroidBuffer(), UnitFactory::addMissileBuffer(), UnitFactory::addNebulaBuffer(), StarSystem::Statistics::AddUnit(), UnitFactory::addUnitBuffer(), UniverseUtil::AdjustRelation(), CommunicatingAI::AdjustRelationTo(), AllUnitsCloseAndEngage(), ApplyDamage(), Arrested(), BaseInterface::BaseInterface(), Planet::beginElement(), buyShip(), StarSystem::Statistics::CheckVitals(), ChooseNavPoint(), BaseInterface::Room::Launch::Click(), Beam::Collide(), BaseComputer::constructControls(), cosAngleTo(), createObjects(), CommunicatingAI::Destroy(), Pilot::DoHit(), WarpTrail::Draw(), drawlistitem(), EjectCargo(), Orders::TurretAI::Execute(), Orders::AggressiveAI::Execute(), FlyByKeyboard::Execute(), FireKeyboard::Execute(), ForceDock(), getAutoRSize(), BaseComputer::getColorForGroup(), Pilot::getCommFace(), UnitUtil::getFactionIndex(), UnitUtil::getFactionName(), UnitUtil::getFactionRelation(), UnitUtil::getPhysicsPriority(), getProperScript(), UniverseUtil::GetRelation(), UnitUtil::getRelationFromFaction(), UnitUtil::getRelationToFaction(), SaveNetUtil::GetSaveStrings(), HelpOut(), Radar::Track::IdentifyType(), CommunicatingAI::InitiateContrabandSearch(), Planet::InitPlanet(), isPlayerFaction(), FireKeyboard::JoinFg(), LoadRow(), UnitUtil::orbit(), UnitUtil::PercentOperational(), Mount::PhysicsAlignedFire(), CommunicatingAI::ProcessCommMessage(), Orders::AggressiveAI::ProcessCurrentFgDirective(), CommunicatingAI::RandomInitiateCommunication(), Enhancement::reactToCollision(), reactToCollision(), BaseComputer::recalcTitle(), StarSystem::Statistics::RemoveUnit(), ScoreKill(), Pilot::SetComm(), Cockpit::SetParent(), BaseComputer::BuyUpgradeOperation::start(), BaseComputer::SellUpgradeOperation::start(), UniverseUtil::StopTargettingEachOther(), UnitUtil::switchFg(), UniverseUtil::TargetEachOther(), TargUn(), CommunicatingAI::TerminateContrabandSearch(), UnDock(), Unit(), UpAndDownGrade(), CommunicatingAI::UpdateContrabandSearch(), UpgradeAllowed(), and UpgradeSubUnitsWithFactory().

StringPool::Reference Unit::filename

Definition at line 233 of file unit_generic.h.

Referenced by WriteUnitString().

Flightgroup* Unit::flightgroup
protected

Definition at line 1454 of file unit_generic.h.

Referenced by getFlightgroup(), and Init().

int Unit::flightgroup_subnumber
protected

Definition at line 1456 of file unit_generic.h.

Referenced by getFgSubnumber(), and Init().

float Unit::fuel
protected

Definition at line 812 of file unit_generic.h.

Referenced by GetMass(), GetMoment(), Init(), LoadRow(), UpAndDownGrade(), and WriteUnitString().

float Unit::gunrange

Definition at line 349 of file unit_generic.h.

float Unit::gunspeed

Definition at line 348 of file unit_generic.h.

float Unit::HeatSink

Definition at line 807 of file unit_generic.h.

Referenced by Init(), LoadRow(), UpAndDownGrade(), and WriteUnitString().

bool Unit::inertialmode

Definition at line 351 of file unit_generic.h.

Referenced by FlyByWire::InertialFlight(), Init(), and GameCockpit::LookupUnitStat().

unsigned char Unit::invisible
protected

Definition at line 866 of file unit_generic.h.

Referenced by Init().

unsigned int Unit::last_processed_sqs

Definition at line 777 of file unit_generic.h.

Referenced by Init(), and UpdateSubunitPhysics().

float Unit::maxenergy
protected
float Unit::maxhull
protected
float Unit::maxwarpenergy
protected

Definition at line 1160 of file unit_generic.h.

Referenced by Init(), Planet::InitPlanet(), LoadRow(), UpAndDownGrade(), and WriteUnitString().

float Unit::missilerange

Definition at line 350 of file unit_generic.h.

float Unit::Momentofinertia
protected

Definition at line 817 of file unit_generic.h.

Referenced by GetMoment(), Init(), LoadRow(), UpAndDownGrade(), and WriteUnitString().

StringPool::Reference Unit::name

Definition at line 232 of file unit_generic.h.

Referenced by BaseComputer::actionConfirmedSaveGame(), NetClient::AddClientObject(), UnitFactory::addMissileBuffer(), NetClient::AddObjects(), ZoneMgr::addPosition(), UnitFactory::addUnitBuffer(), Arrested(), BaseInterface::BaseInterface(), buildCargoDescription(), CheckAccessory(), BaseInterface::Room::Launch::Click(), BaseInterface::Room::Eject::Click(), Beam::Collide(), displayUnitInfo(), GameCockpit::DoAutoLanding(), DockToSavedBases(), DoSpeech(), EjectCargo(), FireKeyboard::Execute(), Orders::AggressiveAI::ExecuteNoEnemies(), FilterDowngradeList(), Pilot::getAnger(), UnitUtil::getName(), getProperScript(), getUnitFromUpgradeName(), getUnitNameAndFgNoBase(), MeshAnimation::Init(), Planet::InitPlanet(), CockpitKeys::Inside(), UnitUtil::isAsteroid(), GameCockpit::LookupUnitStat(), makeFinalBlankUpgrade(), makeMasterPartList(), makeTemplateUpgrade(), MakeUnitXMLPretty(), UnitFactory::parseMissileBuffer(), UnitFactory::parseUnitBuffer(), UnitUtil::PercentOperational(), GamePlanet::reactToCollision(), BaseComputer::recalcTitle(), Orders::AggressiveAI::ReCommandWing(), ReduceToTemplate(), Repair(), RepairUpgrade(), setFullname(), UnitUtil::setName(), showUnitStats(), GameUnit< UnitType >::Split(), BaseComputer::BuyUpgradeOperation::start(), BaseComputer::SellUpgradeOperation::start(), subunitSerializer(), SwapInNewShipName(), UnitUtil::switchFg(), TargSig(), UpAndDownGrade(), Cockpit::Update(), Upgrade(), UpgradeAllowed(), GameUnit< UnitType >::UpgradeInterface(), UpgradeMounts(), UpgradeSubUnitsWithFactory(), WriteUnit(), WriteUnitString(), and ~Unit().

Nebula* Unit::nebula
protected

Definition at line 476 of file unit_generic.h.

Referenced by GetNebula(), and Init().

Vector Unit::net_accel
protected

Definition at line 294 of file unit_generic.h.

Vector Unit::NetForce

Definition at line 791 of file unit_generic.h.

Referenced by Orders::AggressiveAI::Execute(), Init(), and PerformDockingOperations().

Vector Unit::NetLocalForce

Definition at line 793 of file unit_generic.h.

Referenced by Orders::AggressiveAI::Execute(), Init(), and PerformDockingOperations().

Vector Unit::NetLocalTorque

Definition at line 797 of file unit_generic.h.

Referenced by Init(), PerformDockingOperations(), and GameBuilding::UpdatePhysics2().

Vector Unit::NetTorque

Definition at line 795 of file unit_generic.h.

Referenced by Init(), and PerformDockingOperations().

bool Unit::networked
protected

Definition at line 292 of file unit_generic.h.

Referenced by Init().

ClientState Unit::old_state

Definition at line 296 of file unit_generic.h.

Referenced by NetClient::AddClientObject(), and Prediction::InitInterpolation().

MeshAnimation* Unit::pMeshAnimation

Definition at line 1561 of file unit_generic.h.

Referenced by ~Unit().

unsigned int Unit::predicted_priority
float Unit::recharge
protected
bool Unit::resolveforces

Definition at line 930 of file unit_generic.h.

Referenced by Init().

Vector Unit::SavedAccel
protected

Definition at line 818 of file unit_generic.h.

Referenced by GetAcceleration().

bool Unit::selected

Definition at line 703 of file unit_generic.h.

Referenced by Init().

ObjSerial Unit::serial
protected

Definition at line 293 of file unit_generic.h.

Referenced by Dock(), GetSerial(), and UnDock().

float Unit::shieldtight
protected

Definition at line 810 of file unit_generic.h.

Referenced by Init().

UnitSounds* Unit::sound

Definition at line 229 of file unit_generic.h.

Referenced by AddSounds(), Init(), Unit(), and ~Unit().

StringPool::Reference Unit::target_fgid[3]
protected

Definition at line 1218 of file unit_generic.h.

char Unit::turretstatus

Definition at line 352 of file unit_generic.h.

Referenced by Init(), and GameCockpit::LookupUnitStat().

int Unit::ucref

Definition at line 10 of file unit.h.

Referenced by Init(), Ref(), Unit(), UnRef(), and ~Unit().

unsigned char Unit::unit_role
protected

Definition at line 475 of file unit_generic.h.

Referenced by Init(), and unitRole().

float Unit::warpenergy
protected

Definition at line 1162 of file unit_generic.h.

Referenced by GetWarpEnergy(), Init(), jumpReactToCollision(), and LoadRow().

XML* Unit::xml

Definition at line 726 of file unit_generic.h.

Referenced by Init(), and LoadRow().

bool Unit::zapped

Definition at line 9 of file unit.h.

Referenced by Kill(), Killed(), Ref(), Unit(), and UnRef().


The documentation for this class was generated from the following files: