diff --git a/.gitignore b/.gitignore index 8bf3ce07b..540ca1d49 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ BDArmory Ignore ####################################### BDArmory/BDArmory.csproj.user +_LocalDev BahaTurret/.vs BahaTurret/obj diff --git a/BDArmory.Core/BDAPersistantSettingsField.cs b/BDArmory.Core/BDAPersistantSettingsField.cs index 0fe21d16a..e2b14653b 100644 --- a/BDArmory.Core/BDAPersistantSettingsField.cs +++ b/BDArmory.Core/BDAPersistantSettingsField.cs @@ -12,7 +12,6 @@ public class BDAPersistantSettingsField : Attribute public BDAPersistantSettingsField() { } - public static void Save() { ConfigNode fileNode = ConfigNode.Load(BDArmorySettings.settingsConfigURL); @@ -34,7 +33,6 @@ public static void Save() field.Dispose(); fileNode.Save(BDArmorySettings.settingsConfigURL); } - public static void Load() { ConfigNode fileNode = ConfigNode.Load(BDArmorySettings.settingsConfigURL); diff --git a/BDArmory.Core/BDArmorySettings.cs b/BDArmory.Core/BDArmorySettings.cs index 5f6464588..bc4942b39 100644 --- a/BDArmory.Core/BDArmorySettings.cs +++ b/BDArmory.Core/BDArmorySettings.cs @@ -49,6 +49,7 @@ public class BDArmorySettings [BDAPersistantSettingsField] public static float RECOIL_FACTOR = 0.75f; [BDAPersistantSettingsField] public static float DMG_MULTIPLIER = 100f; + [BDAPersistantSettingsField] public static float BALLISTIC_DMG_FACTOR = 1f; [BDAPersistantSettingsField] public static float HITPOINT_MULTIPLIER = 2.0f; [BDAPersistantSettingsField] public static float EXP_DMG_MOD_BALLISTIC; [BDAPersistantSettingsField] public static float EXP_DMG_MOD_MISSILE; diff --git a/BDArmory.Core/Extension/PartExtensions.cs b/BDArmory.Core/Extension/PartExtensions.cs index dee0d2294..3dbd409fa 100644 --- a/BDArmory.Core/Extension/PartExtensions.cs +++ b/BDArmory.Core/Extension/PartExtensions.cs @@ -93,7 +93,7 @@ public static void AddBallisticDamage(this Part p, float damage_ = ((0.5f * (mass * Mathf.Pow(impactVelocity, 2))) * (BDArmorySettings.DMG_MULTIPLIER / 100) * bulletDmgMult - * 1e-4f); + * 1e-4f * BDArmorySettings.BALLISTIC_DMG_FACTOR); ////////////////////////////////////////////////////////// // Armor Reduction factors @@ -274,31 +274,49 @@ public static bool IsMissile(this Part part) part.Modules.Contains("BDModularGuidance"); } - public static float GetArea(this Part part) + public static float GetArea(this Part part, bool isprefab = false, Part prefab = null) { - var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; - float sfcAreaCalc = 2f * (boundsSize.x * boundsSize.y) + 2f * (boundsSize.y * boundsSize.z) + 2f * (boundsSize.x * boundsSize.z); - //Debug.Log("[BDArmory]: Surface Area1: " + part.surfaceAreas.magnitude); - //Debug.Log("[BDArmory]: Surface Area2: " + sfcAreaCalc); - + var size = part.GetSize(); + float sfcAreaCalc = 2f * (size.x * size.y) + 2f * (size.y * size.z) + 2f * (size.x * size.z); + return sfcAreaCalc; } public static float GetAverageBoundSize(this Part part) { - var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; - return (boundsSize.x + boundsSize.y + boundsSize.z) / 3f; + var size = part.GetSize(); + + + + return (size.x + size.y + size.z) / 3f; } public static float GetVolume(this Part part) { - var boundsSize = PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; - return boundsSize.x * boundsSize.y * boundsSize.z; + var size = part.GetSize(); + var volume = size.x * size.y * size.z; + return volume; } - public static float GetDensity (this Part part) + public static Vector3 GetSize(this Part part) { - return (part.mass * 1000) / part.GetVolume(); + + var size = part.GetComponentInChildren().mesh.bounds.size; + + if (part.name.Contains("B9.Aero.Wing.Procedural")) + { + size = size * 0.1f; + } + + float scaleMultiplier = 1f; + if (part.Modules.Contains("TweakScale")) + { + var tweakScaleModule = part.Modules["TweakScale"]; + scaleMultiplier = tweakScaleModule.Fields["currentScale"].GetValue(tweakScaleModule) / + tweakScaleModule.Fields["defaultScale"].GetValue(tweakScaleModule); + } + + return size * scaleMultiplier; } public static bool IsAero(this Part part) @@ -349,7 +367,8 @@ public static bool HasFuel(this Part part) } public static float DamageReduction(float armor, float damage,bool isMissile,float caliber = 0, float penetrationfactor = 0) - { + { + float _damageReduction; if (isMissile) { @@ -368,22 +387,39 @@ public static float DamageReduction(float armor, float damage,bool isMissile,flo } - if(!isMissile && !(penetrationfactor >= 1f)) + if (!isMissile && !(penetrationfactor >= 1f)) { - if (BDAMath.Between(armor, 100f, 200f)) - { - damage *= 0.300f; - } - else if (BDAMath.Between(armor, 200f, 400f)) - { - damage *= 0.250f; - } - else if (BDAMath.Between(armor, 400f, 500f)) + //if (BDAMath.Between(armor, 100f, 200f)) + //{ + // damage *= 0.300f; + //} + //else if (BDAMath.Between(armor, 200f, 400f)) + //{ + // damage *= 0.250f; + //} + //else if (BDAMath.Between(armor, 400f, 500f)) + //{ + // damage *= 0.200f; + //} + + + //y=(98.34817*x)/(97.85935+x) + + _damageReduction = (113 * armor) / (154 + armor); + + + if (BDArmorySettings.DRAW_DEBUG_LABELS) { - damage *= 0.200f; + Debug.Log("[BDArmory]: Damage Before Reduction : " + Math.Round(damage, 2) / 100); + Debug.Log("[BDArmory]: Damage Reduction : " + Math.Round(_damageReduction, 2)/100); + Debug.Log("[BDArmory]: Damage After Armor : " + Math.Round(damage *= (_damageReduction / 100f))); } + + damage *= (_damageReduction / 100f); } + + return damage; } @@ -401,5 +437,10 @@ public static void CheckDamageFX(Part part) } } + + public static Vector3 GetBoundsSize(Part part) + { + return PartGeometryUtil.MergeBounds(part.GetRendererBounds(), part.transform).size; + } } } \ No newline at end of file diff --git a/BDArmory.Core/Extension/VesselExtensions.cs b/BDArmory.Core/Extension/VesselExtensions.cs index 2bb25f00b..d7bb41c37 100644 --- a/BDArmory.Core/Extension/VesselExtensions.cs +++ b/BDArmory.Core/Extension/VesselExtensions.cs @@ -21,7 +21,7 @@ public static bool InOrbit(this Vessel v) public static bool InVacuum(this Vessel v) { - return v.atmDensity <= 0.001; + return v.atmDensity <= 0.001f; } public static Vector3d Velocity(this Vessel v) diff --git a/BDArmory.Core/Module/HitpointTracker.cs b/BDArmory.Core/Module/HitpointTracker.cs index 1fbe8af04..63dede1f2 100644 --- a/BDArmory.Core/Module/HitpointTracker.cs +++ b/BDArmory.Core/Module/HitpointTracker.cs @@ -8,9 +8,12 @@ public class HitpointTracker : PartModule #region KSP Fields [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Hitpoints"), - UI_ProgressBar(affectSymCounterparts = UI_Scene.None,controlEnabled = false,scene = UI_Scene.All,maxValue = 100000,minValue = 0,requireFullControl = false)] + UI_ProgressBar(affectSymCounterparts = UI_Scene.None, controlEnabled = false, scene = UI_Scene.All, maxValue = 100000, minValue = 0, requireFullControl = false)] public float Hitpoints; + [KSPField] + bool hasPrefabRun = false; + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Armor Thickness"), UI_FloatRange(minValue = 1f, maxValue = 500f, stepIncrement = 5f, scene = UI_Scene.All)] public float Armor = 10f; @@ -38,48 +41,44 @@ public class HitpointTracker : PartModule private readonly float hitpointMultiplier = BDArmorySettings.HITPOINT_MULTIPLIER; private float previousHitpoints; - private Part _prefabPart; - private bool _setupRun = false; private bool _firstSetup = true; + private bool _updateHitpoints = false; + private bool _forceUpdateHitpointsUI = false; + private const int HpRounding = 100; - protected virtual void Setup() - { - if (_setupRun) - { - return; - } - _prefabPart = part.partInfo.partPrefab; - _setupRun = true; - } public override void OnLoad(ConfigNode node) { base.OnLoad(node); + if (!HighLogic.LoadedSceneIsEditor && !HighLogic.LoadedSceneIsFlight) return; + if (part.partInfo == null) { // Loading of the prefab from the part config - _prefabPart = part; - SetupPrefab(); + _updateHitpoints = true; } else { // Loading of the part from a saved craft if (HighLogic.LoadedSceneIsEditor) - Setup(); + { + _updateHitpoints = true; + } else enabled = false; } - } - protected virtual void SetupPrefab() + } + + public void SetupPrefab() { if (part != null) { var maxHitPoints_ = CalculateTotalHitpoints(); - if (previousHitpoints == maxHitPoints_) return; + if (!_forceUpdateHitpointsUI && previousHitpoints == maxHitPoints_) return; //Add Hitpoints UI_ProgressBar damageFieldFlight = (UI_ProgressBar)Fields["Hitpoints"].uiControlFlight; @@ -100,17 +99,17 @@ protected virtual void SetupPrefab() UI_FloatRange armorFieldEditor = (UI_FloatRange)Fields["Armor"].uiControlEditor; armorFieldEditor.maxValue = 500f; armorFieldEditor.minValue = 10f; - part.RefreshAssociatedWindows(); - if (!ArmorSet) overrideArmorSetFromConfig(); - - previousHitpoints = Hitpoints; + if (!ArmorSet) overrideArmorSetFromConfig(); + + previousHitpoints = maxHitPoints_; + hasPrefabRun = true; } else { - Debug.Log("[BDArmory]: HitpointTracker::OnStart part is null"); + Debug.Log("[BDArmory]: HitpointTracker::OnStart part is null"); } } @@ -118,7 +117,7 @@ public override void OnStart(StartState state) { isEnabled = true; - if (part != null) SetupPrefab(); + if (part != null) _updateHitpoints = true; if (HighLogic.LoadedSceneIsFlight) { @@ -126,59 +125,70 @@ public override void OnStart(StartState state) //Once started the max value of the field should be the initial one armorField.maxValue = Armor; part.RefreshAssociatedWindows(); - } + } + GameEvents.onEditorShipModified.Add(ShipModified); } - private void ShipModified(ShipConstruct data) + + + private void OnDestroy() { - SetupPrefab(); + GameEvents.onEditorShipModified.Remove(ShipModified); } - void OnGUI() + public void ShipModified(ShipConstruct data) { - if (HighLogic.LoadedSceneIsEditor && _firstSetup) - { - //SetupPrefab(); - } + _updateHitpoints = true; } - public override void OnUpdate() - { - if (!HighLogic.LoadedSceneIsFlight || !FlightGlobals.ready || Hitpoints == 0f) - { - return; - } + { + + RefreshHitPoints(); + } + + public void Update() + { + + RefreshHitPoints(); + } - if (part != null && _firstSetup) + private void RefreshHitPoints() + { + + if (_updateHitpoints) { - _firstSetup = false; SetupPrefab(); - } - } + _updateHitpoints = false; + _forceUpdateHitpointsUI = false; + } + } #region Hitpoints Functions - private float CalculateTotalHitpoints() + public float CalculateTotalHitpoints() { float hitpoints; if (!part.IsMissile()) { - //1. Density of the dry mass of the part. - var density = part.GetDensity(); - //2. Incresing density based on crash tolerance - density += Mathf.Clamp(part.crashTolerance, 10f, 30f); - - //12 square meters is the standard size of MK1 fuselage using it as a base - var areaExcess = Mathf.Max(part.GetArea() - 12f, 0); - var areaCalculation = Mathf.Min(12f, part.GetArea()) + Mathf.Pow(areaExcess, (1f / 3f)); + var averageSize = part.GetAverageBoundSize(); + var sphereRadius = averageSize * 0.5f; + var sphereSurface = 4 * Mathf.PI * sphereRadius * sphereRadius; + var structuralVolume = sphereSurface * 0.1f; + var density = (part.mass * 1000f) / structuralVolume; + density = Mathf.Clamp(density, 1000, 10000); + //Debug.Log("[BDArmory]: Hitpoint Calc" + part.name + " | structuralVolume : " + structuralVolume); + //Debug.Log("[BDArmory]: Hitpoint Calc"+part.name+" | Density : " + density); + + var structuralMass = density * structuralVolume; + //Debug.Log("[BDArmory]: Hitpoint Calc" + part.name + " | structuralMass : " + structuralMass); //3. final calculations - hitpoints = areaCalculation * density * hitpointMultiplier; - hitpoints = Mathf.Round(hitpoints/500) * 500; + hitpoints = structuralMass * hitpointMultiplier *0.33f; + hitpoints = Mathf.Round(hitpoints / HpRounding) * HpRounding; - if (hitpoints <= 0) hitpoints = 500; + if (hitpoints <= 0) hitpoints = HpRounding; } else { @@ -192,16 +202,15 @@ private float CalculateTotalHitpoints() hitpoints = maxHitPoints; } - - if (hitpoints <= 0) hitpoints = 500; + if (hitpoints <= 0) hitpoints = HpRounding; return hitpoints; } public void DestroyPart() { - if(part.mass <= 2f) part.explosionPotential *= 0.85f; + if (part.mass <= 2f) part.explosionPotential *= 0.85f; - PartExploderSystem.AddPartToExplode(part); + PartExploderSystem.AddPartToExplode(part); } public float GetMaxArmor() @@ -212,7 +221,7 @@ public float GetMaxArmor() public float GetMaxHitpoints() { - UI_ProgressBar hitpointField = (UI_ProgressBar) Fields["Hitpoints"].uiControlEditor; + UI_ProgressBar hitpointField = (UI_ProgressBar)Fields["Hitpoints"].uiControlEditor; return hitpointField.maxValue; } @@ -225,7 +234,7 @@ public void SetDamage(float partdamage) { Hitpoints -= partdamage; - if(Hitpoints <= 0) + if (Hitpoints <= 0) { DestroyPart(); } @@ -252,7 +261,7 @@ public void AddDamageToKerbal(KerbalEVA kerbal, float damage) if (Hitpoints <= 0) { // oh the humanity! - PartExploderSystem.AddPartToExplode(kerbal.part); + PartExploderSystem.AddPartToExplode(kerbal.part); } } @@ -267,14 +276,14 @@ public void ReduceArmor(float massToReduce) public void overrideArmorSetFromConfig(float thickness = 0) { - ArmorSet = true; + ArmorSet = true; if (ArmorThickness != 0) { Armor = ArmorThickness; - } + } } #endregion } -} +} \ No newline at end of file diff --git a/BDArmory.Core/Utils/BulletPhysics.cs b/BDArmory.Core/Utils/BulletPhysics.cs index f039a7839..a043edf3c 100644 --- a/BDArmory.Core/Utils/BulletPhysics.cs +++ b/BDArmory.Core/Utils/BulletPhysics.cs @@ -1,5 +1,4 @@ using UnityEngine; -using System.Collections; namespace BDArmory.Core.Utils { diff --git a/BDArmory.Core/Utils/DebugUtils.cs b/BDArmory.Core/Utils/DebugUtils.cs index c1d713102..4aa048c9b 100644 --- a/BDArmory.Core/Utils/DebugUtils.cs +++ b/BDArmory.Core/Utils/DebugUtils.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using UnityEngine; - -namespace BDArmory.Core.Utils +namespace BDArmory.Core.Utils { class DebugUtils { diff --git a/BDArmory.Core/Utils/LayerMask.cs b/BDArmory.Core/Utils/LayerMask.cs index 960ed8471..765fab644 100644 --- a/BDArmory.Core/Utils/LayerMask.cs +++ b/BDArmory.Core/Utils/LayerMask.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; - -namespace BDArmory.Core.Utils +namespace BDArmory.Core.Utils { class LayerMask { diff --git a/BDArmory/BDArmory.csproj b/BDArmory/BDArmory.csproj index 0bfd66240..9116a69d9 100644 --- a/BDArmory/BDArmory.csproj +++ b/BDArmory/BDArmory.csproj @@ -82,11 +82,11 @@ - + @@ -426,7 +426,7 @@ - + @@ -634,7 +634,7 @@ copy /Y "$(TargetDir)"BDArmory*.pdb "%25KSP_DIR%25\GameData\%25ModName%25\Plugin @echo deleting previous build ... if exist "%25DIST_DIR%25\%25ModName%25.*.zip" del "%25DIST_DIR%25\%25ModName%25.*.zip" @echo packaging new build... -call "%25ZA_DIR%25\7za.exe" a -tzip -r "%25DIST_DIR%25\%25ModName%25.@(VersionNumber)_%25DATE:~4,2%25%25DATE:~7,2%25%25DATE:~10,4%25.zip" "$(ProjectDir)Distribution\*.*" +call "%25ZA_DIR%25\7za.exe" a -tzip -r "%25DIST_DIR%25\%25ModName%25.@(VersionNumber)_%25DATE:~4,2%25%25DATE:~7,2%25%25DATE:~10,4%25%25time:~0,2%25%25time:~3,2%25.zip" "$(ProjectDir)Distribution\*.*" @echo Deploy $(ProjectDir) Distribution files to test env: %25KSP_DIR%25\GameData... @echo copying:"$(ProjectDir)Distribution\GameData" to "%25KSP_DIR%25\GameData" diff --git a/BDArmory/BDArmory.sln b/BDArmory/BDArmory.sln index 9edac5287..197553288 100644 --- a/BDArmory/BDArmory.sln +++ b/BDArmory/BDArmory.sln @@ -1,7 +1,6 @@  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 -VisualStudioVersion = 15.0.26730.16 VisualStudioVersion = 15.0.26730.8 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BDArmory", "BDArmory.csproj", "{D86F2003-1724-4F4C-BB5A-B0109CB16F35}" @@ -37,7 +36,6 @@ Global HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {EF436DDF-5293-4F33-9859-AA8492B14669} SolutionGuid = {A3A10DCC-85B5-49BC-8AAC-5547E4143101} EndGlobalSection EndGlobal diff --git a/BDArmory/Control/BDAirspeedControl.cs b/BDArmory/Control/BDAirspeedControl.cs index 9b4f965cc..776ed4ca0 100644 --- a/BDArmory/Control/BDAirspeedControl.cs +++ b/BDArmory/Control/BDAirspeedControl.cs @@ -87,7 +87,7 @@ void SetAcceleration(float accel, FlightCtrlState s) if (engineAccel == 0) { - s.mainThrottle = 0; + s.mainThrottle = accel > 0 ? 1 : 0; return; } diff --git a/BDArmory/Distribution/GameData/BDArmory/BDArmory.version b/BDArmory/Distribution/GameData/BDArmory/BDArmory.version index 05068533a..d66b102ec 100644 --- a/BDArmory/Distribution/GameData/BDArmory/BDArmory.version +++ b/BDArmory/Distribution/GameData/BDArmory/BDArmory.version @@ -12,25 +12,25 @@ { "MAJOR":1, "MINOR":2, - "PATCH":2, - "BUILD":2 + "PATCH":3, + "BUILD":0 }, "KSP_VERSION": { "MAJOR":1, - "MINOR":4, - "PATCH":5 + "MINOR":5, + "PATCH":1 }, "KSP_VERSION_MIN": { "MAJOR":1, - "MINOR":4, - "PATCH":3 + "MINOR":5, + "PATCH":1 }, "KSP_VERSION_MAX": { "MAJOR":1, - "MINOR":4, + "MINOR":5, "PATCH":999 } } diff --git a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg index eb1105960..39556ecaf 100644 --- a/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/BulletDefs/BD_Bullets.cfg @@ -320,7 +320,7 @@ BULLET { name = 30x173Bullet caliber = 30 - bulletVelocity = 1180 + bulletVelocity = 1109 bulletMass = 0.3880 //HE Bullet Values explosive = False @@ -337,11 +337,11 @@ BULLET { name = 30x173HEBullet caliber = 30 - bulletVelocity = 1180 + bulletVelocity = 1109 bulletMass = 0.3880 //HE Bullet Values explosive = True - tntMass = 0.3104 + tntMass = 0.254 blastPower = 2 blastHeat = 3.7 blastRadius = 2.5 @@ -629,7 +629,24 @@ BULLET { name = 120mmBullet caliber = 120 - bulletVelocity = 1750 + bulletVelocity = 850 + bulletMass = 12 + //HE Bullet Values + explosive = False + tntMass = 0 + blastPower = 0 + blastHeat = 0 + blastRadius = 0 + apBulletMod = 6 + bulletDragTypeName = AnalyticEstimate + +} + +BULLET +{ + name = 120mmBulletHE + caliber = 120 + bulletVelocity = 800 bulletMass = 19.6 //HE Bullet Values explosive = True @@ -642,6 +659,23 @@ BULLET } +BULLET +{ + name = 120mmBulletSabot + caliber = 120 + bulletVelocity = 1750 + bulletMass = 9 + //HE Bullet Values + explosive = False + tntMass = 0 + blastPower = 0 + blastHeat = 0 + blastRadius = 0 + apBulletMod = 20 + bulletDragTypeName = AnalyticEstimate + +} + BULLET { name = 122mmBullet @@ -659,6 +693,40 @@ BULLET } +BULLET +{ + name = 125mmBulletHE + caliber = 125 + bulletVelocity = 915 + bulletMass = 18.4 + //HE Bullet Values + explosive = True + tntMass = 8.5 + blastPower = 25 + blastHeat = 30 + blastRadius = 30 + apBulletMod = 6 + bulletDragTypeName = AnalyticEstimate + +} + +BULLET +{ + name = 125mmBulletSabot + caliber = 125 + bulletVelocity = 2050 + bulletMass = 9.52 + //HE Bullet Values + explosive = False + tntMass = 0 + blastPower = 0 + blastHeat = 0 + blastRadius = 0 + apBulletMod = 20 + bulletDragTypeName = AnalyticEstimate + +} + BULLET { name = 130Bullet diff --git a/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt b/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt index 8f01ba91e..5cc2c2edd 100644 --- a/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt +++ b/BDArmory/Distribution/GameData/BDArmory/ChangeLog.txt @@ -1,4 +1,49 @@ -v1.2.2.2a +v1.2.3 +* NEW FEATURES: + * Recompiled for KSP 1.5.1 + * EC per shot for energy weapons like Rail guns. #486 + * EMP Weapons logic. + * Modular Missiles: Min speed before guidance trigger, time between stages. + * New High Explosive resource for missiles. + * New smoke model. + * Autopilot: Orbiting direction can be set. + +* ENHANCEMENTS: + * Explosive blast forces increased. + * Hitpoints rounding reduced to 100. #432 + * Missiles can be jettisoned using action group #539 + * Max detonation range for air explosive bullets increased from 3500m to 8000m. + * Autopilot improvements: pitchKi has saner values, also steering added. + * Guard mode: Better calculation of missiles away. + * Better bullet distribution. + * FX performance improved limiting number of parallel animations. + * Better checks for missile detonations. + +* FIXES + * HE bullets now do less kinetic damage after substracting HE mass + * HitPoints calculations: values remain the same between scenes + * HitPoints calculations: bigger vessels now have more sensible HP values. #477 + * Stop explosions moving across the ground + * Fixed detonation on collision #566 + * CSV parts export now show all parts + * Fixed weapons category due to localization issues. #580 + * Stage icons fixed for KSP 1.5.1 + * Some exceptions controlled + * Heat missiles will not lock friendly vessels. #586 + * Fixed issue where modular missiles were detecting themselves as enemy vessels and detonating. + * Modular Missiles: roll correction fixed. + +* BALANCE + * Bullet mass rebalance for lower calibers #515 + * No damage reductions for lower calibers #515 + * 120mm bullet improvements. +- Thanks to SpannerMoneky, Gedas-S, DoctorDavinci, Kergan, Gomker, PapaJoesSoup, TheDogKSP, Duck1998, and Fitiales for their work on this release! + +v1.2.2.2a +* FIXES +* added in missing high speed missle fix. somehow got lost in the merge migration. + +v1.2.2.2a * FIXES * added in missing high speed missle fix. somehow got lost in the merge migration. diff --git a/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg b/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg index 77484d22b..8c9d23f5d 100644 --- a/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/Localization/localization-zh-cn.cfg @@ -6,7 +6,7 @@ #loc_BDArmory_agent_title = 巴哈姆特动力 #loc_BDArmory_agent_description = 军用武器与弹药业界的领军品牌。该公司同事也和太空计划有长期合作关系,为其提供独特的工程解决方案。 - #loc_BDArmory_part_manufacturer = 巴哈姆特动力 + #loc_BDArmory_part_manufacturer = Bahamuto Dynamics //Vulcan Turret #loc_BDArmory_part_bahaGatlingGun_title = “火神”炮塔 diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg index 7d78369bf..6952397eb 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/000000_HitpointModule_PartFixes.cfg @@ -4,9 +4,8 @@ @PART[turboJet] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 2000 ExplodeMode = Never @@ -16,9 +15,8 @@ @PART[elevon*] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 500 ExplodeMode = Never @@ -29,9 +27,8 @@ @PART[B9.Aero.Wing.Procedural.TypeB] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 500 ExplodeMode = Never @@ -41,9 +38,8 @@ @PART[winglet3] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 650 ExplodeMode = Never @@ -53,9 +49,8 @@ @PART[tailfin] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never @@ -65,9 +60,8 @@ @PART[AdvancedCanard] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never @@ -77,9 +71,8 @@ @PART[CanardController] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never @@ -89,9 +82,8 @@ @PART[nacelleBody] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 750 ExplodeMode = Never diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg index 79cf72f70..37a11cace 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Armor_CVE.cfg @@ -1,8 +1,7 @@ @PART[EHInimitzRadar] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 50 maxHitPoints = 8000 ExplodeMode = Never @@ -12,9 +11,8 @@ @PART[EHInimitz] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 300000 ExplodeMode = Never @@ -24,9 +22,8 @@ @PART[ehiNimitzBridge] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ArmorThickness = 10 maxHitPoints = 100000 ExplodeMode = Never diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg index c943a8170..6093d2004 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_Armor.cfg @@ -1,8 +1,8 @@ @PART[BD*Armor] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker + maxHitPoints = 8000 ArmorThickness = 150 } } diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg index c07d31a02..9df9455de 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/BDA_TweakScale.cfg @@ -6,3 +6,12 @@ defaultScale = 2.5 } } + +@PART[awacsRadar] +{ + %MODULE[TweakScale] + { + %name = TweakScale + %type = free + } +} \ No newline at end of file diff --git a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg index c44cd940d..16c022609 100644 --- a/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/MMPatches/Explode_Mode_Squad_Tanks.cfg @@ -2,98 +2,87 @@ @PART[fuelTank] // FL-T400 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank_long] // FL-T800 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank1-2] // Rockomax X200-32 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank2-2] // Rockomax X200-16 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank3-2] // Rockomax Jumbo-64 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTank4-2] // Rockomax X200-8 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTankSmall] // FL-T200 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[fuelTankSmallFlat] // FL-T100 Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[miniFuelTank] // Oscar-B Fuel Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[MK1Fuselage] // Mk1 Fuselage - Jet Fuel { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[miniFuselage] // Mk0 Liquid Fuel Fuselage { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @@ -101,63 +90,56 @@ // ========== MK3-Parts ======== @PART[mk3FuselageLF_25] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLF_50] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageMONO] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLFO_25] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLFO_50] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLF_100] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk3FuselageLFO_100] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @@ -165,95 +147,84 @@ @PART[adapterMk3-Mk2] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterMk3-Size2] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterMk3-Size2Slant] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize3-Mk3] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize2-Mk2] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize2-Size1] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterSize2-Size1Slant] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[adapterEngines] // Mk3 Engine Mount { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[Size3LargeTank] // Kerbodyne S3-14400 Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[Size3MediumTank] // Kerbodyne S3-7200 Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[Size3SmallTank] // Kerbodyne S3-3600 Tank { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @@ -261,80 +232,71 @@ @PART[Size3to2Adapter] // Kerbodyne ADTP-2-3 { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic - }} + } } @PART[mk2_1m_Bicoupler] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2_1m_AdapterLong] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2SpacePlaneAdapter] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2Fuselage] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageLongLFO] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageShortLiquid] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageShortLFO] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } @PART[mk2FuselageShortMono] { - MODULE + %MODULE[HitpointTracker] { - name = HitpointTracker ExplodeMode = Dynamic } } diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg index f98379bc6..8112a3231 100644 --- a/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/gau-8/gau8.cfg @@ -54,7 +54,7 @@ PART fireAnimName = fireAnim spinDownAnimation = true - roundsPerMinute = 4200 + roundsPerMinute = 3900 maxDeviation = 0.45 maxEffectiveDistance = 4000 maxTargetingRange = 5000 diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/hellfireMissile/HellfireEMP.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/hellfireMissile/HellfireEMP.cfg new file mode 100644 index 000000000..864543746 --- /dev/null +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/hellfireMissile/HellfireEMP.cfg @@ -0,0 +1,102 @@ +PART +{ +name = HellfireEMP +module = Part +author = BahamutoD / Darren9 / V8Jester + +// --- asset parameters --- +MODEL + { + model = BDArmory/Parts/hellfireMissile/model + texture = texture, BDArmory/Parts/hellfireMissile/texture + } +rescaleFactor = 1 + +// --- node definitions --- + +node_attach = 0.0, 0.089, 0, 0, 1, 0, 0 +node_stack_top = 0.0, 0.089, 0, 0, 1, 0, 0 + +// --- editor parameters --- +TechRequired = precisionEngineering +entryCost = 2100 +cost = 650 +category = Control +subcategory = 0 +title = AGM-114 Hellfire Missile EMP +manufacturer = BDAc +description = Small, quick, laser guided homing missile. +// attachment rules: stack, srfAttach, allowStack, allowSrfAttach, allowCollision +attachRules = 1,1,0,0,1 + +// --- standard part parameters --- +mass = 0.004 +dragModelType = default +maximum_drag = 0.01 +minimum_drag = 0.01 +angularDrag = 2 +crashTolerance = 5 +maxTemp = 3600 + +DRAG_CUBE +{ + cube = Default,0.02697,0.007588,0.1543,0.02701,0.007579,0.1556,0.02699,0.007581,0.1556,0.02697,0.007588,0.1543,0.002363,0.004685,0.4645,0.002363,0.006749,0.1308, -1.118E-08,1.118E-08,-0.004143, 0.1225,0.122,0.62 +} + +MODULE +{ + name = MissileLauncher + + shortName = AGM-114 + + thrust = 0.3 //KN thrust during boost phase + cruiseThrust = 0 //thrust during cruise phase + dropTime = 0 //how many seconds after release until engine ignites + boostTime = 9 //seconds of boost phase + cruiseTime = 0 //seconds of cruise phase + + guidanceActive = true //missile has guidanceActive + maxTurnRateDPS = 45 //degrees per second + + decoupleSpeed = 10 + decoupleForward = true + + + missileType = missile + homingType = AGM + targetingType = laser + maxOffBoresight = 180 + lockedSensorFOV = 7 + optimumAirspeed = 450 + DetonationDistance = 0.1 + agmDescentRatio = 1.1 + + maxAoA = 45 + + aero = true + liftArea = 0.0002 + steerMult = 0.2 + maxTorque = 1 + torqueRampUp = 25 + aeroSteerDamping = 2.5 + + minStaticLaunchRange = 200 + maxStaticLaunchRange = 6000 + + audioClipPath = BDArmory/Sounds/rocketLoop + exhaustPrefabPath = BDArmory/Models/exhaust/smallExhaust + boostExhaustPrefabPath = BDArmory/Models/exhaust/mediumExhaust +} +MODULE + { + name = BDExplosivePart + tntMass = 5 + } + +MODULE + { + name = ModuleEMP + proximity = 5000 + } + +} \ No newline at end of file diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_he.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_he.cfg new file mode 100644 index 000000000..43d2f120a --- /dev/null +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_he.cfg @@ -0,0 +1,123 @@ +PART +{ +// Kerbal Space Program - Part Config +// +// + +// --- general parameters --- +name = bahaM1Abrams +module = Part +author = BahamutoD + +// --- asset parameters --- +mesh = model.mu +rescaleFactor = 1 + + +// --- node definitions --- +node_attach = 0.0, -0.178, 0, 0, -1, 0, 0 + +// --- editor parameters --- +TechRequired = precisionEngineering +entryCost = 2100 +cost = 3500 +category = none +subcategory = 0 +title = M1 Abrams Cannon - HE +manufacturer = Bahamuto Dynamics +description = A 120mm cannon on an armored turret. CannonShells +// attachment rules: stack, srfAttach, allowStack, allowSrfAttach, allowCollision +attachRules = 0,1,0,0,1 + +// --- standard part parameters --- +mass = 2 +dragModelType = default +maximum_drag = 0.2 +minimum_drag = 0.2 +angularDrag = 2 +crashTolerance = 125 +maxTemp = 3600 + +stagingIcon = SOLID_BOOSTER + +MODULE +{ + name = ModuleTurret + + yawTransformName = aimRotate + pitchTransformName = aimPitch + + pitchSpeedDPS = 60 + yawSpeedDPS = 40 + + minPitch = -4 + maxPitch = 27 + yawRange = 360 + + smoothRotation = true + smoothMultiplier = 10 + + audioPath = BDArmory/Sounds/hydraulicLoop + maxAudioPitch = 0.42 + minAudioPitch = 0.15 + maxVolume = 0.60 +} + +MODULE +{ + name = ModuleWeapon + + fireTransformName = fireTransform + + hasDeployAnim = false + + hasFireAnimation = true + fireAnimName = fireAnim + spinDownAnimation = false + + roundsPerMinute = 10 + maxDeviation = 0.2 + maxTargetingRange = 8000 + maxEffectiveDistance = 8000 + + ammoName = CannonShells + bulletType = 120mmBulletHE + requestResourceAmount = 1 + + hasRecoil = true + onlyFireInRange = true + bulletDrop = true + + weaponType = ballistic + + projectileColor = 255, 90, 0, 190 + + tracerStartWidth = 0.27 + tracerEndWidth = 0.20 + tracerLength = 0 + tracerDeltaFactor = 3.75 + tracerLuminance = 2 + + maxHeat = 3600 + heatPerShot = 60 + heatLoss = 740 + + fireSoundPath = BDArmory/Parts/m1Abrams/sounds/shot + overheatSoundPath = BDArmory/Parts/50CalTurret/sounds/turretOverheat + oneShotSound = true + showReloadMeter = true + reloadAudioPath = BDArmory/Parts/m1Abrams/sounds/reload + +} + + + + +RESOURCE +{ + name = CannonShells + amount = 20 + maxAmount = 20 +} + +} diff --git a/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_sabot.cfg b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_sabot.cfg new file mode 100644 index 000000000..45171ce86 --- /dev/null +++ b/BDArmory/Distribution/GameData/BDArmory/Parts/m1Abrams/m1Abrams_sabot.cfg @@ -0,0 +1,123 @@ +PART +{ +// Kerbal Space Program - Part Config +// +// + +// --- general parameters --- +name = bahaM1Abrams +module = Part +author = BahamutoD + +// --- asset parameters --- +mesh = model.mu +rescaleFactor = 1 + + +// --- node definitions --- +node_attach = 0.0, -0.178, 0, 0, -1, 0, 0 + +// --- editor parameters --- +TechRequired = precisionEngineering +entryCost = 2100 +cost = 3500 +category = none +subcategory = 0 +title = M1 Abrams Cannon - Sabot +manufacturer = Bahamuto Dynamics +description = A 120mm cannon on an armored turret. CannonShells +// attachment rules: stack, srfAttach, allowStack, allowSrfAttach, allowCollision +attachRules = 0,1,0,0,1 + +// --- standard part parameters --- +mass = 2 +dragModelType = default +maximum_drag = 0.2 +minimum_drag = 0.2 +angularDrag = 2 +crashTolerance = 125 +maxTemp = 3600 + +stagingIcon = SOLID_BOOSTER + +MODULE +{ + name = ModuleTurret + + yawTransformName = aimRotate + pitchTransformName = aimPitch + + pitchSpeedDPS = 60 + yawSpeedDPS = 40 + + minPitch = -4 + maxPitch = 27 + yawRange = 360 + + smoothRotation = true + smoothMultiplier = 10 + + audioPath = BDArmory/Sounds/hydraulicLoop + maxAudioPitch = 0.42 + minAudioPitch = 0.15 + maxVolume = 0.60 +} + +MODULE +{ + name = ModuleWeapon + + fireTransformName = fireTransform + + hasDeployAnim = false + + hasFireAnimation = true + fireAnimName = fireAnim + spinDownAnimation = false + + roundsPerMinute = 10 + maxDeviation = 0.2 + maxTargetingRange = 8000 + maxEffectiveDistance = 8000 + + ammoName = CannonShells + bulletType = 120mmBulletSabot + requestResourceAmount = 1 + + hasRecoil = true + onlyFireInRange = true + bulletDrop = true + + weaponType = ballistic + + projectileColor = 255, 90, 0, 190 + + tracerStartWidth = 0.27 + tracerEndWidth = 0.20 + tracerLength = 0 + tracerDeltaFactor = 3.75 + tracerLuminance = 2 + + maxHeat = 3600 + heatPerShot = 60 + heatLoss = 740 + + fireSoundPath = BDArmory/Parts/m1Abrams/sounds/shot + overheatSoundPath = BDArmory/Parts/50CalTurret/sounds/turretOverheat + oneShotSound = true + showReloadMeter = true + reloadAudioPath = BDArmory/Parts/m1Abrams/sounds/reload + +} + + + + +RESOURCE +{ + name = CannonShells + amount = 20 + maxAmount = 20 +} + +} diff --git a/BDArmory/Distribution/GameData/BDArmory/settings.cfg b/BDArmory/Distribution/GameData/BDArmory/settings.cfg index d14874b21..ead59d1f2 100644 --- a/BDArmory/Distribution/GameData/BDArmory/settings.cfg +++ b/BDArmory/Distribution/GameData/BDArmory/settings.cfg @@ -1,14 +1,16 @@ BDASettings { INSTAKILL = False + INFINITE_AMMO = False BULLET_HITS = True + EJECT_SHELLS = True + SHELL_COLLISIONS = True + RECOIL_FACTOR = 0.75 PHYSICS_RANGE = 200000 MAX_BULLET_RANGE = 8000 MAX_GUARD_VISUAL_RANGE = 200000 - MAX_ACTIVE_RADAR_RANGE = 200000 - MAX_ENGAGEMENT_RANGE = 200000 - EJECT_SHELLS = True - INFINITE_AMMO = False + MAX_ACTIVE_RADAR_RANGE = 200000 + MAX_ENGAGEMENT_RANGE = 200000 DRAW_DEBUG_LINES = False DRAW_AIMERS = True AIM_ASSIST = True @@ -23,25 +25,24 @@ BDASettings SMOKE_DEFLECTION_FACTOR = 10 FLARE_THERMAL = 1350 RWR_WINDOW_SIZE = 1.0 - RADAR_WINDOW_SIZE = 1.0 - BDARMORY_UI_VOLUME = 0.35 + RADAR_WINDOW_SIZE = 1.0 + BDARMORY_UI_VOLUME = 0.35 BDARMORY_WEAPONS_VOLUME = 0.45 GLOBAL_LIFT_MULTIPLIER = 0.25 GLOBAL_DRAG_MULTIPLIER = 6 IVA_LOWPASS_FREQ = 2500 - PEACE_MODE = False - SHELL_COLLISIONS = True - HITPOINT_MULTIPLIER = 2.0 - RECOIL_FACTOR = 0.75 - DMG_MULTIPLIER = 100 - EXP_DMG_MOD_BALLISTIC = 1.125 - EXP_DMG_MOD_MISSILE = 6.75 - EXP_IMP_MOD = 0.125 - ADVANCED_EDIT = true + PEACE_MODE = False MAX_FIRES_PER_VESSEL = 10 FIRELIFETIME_IN_SECONDS = 90 PERFORMANCE_LOGGING = false - IGNORE_TERRAIN_CHECK = false + IGNORE_TERRAIN_CHECK = false + HITPOINT_MULTIPLIER = 3.0 + DMG_MULTIPLIER = 100 + BALLISTIC_DMG_FACTOR = 1.55 + EXP_DMG_MOD_BALLISTIC = 1.125 + EXP_DMG_MOD_MISSILE = 6.75 + EXP_IMP_MOD = 0.250 + ADVANCED_EDIT = true } BDAInputSettings { diff --git a/BDArmory/FX/BulletHitFX.cs b/BDArmory/FX/BulletHitFX.cs index 91a792a24..6d14d7a2f 100644 --- a/BDArmory/FX/BulletHitFX.cs +++ b/BDArmory/FX/BulletHitFX.cs @@ -20,7 +20,8 @@ public class BulletHitFX : MonoBehaviour public GameObject bulletHoleDecalPrefab; public static ObjectPool decalPool_small; public static ObjectPool decalPool_large; - public static Dictionary> PartsOnFire = new Dictionary>(); + public static Dictionary> PartsOnFire = new Dictionary>(); + public static Queue HitsLoaded = new Queue(); public static int MaxFiresPerVessel = 3; public static float FireLifeTimeInSeconds = 5f; @@ -124,6 +125,7 @@ private static bool CanFlamesBeAttached(Part hitPart) void Start() { + HitsLoaded.Enqueue(this); if (decalPool_large == null || decalPool_small == null) SetupShellPool(); @@ -192,8 +194,9 @@ void Update() pe.Dispose(); disabled = true; } - if (Time.time - startTime > 2f) + if (Time.time - startTime > 0.3f) { + HitsLoaded.Dequeue(); Destroy(gameObject); } } @@ -202,7 +205,9 @@ void Update() public static void CreateBulletHit(Part hitPart,Vector3 position, RaycastHit hit, Vector3 normalDirection, bool ricochet,float caliber,float penetrationfactor) { - + if (HitsLoaded.Count > 5) return; + + if (decalPool_large == null || decalPool_small == null) SetupShellPool(); diff --git a/BDArmory/FX/ExplosionFX.cs b/BDArmory/FX/ExplosionFX.cs index 93cfcb2c1..862fa9b6e 100644 --- a/BDArmory/FX/ExplosionFX.cs +++ b/BDArmory/FX/ExplosionFX.cs @@ -39,8 +39,11 @@ public class ExplosionFx : MonoBehaviour private float particlesMaxEnergy; + public static Queue ExplosionsLoaded = new Queue(); + private void Start() { + ExplosionsLoaded.Enqueue(this); StartTime = Time.time; MaxTime = (Range / ExplosionVelocity)*3f; CalculateBlastEvents(); @@ -234,13 +237,15 @@ public void Update() pe.Dispose(); } - if (ExplosionEvents.Count == 0 && TimeIndex > Math.Max(MaxTime, particlesMaxEnergy)) + if (ExplosionEvents.Count == 0 && TimeIndex > 2f*MaxTime) { if (BDArmorySettings.DRAW_DEBUG_LABELS) { Debug.Log( "[BDArmory]:Explosion Finished"); } + + ExplosionsLoaded.Dequeue(); Destroy(gameObject); return; } @@ -248,6 +253,12 @@ public void Update() public void FixedUpdate() { + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) + { + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + } + while (ExplosionEvents.Count > 0 && ExplosionEvents.Peek().TimeToImpact <= TimeIndex) { BlastHitEvent eventToExecute = ExplosionEvents.Dequeue(); @@ -369,6 +380,7 @@ private void ExecutePartBlastEvent(PartBlastHitEvent eventToExecute) public static void CreateExplosion(Vector3 position, float tntMassEquivalent, string explModelPath, string soundPath, bool isMissile = true,float caliber = 0, Part explosivePart = null, Vector3 direction = default(Vector3)) { + if (ExplosionsLoaded.Count > 5) return; var go = GameDatabase.Instance.GetModel(explModelPath); var soundClip = GameDatabase.Instance.GetAudioClip(soundPath); diff --git a/BDArmory/Misc/BDAEditorCategory.cs b/BDArmory/Misc/BDAEditorCategory.cs index f620aa513..3229bba86 100644 --- a/BDArmory/Misc/BDAEditorCategory.cs +++ b/BDArmory/Misc/BDAEditorCategory.cs @@ -124,14 +124,14 @@ void dumpParts() ); fileradars.WriteLine("NAME;TITLE;AUTHOR;MANUFACTURER;PART_MASS;PART_COST;PART_CRASHTOLERANCE;PART_MAXTEMP;radar_name;rwrThreatType;omnidirectional;directionalFieldOfView;boresightFOV;" + "scanRotationSpeed;lockRotationSpeed;lockRotationAngle;showDirectionWhileScan;multiLockFOV;lockAttemptFOV;canScan;canLock;canTrackWhileScan;canRecieveRadarData;" + - "DEPRECATED_minSignalThreshold;DEPRECATED_minLockedSignalThreshold;maxLocks;radarGroundClutterFactor;radarDetectionCurve;radarLockTrackCurve" + "maxLocks;radarGroundClutterFactor;radarDetectionCurve;radarLockTrackCurve" ); filejammers.WriteLine("NAME;TITLE;AUTHOR;MANUFACTURER;PART_MASS;PART_COST;PART_CRASHTOLERANCE;PART_MAXTEMP;alwaysOn;rcsReduction;rcsReducationFactor;lockbreaker;lockbreak_strength;jammerStrength"); Debug.Log("Dumping parts..."); // 3. iterate weapons and write out fields - foreach (var item in availableParts) + foreach (var item in PartLoader.LoadedPartsList) { weapon = null; diff --git a/BDArmory/Misc/VectorUtils.cs b/BDArmory/Misc/VectorUtils.cs index 047e41cca..fa722ecd1 100644 --- a/BDArmory/Misc/VectorUtils.cs +++ b/BDArmory/Misc/VectorUtils.cs @@ -5,6 +5,8 @@ namespace BDArmory.Misc { public static class VectorUtils { + private static System.Random RandomGen = new System.Random(); + /// Right compared to fromDirection, make sure it's not orthogonal to toDirection, or you'll get unstable signs public static float SignedAngle(Vector3 fromDirection, Vector3 toDirection, Vector3 referenceRight) { @@ -89,27 +91,17 @@ public static Vector3 GaussianDirectionDeviation(Vector3 direction, float standa } /// Random float distributed with an approximated standard normal distribution - /// https://www.johndcook.com/blog/csharp_phi/ + /// https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform /// Note a standard normal variable is technically unbounded public static float Gaussian() { - const float a1 = 0.254829592f; - const float a2 = -0.284496736f; - const float a3 = 1.421413741f; - const float a4 = -1.453152027f; - const float a5 = 1.061405429f; - const float p = 0.3275911f; - const float invsqrt2 = 0.70710678118654752440084436210485f; - - float x = UnityEngine.Random.Range(-invsqrt2, invsqrt2); - int sign = Math.Sign(x); - x = Mathf.Abs(x); - - // A&S formula 7.1.26 - float t = 1f / (1f + p * x); - float y = 1f - (((((a5 * t + a4) * t) + a3) * t + a2) * t + a1) * t * Mathf.Exp(-x * x); - - return 0.5f * (1f + sign * y); + // Technically this will raise an exception if the first random produces a zero + try { + return Mathf.Sqrt(-2 * Mathf.Log(UnityEngine.Random.value)) * Mathf.Cos(Mathf.PI * UnityEngine.Random.value); + } + catch (Exception) { // I have no idea what exception Mathf.Log raises when it gets a zero + return 0; + } } /// diff --git a/BDArmory/Modules/BDModularGuidance.cs b/BDArmory/Modules/BDModularGuidance.cs index e3be08c79..74755d358 100644 --- a/BDArmory/Modules/BDModularGuidance.cs +++ b/BDArmory/Modules/BDModularGuidance.cs @@ -9,6 +9,7 @@ using KSP.UI.Screens; using UniLinq; using UnityEngine; +using VehiclePhysics; namespace BDArmory.Modules { @@ -55,7 +56,7 @@ public class BDModularGuidance : MissileBase [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Steer Limiter"), UI_FloatRange(minValue = .1f, maxValue = 1f, stepIncrement = .05f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] public float MaxSteer = 1; - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Stages Number"), UI_FloatRange(minValue = 1f, maxValue = 5f, stepIncrement = 1f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Stages Number"), UI_FloatRange(minValue = 1f, maxValue = 9f, stepIncrement = 1f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] public float StagesNumber = 1; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Stage to Trigger On Proximity"), UI_FloatRange(minValue = 0f, maxValue = 6f, stepIncrement = 1f, scene = UI_Scene.Editor, affectSymCounterparts = UI_Scene.All)] @@ -71,11 +72,26 @@ public class BDModularGuidance : MissileBase public bool RollCorrection = false; + [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Time Between Stages"), + UI_FloatRange(minValue = 0f, maxValue = 5f, stepIncrement = 0.5f, scene = UI_Scene.Editor)] + public float timeBetweenStages = 1f; + + [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Min Speed before guidance"), + UI_FloatRange(minValue = 0f, maxValue = 1000f, stepIncrement = 50f, scene = UI_Scene.Editor)] + public float MinSpeedGuidance = 200f; + private Vector3 initialMissileRollPlane; private Vector3 initialMissileForward; private float rollError; + private bool _minSpeedAchieved = false; + private double lastRollAngle; + private double angularVelocity; + private double angularAcceleration; + private double lasAngularVelocity + ; + #endregion public TransformAxisVectors ForwardTransformAxis { get; set; } @@ -131,7 +147,11 @@ private void RefreshGuidanceMode() Fields["BallisticOverShootFactor"].guiActive = GuidanceMode == GuidanceModes.AGMBallistic; Fields["BallisticOverShootFactor"].guiActiveEditor = GuidanceMode == GuidanceModes.AGMBallistic; } - + if (Fields["SoftAscent"] != null) + { + Fields["SoftAscent"].guiActive = GuidanceMode == GuidanceModes.AGMBallistic; + Fields["SoftAscent"].guiActiveEditor = GuidanceMode == GuidanceModes.AGMBallistic; + } Misc.Misc.RefreshAssociatedWindows(part); } public override void OnFixedUpdate() @@ -140,6 +160,7 @@ public override void OnFixedUpdate() if (HasFired && !HasExploded) { UpdateGuidance(); + CheckDetonationState(); CheckDetonationDistance(); CheckDelayedFired(); CheckNextStage(); @@ -160,11 +181,26 @@ private void CheckNextStage() { if (ShouldExecuteNextStage()) { - ExecuteNextStage(); - + if (!nextStageCountdownStart) + { + this.nextStageCountdownStart = true; + this.stageCutOfftime = Time.time; + } + else + { + if ((Time.time - stageCutOfftime) >= timeBetweenStages) + { + ExecuteNextStage(); + nextStageCountdownStart = false; + } + } } } + public bool nextStageCountdownStart { get; set; } = false; + + public float stageCutOfftime { get; set; } = 0f; + private void CheckDelayedFired() { if (_missileIgnited) return; @@ -609,25 +645,39 @@ public void GuidanceSteer(FlightCtrlState s) debugString.Length = 0; if (guidanceActive && MissileReferenceTransform != null && _velocityTransform != null) { - Vector3 newTargetPosition = new Vector3(); - if (GuidanceIndex == 1) - { - newTargetPosition = AAMGuidance(); - CheckMiss(newTargetPosition); - } - else if (GuidanceIndex == 2) + if (vessel.Velocity().magnitude < MinSpeedGuidance) { - newTargetPosition = AGMGuidance(); + if (!_minSpeedAchieved) + { + s.mainThrottle = 1; + return; + } } - else if (GuidanceIndex == 3) + else { - newTargetPosition = CruiseGuidance(); + _minSpeedAchieved = true; } - else if (GuidanceIndex == 4) + + + Vector3 newTargetPosition = new Vector3(); + switch (GuidanceIndex) { - newTargetPosition = BallisticGuidance(); + case 1: + newTargetPosition = AAMGuidance(); + break; + case 2: + newTargetPosition = AGMGuidance(); + break; + case 3: + newTargetPosition = CruiseGuidance(); + break; + case 4: + newTargetPosition = BallisticGuidance(); + break; } + CheckMiss(newTargetPosition); + //Updating aero surfaces if (TimeIndex > dropTime + 0.5f) @@ -640,36 +690,54 @@ public void GuidanceSteer(FlightCtrlState s) float steerYaw = SteerMult * targetDirection.x - SteerDamping * -localAngVel.z; float steerPitch = SteerMult * targetDirection.y - SteerDamping * -localAngVel.x; + s.yaw = Mathf.Clamp(steerYaw, -MaxSteer, MaxSteer); s.pitch = Mathf.Clamp(steerPitch, -MaxSteer, MaxSteer); if (RollCorrection) { - s.roll = GetRoll(); + SetRoll(); + s.roll = Roll; } } s.mainThrottle = Throttle; } } - - private float GetRoll() + private void SetRoll() { - Vector3 rollA = this.initialMissileForward; - Vector3 rollB = Vector3.ProjectOnPlane(vessel.transform.forward, this.initialMissileRollPlane).normalized; + var vesselTransform = vessel.transform.position; + + Vector3 gravityVector = FlightGlobals.getGeeForceAtPosition(vesselTransform).normalized; + Vector3 rollVessel = -vessel.transform.right.normalized; + + var currentAngle = Vector3.SignedAngle(rollVessel, gravityVector,Vector3.Cross(rollVessel, gravityVector) ) - 90f; - var angle = Vector3.Angle(rollA, rollB); + debugString.Append($"Roll angle: {currentAngle}"); + debugString.Append(Environment.NewLine); + this.angularVelocity = currentAngle - this.lastRollAngle; + //this.angularAcceleration = angularVelocity - this.lasAngularVelocity; - var crossErrorAngle = Vector3.Cross(rollA, rollB); + var futureAngle = currentAngle + angularVelocity / Time.fixedDeltaTime * 1f; - if (crossErrorAngle.y > 0) + debugString.Append($"future Roll angle: {futureAngle}"); + + if (futureAngle > 0.5f || currentAngle > 0.5f) + { + this.Roll = Mathf.Clamp(Roll + 0.001f, 0, 1f); + } + else if (futureAngle < -0.5f || currentAngle < -0.5f) { - angle = angle * -1; + this.Roll = Mathf.Clamp(Roll - 0.001f, -1f, 0f); } + debugString.Append($"Roll value: {this.Roll}"); - return angle * (1f / -180f); + lastRollAngle = currentAngle; + //lasAngularVelocity = angularVelocity; } + public float Roll { get; set; } + private Vector3 BallisticGuidance() { return CalculateAGMBallisticGuidance(this, TargetPosition); diff --git a/BDArmory/Modules/BDModulePilotAI.cs b/BDArmory/Modules/BDModulePilotAI.cs index 07c528e51..a550284a0 100644 --- a/BDArmory/Modules/BDModulePilotAI.cs +++ b/BDArmory/Modules/BDModulePilotAI.cs @@ -71,9 +71,9 @@ Transform velocityTransform public float steerMult = 6; //make a combat steer mult and idle steer mult - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Pitch Ki"), - UI_FloatRange(minValue = 0f, maxValue = 20f, stepIncrement = .1f, scene = UI_Scene.All)] - public float pitchKiAdjust = 5; + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Steer Ki"), + UI_FloatRange(minValue = 0.01f, maxValue = 1f, stepIncrement = 0.01f, scene = UI_Scene.All)] + public float steerKiAdjust = 0.05f; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Steer Limiter"), @@ -110,7 +110,11 @@ Transform velocityTransform float maxAllowedCosAoA; float lastAllowedAoA; - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Unclamp tuning ", advancedTweakable = true), + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Orbit ", advancedTweakable = true), + UI_Toggle(enabledText = "Starboard (CW)", disabledText = "Port (CCW)", scene = UI_Scene.All),] + public bool ClockwiseOrbit = true; + + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Unclamp tuning ", advancedTweakable = true), UI_Toggle(enabledText = "Unclamped", disabledText = "Clamped", scene = UI_Scene.All),] public bool UpToEleven = false; bool toEleven = false; @@ -120,7 +124,7 @@ Transform velocityTransform { nameof(defaultAltitude), 100000f }, { nameof(minAltitude), 30000f }, { nameof(steerMult), 200f }, - { nameof(pitchKiAdjust), 400f }, + { nameof(steerKiAdjust), 20f }, { nameof(steerDamping), 100f }, { nameof(maxSpeed), 3000f }, { nameof(takeOffSpeed), 2000f }, @@ -161,6 +165,7 @@ Transform velocityTransform //Controller Integral float pitchIntegral; + float yawIntegral; //instantaneous turn radius and possible acceleration from lift //properties can be used so that other AI modules can read this for future maneuverability comparisons between craft @@ -499,7 +504,7 @@ void UpdateAI(FlightCtrlState s) if(!extending) { currentStatus = "Orbiting"; - FlyOrbit(s, assignedPositionGeo, 2000, idleSpeed, true); + FlyOrbit(s, assignedPositionGeo, 2000, idleSpeed, ClockwiseOrbit); } } @@ -802,6 +807,7 @@ float GetSteerLimiterForSpeedAndPower() } Vector3 prevTargetDir; + Vector3 debugPos; bool useVelRollTarget; void FlyToPosition(FlightCtrlState s, Vector3 targetPosition) { @@ -885,6 +891,7 @@ void FlyToPosition(FlightCtrlState s, Vector3 targetPosition) targetDirectionYaw = targetDirection; } + debugPos = vessel.transform.position + (targetPosition - vesselTransform.position) * 5000; pitchError = VectorUtils.SignedAngle(Vector3.up, Vector3.ProjectOnPlane(targetDirection, Vector3.right), Vector3.back); yawError = VectorUtils.SignedAngle(Vector3.up, Vector3.ProjectOnPlane(targetDirectionYaw, Vector3.forward), Vector3.right); @@ -945,19 +952,24 @@ void FlyToPosition(FlightCtrlState s, Vector3 targetPosition) pitchError = pitchError * Mathf.Clamp01((21 - Mathf.Exp(Mathf.Abs(rollError) / 30)) / 20); } - float steerPitch = (0.015f * steerMult * pitchError) - (steerDamping * -localAngVel.x); - float steerYaw = (0.005f * steerMult * yawError) - (steerDamping * 0.2f * -localAngVel.z); + float steerPitch = (0.015f * steerMult * pitchError) - (steerDamping * -localAngVel.x * (1 + steerKiAdjust)); + float steerYaw = (0.005f * steerMult * yawError) - (steerDamping * 0.2f * -localAngVel.z * (1 + steerKiAdjust)); pitchIntegral += pitchError; + yawIntegral += yawError; steerPitch *= dynamicAdjustment; steerYaw *= dynamicAdjustment; - float pitchKi = 0.1f * (pitchKiAdjust/5); //This is what should be allowed to be tweaked by the player, just like the steerMult, it is very low right now + float pitchKi = 0.1f * (steerKiAdjust/5); //This is what should be allowed to be tweaked by the player, just like the steerMult, it is very low right now pitchIntegral = Mathf.Clamp(pitchIntegral, -0.2f / (pitchKi * dynamicAdjustment), 0.2f / (pitchKi * dynamicAdjustment)); //0.2f is the limit of the integral variable, making it bigger increases overshoot steerPitch += pitchIntegral * pitchKi * dynamicAdjustment; //Adds the integral component to the mix - float roll = Mathf.Clamp(steerRoll, -maxSteer, maxSteer); + float yawKi = 0.1f * (steerKiAdjust / 15); + yawIntegral = Mathf.Clamp(yawIntegral, -0.2f / (yawKi * dynamicAdjustment), 0.2f / (yawKi * dynamicAdjustment)); + steerYaw += yawIntegral * yawKi * dynamicAdjustment; + + float roll = Mathf.Clamp(steerRoll, -maxSteer, maxSteer); s.roll = roll; s.yaw = Mathf.Clamp(steerYaw, -finalMaxSteer, finalMaxSteer); s.pitch = Mathf.Clamp(steerPitch, Mathf.Min(-finalMaxSteer, -0.2f), finalMaxSteer); @@ -1654,12 +1666,12 @@ void UpdateCommand(FlightCtrlState s) else if(command == PilotCommands.FlyTo) { currentStatus = "Fly To"; - FlyOrbit(s, assignedPositionGeo, 2500, idleSpeed, true); + FlyOrbit(s, assignedPositionGeo, 2500, idleSpeed, ClockwiseOrbit); } else if(command == PilotCommands.Attack) { currentStatus = "Attack"; - FlyOrbit(s, assignedPositionGeo, 4500, maxSpeed, true); + FlyOrbit(s, assignedPositionGeo, 4500, maxSpeed, ClockwiseOrbit); } } @@ -1781,6 +1793,9 @@ protected override void OnGUI() BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, debugFollowPosition, 2, Color.red); } + BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, debugPos, 5, Color.red); + BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, vesselTransform.position + vesselTransform.up * 5000, 3, Color.white); + BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position, vesselTransform.position + rollTarget, 2, Color.blue); BDGUIUtils.DrawLineBetweenWorldPositions(vesselTransform.position + (0.05f * vesselTransform.right), vesselTransform.position + (0.05f * vesselTransform.right) + angVelRollTarget, 2, Color.green); } diff --git a/BDArmory/Modules/BDModuleSurfaceAI.cs b/BDArmory/Modules/BDModuleSurfaceAI.cs index e6ecb9703..2c8fc29cd 100644 --- a/BDArmory/Modules/BDModuleSurfaceAI.cs +++ b/BDArmory/Modules/BDModuleSurfaceAI.cs @@ -29,7 +29,6 @@ public class BDModuleSurfaceAI : BDGenericAIBase, IBDAIControl float weaveDirection = 1; const float weaveLimit = 15; const float weaveFactor = 6.5f; - int sideSlipDirection = 0; Vector3 upDir; @@ -115,6 +114,14 @@ public AIUtils.VehicleMovementType SurfaceType UI_FloatRange(minValue = 0f, maxValue = 100f, stepIncrement = 1f, scene = UI_Scene.All),] public float AvoidMass = 0f; + [KSPField(isPersistant = true, guiActiveEditor = true, guiName = "Preferred broadside direction", advancedTweakable = true), + UI_ChooseOption(options = new string[3] { "Starboard", "Whatever", "Port" }, scene = UI_Scene.All),] + public string OrbitDirectionName = "Whatever"; + readonly string[] orbitDirections = new string[3] { "Starboard", "Whatever", "Port" }; + + [KSPField(isPersistant = true)] + int sideSlipDirection = 0; + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Goes up to ", advancedTweakable = true), UI_Toggle(enabledText = "eleven", disabledText = "ten", scene = UI_Scene.All), ] public bool UpToEleven = false; @@ -181,8 +188,12 @@ public override void ActivatePilot() } motorControl.Activate(); - if (BroadsideAttack) - sideSlipDirection = UnityEngine.Random.Range(0, 2) > 1 ? 1 : -1; + if (BroadsideAttack && sideSlipDirection == 0) + { + sideSlipDirection = orbitDirections.IndexOf(OrbitDirectionName); + if (sideSlipDirection == 0) + sideSlipDirection = UnityEngine.Random.Range(0, 2) > 1 ? 1 : -1; + } leftPath = true; extendingTarget = null; diff --git a/BDArmory/Modules/ClusterBomb.cs b/BDArmory/Modules/ClusterBomb.cs index 041a14f60..d7734fb64 100644 --- a/BDArmory/Modules/ClusterBomb.cs +++ b/BDArmory/Modules/ClusterBomb.cs @@ -121,13 +121,12 @@ void DeploySubmunitions() Vector3 direction = (sub.Current.transform.position - part.transform.position).normalized; Rigidbody subRB = sub.Current.GetComponent(); subRB.isKinematic = false; - subRB.velocity = part.rb.velocity + + subRB.velocity = part.rb.velocity + Krakensbane.GetFrameVelocityV3f() + (UnityEngine.Random.Range(submunitionMaxSpeed/10, submunitionMaxSpeed)*direction); Submunition subScript = sub.Current.AddComponent(); subScript.enabled = true; subScript.deployed = true; - subScript.sourceVessel = missileLauncher.SourceVessel; subScript.blastForce = missileLauncher.GetTntMass(); subScript.blastHeat = missileLauncher.blastHeat; subScript.blastRadius = missileLauncher.GetBlastRadius(); @@ -143,12 +142,11 @@ void DeploySubmunitions() Vector3 direction = (fairing.Current.transform.position - part.transform.position).normalized; Rigidbody fRB = fairing.Current.GetComponent(); fRB.isKinematic = false; - fRB.velocity = part.rb.velocity + ((submunitionMaxSpeed + 2)*direction); + fRB.velocity = part.rb.velocity + Krakensbane.GetFrameVelocityV3f() + ((submunitionMaxSpeed + 2)*direction); fairing.Current.AddComponent(); fairing.Current.GetComponent().drag = 0.2f; ClusterBombFairing fairingScript = fairing.Current.AddComponent(); fairingScript.deployed = true; - fairingScript.sourceVessel = vessel; } fairing.Dispose(); @@ -177,10 +175,8 @@ public class Submunition : MonoBehaviour public float blastHeat; public string subExplModelPath; public string subExplSoundPath; - public Vessel sourceVessel; Vector3 currPosition; Vector3 prevPosition; - Vector3 relativePos; float startTime; @@ -189,7 +185,6 @@ public class Submunition : MonoBehaviour void Start() { startTime = Time.time; - relativePos = transform.position - sourceVessel.transform.position; currPosition = transform.position; prevPosition = transform.position; rb = GetComponent(); @@ -206,59 +201,53 @@ void FixedUpdate() { if (deployed) { - if (deployed) + if (Time.time - startTime > 30) { - if (Time.time - startTime > 30) + Destroy(gameObject); + return; + } + + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) + { + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + prevPosition -= FloatingOrigin.OffsetNonKrakensbane; + } + + currPosition = transform.position; + float dist = (currPosition - prevPosition).magnitude; + Ray ray = new Ray(prevPosition, currPosition - prevPosition); + RaycastHit hit; + + if (Physics.Raycast(ray, out hit, dist, 9076737)) + { + Part hitPart = null; + try { - Destroy(gameObject); - return; + hitPart = hit.collider.gameObject.GetComponentInParent(); } - - //floatingOrigin fix - if (sourceVessel != null && - ((transform.position - sourceVessel.transform.position) - relativePos).sqrMagnitude > 800 * 800) + catch (NullReferenceException) { - transform.position = sourceVessel.transform.position + relativePos + - (rb.velocity * Time.fixedDeltaTime); + Debug.Log("[BDArmory]:NullReferenceException for Submunition Hit"); + return; } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // - - currPosition = transform.position; - float dist = (currPosition - prevPosition).magnitude; - Ray ray = new Ray(prevPosition, currPosition - prevPosition); - RaycastHit hit; - if (Physics.Raycast(ray, out hit, dist, 9076737)) + if (hitPart != null || CheckBuildingHit(hit)) { - Part hitPart = null; - try - { - hitPart = hit.collider.gameObject.GetComponentInParent(); - } - catch (NullReferenceException) - { - Debug.Log("[BDArmory]:NullReferenceException for Submunition Hit"); - return; - } - - if (hitPart?.vessel == sourceVessel) return; - - if (hitPart != null || CheckBuildingHit(hit)) - { - Detonate(hit.point); - } - else if (hitPart == null) - { - Detonate(currPosition); - } - + Detonate(hit.point); } - else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) + else if (hitPart == null) { Detonate(currPosition); } + } + else if (FlightGlobals.getAltitudeAtPos(currPosition) <= 0) + { + Detonate(currPosition); + } + + prevPosition = transform.position; } } @@ -290,10 +279,8 @@ public class ClusterBombFairing : MonoBehaviour { public bool deployed; - public Vessel sourceVessel; Vector3 currPosition; Vector3 prevPosition; - Vector3 relativePos; float startTime; Rigidbody rb; @@ -303,7 +290,6 @@ void Start() startTime = Time.time; currPosition = transform.position; prevPosition = transform.position; - relativePos = transform.position - sourceVessel.transform.position; rb = GetComponent(); } @@ -311,15 +297,12 @@ void FixedUpdate() { if (deployed) { - //floatingOrigin fix - if (sourceVessel != null && - ((transform.position - sourceVessel.transform.position) - relativePos).sqrMagnitude > 800*800) + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) { - transform.position = sourceVessel.transform.position + relativePos + - (rb.velocity*Time.fixedDeltaTime); + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + prevPosition -= FloatingOrigin.OffsetNonKrakensbane; } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // currPosition = transform.position; float dist = (currPosition - prevPosition).magnitude; diff --git a/BDArmory/Modules/MissileBase.cs b/BDArmory/Modules/MissileBase.cs index 06cc04bd2..a9947d0b1 100644 --- a/BDArmory/Modules/MissileBase.cs +++ b/BDArmory/Modules/MissileBase.cs @@ -230,7 +230,7 @@ public float Throttle private float _throttle = 1f; private float _originalDistance = float.MinValue; private Vector3 _startPoint; - + Vector3 previousPos; public string GetSubLabel() { @@ -359,7 +359,7 @@ protected void UpdateHeatTarget() if (lockFailTimer >= 0) { Ray lookRay = new Ray(transform.position, heatTarget.position + (heatTarget.velocity * Time.fixedDeltaTime) - transform.position); - heatTarget = BDATargetManager.GetHeatTarget(lookRay, lockedSensorFOV / 2, heatThreshold, allAspect); + heatTarget = BDATargetManager.GetHeatTarget(lookRay, lockedSensorFOV / 2, heatThreshold, allAspect, SourceVessel.gameObject.GetComponent()); if (heatTarget.exists) { @@ -770,7 +770,7 @@ protected void UpdateAntiRadiationTarget() } } - public void DrawDebugLine(Vector3 start, Vector3 end) + public void DrawDebugLine(Vector3 start, Vector3 end,Color color = default(Color)) { if (BDArmorySettings.DRAW_DEBUG_LINES) { @@ -778,7 +778,7 @@ public void DrawDebugLine(Vector3 start, Vector3 end) { LR = gameObject.AddComponent(); LR.material = new Material(Shader.Find("KSP/Emissive/Diffuse")); - LR.material.SetColor("_EmissiveColor", Color.red); + LR.material.SetColor("_EmissiveColor", color); } else { @@ -918,144 +918,30 @@ public void CheckDetonationState() { //Guard clauses if (!TargetAcquired) return; - //skip check of user set to zero, rely on OnCollisionEnter if missile speed is below mach 1 (340 m/s) - //otherwise use an autocalculated value based off the missiles surface speed to determine the - //detonation offset in order to prevent phasing through a part and exploding inside - if (DetonationDistance == 0) - { - if (this.vessel.srfSpeed <= 340) - { - return; - } - else - { - if (autoDetCalc) - { - _DetonationOffset = (float)((this.vessel.srfSpeed / 600) * 0.1); - - if (_DetonationOffset <= 0.1f) - { - _DetonationOffset = 0.1f; - } - } - else - { - _DetonationOffset = DetonationOffset; - } - - var targetDistancePerFrame = TargetVelocity * Time.deltaTime; - var missileDistancePerFrame = vessel.Velocity() * Time.deltaTime; - - var futureTargetPosition = (TargetPosition + targetDistancePerFrame); - var futureMissilePosition = (vessel.CoM + missileDistancePerFrame); - - switch (DetonationDistanceState) - { - case DetonationDistanceStates.NotSafe: - //Lets check if we are at a safe distance from the source vessel - Ray raySourceVessel = new Ray(futureMissilePosition, SourceVessel.CoM + SourceVessel.Velocity() * Time.deltaTime); - - var hits = Physics.RaycastAll(raySourceVessel, GetBlastRadius() * 2, 557057).AsEnumerable(); - - using (var hitsEnu = hits.GetEnumerator()) - { - while (hitsEnu.MoveNext()) - { - RaycastHit hit = hitsEnu.Current; - - try - { - var hitPart = hit.collider.gameObject.GetComponentInParent(); - - if (hitPart?.vessel == SourceVessel) - { - //We found a hit to the vessel - return; - } - } - catch - { - // ignored - } - } - } - - //We are safe and we can continue with the next state - DetonationDistanceState = DetonationDistanceStates.Cruising; - break; - case DetonationDistanceStates.Cruising: - - if (Vector3.Distance(futureMissilePosition, futureTargetPosition) < GetBlastRadius() * 10) - { - //We are now close enough to start checking the detonation distance - DetonationDistanceState = DetonationDistanceStates.CheckingProximity; - } - break; - case DetonationDistanceStates.CheckingProximity: - - float optimalDistance = (float)(_DetonationOffset + missileDistancePerFrame.magnitude); - - using (var hitsEnu = Physics.OverlapSphere(vessel.CoM, optimalDistance, 557057).AsEnumerable().GetEnumerator()) - { - while (hitsEnu.MoveNext()) - { - if (hitsEnu.Current == null) continue; - - try - { - Part partHit = hitsEnu.Current.GetComponentInParent(); - - if (partHit?.vessel == vessel) continue; - - Debug.Log("[BDArmory]: Missile proximity sphere hit | Distance overlap = " + optimalDistance + "| Part name = " + partHit.name); - - //We found a hit a different vessel than ours - DetonationDistanceState = DetonationDistanceStates.Detonate; - return; - } - catch - { - // ignored - } - } - } - - break; - } - if (BDArmorySettings.DRAW_DEBUG_LABELS) - { - Debug.Log("[BDArmory]: DetonationDistanceState = : " + DetonationDistanceState); - } - } - } - else - { - var targetDistancePerFrame = TargetVelocity * Time.deltaTime; - var missileDistancePerFrame = vessel.Velocity() * Time.deltaTime; + var targetDistancePerFrame = TargetVelocity * Time.fixedDeltaTime; + var missileDistancePerFrame = vessel.Velocity() * Time.fixedDeltaTime; var futureTargetPosition = (TargetPosition + targetDistancePerFrame); var futureMissilePosition = (vessel.CoM + missileDistancePerFrame); + var relativeSpeed = (TargetVelocity - vessel.Velocity()).magnitude * Time.fixedDeltaTime; + switch (DetonationDistanceState) { case DetonationDistanceStates.NotSafe: //Lets check if we are at a safe distance from the source vessel - Ray raySourceVessel = new Ray(futureMissilePosition, SourceVessel.CoM + SourceVessel.Velocity() * Time.deltaTime); - var hits = Physics.RaycastAll(raySourceVessel, GetBlastRadius() * 2, 557057).AsEnumerable(); - - using (var hitsEnu = hits.GetEnumerator()) + using (var hitsEnu = Physics.OverlapSphere(futureMissilePosition, GetBlastRadius() * 3f, 557057).AsEnumerable().GetEnumerator()) { while (hitsEnu.MoveNext()) { - RaycastHit hit = hitsEnu.Current; - + if (hitsEnu.Current == null) continue; try { - var hitPart = hit.collider.gameObject.GetComponentInParent(); + Part partHit = hitsEnu.Current.GetComponentInParent(); - if (hitPart?.vessel == SourceVessel) + if (partHit?.vessel == SourceVessel) { //We found a hit to the vessel return; @@ -1068,7 +954,8 @@ public void CheckDetonationState() } } - //We are safe and we can continue with the next state + //We are safe and we can continue with the cruising phase + DetonationDistanceState = DetonationDistanceStates.Cruising; break; case DetonationDistanceStates.Cruising: @@ -1081,32 +968,76 @@ public void CheckDetonationState() break; case DetonationDistanceStates.CheckingProximity: - float optimalDistance = (float)(DetonationDistance + missileDistancePerFrame.magnitude); - - using (var hitsEnu = Physics.OverlapSphere(vessel.CoM, optimalDistance, 557057).AsEnumerable().GetEnumerator()) + if (DetonationDistance == 0) { - while (hitsEnu.MoveNext()) + if (weaponClass == WeaponClasses.Bomb) return; + + if (TimeIndex > 1f && vessel.srfSpeed > part.crashTolerance) { - if (hitsEnu.Current == null) continue; + //Vector3 floatingorigin_current = FloatingOrigin.Offset; + + Ray rayFuturePosition = new Ray(vessel.CoM, futureMissilePosition); - try - { - Part partHit = hitsEnu.Current.GetComponentInParent(); + var hitsFuture = Physics.RaycastAll(rayFuturePosition, (float) missileDistancePerFrame.magnitude, 557057).AsEnumerable(); - if (partHit?.vessel == vessel) continue; + using (var hitsEnu = hitsFuture.GetEnumerator()) + { + while (hitsEnu.MoveNext()) + { + RaycastHit hit = hitsEnu.Current; - Debug.Log("[BDArmory]: Missile proximity sphere hit | Distance overlap = " + optimalDistance + "| Part name = " + partHit.name); + try + { + var hitPart = hit.collider.gameObject.GetComponentInParent(); - //We found a hit a different vessel than ours - DetonationDistanceState = DetonationDistanceStates.Detonate; - return; + if (hitPart?.vessel != SourceVessel && hitPart?.vessel != vessel ) + { + //We found a hit to other vessel + vessel.transform.position = hit.point; + DetonationDistanceState = DetonationDistanceStates.Detonate; + return; + } + } + catch + { + // ignored + } + } } - catch + } + + previousPos = part.transform.position; + + } + else + { + float optimalDistance = (float)(Math.Max(DetonationDistance, relativeSpeed)); + + using (var hitsEnu = Physics.OverlapSphere(vessel.CoM, optimalDistance, 557057).AsEnumerable().GetEnumerator()) + { + while (hitsEnu.MoveNext()) { - // ignored + if (hitsEnu.Current == null) continue; + + try + { + Part partHit = hitsEnu.Current.GetComponentInParent(); + + if (partHit?.vessel == vessel || partHit?.vessel == SourceVessel) continue; + + Debug.Log("[BDArmory]: Missile proximity sphere hit | Distance overlap = " + optimalDistance + "| Part name = " + partHit.name); + + //We found a hit a different vessel than ours + DetonationDistanceState = DetonationDistanceStates.Detonate; + return; + } + catch + { + // ignored + } } } - } + } break; } @@ -1115,7 +1046,7 @@ public void CheckDetonationState() { Debug.Log("[BDArmory]: DetonationDistanceState = : " + DetonationDistanceState); } - } + } protected void SetInitialDetonationDistance() diff --git a/BDArmory/Modules/MissileFire.cs b/BDArmory/Modules/MissileFire.cs index 5f6f4418b..b51654400 100644 --- a/BDArmory/Modules/MissileFire.cs +++ b/BDArmory/Modules/MissileFire.cs @@ -902,8 +902,7 @@ private void CalculateMissilesAway() if(missileBase.SourceVessel != this.vessel) continue; - if (missileBase.guidanceActive == true && !missileBase.HasMissed && - missileBase.MissileState != MissileBase.MissileStates.PostThrust) + if (!missileBase.HasMissed) { tempMissilesAway++; } @@ -1576,7 +1575,8 @@ IEnumerator GuardBombRoutine() hasSetCargoBays = true; } - if (targetDist > radius) + if (targetDist > radius + || Vector3.Dot(VectorUtils.GetUpDirection(vessel.CoM), vessel.transform.forward) > 0) // roll check { if (targetDist < Mathf.Max(radius * 2, 800f) && Vector3.Dot(guardTarget.CoM - bombAimerPosition, guardTarget.CoM - transform.position) < 0) @@ -3802,7 +3802,7 @@ void SearchForHeatTarget() heatTarget.predictedPosition - CurrentMissile.MissileReferenceTransform.position : CurrentMissile.GetForwardTransform(); - heatTarget = BDATargetManager.GetHeatTarget(new Ray(CurrentMissile.MissileReferenceTransform.position + (50 * CurrentMissile.GetForwardTransform()), direction), scanRadius, CurrentMissile.heatThreshold, CurrentMissile.allAspect); + heatTarget = BDATargetManager.GetHeatTarget(new Ray(CurrentMissile.MissileReferenceTransform.position + (50 * CurrentMissile.GetForwardTransform()), direction), scanRadius, CurrentMissile.heatThreshold, CurrentMissile.allAspect, this); } } @@ -3939,7 +3939,10 @@ void GuardMode() if (weapon.Current.part.partInfo.title != selectedWeapon.GetPart().partInfo.title) continue; weapon.Current.EnableWeapon(); weapon.Current.aiControlled = true; - weapon.Current.maxAutoFireCosAngle = vessel.LandedOrSplashed ? 0.9993908f : 0.9975641f; //2 : 4 degrees + if (weapon.Current.yawRange >= 5 && (weapon.Current.maxPitch - weapon.Current.minPitch) >= 5) + weapon.Current.maxAutoFireCosAngle = 1; + else + weapon.Current.maxAutoFireCosAngle = vessel.LandedOrSplashed ? 0.9993908f : 0.9975641f; //2 : 4 degrees } weapon.Dispose(); } diff --git a/BDArmory/Modules/MissileLauncher.cs b/BDArmory/Modules/MissileLauncher.cs index e5fb96819..234277a13 100644 --- a/BDArmory/Modules/MissileLauncher.cs +++ b/BDArmory/Modules/MissileLauncher.cs @@ -3,131 +3,131 @@ using System.Collections.Generic; using System.Text; using BDArmory.Core; +using BDArmory.UI; using BDArmory.Core.Extension; using BDArmory.Core.Utils; using BDArmory.FX; using BDArmory.Guidances; using BDArmory.Misc; -using BDArmory.Parts; using BDArmory.Radar; -using BDArmory.Targeting; -using BDArmory.UI; using UniLinq; using UnityEngine; +using BDArmory.Targeting; +using BDArmory.Parts; namespace BDArmory.Modules -{ - public class MissileLauncher : MissileBase +{ + public class MissileLauncher : MissileBase { #region Variable Declarations [KSPField] - public string homingType = "AAM"; + public string homingType = "AAM"; [KSPField] - public string targetingType = "none"; - + public string targetingType = "none"; + public MissileTurret missileTurret = null; - public BDRotaryRail rotaryRail = null; + public BDRotaryRail rotaryRail = null; - [KSPField] - public string exhaustPrefabPath; + [KSPField] + public string exhaustPrefabPath; - [KSPField] - public string boostExhaustPrefabPath; + [KSPField] + public string boostExhaustPrefabPath; - [KSPField] - public string boostExhaustTransformName; + [KSPField] + public string boostExhaustTransformName; #region Aero [KSPField] - public bool aero = false; - [KSPField] - public float liftArea = 0.015f; - [KSPField] - public float steerMult = 0.5f; - [KSPField] - public float torqueRampUp = 30f; - Vector3 aeroTorque = Vector3.zero; - float controlAuthority; - float finalMaxTorque; - [KSPField] - public float aeroSteerDamping = 0; + public bool aero = false; + [KSPField] + public float liftArea = 0.015f; + [KSPField] + public float steerMult = 0.5f; + [KSPField] + public float torqueRampUp = 30f; + Vector3 aeroTorque = Vector3.zero; + float controlAuthority; + float finalMaxTorque; + [KSPField] + public float aeroSteerDamping = 0; #endregion [KSPField] - public float maxTorque = 90; - - [KSPField] - public float thrust = 30; - [KSPField] - public float cruiseThrust = 3; - - [KSPField] - public float boostTime = 2.2f; - [KSPField] - public float cruiseTime = 45; - [KSPField] - public float cruiseDelay = 0; - - [KSPField] - public float maxAoA = 35; - - [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = false, guiName = "Direction: "), - UI_Toggle(disabledText = "Lateral", enabledText = "Forward")] - public bool decoupleForward = false; + public float maxTorque = 90; + + [KSPField] + public float thrust = 30; + [KSPField] + public float cruiseThrust = 3; + + [KSPField] + public float boostTime = 2.2f; + [KSPField] + public float cruiseTime = 45; + [KSPField] + public float cruiseDelay = 0; + + [KSPField] + public float maxAoA = 35; + + [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = false, guiName = "Direction: "), + UI_Toggle(disabledText = "Lateral", enabledText = "Forward")] + public bool decoupleForward = false; [KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Decouple Speed"), UI_FloatRange(minValue = 0f, maxValue = 10f, stepIncrement = 0.1f, scene = UI_Scene.Editor)] public float decoupleSpeed = 0; [KSPField] - public float optimumAirspeed = 220; - - [KSPField] - public float blastRadius = 150; + public float optimumAirspeed = 220; + + [KSPField] + public float blastRadius = 150; [KSPField] public float blastPower = 25; [KSPField] - public float blastHeat = -1; + public float blastHeat = -1; [KSPField] - public float maxTurnRateDPS = 20; + public float maxTurnRateDPS = 20; [KSPField] - public bool proxyDetonate = true; - - [KSPField] - public string audioClipPath = string.Empty; + public bool proxyDetonate = true; - AudioClip thrustAudio; + [KSPField] + public string audioClipPath = string.Empty; - [KSPField] - public string boostClipPath = string.Empty; + AudioClip thrustAudio; + + [KSPField] + public string boostClipPath = string.Empty; + + AudioClip boostAudio; + + [KSPField] + public bool isSeismicCharge = false; + + [KSPField] + public float rndAngVel = 0; - AudioClip boostAudio; - - [KSPField] - public bool isSeismicCharge = false; - - [KSPField] - public float rndAngVel = 0; - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Max Altitude"), UI_FloatRange(minValue = 0f, maxValue = 5000f, stepIncrement = 10f, scene = UI_Scene.All)] public float maxAltitude = 0f; [KSPField] - public string rotationTransformName = string.Empty; - Transform rotationTransform; + public string rotationTransformName = string.Empty; + Transform rotationTransform; - [KSPField] - public bool terminalManeuvering = false; + [KSPField] + public bool terminalManeuvering = false; [KSPField] public string terminalGuidanceType = ""; @@ -139,87 +139,87 @@ public class MissileLauncher : MissileBase public bool terminalGuidanceShouldActivate = true; [KSPField] - public string explModelPath = "BDArmory/Models/explosion/explosion"; - - public string explSoundPath = "BDArmory/Sounds/explode1"; - - [KSPField] - public bool spoolEngine = false; - - [KSPField] - public bool hasRCS = false; - [KSPField] - public float rcsThrust = 1; - float rcsRVelThreshold = 0.13f; - KSPParticleEmitter upRCS; - KSPParticleEmitter downRCS; - KSPParticleEmitter leftRCS; - KSPParticleEmitter rightRCS; - KSPParticleEmitter forwardRCS; - float rcsAudioMinInterval = 0.2f; - - private AudioSource audioSource; - public AudioSource sfAudioSource; - List pEmitters; - List gaplessEmitters; - - float cmTimer; - - //deploy animation - [KSPField] - public string deployAnimationName = ""; - - [KSPField] - public float deployedDrag = 0.02f; - - [KSPField] - public float deployTime = 0.2f; + public string explModelPath = "BDArmory/Models/explosion/explosion"; - [KSPField] - public bool useSimpleDrag = false; + public string explSoundPath = "BDArmory/Sounds/explode1"; [KSPField] - public float simpleDrag = 0.02f; + public bool spoolEngine = false; [KSPField] - public float simpleStableTorque = 5; + public bool hasRCS = false; + [KSPField] + public float rcsThrust = 1; + float rcsRVelThreshold = 0.13f; + KSPParticleEmitter upRCS; + KSPParticleEmitter downRCS; + KSPParticleEmitter leftRCS; + KSPParticleEmitter rightRCS; + KSPParticleEmitter forwardRCS; + float rcsAudioMinInterval = 0.2f; + + private AudioSource audioSource; + public AudioSource sfAudioSource; + List pEmitters; + List gaplessEmitters; + + float cmTimer; + + //deploy animation + [KSPField] + public string deployAnimationName = ""; - [KSPField] - public Vector3 simpleCoD = new Vector3(0,0,-1); + [KSPField] + public float deployedDrag = 0.02f; - [KSPField] - public float agmDescentRatio = 1.45f; - - float currentThrust; - - public bool deployed; - //public float deployedTime; - - AnimationState[] deployStates; - - bool hasPlayedFlyby; - - float debugTurnRate; + [KSPField] + public float deployTime = 0.2f; - List boosters; - [KSPField] - public bool decoupleBoosters = false; - [KSPField] - public float boosterDecoupleSpeed = 5; - [KSPField] - public float boosterMass = 0; + [KSPField] + public bool useSimpleDrag = false; - Transform vesselReferenceTransform; + [KSPField] + public float simpleDrag = 0.02f; - [KSPField] - public string boostTransformName = string.Empty; - List boostEmitters; - List boostGaplessEmitters; - - [KSPField] - public bool torpedo = false; - [KSPField] - public float waterImpactTolerance = 25; + [KSPField] + public float simpleStableTorque = 5; + + [KSPField] + public Vector3 simpleCoD = new Vector3(0, 0, -1); + + [KSPField] + public float agmDescentRatio = 1.45f; + + float currentThrust; + + public bool deployed; + //public float deployedTime; + + AnimationState[] deployStates; + + bool hasPlayedFlyby; + + float debugTurnRate; + + List boosters; + [KSPField] + public bool decoupleBoosters = false; + [KSPField] + public float boosterDecoupleSpeed = 5; + [KSPField] + public float boosterMass = 0; + + Transform vesselReferenceTransform; + + [KSPField] + public string boostTransformName = string.Empty; + List boostEmitters; + List boostGaplessEmitters; + + [KSPField] + public bool torpedo = false; + [KSPField] + public float waterImpactTolerance = 25; //ballistic options [KSPField] @@ -284,6 +284,12 @@ public override void Jettison() if (BDArmorySetup.Instance.ActiveWeaponManager != null) BDArmorySetup.Instance.ActiveWeaponManager.UpdateList(); } + [KSPAction("Jettison")] + public void AGJettsion(KSPActionParam param) + { + Jettison(); + } + void ParseWeaponClass() { missileType = missileType.ToLower(); @@ -869,7 +875,7 @@ public override void OnFixedUpdate() private void CheckMiss() { float sqrDist = ((TargetPosition + (TargetVelocity * Time.fixedDeltaTime)) - (transform.position + (part.rb.velocity * Time.fixedDeltaTime))).sqrMagnitude; - if (sqrDist < 160000 || (MissileState == MissileStates.PostThrust && (GuidanceMode == GuidanceModes.AAMLead || GuidanceMode == GuidanceModes.AAMPure))) + if (sqrDist < 160000 || MissileState == MissileStates.PostThrust) { checkMiss = true; } @@ -1085,7 +1091,7 @@ private void UpdateTerminalGuidance() { case TargetingModes.Heat: // get ground heat targets - heatTarget = BDATargetManager.GetHeatTarget(new Ray(transform.position + (50 * GetForwardTransform()), TargetPosition - GetForwardTransform()), terminalGuidanceDistance, heatThreshold, true, null, true); + heatTarget = BDATargetManager.GetHeatTarget(new Ray(transform.position + (50 * GetForwardTransform()), TargetPosition - GetForwardTransform()), terminalGuidanceDistance, heatThreshold, true, SourceVessel.gameObject.GetComponent(), true); if (heatTarget.exists) { if (BDArmorySettings.DRAW_DEBUG_LABELS) diff --git a/BDArmory/Modules/ModuleDrainEC.cs b/BDArmory/Modules/ModuleDrainEC.cs index 9118dc220..06d6e893d 100644 --- a/BDArmory/Modules/ModuleDrainEC.cs +++ b/BDArmory/Modules/ModuleDrainEC.cs @@ -1,176 +1,176 @@ -using System.Linq; - -namespace BDArmory.Modules -{ - public class ModuleDrainEC : PartModule - { - public bool armed = true; - private bool setup = true; - private int minCrew = 0; - - public override void OnStart(StartState state) - { - if (HighLogic.LoadedSceneIsFlight) - { - part.force_activate(); - vessel.OnFlyByWire += ThrottleControl; - part.OnJustAboutToBeDestroyed += EnableVessel; - } - base.OnStart(state); - } - - public void Update() - { - if (HighLogic.LoadedSceneIsFlight) - { - if (armed) - { - DisableVessel(); - } - else - { - EnableVessel(); - } - } - } - - void ThrottleControl(FlightCtrlState s) - { - this.vessel.Autopilot.Enabled = false; - s.mainThrottle = 0; - s.rollTrim += 0.1f; - s.wheelSteerTrim += 0.1f; - s.yawTrim += 0.1f; - s.yaw += 0.1f; - s.roll += 0.1f; - s.pitch -= 0.1f; - s.pitchTrim -= 0.1f; - } - - private void EnableVessel() - { - foreach (Part p in vessel.parts) - { - var command = p.FindModuleImplementing(); - - if (command != null) - { - //command.minimumCrew = minCrew; - } - - foreach (ModuleEnginesFX engineFX in p.Modules) - { - engineFX.allowRestart = true; - } - - foreach (ModuleEngines engine in p.Modules) - { - engine.allowRestart = true; - } - } - - Destroy(this); - } - - private void DisableVessel() - { - vessel.OnFlyByWire -= ThrottleControl; - vessel.OnFlyByWire += ThrottleControl; - - if (setup) - { - setup = false; - - foreach (Part p in this.vessel.parts) - { - var camera = p.FindModuleImplementing(); - var radar = p.FindModuleImplementing(); - var spaceRadar = p.FindModuleImplementing(); - - if (radar != null) - { - if (radar.radarEnabled) - { - radar.DisableRadar(); - } - } - - if (spaceRadar != null) - { - if (spaceRadar.radarEnabled) - { - spaceRadar.DisableRadar(); - } - } - - if (camera != null) - { - if (camera.cameraEnabled) - { - camera.DisableCamera(); - } - } - - var command = p.FindModuleImplementing(); - var weapon = p.FindModuleImplementing(); - var turret = p.FindModuleImplementing(); - - if (turret != null) - { - turret.maxPitch = 0; - turret.yawRange = 0; - turret.yawRangeLimit = 0; - } - - if (weapon != null) - { - weapon.onlyFireInRange = true; - weapon.engageRangeMax = 0; - weapon.engageRangeMin = 0; - weapon.engageSLW = false; - weapon.engageMissile = false; - weapon.engageGround = false; - weapon.engageAir = false; - } - - if (command != null) - { - minCrew = command.minimumCrew; - //command.minimumCrew = 100; - } - - var PAI = this.vessel.FindPartModuleImplementing(); - var SAI = this.vessel.FindPartModuleImplementing(); - - if (SAI != null) - { - if (SAI.pilotEnabled) - { - SAI.TogglePilot(); - } - } - - if (PAI != null) - { - if (PAI.pilotEnabled) - { - PAI.TogglePilot(); - } - } - } - } - - foreach (Part p in vessel.parts) - { - PartResource r = p.Resources.Where(pr => pr.resourceName == "ElectricCharge").FirstOrDefault(); - if (r != null) - { - if (r.amount >= 0) - { - p.RequestResource("ElectricCharge", r.amount); - } - } - } - } - } +using System.Linq; + +namespace BDArmory.Modules +{ + public class ModuleDrainEC : PartModule + { + public bool armed = true; + private bool setup = true; + private int minCrew = 0; + + public override void OnStart(StartState state) + { + if (HighLogic.LoadedSceneIsFlight) + { + part.force_activate(); + vessel.OnFlyByWire += ThrottleControl; + part.OnJustAboutToBeDestroyed += EnableVessel; + } + base.OnStart(state); + } + + public void Update() + { + if (HighLogic.LoadedSceneIsFlight) + { + if (armed) + { + DisableVessel(); + } + else + { + EnableVessel(); + } + } + } + + void ThrottleControl(FlightCtrlState s) + { + this.vessel.Autopilot.Enabled = false; + s.mainThrottle = 0; + s.rollTrim += 0.1f; + s.wheelSteerTrim += 0.1f; + s.yawTrim += 0.1f; + s.yaw += 0.1f; + s.roll += 0.1f; + s.pitch -= 0.1f; + s.pitchTrim -= 0.1f; + } + + private void EnableVessel() + { + foreach (Part p in vessel.parts) + { + var command = p.FindModuleImplementing(); + + if (command != null) + { + //command.minimumCrew = minCrew; + } + + foreach (ModuleEnginesFX engineFX in p.Modules) + { + engineFX.allowRestart = true; + } + + foreach (ModuleEngines engine in p.Modules) + { + engine.allowRestart = true; + } + } + + Destroy(this); + } + + private void DisableVessel() + { + vessel.OnFlyByWire -= ThrottleControl; + vessel.OnFlyByWire += ThrottleControl; + + if (setup) + { + setup = false; + + foreach (Part p in this.vessel.parts) + { + var camera = p.FindModuleImplementing(); + var radar = p.FindModuleImplementing(); + var spaceRadar = p.FindModuleImplementing(); + + if (radar != null) + { + if (radar.radarEnabled) + { + radar.DisableRadar(); + } + } + + if (spaceRadar != null) + { + if (spaceRadar.radarEnabled) + { + spaceRadar.DisableRadar(); + } + } + + if (camera != null) + { + if (camera.cameraEnabled) + { + camera.DisableCamera(); + } + } + + var command = p.FindModuleImplementing(); + var weapon = p.FindModuleImplementing(); + var turret = p.FindModuleImplementing(); + + if (turret != null) + { + turret.maxPitch = 0; + turret.yawRange = 0; + turret.yawRangeLimit = 0; + } + + if (weapon != null) + { + weapon.onlyFireInRange = true; + weapon.engageRangeMax = 0; + weapon.engageRangeMin = 0; + weapon.engageSLW = false; + weapon.engageMissile = false; + weapon.engageGround = false; + weapon.engageAir = false; + } + + if (command != null) + { + minCrew = command.minimumCrew; + //command.minimumCrew = 100; + } + + var PAI = this.vessel.FindPartModuleImplementing(); + var SAI = this.vessel.FindPartModuleImplementing(); + + if (SAI != null) + { + if (SAI.pilotEnabled) + { + SAI.TogglePilot(); + } + } + + if (PAI != null) + { + if (PAI.pilotEnabled) + { + PAI.TogglePilot(); + } + } + } + } + + foreach (Part p in vessel.parts) + { + PartResource r = p.Resources.Where(pr => pr.resourceName == "ElectricCharge").FirstOrDefault(); + if (r != null) + { + if (r.amount >= 0) + { + p.RequestResource("ElectricCharge", r.amount); + } + } + } + } + } } \ No newline at end of file diff --git a/BDArmory/Modules/ModuleEMP.cs b/BDArmory/Modules/ModuleEMP.cs index 072c13270..6c0098a90 100644 --- a/BDArmory/Modules/ModuleEMP.cs +++ b/BDArmory/Modules/ModuleEMP.cs @@ -1,52 +1,52 @@ - -namespace BDArmory.Modules -{ - public class ModuleEMP : PartModule - { - [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = false, guiName = "EMP Blast Radius"), - UI_Label(affectSymCounterparts = UI_Scene.All, controlEnabled = true, scene = UI_Scene.All)] - public float proximity = 5000; - - public override void OnStart(StartState state) - { - if (HighLogic.LoadedSceneIsFlight) - { - part.force_activate(); - part.OnJustAboutToBeDestroyed += DetonateEMPRoutine; - } - base.OnStart(state); - } - - public void DetonateEMPRoutine() - { - foreach (Vessel v in FlightGlobals.Vessels) - { - if (!v.HoldPhysics) - { - double targetDistance = Vector3d.Distance(this.vessel.GetWorldPos3D(), v.GetWorldPos3D()); - - if (targetDistance <= proximity) - { - var count = 0; - - foreach (Part p in v.parts) - { - var wmPart = p.FindModuleImplementing(); - - if (wmPart != null) - { - count = 1; - p.AddModule("ModuleDrainEC"); - } - } - - if (count == 0) - { - v.rootPart.AddModule("ModuleDrainEC"); - } - } - } - } - } - } + +namespace BDArmory.Modules +{ + public class ModuleEMP : PartModule + { + [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = false, guiName = "EMP Blast Radius"), + UI_Label(affectSymCounterparts = UI_Scene.All, controlEnabled = true, scene = UI_Scene.All)] + public float proximity = 5000; + + public override void OnStart(StartState state) + { + if (HighLogic.LoadedSceneIsFlight) + { + part.force_activate(); + part.OnJustAboutToBeDestroyed += DetonateEMPRoutine; + } + base.OnStart(state); + } + + public void DetonateEMPRoutine() + { + foreach (Vessel v in FlightGlobals.Vessels) + { + if (!v.HoldPhysics) + { + double targetDistance = Vector3d.Distance(this.vessel.GetWorldPos3D(), v.GetWorldPos3D()); + + if (targetDistance <= proximity) + { + var count = 0; + + foreach (Part p in v.parts) + { + var wmPart = p.FindModuleImplementing(); + + if (wmPart != null) + { + count = 1; + p.AddModule("ModuleDrainEC"); + } + } + + if (count == 0) + { + v.rootPart.AddModule("ModuleDrainEC"); + } + } + } + } + } + } } \ No newline at end of file diff --git a/BDArmory/Modules/ModuleRadar.cs b/BDArmory/Modules/ModuleRadar.cs index 8035fc08c..aa33f0451 100644 --- a/BDArmory/Modules/ModuleRadar.cs +++ b/BDArmory/Modules/ModuleRadar.cs @@ -119,7 +119,6 @@ public class ModuleRadar : PartModule #endregion - #region KSP Events & Actions [KSPAction("Toggle Radar")] public void AGEnable(KSPActionParam param) @@ -161,7 +160,6 @@ public void TargetPrev(KSPActionParam param) #endregion - #region Part members //locks [KSPField(isPersistant = false, guiActive = true, guiActiveEditor = false, guiName = "Current Locks")] @@ -266,15 +264,13 @@ public MissileFire weaponManager public float leftLimit; public float rightLimit; private int snapshotTicker; - #endregion - + #endregion void UpdateToggleGuiName() { Events["Toggle"].guiName = radarEnabled ? "Disable Radar" : "Enable Radar"; } - public void EnsureVesselRadarData() { @@ -290,7 +286,6 @@ public void EnsureVesselRadarData() vesselRadarData.weaponManager = weaponManager; } } - public void EnableRadar() { @@ -313,7 +308,6 @@ public void EnableRadar() UpdateToggleGuiName(); vesselRadarData.AddRadar(this); } - public void DisableRadar() { @@ -339,7 +333,6 @@ public void DisableRadar() vrd.Dispose(); } - void OnDestroy() { if (HighLogic.LoadedSceneIsFlight) @@ -370,7 +363,6 @@ void OnDestroy() } } - public override void OnStart(StartState state) { base.OnStart(state); @@ -451,7 +443,6 @@ public override void OnStart(StartState state) Debug.Log("[BDArmory]: WARNING: " + part.name + " has legacy definition, missing new radarDetectionCurve and radarLockTrackCurve definitions! Please update for the part to be usable!"); } } - /* void OnGoOnRails(Vessel v) { @@ -488,8 +479,7 @@ IEnumerator StartUpRoutine() UpdateToggleGuiName(); startupComplete = true; } - - + void Update() { if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && !vessel.packed && radarEnabled) @@ -513,8 +503,7 @@ void Update() drawGUI = (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && !vessel.packed && radarEnabled && vessel.isActiveVessel && BDArmorySetup.GAME_UI_ENABLED && !MapView.MapIsEnabled); } - - + void FixedUpdate() { if (HighLogic.LoadedSceneIsFlight && FlightGlobals.ready && startupComplete) @@ -552,8 +541,7 @@ void FixedUpdate() } } - - + void UpdateSlaveData() { if (slaveTurrets && weaponManager) @@ -568,8 +556,7 @@ void UpdateSlaveData() } } } - - + void LateUpdate() { if (HighLogic.LoadedSceneIsFlight && (canScan || canLock)) @@ -577,8 +564,7 @@ void LateUpdate() UpdateModel(); } } - - + void UpdateModel() { //model rotation @@ -634,8 +620,7 @@ void UpdateModel() } } } - - + void Scan() { float angleDelta = scanRotationSpeed*Time.fixedDeltaTime; @@ -681,7 +666,6 @@ void Scan() } } - public bool TryLockTarget(Vector3 position) { if (!canLock) @@ -711,7 +695,7 @@ public bool TryLockTarget(Vector3 position) for (int i = 0; i < attemptedLocks.Length; i++) { - if (attemptedLocks[i].exists && (attemptedLocks[i].predictedPosition - position).sqrMagnitude < 40*40) + if (attemptedLocks[i].exists && (attemptedLocks[i].predictedPosition - position).sqrMagnitude < 40 * 40) { if (!locked && !omnidirectional) { @@ -736,9 +720,8 @@ public bool TryLockTarget(Vector3 position) Debug.Log("[BDArmory]: - Failed to lock on target."); return false; - } + } - void BoresightScan() { if (locked) @@ -758,8 +741,7 @@ void BoresightScan() return; } } - - + void UpdateLock(int index) { TargetSignatureData lockedTarget = lockedTargets[index]; @@ -835,8 +817,7 @@ void UpdateLock(int index) } } } - - + public void UnlockAllTargets() { if (!locked) return; @@ -853,8 +834,7 @@ public void UnlockAllTargets() if (BDArmorySettings.DRAW_DEBUG_LABELS) Debug.Log("[BDArmory]: Radar Targets were cleared (" + radarName + ")."); } - - + public void SetActiveLock(TargetSignatureData target) { for (int i = 0; i < lockedTargets.Count; i++) @@ -866,8 +846,7 @@ public void SetActiveLock(TargetSignatureData target) } } } - - + public void UnlockTargetAt(int index, bool tryRelock = false) { Vessel rVess = lockedTargets[index].vessel; @@ -899,15 +878,13 @@ public void UnlockTargetAt(int index, bool tryRelock = false) vesselRadarData.RemoveVesselFromTargets(rVess); } } - - + IEnumerator RetryLockRoutine(Vessel v) { yield return null; vesselRadarData.TryLockTarget(v); } - - + public void UnlockTargetVessel(Vessel v) { for (int i = 0; i < lockedTargets.Count; i++) @@ -919,8 +896,7 @@ public void UnlockTargetVessel(Vessel v) } } } - - + void SlaveTurrets() { List.Enumerator mtc = vessel.FindPartModulesImplementing().GetEnumerator(); @@ -941,8 +917,7 @@ void SlaveTurrets() slaveTurrets = true; } - - + void UnslaveTurrets() { List.Enumerator mtc = vessel.FindPartModulesImplementing().GetEnumerator(); @@ -966,8 +941,7 @@ void UnslaveTurrets() slaveTurrets = false; } - - + public void UpdateLockedTargetInfo(TargetSignatureData newData) { int index = -1; @@ -983,8 +957,7 @@ public void UpdateLockedTargetInfo(TargetSignatureData newData) lockedTargets[index] = newData; } } - - + public void ReceiveContactData(TargetSignatureData contactData, bool _locked) { if (vesselRadarData) @@ -1003,8 +976,7 @@ public void ReceiveContactData(TargetSignatureData contactData, bool _locked) } vrd.Dispose(); } - - + public void AddExternalVRD(VesselRadarData vrd) { if (!linkedToVessels.Contains(vrd)) @@ -1012,14 +984,12 @@ public void AddExternalVRD(VesselRadarData vrd) linkedToVessels.Add(vrd); } } - - + public void RemoveExternalVRD(VesselRadarData vrd) { linkedToVessels.Remove(vrd); } - - + void OnGUI() { if (drawGUI) @@ -1031,8 +1001,7 @@ void OnGUI() } } } - - + public void RecoverLinkedVessels() { string[] vesselIDs = linkedVesselID.Split(new char[] {','}); @@ -1041,8 +1010,7 @@ public void RecoverLinkedVessels() StartCoroutine(RecoverLinkedVesselRoutine(vesselIDs[i])); } } - - + IEnumerator RecoverLinkedVesselRoutine(string vesselID) { while (true) @@ -1062,8 +1030,7 @@ IEnumerator RecoverLinkedVesselRoutine(string vesselID) yield return new WaitForSeconds(0.5f); } } - - + IEnumerator RelinkVRDWhenReadyRoutine(VesselRadarData vrd) { while (!vrd.radarsReady || vrd.vessel.packed) @@ -1075,8 +1042,7 @@ IEnumerator RelinkVRDWhenReadyRoutine(VesselRadarData vrd) Debug.Log("[BDArmory]: Radar data link recovered: Local - " + vessel.vesselName + ", External - " + vrd.vessel.vesselName); } - - + public string getRWRType(int i) { switch (i) @@ -1099,7 +1065,6 @@ public string getRWRType(int i) //{SAM = 0, Fighter = 1, AWACS = 2, MissileLaunch = 3, MissileLock = 4, Detection = 5, Sonar = 6} } - // RMB info in editor public override string GetInfo() { @@ -1142,8 +1107,7 @@ public override string GetInfo() return output.ToString(); } - - + void DrainElectricity() { if (resourceDrain <= 0) diff --git a/BDArmory/Modules/ModuleWeapon.cs b/BDArmory/Modules/ModuleWeapon.cs index 53aa48d29..977a69237 100644 --- a/BDArmory/Modules/ModuleWeapon.cs +++ b/BDArmory/Modules/ModuleWeapon.cs @@ -20,10 +20,6 @@ public class ModuleWeapon : EngageableWeapon, IBDWeapon { #region Declarations - #region Variables - - #endregion - public static ObjectPool bulletPool; public static ObjectPool shellPool; @@ -252,7 +248,7 @@ public string GetMissileType() [KSPField] public float roundsPerMinute = 850; //rate of fire [KSPField] - public float maxDeviation = 1; //max inaccuracy deviation in degrees + public float maxDeviation = 1; //inaccuracy two standard deviations in degrees (two because backwards compatibility :) [KSPField] public float maxEffectiveDistance = 2500; //used by AI to select appropriate weapon [KSPField] @@ -263,6 +259,8 @@ public string GetMissileType() public float bulletDmgMult = 1; //Used for heat damage modifier for non-explosive bullets [KSPField] public float bulletVelocity = 1030; //velocity in meters/second + [KSPField] + public float ECPerShot = 0; //EC to use per shot for weapons like railguns [KSPField] public string bulletDragTypeName = "AnalyticEstimate"; @@ -408,7 +406,7 @@ public string GetMissileType() public bool proximityDetonation = false; [KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "Default Detonation Range"), - UI_FloatRange(minValue = 500, maxValue = 3500f, stepIncrement = 1f, scene = UI_Scene.All)] + UI_FloatRange(minValue = 500, maxValue = 8000f, stepIncrement = 5f, scene = UI_Scene.All)] public float defaultDetonationRange = 3500; [KSPField] @@ -524,11 +522,25 @@ IEnumerator FireHoldRoutine(KSPActionGroup group) #region KSP Events + public override void OnAwake() + { + base.OnAwake(); + + part.stagingIconAlwaysShown = true; + this.part.stackIconGrouping = StackIconGrouping.SAME_TYPE; + } + public override void OnStart(StartState state) { base.OnStart(state); - ParseWeaponType(); + part.stagingIconAlwaysShown = true; + this.part.stackIconGrouping = StackIconGrouping.SAME_TYPE; + + GameEvents.onVesselSwitching.Add(ReloadIconOnVesselSwitch); + + + ParseWeaponType(); // extension for feature_engagementenvelope InitializeEngagementRange(0, maxEffectiveDistance); @@ -689,6 +701,18 @@ public override void OnStart(StartState state) BDArmorySetup.OnVolumeChange += UpdateVolume; } + private void ReloadIconOnVesselSwitch(Vessel data0, Vessel data1) + { + if (part == null) return; + if (part.vessel == null) return; + + if (part.vessel.isActiveVessel) + { + part.stagingIconAlwaysShown = true; + this.part.stackIconGrouping = StackIconGrouping.SAME_TYPE; + } + } + void OnDestroy() { BDArmorySetup.OnVolumeChange -= UpdateVolume; @@ -770,11 +794,6 @@ void FixedUpdate() return; } - if (part.stackIcon.StageIcon == null) - { - part.stackIcon.CreateIcon(); - } - if (vessel.isActiveVessel) { @@ -793,9 +812,6 @@ void FixedUpdate() if (weaponState == WeaponStates.Enabled && (TimeWarp.WarpMode != TimeWarp.Modes.HIGH || TimeWarp.CurrentRate == 1)) { - UpdateTargetVessel(); - updateAcceleration(targetVelocity); - relativeVelocity = targetVelocity - vessel.rb_velocity; //Aim(); StartCoroutine(AimAndFireAtEndOfFrame()); @@ -825,50 +841,6 @@ void FixedUpdate() } audioSource.Stop(); } - - - //autofiring with AI - if (targetAcquired && aiControlled) - { - Transform fireTransform = fireTransforms[0]; - Vector3 targetRelPos = (finalAimTarget) - fireTransform.position; - Vector3 aimDirection = fireTransform.forward; - float targetCosAngle = Vector3.Dot(aimDirection, targetRelPos.normalized); - - Vector3 targetDiffVec = finalAimTarget - lastFinalAimTarget; - Vector3 projectedTargetPos = targetDiffVec; - //projectedTargetPos /= TimeWarp.fixedDeltaTime; - //projectedTargetPos *= TimeWarp.fixedDeltaTime; - projectedTargetPos *= 2; //project where the target will be in 2 timesteps - projectedTargetPos += finalAimTarget; - - targetDiffVec.Normalize(); - Vector3 lastTargetRelPos = (lastFinalAimTarget) - fireTransform.position; - - if (BDATargetManager.CheckSafeToFireGuns(weaponManager, aimDirection, 1000, 0.999848f) && - //~1 degree of unsafe angle - (targetCosAngle >= maxAutoFireCosAngle || //check if directly on target - (Vector3.Dot(targetDiffVec, targetRelPos) * Vector3.Dot(targetDiffVec, lastTargetRelPos) < 0 && - targetCosAngle > 0))) //check if target will pass this point soon - { - autoFire = true; - } - else - { - autoFire = false; - } - } - else - { - autoFire = false; - } - - //disable autofire after burst length - if (autoFire && Time.time - autoFireTimer > autoFireLength) - { - autoFire = false; - legacyTargetVessel = null; - } } lastFinalAimTarget = finalAimTarget; } @@ -973,15 +945,20 @@ private void Fire() } float timeGap = (60 / roundsPerMinute) * TimeWarp.CurrentRate; - if (Time.time - timeFired > timeGap && !isOverheated && !pointingAtSelf && !Misc.Misc.CheckMouseIsOnGui() && - WMgrAuthorized()) + if (Time.time - timeFired > timeGap + && !isOverheated + && !pointingAtSelf + && (aiControlled || !Misc.Misc.CheckMouseIsOnGui()) + && WMgrAuthorized()) { bool effectsShot = false; //Transform[] fireTransforms = part.FindModelTransforms("fireTransform"); + for (float iTime = Mathf.Min(Time.time - timeFired - timeGap, TimeWarp.fixedDeltaTime); iTime >= 0; iTime -= timeGap) for (int i = 0; i < fireTransforms.Length; i++) { - if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) - { + //if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) + if (CanFire()) + { Transform fireTransform = fireTransforms[i]; spinningDown = false; @@ -1110,17 +1087,18 @@ private void Fire() pBullet.ballisticCoefficient = bulletBallisticCoefficient; - pBullet.flightTimeElapsed = 0; + pBullet.flightTimeElapsed = iTime; // measure bullet lifetime in time rather than in distance, because distances get very relative in orbit pBullet.timeToLiveUntil = Mathf.Max(maxTargetingRange, maxEffectiveDistance) / bulletVelocity * 1.1f + Time.time; - timeFired = Time.time; + timeFired = Time.time - iTime; Vector3 firedVelocity = - VectorUtils.GaussianDirectionDeviation(fireTransform.forward, maxDeviation) * bulletVelocity; + VectorUtils.GaussianDirectionDeviation(fireTransform.forward, maxDeviation / 2) * bulletVelocity; - firedBullet.transform.position += (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) * Time.fixedDeltaTime; pBullet.currentVelocity = (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) + firedVelocity; // use the real velocity, w/o offloading + firedBullet.transform.position += (part.rb.velocity + Krakensbane.GetFrameVelocityV3f()) * Time.fixedDeltaTime + + pBullet.currentVelocity * iTime; pBullet.sourceVessel = vessel; pBullet.bulletTexturePath = bulletTexturePath; @@ -1211,6 +1189,8 @@ private void Fire() //heat heat += heatPerShot; + //EC + DrainECPerShot(); } else { @@ -1446,6 +1426,34 @@ void ParseWeaponType() } } + void DrainECPerShot() + { + if (ECPerShot == 0) return; + //double drainAmount = ECPerShot * TimeWarp.fixedDeltaTime; + double drainAmount = ECPerShot; + double chargeAvailable = part.RequestResource("ElectricCharge", drainAmount, ResourceFlowMode.ALL_VESSEL); + } + + bool CanFire() + { + + if (ECPerShot != 0) + { + double chargeAvailable = part.RequestResource("ElectricCharge", ECPerShot, ResourceFlowMode.ALL_VESSEL); + if (chargeAvailable < ECPerShot * 0.95f) + { + ScreenMessages.PostScreenMessage("Weapon Requires EC", 5.0f, ScreenMessageStyle.UPPER_CENTER); + return false; + } + } + + if ((BDArmorySettings.INFINITE_AMMO || part.RequestResource(ammoName, requestResourceAmount) > 0)) + { + return true; + } + + return false; + } #endregion @@ -1683,13 +1691,62 @@ void Aim() } } + void CheckAIAutofire() + { + //autofiring with AI + if (targetAcquired && aiControlled) + { + Transform fireTransform = fireTransforms[0]; + Vector3 targetRelPos = (finalAimTarget) - fireTransform.position; + Vector3 aimDirection = fireTransform.forward; + float targetCosAngle = Vector3.Dot(aimDirection, targetRelPos.normalized); + + Vector3 targetDiffVec = finalAimTarget - lastFinalAimTarget; + Vector3 projectedTargetPos = targetDiffVec; + //projectedTargetPos /= TimeWarp.fixedDeltaTime; + //projectedTargetPos *= TimeWarp.fixedDeltaTime; + projectedTargetPos *= 2; //project where the target will be in 2 timesteps + projectedTargetPos += finalAimTarget; + + targetDiffVec.Normalize(); + Vector3 lastTargetRelPos = (lastFinalAimTarget) - fireTransform.position; + + if (BDATargetManager.CheckSafeToFireGuns(weaponManager, aimDirection, 1000, 0.999848f) //~1 degree of unsafe angle + && targetCosAngle >= maxAutoFireCosAngle) //check if directly on target + { + autoFire = true; + } + else + { + autoFire = false; + } + } + else + { + autoFire = false; + } + + //disable autofire after burst length + if (autoFire && Time.time - autoFireTimer > autoFireLength) + { + autoFire = false; + legacyTargetVessel = null; + } + } + IEnumerator AimAndFireAtEndOfFrame() { + if (eWeaponType != WeaponTypes.Laser) yield return new WaitForEndOfFrame(); + + UpdateTargetVessel(); + updateAcceleration(targetVelocity); + relativeVelocity = targetVelocity - vessel.rb_velocity; + RunTrajectorySimulation(); Aim(); CheckWeaponSafety(); + CheckAIAutofire(); - if (eWeaponType != WeaponTypes.Laser) yield return new WaitForEndOfFrame(); if (finalFire) { if (eWeaponType == WeaponTypes.Laser) @@ -2253,7 +2310,7 @@ public override string GetInfo() } else { - output.AppendLine($"Rounds Per Minute: {roundsPerMinute}"); + output.AppendLine($"Rounds Per Minute: {roundsPerMinute * (fireTransforms?.Length ?? 1)}"); output.AppendLine($"Ammunition: {ammoName}"); output.AppendLine($"Bullet type: {bulletType}"); output.AppendLine($"Bullet mass: {Math.Round(binfo.bulletMass,2)} kg"); diff --git a/BDArmory/Modules/ModuleWingCommander.cs b/BDArmory/Modules/ModuleWingCommander.cs index 44a13352f..b649d3fde 100644 --- a/BDArmory/Modules/ModuleWingCommander.cs +++ b/BDArmory/Modules/ModuleWingCommander.cs @@ -364,7 +364,7 @@ void WingmenWindow(int windowID) GUI.HorizontalSlider( new Rect(margin + (buttonWidth/3), buttonEndY + margin + (commandButtonLine*(buttonHeight + buttonGap)), 2*buttonWidth/3, 20), - spread, 20f, 200f, BDArmorySetup.BDGuiSkin.horizontalSlider, BDArmorySetup.BDGuiSkin.horizontalSliderThumb); + spread, 1f, 200f, BDArmorySetup.BDGuiSkin.horizontalSlider, BDArmorySetup.BDGuiSkin.horizontalSliderThumb); commandButtonLine++; GUI.Label( new Rect(margin, buttonEndY + margin + (commandButtonLine*(buttonHeight + buttonGap)), buttonWidth/3, 20), diff --git a/BDArmory/Modules/RocketLauncher.cs b/BDArmory/Modules/RocketLauncher.cs index ce0db45e6..c1f796f17 100644 --- a/BDArmory/Modules/RocketLauncher.cs +++ b/BDArmory/Modules/RocketLauncher.cs @@ -571,10 +571,6 @@ public void FireRocket() rocket.thrust = thrust; rocket.thrustTime = thrustTime; rocket.randomThrustDeviation = thrustDeviation; - if (BDArmorySettings.ALLOW_LEGACY_TARGETING && vessel.targetObject != null) - { - rocket.targetVessel = vessel.targetObject.GetVessel(); - } rocket.sourceVessel = vessel; rocketObj.SetActive(true); @@ -803,9 +799,7 @@ public override string GetInfo() public class Rocket : MonoBehaviour { public Transform spawnTransform; - public Vessel targetVessel; public Vessel sourceVessel; - public Vector3 startVelocity; public float mass; public float thrust; public float thrustTime; @@ -825,9 +819,6 @@ public class Rocket : MonoBehaviour Vector3 prevPosition; Vector3 currPosition; - - Vector3 relativePos; - float stayTime = 0.04f; float lifeTime = 10; @@ -886,14 +877,12 @@ void Start() void FixedUpdate() { - //floatingOrigin fix - if (sourceVessel != null && - (transform.position - sourceVessel.transform.position - relativePos).sqrMagnitude > 800*800) + //floating origin and velocity offloading corrections + if (!FloatingOrigin.Offset.IsZero() || !Krakensbane.GetFrameVelocity().IsZero()) { - transform.position = sourceVessel.transform.position + relativePos + (rb.velocity*Time.fixedDeltaTime); + transform.position -= FloatingOrigin.OffsetNonKrakensbane; + prevPosition -= FloatingOrigin.OffsetNonKrakensbane; } - if (sourceVessel != null) relativePos = transform.position - sourceVessel.transform.position; - // if (Time.time - startTime < stayTime && transform.parent != null) @@ -906,10 +895,9 @@ void FixedUpdate() { if (transform.parent != null && parentRB) { - startVelocity = parentRB.velocity; transform.parent = null; rb.isKinematic = false; - rb.velocity = startVelocity; + rb.velocity = parentRB.velocity + Krakensbane.GetFrameVelocityV3f(); } } @@ -1030,13 +1018,6 @@ void FixedUpdate() { Detonate(transform.position); } - - //proxy detonation - if (targetVessel != null && - (transform.position - targetVessel.transform.position).sqrMagnitude < 0.5f*blastRadius*blastRadius) - { - Detonate(transform.position); - } } void Update() diff --git a/BDArmory/Properties/AssemblyInfo.cs b/BDArmory/Properties/AssemblyInfo.cs index c654c2df8..eaeb3f0a0 100644 --- a/BDArmory/Properties/AssemblyInfo.cs +++ b/BDArmory/Properties/AssemblyInfo.cs @@ -18,8 +18,8 @@ // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. -[assembly: AssemblyVersion("1.2.2.2")] -[assembly: AssemblyFileVersion("1.2.2.2")] +[assembly: AssemblyVersion("1.2.3.0")] +[assembly: AssemblyFileVersion("1.2.3.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. diff --git a/BDArmory/UI/BDATargetManager.cs b/BDArmory/UI/BDATargetManager.cs index 113a534cb..f2fc1617d 100644 --- a/BDArmory/UI/BDATargetManager.cs +++ b/BDArmory/UI/BDATargetManager.cs @@ -346,7 +346,13 @@ public static TargetSignatureData GetHeatTarget(Ray ray, float scanRadius, float } } - + if (mf != null && tInfo != null) + { + if (BoolToTeam(mf.team) == tInfo.team) + { + continue; + } + } float angle = Vector3.Angle(vessel.CoM-ray.origin, ray.direction); if(angle < scanRadius) { diff --git a/BDArmory/UI/BDGUIUtils.cs b/BDArmory/UI/BDGUIUtils.cs index b98299f56..f25ffd63b 100644 --- a/BDArmory/UI/BDGUIUtils.cs +++ b/BDArmory/UI/BDGUIUtils.cs @@ -61,6 +61,9 @@ public static bool WorldToGUIPos(Vector3 worldPos, out Vector2 guiPos) public static void DrawLineBetweenWorldPositions(Vector3 worldPosA, Vector3 worldPosB, float width, Color color) { Camera cam = GetMainCamera(); + + if (cam == null) return; + GUI.matrix = Matrix4x4.identity; bool aBehind = false; diff --git a/DamageCurves/ArmorCurve.txt b/DamageCurves/ArmorCurve.txt new file mode 100644 index 000000000..6b81a3eec --- /dev/null +++ b/DamageCurves/ArmorCurve.txt @@ -0,0 +1,18 @@ + 25 5 + 50 10 + 75 35 + 100 50 + 125 55 + 150 65 + 175 68 + 200 70 + 250 73 + 300 75 + 350 76 + 400 77 + 450 80 + 500 85 + +y\ =\ \ 80.58079\ +\frac{\ \left(-0.18818185\ -\ 80.5\right)}{1+\ \left(\frac{x}{\left(90\right)}\right)^{2.5}} + +y=(113*x)/(154+x) \ No newline at end of file