void Start () {
		player = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerMovement> ();
        gun = player.GetComponentInChildren<Gun> ();
        missiles = player.GetComponentInChildren<MissileLauncher> ();
		participants = GameObject.FindGameObjectWithTag ("Participants").GetComponent<ParticipantManager> ();
		targetHold = targetLookDelay;
	}
    void Awake()
    {
        startingHull = (int)hullIntegritySlider.maxValue;
        startingShield = (int)shieldSlider.maxValue;
        mlScript = GetComponentInChildren<MissileLauncher>();

        dashboardAnim = GetComponent<Animator>();
        UIScreenOverlay = GameObject.FindGameObjectWithTag("UIScreenOverlay");
        UIScreenOverlayAC = UIScreenOverlay.GetComponent<Animator>();
    }
Example #3
0
        public override void OnStart(PartModule.StartState state)
        {
            submunitions = new List <GameObject>();
            foreach (var sub in part.FindModelTransforms("submunition"))
            {
                submunitions.Add(sub.gameObject);
                if (HighLogic.LoadedSceneIsFlight)
                {
                    Rigidbody subRb = sub.gameObject.GetComponent <Rigidbody>();
                    if (!subRb)
                    {
                        subRb = sub.gameObject.AddComponent <Rigidbody>();
                    }
                    subRb.isKinematic = true;
                    subRb.mass        = part.mass / part.FindModelTransforms("submunition").Length;
                }
                sub.gameObject.SetActive(false);
            }

            fairings = new List <GameObject>();
            foreach (var fairing in part.FindModelTransforms("fairing"))
            {
                fairings.Add(fairing.gameObject);
                if (HighLogic.LoadedSceneIsFlight)
                {
                    Rigidbody fairingRb = fairing.gameObject.GetComponent <Rigidbody>();
                    if (!fairingRb)
                    {
                        fairingRb = fairing.gameObject.AddComponent <Rigidbody>();
                    }
                    fairingRb.isKinematic = true;
                    fairingRb.mass        = 0.05f;
                }
            }

            missileLauncher = part.GetComponent <MissileLauncher>();
            //missileLauncher.deployTime = deployDelay;
        }
Example #4
0
        public static Vector3 GetAirToAirFireSolution(MissileLauncher missile, Vessel targetVessel)
        {
            if (!targetVessel)
            {
                return(missile.transform.position + (missile.transform.forward * 1000));
            }
            Vector3 targetPosition = targetVessel.transform.position;
            float   leadTime       = 0;
            float   targetDistance = Vector3.Distance(targetVessel.transform.position, missile.transform.position);

            Vector3 simMissileVel = missile.optimumAirspeed * (targetPosition - missile.transform.position).normalized;

            leadTime       = targetDistance / (float)(targetVessel.srf_velocity - simMissileVel).magnitude;
            leadTime       = Mathf.Clamp(leadTime, 0f, 8f);
            targetPosition = targetPosition + (targetVessel.srf_velocity * leadTime);

            if (targetVessel && targetDistance < 800)
            {
                targetPosition += (Vector3)targetVessel.acceleration * 0.05f * leadTime * leadTime;
            }

            return(targetPosition);
        }
        private void GetSettings()
        {
            MissileLauncher val = base.part.FindModuleImplementing <MissileLauncher>();

            if ((Object)val != (Object)null)
            {
                mass            = base.part.mass;
                maxOffBoresight = val.maxOffBoresight;
                maxTurnRateDPS  = val.maxTurnRateDPS;
                maxTorque       = val.maxTorque;
                clearanceRadius = val.clearanceRadius;
                clearanceLength = val.clearanceLength;

                //Debug.Log("[VLS Missile] SAVING ... maxOffBoresight = " + maxOffBoresight);
                //Debug.Log("[VLS Missile] SAVING ... maxTurnRateDPS = " + maxTurnRateDPS);
                //Debug.Log("[VLS Missile] SAVING ... maxTorque = " + maxTorque);
                //Debug.Log("[VLS Missile] SAVING ... clearanceRadius = " + clearanceRadius);
                //Debug.Log("[VLS Missile] SAVING ... clearanceLength = " + clearanceLength);

                //Debug.Log("[VLS Missile] ... ADJUSTING SETTINGS FOR LAUNCH ...");

                base.part.mass      = mass / 100f;
                val.maxOffBoresight = 270f;
                val.maxTurnRateDPS  = 0f;
                val.maxTorque       = 0f;
                val.clearanceRadius = 0.01f;
                val.clearanceLength = 0.01f;

                //Debug.Log("[VLS Missile] CHANGING ... mass = " + part.mass);
                //Debug.Log("[VLS Missile] CHANGING ... maxOffBoresight = " + val.maxOffBoresight);
                //Debug.Log("[VLS Missile] CHANGING ... maxTurnRateDPS = " + val.maxTurnRateDPS);
                //Debug.Log("[VLS Missile] CHANGING ... maxTorque = " + val.maxTorque);
                //Debug.Log("[VLS Missile] CHANGING ... clearanceRadius = " + val.clearanceRadius);
                //Debug.Log("[VLS Missile] CHANGING ... clearanceLength = " + val.clearanceLength);
            }
        }
Example #6
0
        void RotateToIndex(int index, bool instant)
        {
            //Debug.Log("Rotary rail is rotating to index: " + index);

            if (rotationRoutine != null)
            {
                StopCoroutine(rotationRoutine);
            }

            nextMissile = null;
            if (missileCount > 0)
            {
                var railCount = Mathf.RoundToInt(numberOfRails);
                for (int i = index; i < index + numberOfRails; ++i)
                {
                    if (railToMissileIndex.ContainsKey(index % railCount) && (nextMissile = missileChildren[railToMissileIndex[index % railCount]]) != null)
                    {
                        rotationRoutine = StartCoroutine(RotateToIndexRoutine(index, instant));
                        return;
                    }
                }
                Debug.LogError("[BDArmory.BDRotaryRail]: No missiles found, but missile count is non-zero.");
            }
        }
Example #7
0
        float findMinDepth(string type)
        {
            float min = -1.0f;

            foreach (var current in FlightGlobals.ActiveVessel.Parts)
            {
                ModuleAntiSubmarineWeapon target          = current.GetComponent <ModuleAntiSubmarineWeapon>();
                MissileLauncher           missileLauncher = current.GetComponent <MissileLauncher>();

                if (target == null || target.type != type || missileLauncher.HasFired)
                {
                    continue;
                }

                min = target.maxDepth < min ? target.maxDepth : min;

                if (min < 0)
                {
                    min = target.maxDepth;
                }
            }

            return(min);
        }
Example #8
0
        void dumpParts()
        {
            String          gunName     = "bda_weapons_list.csv";
            String          missileName = "bda_missile_list.csv";
            String          radarName   = "bda_radar_list.csv";
            String          jammerName  = "bda_jammer_list.csv";
            ModuleWeapon    weapon      = null;
            MissileLauncher missile     = null;
            ModuleRadar     radar       = null;
            ModuleECMJammer jammer      = null;

            // 1. create the file
            var fileguns     = KSP.IO.TextWriter.CreateForType <BDAEditorCategory>(gunName);
            var filemissiles = KSP.IO.TextWriter.CreateForType <BDAEditorCategory>(missileName);
            var fileradars   = KSP.IO.TextWriter.CreateForType <BDAEditorCategory>(radarName);
            var filejammers  = KSP.IO.TextWriter.CreateForType <BDAEditorCategory>(jammerName);

            // 2. write header
            fileguns.WriteLine("NAME;TITLE;AUTHOR;MANUFACTURER;PART_MASS;PART_COST;PART_CRASHTOLERANCE;PART_MAXTEMP;WEAPON_RPM;WEAPON_DEVIATION;WEAPON_MAXEFFECTIVEDISTANCE;WEAPON_TYPE;WEAPON_BULLETTYPE;WEAPON_AMMONAME;WEAPON_BULLETMASS;WEAPON_BULLET_VELOCITY;WEAPON_MAXHEAT;WEAPON_HEATPERSHOT;WEAPON_HEATLOSS;CANNON_SHELLPOWER;CANNON_SHELLHEAT;CANNON_SHELLRADIUS;CANNON_AIRDETONATION");
            filemissiles.WriteLine("NAME;TITLE;AUTHOR;MANUFACTURER;PART_MASS;PART_COST;PART_CRASHTOLERANCE;PART_MAXTEMP;" +
                                   "MISSILE_THRUST;MISSILE_BOOSTTIME;MISSILE_CRUISETHRUST;MISSILE_CRUISETIME;MISSILE_MAXTURNRATEDPS;MISSILE_BLASTPOWER;MISSILE_BLASTHEAT;MISSILE_BLASTRADIUS;MISSILE_GUIDANCEACTIVE;MISSILE_HOMINGTYPE;MISSILE_TARGETINGTYPE;MISSILE_MINLAUNCHSPEED;MISSILE_MINSTATICLAUNCHRANGE;MISSILE_MAXSTATICLAUNCHRANGE;MISSILE_OPTIMUMAIRSPEED;" +
                                   "CRUISE_TERMINALMANEUVERING; CRUISE_TERMINALGUIDANCETYPE; CRUISE_TERMINALGUIDANCEDISTANCE;" +
                                   "RADAR_ACTIVERADARRANGE;RADAR_RADARLOAL;" +
                                   "TRACK_MAXOFFBORESIGHT;TRACK_LOCKEDSENSORFOV;" +
                                   "HEAT_HEATTHRESHOLD;" +
                                   "LASER_BEAMCORRECTIONFACTOR; LASER_BEAMCORRECTIONDAMPING"
                                   );
            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"
                                 );
            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)
            {
                weapon  = null;
                missile = null;
                radar   = null;
                jammer  = null;
                weapon  = item.partPrefab.GetComponent <ModuleWeapon>();
                missile = item.partPrefab.GetComponent <MissileLauncher>();
                radar   = item.partPrefab.GetComponent <ModuleRadar>();
                jammer  = item.partPrefab.GetComponent <ModuleECMJammer>();

                if (weapon != null)
                {
                    fileguns.WriteLine(
                        item.name + ";" + item.title + ";" + item.author + ";" + item.manufacturer + ";" + item.partPrefab.mass + ";" + item.cost + ";" + item.partPrefab.crashTolerance + ";" + item.partPrefab.maxTemp + ";" +
                        weapon.roundsPerMinute + ";" + weapon.maxDeviation + ";" + weapon.maxEffectiveDistance + ";" + weapon.weaponType + ";" + weapon.bulletType + ";" + weapon.ammoName + ";" + weapon.bulletMass + ";" + weapon.bulletVelocity + ";" +
                        weapon.maxHeat + ";" + weapon.heatPerShot + ";" + weapon.heatLoss + ";" + weapon.cannonShellPower + ";" + weapon.cannonShellHeat + ";" + weapon.cannonShellRadius + ";" + weapon.airDetonation
                        );
                }

                if (missile != null)
                {
                    filemissiles.WriteLine(
                        item.name + ";" + item.title + ";" + item.author + ";" + item.manufacturer + ";" + item.partPrefab.mass + ";" + item.cost + ";" + item.partPrefab.crashTolerance + ";" + item.partPrefab.maxTemp + ";" +
                        missile.thrust + ";" + missile.boostTime + ";" + missile.cruiseThrust + ";" + missile.cruiseTime + ";" + missile.maxTurnRateDPS + ";" + missile.blastPower + ";" + missile.blastHeat + ";" + missile.blastRadius + ";" + missile.guidanceActive + ";" + missile.homingType + ";" + missile.targetingType + ";" + missile.minLaunchSpeed + ";" + missile.minStaticLaunchRange + ";" + missile.maxStaticLaunchRange + ";" + missile.optimumAirspeed + ";" +
                        missile.terminalManeuvering + ";" + missile.terminalGuidanceType + ";" + missile.terminalGuidanceDistance + ";" +
                        missile.activeRadarRange + ";" + missile.radarLOAL + ";" +
                        missile.maxOffBoresight + ";" + missile.lockedSensorFOV + ";" +
                        missile.heatThreshold + ";" +
                        missile.beamCorrectionFactor + ";" + missile.beamCorrectionDamping
                        );
                }

                if (radar != null)
                {
                    fileradars.WriteLine(
                        item.name + ";" + item.title + ";" + item.author + ";" + item.manufacturer + ";" + item.partPrefab.mass + ";" + item.cost + ";" + item.partPrefab.crashTolerance + ";" + item.partPrefab.maxTemp + ";" +
                        radar.radarName + ";" + radar.getRWRType(radar.rwrThreatType) + ";" + radar.omnidirectional + ";" + radar.directionalFieldOfView + ";" + radar.boresightFOV + ";" + radar.scanRotationSpeed + ";" + radar.lockRotationSpeed + ";" +
                        radar.lockRotationAngle + ";" + radar.showDirectionWhileScan + ";" + radar.multiLockFOV + ";" + radar.lockAttemptFOV + ";" +
                        radar.canScan + ";" + radar.canLock + ";" + radar.canTrackWhileScan + ";" + radar.canRecieveRadarData + ";" +
                        radar.maxLocks + ";" + radar.radarGroundClutterFactor + ";" +
                        radar.radarDetectionCurve.Evaluate(radar.radarMaxDistanceDetect) + "@" + radar.radarMaxDistanceDetect + ";" +
                        radar.radarLockTrackCurve.Evaluate(radar.radarMaxDistanceLockTrack) + "@" + radar.radarMaxDistanceLockTrack
                        );
                }

                if (jammer != null)
                {
                    filejammers.WriteLine(
                        item.name + ";" + item.title + ";" + item.author + ";" + item.manufacturer + ";" + item.partPrefab.mass + ";" + item.cost + ";" + item.partPrefab.crashTolerance + ";" + item.partPrefab.maxTemp + ";" +
                        jammer.alwaysOn + ";" + jammer.rcsReduction + ";" + jammer.rcsReductionFactor + ";" + jammer.lockBreaker + ";" + jammer.lockBreakerStrength + ";" + jammer.jammerStrength
                        );
                }
            }

            // 4. close file
            fileguns.Close();
            filemissiles.Close();
            fileradars.Close();
            filejammers.Close();
            Debug.Log("...dumping parts complete.");
        }
        /// <summary>
        /// Gets the dynamic launch parameters.
        /// </summary>
        /// <returns>The dynamic launch parameters.</returns>
        /// <param name="launcherVelocity">Launcher velocity.</param>
        /// <param name="targetVelocity">Target velocity.</param>
        public static MissileLaunchParams GetDynamicLaunchParams(MissileBase missile, Vector3 targetVelocity, Vector3 targetPosition)
        {
            Vector3 launcherVelocity = missile.vessel.Velocity();
            float   launcherSpeed    = (float)missile.vessel.srfSpeed;
            float   minLaunchRange   = missile.minStaticLaunchRange;
            float   maxLaunchRange   = missile.maxStaticLaunchRange;

            float bodyGravity = (float)PhysicsGlobals.GravitationalAcceleration * (float)missile.vessel.orbit.referenceBody.GeeASL; // Set gravity for calculations;

            float missileActiveTime = 2f;

            float rangeAddMin = 0;
            float rangeAddMax = 0;
            float relSpeed;

            // Calculate relative speed
            Vector3 relV           = targetVelocity - launcherVelocity;
            Vector3 vectorToTarget = targetPosition - missile.part.transform.position;
            Vector3 relVProjected  = Vector3.Project(relV, vectorToTarget);

            relSpeed = -Mathf.Sign(Vector3.Dot(relVProjected, vectorToTarget)) * relVProjected.magnitude;

            if (missile.GetComponent <BDModularGuidance>() == null)
            {
                // Basic time estimate for missile to drop and travel a safe distance from vessel assuming constant acceleration and firing vessel not accelerating
                MissileLauncher ml = missile.GetComponent <MissileLauncher>();
                float           maxMissileAccel = ml.thrust / missile.part.mass;
                float           blastRadius     = Mathf.Min(missile.GetBlastRadius(), 150f);                                                                  // Allow missiles with absurd blast ranges to still be launched if desired
                missileActiveTime = Mathf.Min((missile.vessel.LandedOrSplashed ? 0f : missile.dropTime) + Mathf.Sqrt(2 * blastRadius / maxMissileAccel), 2f); // Clamp at 2s for now

                // Rough range estimate of max missile G in a turn after launch, the following code is quite janky but works decently well in practice
                float maxEstimatedGForce = Mathf.Max(bodyGravity * ml.maxTorque, 15f); // Rough estimate of max G based on missile torque, use minimum of 15G to prevent some VLS parts from not working
                if (ml.aero)                                                           // If missile has aerodynamics, modify G force by AoA limit
                {
                    maxEstimatedGForce *= Mathf.Sin(ml.maxAoA * Mathf.Deg2Rad);
                }

                // Rough estimate of turning radius and arc length to travel
                float arcLength = 0;
                if ((!missile.vessel.LandedOrSplashed) && (missile.GetWeaponClass() != WeaponClasses.SLW)) // If the missile isn't a torpedo
                {
                    float   futureTime        = Mathf.Clamp((missile.vessel.LandedOrSplashed ? 0f : missile.dropTime), 0f, 2f);
                    Vector3 futureRelPosition = (targetPosition + targetVelocity * futureTime) - (missile.part.transform.position + launcherVelocity * futureTime);
                    float   missileTurnRadius = (ml.optimumAirspeed * ml.optimumAirspeed) / maxEstimatedGForce;
                    float   targetAngle       = Vector3.Angle(missile.GetForwardTransform(), futureRelPosition);
                    arcLength = Mathf.Deg2Rad * targetAngle * missileTurnRadius;
                }

                // Add additional range term for the missile to manuever to target at missileActiveTime
                rangeAddMin += arcLength;
            }

            float missileMaxRangeTime = 8f; // Placeholder value since this doesn't really matter much in BDA combat

            // Add to ranges
            rangeAddMin += relSpeed * missileActiveTime;
            rangeAddMax += relSpeed * missileMaxRangeTime;

            // Add altitude term to max
            double diffAlt = missile.vessel.altitude - FlightGlobals.getAltitudeAtPos(targetPosition);

            rangeAddMax += (float)diffAlt;

            float min = Mathf.Clamp(minLaunchRange + rangeAddMin, 0, BDArmorySettings.MAX_ENGAGEMENT_RANGE);
            float max = Mathf.Clamp(maxLaunchRange + rangeAddMax, min + 100, BDArmorySettings.MAX_ENGAGEMENT_RANGE);

            return(new MissileLaunchParams(min, max));
        }
Example #10
0
        IEnumerator RotateToIndexRoutine(int index, bool instant)
        {
            rdyToFire  = false;
            rdyMissile = null;
            railIndex  = index;

            /*
             * MissileLauncher foundMissile = null;
             *
             * foreach(var mIndex in missileToRailIndex.Keys)
             * {
             *      if(missileToRailIndex[mIndex] == index)
             *      {
             *              foundMissile = missileChildren[mIndex];
             *      }
             * }
             * nextMissile = foundMissile;
             */



            yield return(new WaitForSeconds(rotationDelay));

            Quaternion targetRot = Quaternion.Euler(0, 0, (float)index * -railAngle);

            if (instant)
            {
                for (int i = 0; i < rotationTransforms.Count; i++)
                {
                    rotationTransforms[i].localRotation = targetRot;
                }

                UpdateMissilePositions();
                //yield break;
            }
            else
            {
                while (rotationTransforms[0].localRotation != targetRot)
                {
                    for (int i = 0; i < rotationTransforms.Count; i++)
                    {
                        rotationTransforms[i].localRotation = Quaternion.RotateTowards(rotationTransforms[i].localRotation, targetRot, rotationSpeed * Time.fixedDeltaTime);
                    }

                    UpdateMissilePositions();
                    yield return(new WaitForFixedUpdate());
                }
            }

            if (nextMissile)
            {
                rdyMissile  = nextMissile;
                rdyToFire   = true;
                nextMissile = null;

                if (weaponManager)
                {
                    if (wm.weaponIndex > 0 && wm.selectedWeapon.GetPart().name == rdyMissile.part.name)
                    {
                        wm.selectedWeapon = rdyMissile;
                        wm.currentMissile = rdyMissile;
                    }
                }
            }
        }
 void Start()
 {
     parent = transform.parent.GetComponent<MissileLauncher>();
 }
Example #12
0
        void FlyToTargetVessel(FlightCtrlState s, Vessel v)
        {
            Vector3         target           = v.CoM;
            MissileLauncher missile          = null;
            Vector3         vectorToTarget   = v.transform.position - vesselTransform.position;
            float           distanceToTarget = vectorToTarget.magnitude;

            if (weaponManager)
            {
                missile = weaponManager.currentMissile;
                if (missile != null)
                {
                    if (missile.targetingMode == MissileLauncher.TargetingModes.Heat && !weaponManager.heatTarget.exists)
                    {
                        target += v.srf_velocity.normalized * 10;
                    }
                    else
                    {
                        target = MissileGuidance.GetAirToAirFireSolution(missile, v);
                    }

                    if (Vector3.Angle(target - vesselTransform.position, vesselTransform.forward) < 15)
                    {
                        steerMode = SteerModes.Aiming;
                    }
                }
                else
                {
                    ModuleWeapon weapon = weaponManager.currentGun;
                    if (weapon != null)
                    {
                        //target -= 1.30f*weapon.GetLeadOffset();
                        Vector3 leadOffset = weapon.GetLeadOffset();

                        float targetAngVel = 1.65f * Vector3.Angle(v.transform.position - vessel.transform.position, v.transform.position + (vessel.srf_velocity) - vessel.transform.position);
                        debugString += "\ntargetAngVel: " + targetAngVel;
                        float magnifier = Mathf.Clamp(targetAngVel, 1.25f, 5);
                        target -= magnifier * leadOffset;
                        float angleToLead = Vector3.Angle(vesselTransform.up, target - vesselTransform.position);
                        if (distanceToTarget < 1600 && angleToLead < 20)
                        {
                            steerMode = SteerModes.Aiming;                             //steer to aim
                        }
                    }
                }
            }



            float targetDot = Vector3.Dot(vesselTransform.up, v.transform.position - vessel.transform.position);

            //manage speed when close to enemy
            float finalMaxSpeed = ((distanceToTarget - 100) / 8) + (float)v.srfSpeed;

            AdjustThrottle(finalMaxSpeed, true);

            if ((targetDot < 0 || vessel.srfSpeed > finalMaxSpeed) &&
                distanceToTarget < 800)                    //distance is less than 800m
            {
                debugString += ("\nEnemy on tail. Braking");
                AdjustThrottle(minSpeed, true);
            }
            if (missile != null &&
                targetDot > 0 &&
                distanceToTarget < 300 &&
                vessel.srfSpeed > 130)
            {
                extending          = true;
                lastTargetPosition = v.transform.position;
            }


            FlyToPosition(s, target);
        }
Example #13
0
        public override void OnStart(StartState state)
        {
            base.OnStart(state);

            _data = new AswData {
                Type = type
            };

            switch (_data.Type)
            {
            case "DepthCharge":
                _bomb = new BombSystem();
                _bomb.ChargeDataWrite(errorRange, maxDepth, maxDepth);
                _bomb.Ran();

                _buoyancy = new Buoyancy();
                _buoyancy.BuoyancyDataWrite(volumebuoyancy, volum, buoyancyForce);

                _rota = new RotationSystem();
                _rota.RotationData(airMaxTorque, waterMaxTorque, airCocf, waterCocf);

                _missileLauncher = GetComponent <MissileLauncher>();
                if (_missileLauncher == null)
                {
                    Debug.LogError("Failed when find the MissileLauncher!");
                }

                _depthField = Fields["autoDestroyDepth"].uiControlFlight;

                Fields["cruiseDepth"].guiActive            = false;
                Fields["cruiseDepth"].guiActiveEditor      = false;
                Fields["autoDestroyDepth"].guiActive       = true;
                Fields["autoDestroyDepth"].guiActiveEditor = true;
                Fields["autoDestroyDepth"].guiName         = Localizer.Format("#autoLOC_NAS_Editor_detonateDepth");

                ((UI_FloatRange)Fields["autoDestroyDepth"].uiControlEditor).maxValue = maxDepth;
                ((UI_FloatRange)Fields["autoDestroyDepth"].uiControlFlight).maxValue = maxDepth;
                break;

            case "Torpedo":
                _pida = new PidSystem();
                _pida.PidDataWrite(maxRotate.z, pidAngleInfo.x, pidAngleInfo.y, pidAngleInfo.z);
                _pidt = new PidSystem();
                _pidt.PidDataWrite(maxTorque.x, pidTorqueInfo.x, pidTorqueInfo.y, pidTorqueInfo.z);

                _buoyancy = new Buoyancy();
                _buoyancy.BuoyancyDataWrite(volumebuoyancy, volum, buoyancyForce);

                _rota = new RotationSystem();
                _rota.RotationData(airMaxTorque, waterMaxTorque, airCocf, waterCocf);

                _missileLauncher = GetComponent <MissileLauncher>();
                if (_missileLauncher == null)
                {
                    Debug.LogError("Failed when find the MissileLauncher!");
                }

                Fields["autoDestroyDepth"].guiActive       = false;
                Fields["autoDestroyDepth"].guiActiveEditor = false;
                Fields["cruiseDepth"].guiActive            = true;
                Fields["cruiseDepth"].guiActiveEditor      = true;
                Fields["cruiseDepth"].guiName = Localizer.Format("#autoLOC_NAS_Editor_cruiseDepth");

                ((UI_FloatRange)Fields["cruiseDepth"].uiControlEditor).maxValue = maxDepth - 2;
                ((UI_FloatRange)Fields["cruiseDepth"].uiControlFlight).maxValue = maxDepth - 2;
                break;

            default:
                Debug.LogWarning("[NAS-ASW]Neither depth charge nor torpedo!");
                break;
            }

            autoDestroyDepth = ModUiManager.setAllDepthCharges;
            cruiseDepth      = ModUiManager.setAllTorpedos;
        }
Example #14
0
 void Awake()
 {
     m_launcher      = GetComponent <MissileLauncher> ();
     m_indicatorRect = new Rect(0.0f, 0.0f, indicatorSize, indicatorSize);
     textColor       = new Color(0.2f, 0.2f, 0.5f);
 }
Example #15
0
    public void EquipCustomWeapons(Loadout loadout, WeaponManager wm)
    {
        triggered = true;
        Traverse traverse = Traverse.Create(wm);

        HPEquippable[] equips    = (HPEquippable[])traverse.Field("equips").GetValue();
        MassUpdater    component = wm.vesselRB.GetComponent <MassUpdater>();

        string[] hpLoadout = loadout.hpLoadout;
        int      num       = 0;

        Debug.Log("sLoadout\n" + loadout.hpLoadout.ToString());
        // var bundle = AssetBundle.LoadFromFile(resourcePath);
        while (num < wm.hardpointTransforms.Length && num < hpLoadout.Length)
        {
            if (!string.IsNullOrEmpty(hpLoadout[num]) && hpLoadout[num] == "Nuke")
            {
                Debug.Log(hpLoadout[num] + " will be tried to be loaded.");
                GameObject missileObject = PatcherHelper.GetAssetBundle().LoadAsset <GameObject>(hpLoadout[num]);
                Debug.Log("Got missileObject");
                //GameObject missileObject = Instantiate(@object, wm.hardpointTransforms[num]);
                // toCheckAgainst = wm.hardpointTransforms[num];
                Debug.Log("Instantiated custom weapon.");
                missileObject.name = hpLoadout[num];
                Debug.Log("Changed name.");
                missileObject.transform.localRotation = Quaternion.identity;
                Debug.Log("Quaternion identity.");
                missileObject.transform.localPosition = Vector3.zero;
                Debug.Log("local position.");
                missileObject.transform.localScale = new Vector3(20f, 20f, 20f);
                Debug.Log("local scale.");
                if (missileObject == null)
                {
                    Debug.LogError("missileObject is null.");
                }
                // missileLauncher.SetParentRigidbody(rB);
                GameObject equipper      = Instantiate(new GameObject());
                GameObject edgeTransform = missileObject.transform.GetChild(0).gameObject;
                Nuke       nuke          = missileObject.AddComponent <Nuke>();
                nuke.edgeTransform = edgeTransform;
                nuke.equipper      = equipper;
                equipper.SetActive(true);
                Debug.Log("Nuke added.");
                nuke.init();
                Debug.Log("Nuke inited.");
                if (equipper == null)
                {
                    Debug.LogError("Equipper is null.");
                }
                if (equipper.transform.position == null)
                {
                    Debug.LogError("Equipper transform posiiton null");
                }
                if (wm.hardpointTransforms[num].position == null)
                {
                    Debug.LogError("wm hardopint transforms position null");
                }
                equipper.transform.position = wm.hardpointTransforms[num].position;
                Debug.Log("Equipper transform.");
                equipper.transform.parent = wm.hardpointTransforms[num];
                Debug.Log("Equipper transform parent.");
                HPEquipBombRack HPEquipper = nuke.HPEquipper;
                Debug.Log("HPEquipper inited.");
                HPEquipper.SetWeaponManager(wm);
                Debug.Log("Weapon Manager.");
                equips[num] = HPEquipper;
                Debug.Log("equips = component.");
                HPEquipper.wasPurchased = true;
                Debug.Log("was purchased.");
                HPEquipper.hardpointIdx = num;
                Debug.Log("hardpointIDX.");
                HPEquipper.Equip();
                Debug.Log("Equip().");
                Debug.Log("Tipping nuke");
                if (HPEquipper.jettisonable)
                {
                    Rigidbody component3 = HPEquipper.GetComponent <Rigidbody>();
                    if (component3)
                    {
                        component3.interpolation = RigidbodyInterpolation.None;
                    }
                }
                Debug.Log("jettisonable.");
                if (HPEquipper.armable)
                {
                    HPEquipper.armed = true;
                    wm.RefreshWeapon();
                }
                Debug.Log("RefrshWeapon().");
                missileObject.SetActive(true);
                foreach (Component component4 in HPEquipper.gameObject.GetComponentsInChildren <Component>())
                {
                    if (component4 is IParentRBDependent)
                    {
                        ((IParentRBDependent)component4).SetParentRigidbody(wm.vesselRB);
                    }
                    if (component4 is IRequiresLockingRadar)
                    {
                        ((IRequiresLockingRadar)component4).SetLockingRadar(wm.lockingRadar);
                    }
                    if (component4 is IRequiresOpticalTargeter)
                    {
                        ((IRequiresOpticalTargeter)component4).SetOpticalTargeter(wm.opticalTargeter);
                    }
                }
                Debug.Log("DLZ shit");
                MissileLauncher missileLauncher = nuke.missileLauncher;
                if (missileLauncher.missilePrefab == null)
                {
                    Debug.LogError("MissilePrefab is null");
                }
                if (missileLauncher.missilePrefab.GetComponent <Missile>() == null)
                {
                    Debug.LogError("Missile not found on prefab");
                }
                if (missileLauncher.hardpoints[0] == null)
                {
                    Debug.LogError("Hardpoints null");
                }
                missileLauncher.LoadAllMissiles();
                Debug.Log(missileLauncher.missiles[0]);
                Debug.Log("HEY IT WORKED");
                Warhead nyuk = missileLauncher.missiles[0].gameObject.AddComponent <Warhead>();
                missileLauncher.missiles[0].OnDetonate = new UnityEvent();
                missileLauncher.missiles[0].OnDetonate.AddListener(new UnityAction(() =>
                {
                    Debug.Log("Nuke is now critical.");
                    nyuk.DoNuke();
                }));
                missileLauncher.missiles[0].enabled = true;
                if (missileLauncher.missiles[0].transform == null)
                {
                    Debug.LogError("Missile[0] null");
                }
                Debug.Log("Nuke should now have teeth");
                if (missileLauncher.overrideDecoupleSpeed > 0f)
                {
                    missileLauncher.missiles[0].decoupleSpeed = missileLauncher.overrideDecoupleSpeed;
                }
                if (missileLauncher.overrideDecoupleDirections != null && missileLauncher.overrideDecoupleDirections.Length > 0 && missileLauncher.overrideDecoupleDirections[0] != null)
                {
                    missileLauncher.missiles[0].overrideDecoupleDirTf = missileLauncher.overrideDecoupleDirections[0];
                }
                if (missileLauncher.overrideDropTime >= 0f)
                {
                    missileLauncher.missiles[0].thrustDelay = missileLauncher.overrideDropTime;
                }
                // int missileCount = missileLauncher.missileCount;

                /*GameObject dummyMissile = Instantiate(@object, wm.hardpointTransforms[num]);
                 * dummyMissile.transform.localScale = new Vector3(20f, 20f, 20f);
                 * dummyMissile.transform.eulerAngles = new Vector3(dummyMissile.transform.eulerAngles.x, dummyMissile.transform.eulerAngles.y, dummyMissile.transform.eulerAngles.z + 90f);
                 * dummyMissile.SetActive(true);*/
                missileLauncher.missiles[0].transform.localScale  = new Vector3(20f, 20f, 20f);
                missileLauncher.missiles[0].transform.parent      = equipper.transform;
                missileLauncher.missiles[0].transform.position    = equipper.transform.position;
                missileLauncher.missiles[0].transform.eulerAngles = new Vector3(missileLauncher.missiles[0].transform.eulerAngles.x, missileLauncher.missiles[0].transform.eulerAngles.y, missileLauncher.missiles[0].transform.eulerAngles.z + 90f);
                missileLauncher.missiles[0].gameObject.SetActive(true);
                // Destroy(dummyMissile);
                Missile.LaunchEvent launchEvent = new Missile.LaunchEvent();
                launchEvent.delay       = 0f;
                launchEvent.launchEvent = new UnityEvent();
                launchEvent.launchEvent.AddListener(new UnityAction(() =>
                {
                    Debug.Log("Launch event was called.");
                    // dummyMissile.SetActive(false);
                    /*Destroy(dummyMissile); */
                }));
                missileLauncher.missiles[0].launchEvents = new List <Missile.LaunchEvent>();
                missileLauncher.missiles[0].launchEvents.Add(launchEvent);
                toCheck = missileLauncher.missiles[0];
                Debug.Log("Missiles loaded!");
            }
            else
            {
                Debug.LogError(hpLoadout[num] + " is null or empty.");
            }
            num++;
        }
        if (wm.vesselRB)
        {
            wm.vesselRB.ResetInertiaTensor();
        }
        Debug.Log("intertia tensor.");
        if (loadout.cmLoadout != null)
        {
            CountermeasureManager componentInChildren = GetComponentInChildren <CountermeasureManager>();
            if (componentInChildren)
            {
                int num2 = 0;
                while (num2 < componentInChildren.countermeasures.Count && num2 < loadout.cmLoadout.Length)
                {
                    componentInChildren.countermeasures[num2].count = Mathf.Clamp(loadout.cmLoadout[num2], 0, componentInChildren.countermeasures[num2].maxCount);
                    componentInChildren.countermeasures[num2].UpdateCountText();
                    num2++;
                }
            }
        }
        traverse.Field("weaponIdx").SetValue(0);
        Debug.Log("weaponIDX.");
        wm.ToggleMasterArmed();
        wm.ToggleMasterArmed();
        if (wm.OnWeaponChanged != null)
        {
            wm.OnWeaponChanged.Invoke();
        }
        component.UpdateMassObjects();
        traverse.Field("rcsAddDirty").SetValue(true);
        // wm.ReattachWeapons();
        Debug.Log("Should be working now...");
        wm.RefreshWeapon();
        foreach (var equip in wm.GetCombinedEquips())
        {
            Debug.Log(equip);
        }
    }
        protected override void DrawSelf(SpriteBatch spriteBatch)
        {
            MissileLauncher missileLauncherTarget = Main.LocalPlayer.inventory[((MetroidMod)MetroidMod.Instance).selectedItem].modItem as MissileLauncher;

            spriteBatch.Draw(itemBoxTexture, drawRectangle, Color.White);

            // Item drawing.
            if (missileLauncherTarget.missileMods[missileSlotType].IsAir)
            {
                return;
            }

            Color           itemColor       = missileLauncherTarget.missileMods[missileSlotType].GetAlpha(Color.White);
            Texture2D       itemTexture     = Main.itemTexture[missileLauncherTarget.missileMods[missileSlotType].type];
            CalculatedStyle innerDimensions = base.GetDimensions();

            if (base.IsMouseHovering)
            {
                Main.hoverItemName = missileLauncherTarget.missileMods[missileSlotType].Name;
                Main.HoverItem     = missileLauncherTarget.missileMods[missileSlotType].Clone();
            }

            var frame = Main.itemAnimations[missileLauncherTarget.missileMods[missileSlotType].type] != null
                        ? Main.itemAnimations[missileLauncherTarget.missileMods[missileSlotType].type].GetFrame(itemTexture)
                        : itemTexture.Frame(1, 1, 0, 0);

            float drawScale = 1f;

            if ((float)frame.Width > innerDimensions.Width || (float)frame.Height > innerDimensions.Width)
            {
                if (frame.Width > frame.Height)
                {
                    drawScale = innerDimensions.Width / (float)frame.Width;
                }
                else
                {
                    drawScale = innerDimensions.Width / (float)frame.Height;
                }
            }

            var unreflectedScale = drawScale;
            var tmpcolor         = Color.White;

            ItemSlot.GetItemLight(ref tmpcolor, ref drawScale, missileLauncherTarget.missileMods[missileSlotType].type);

            Vector2 drawPosition = new Vector2(innerDimensions.X, innerDimensions.Y);

            drawPosition.X += (float)innerDimensions.Width * 1f / 2f - (float)frame.Width * drawScale / 2f;
            drawPosition.Y += (float)innerDimensions.Height * 1f / 2f - (float)frame.Height * drawScale / 2f;

            spriteBatch.Draw(itemTexture, drawPosition, new Rectangle?(frame), itemColor, 0f,
                             Vector2.Zero, drawScale, SpriteEffects.None, 0f);

            if (missileLauncherTarget.missileMods[missileSlotType].stack > 1)
            {
                Utils.DrawBorderStringFourWay(
                    spriteBatch,
                    Main.fontItemStack,
                    Math.Min(9999, missileLauncherTarget.missileMods[missileSlotType].stack).ToString(),
                    innerDimensions.Position().X + 10f,
                    innerDimensions.Position().Y + 26f,
                    Color.White,
                    Color.Black,
                    Vector2.Zero,
                    unreflectedScale * 0.8f);
            }
        }
Example #17
0
        public void UpdateMissileChildren()
        {
            missileCount = 0;

            //setup com dictionary
            if (comOffsets == null)
            {
                comOffsets = new Dictionary <string, Vector3>();
            }

            //destroy the existing reference transform objects
            if (missileReferenceTransforms != null)
            {
                for (int i = 0; i < missileReferenceTransforms.Length; i++)
                {
                    if (missileReferenceTransforms[i])
                    {
                        GameObject.Destroy(missileReferenceTransforms[i].gameObject);
                    }
                }
            }

            List <MissileLauncher> msl  = new List <MissileLauncher>();
            List <Transform>       mtfl = new List <Transform>();
            List <Transform>       mrl  = new List <Transform>();

            foreach (var child in part.children)
            {
                if (child.parent != part)
                {
                    continue;
                }

                MissileLauncher ml = child.FindModuleImplementing <MissileLauncher>();

                if (!ml)
                {
                    continue;
                }

                Transform mTf = child.FindModelTransform("missileTransform");
                //fix incorrect hierarchy
                if (!mTf)
                {
                    Transform modelTransform = ml.part.partTransform.FindChild("model");

                    mTf = new GameObject("missileTransform").transform;
                    Transform[] tfchildren = new Transform[modelTransform.childCount];
                    for (int i = 0; i < modelTransform.childCount; i++)
                    {
                        tfchildren[i] = modelTransform.GetChild(i);
                    }
                    mTf.parent        = modelTransform;
                    mTf.localPosition = Vector3.zero;
                    mTf.localRotation = Quaternion.identity;
                    mTf.localScale    = Vector3.one;
                    for (int i = 0; i < tfchildren.Length; i++)
                    {
                        Debug.Log("MissileTurret moving transform: " + tfchildren[i].gameObject.name);
                        tfchildren[i].parent = mTf;
                    }
                }

                if (ml && mTf)
                {
                    msl.Add(ml);
                    mtfl.Add(mTf);
                    Transform mRef = new GameObject().transform;
                    mRef.position = mTf.position;
                    mRef.rotation = mTf.rotation;
                    mRef.parent   = finalTransform;
                    mrl.Add(mRef);

                    ml.missileReferenceTransform = mTf;
                    ml.missileTurret             = this;

                    ml.decoupleForward = true;
                    ml.dropTime        = 0;

                    if (!comOffsets.ContainsKey(ml.part.name))
                    {
                        comOffsets.Add(ml.part.name, ml.part.CoMOffset);
                    }

                    missileCount++;
                }
            }

            missileChildren            = msl.ToArray();
            missileTransforms          = mtfl.ToArray();
            missileReferenceTransforms = mrl.ToArray();
        }
Example #18
0
        public static void DoExplosionRay(Ray ray, float power, float maxDistance, ref List <Part> ignoreParts, ref List <DestructibleBuilding> ignoreBldgs, Vessel sourceVessel = null)
        {
            RaycastHit rayHit;

            if (Physics.Raycast(ray, out rayHit, maxDistance, 557057))
            {
                float sqrDist        = (rayHit.point - ray.origin).sqrMagnitude;
                float sqrMaxDist     = maxDistance * maxDistance;
                float distanceFactor = Mathf.Clamp01((sqrMaxDist - sqrDist) / sqrMaxDist);
                //parts
                Part part = rayHit.collider.GetComponentInParent <Part>();
                if (part)
                {
                    Vessel missileSource = null;
                    if (sourceVessel != null)
                    {
                        MissileLauncher ml = part.FindModuleImplementing <MissileLauncher>();
                        if (ml)
                        {
                            missileSource = ml.sourceVessel;
                        }
                    }


                    if (!ignoreParts.Contains(part) && part.physicalSignificance == Part.PhysicalSignificance.FULL && (!sourceVessel || sourceVessel != missileSource))
                    {
                        ignoreParts.Add(part);
                        Rigidbody rb = part.GetComponent <Rigidbody>();
                        if (rb)
                        {
                            rb.AddForceAtPosition(ray.direction * power * distanceFactor * ExplosionImpulseMultiplier, rayHit.point, ForceMode.Impulse);
                        }

                        float heatDamage = ExplosionHeatMultiplier * power * distanceFactor / part.crashTolerance;
                        part.temperature += heatDamage;
                        if (BDArmorySettings.DRAW_DEBUG_LABELS)
                        {
                            Debug.Log("====== Explosion ray hit part! Damage: " + heatDamage);
                        }
                        return;
                    }
                }

                //buildings
                DestructibleBuilding building = rayHit.collider.GetComponentInParent <DestructibleBuilding>();
                if (building && !ignoreBldgs.Contains(building))
                {
                    ignoreBldgs.Add(building);
                    float damageToBuilding = ExplosionHeatMultiplier * 0.00685f * power * distanceFactor;
                    if (damageToBuilding > building.impactMomentumThreshold / 10)
                    {
                        building.AddDamage(damageToBuilding);
                    }
                    if (building.Damage > building.impactMomentumThreshold)
                    {
                        building.Demolish();
                    }
                    if (BDArmorySettings.DRAW_DEBUG_LABELS)
                    {
                        Debug.Log("== Explosion hit destructible building! Damage: " + (damageToBuilding).ToString("0.00") + ", total Damage: " + building.Damage);
                    }
                }
            }
        }
Example #19
0
 public override void OnInitialize()
 {
     weapon = GetComponent <MissileLauncher>();
 }
Example #20
0
#pragma warning restore CS0649

    private void Awake()
    {
        _missileParent = FindObjectOfType <MissileLauncher>();
    }
Example #21
0
        public static Vector3 DoAeroForces(MissileLauncher ml, Vector3 targetPosition, float liftArea, float steerMult, Vector3 previousTorque, float maxTorque, float maxAoA, FloatCurve liftCurve, FloatCurve dragCurve)
        {
            Rigidbody rb         = ml.part.rb;
            double    airDensity = ml.vessel.atmDensity;
            double    airSpeed   = ml.vessel.srfSpeed;
            Vector3d  velocity   = ml.vessel.srf_velocity;

            //temp values
            Vector3 CoL            = new Vector3(0, 0, -1f);
            float   liftMultiplier = BDArmorySettings.GLOBAL_LIFT_MULTIPLIER;
            float   dragMultiplier = BDArmorySettings.GLOBAL_DRAG_MULTIPLIER;


            //lift
            float AoA = Mathf.Clamp(Vector3.Angle(ml.transform.forward, velocity.normalized), 0, 90);

            if (AoA > 0)
            {
                double  liftForce      = 0.5 * airDensity * Math.Pow(airSpeed, 2) * liftArea * liftMultiplier * liftCurve.Evaluate(AoA);
                Vector3 forceDirection = Vector3.ProjectOnPlane(-velocity, ml.transform.forward).normalized;
                rb.AddForceAtPosition((float)liftForce * forceDirection, ml.transform.TransformPoint(CoL));
            }

            //drag
            if (airSpeed > 0)
            {
                double dragForce = 0.5 * airDensity * Math.Pow(airSpeed, 2) * liftArea * dragMultiplier * dragCurve.Evaluate(AoA);
                rb.AddForceAtPosition((float)dragForce * -velocity.normalized, ml.transform.TransformPoint(CoL));
            }


            //guidance
            if (airSpeed > 1)
            {
                Vector3 targetDirection;
                float   targetAngle;
                if (AoA < maxAoA)
                {
                    targetDirection = (targetPosition - ml.transform.position);
                    targetAngle     = Vector3.Angle(velocity.normalized, targetDirection) * 4;
                }
                else
                {
                    targetDirection = velocity.normalized;
                    targetAngle     = AoA;
                }

                Vector3 torqueDirection = -Vector3.Cross(targetDirection, velocity.normalized).normalized;
                torqueDirection = ml.transform.InverseTransformDirection(torqueDirection);

                float   torque      = Mathf.Clamp(targetAngle * steerMult, 0, maxTorque);
                Vector3 finalTorque = Vector3.ProjectOnPlane(Vector3.Lerp(previousTorque, torqueDirection * torque, 0.86f), Vector3.forward);

                rb.AddRelativeTorque(finalTorque);

                return(finalTorque);
            }
            else
            {
                Vector3 finalTorque = Vector3.ProjectOnPlane(Vector3.Lerp(previousTorque, Vector3.zero, 0.25f), Vector3.forward);
                rb.AddRelativeTorque(finalTorque);
                return(finalTorque);
            }
        }
	void Start(){
		if(!missileLauncher) missileLauncher = GetComponent<MissileLauncher>();
	}
    void Update()
    {
        mechInUse = mechScript.inUse;


        if (mechInUse == false || mechScript.driver == null)
        {
            return;
        }


        if (mechScript.inUse)
        {
            inputUp    = mechScript.driver.inputUp;
            inputDown  = mechScript.driver.inputDown;
            inputRight = mechScript.driver.inputRight;
            inputLeft  = mechScript.driver.inputLeft;
            inputFire  = mechScript.driver.inputFire;
        }



        //Mech fly animation: raycast dist to ground
        float   minDistToGround = 0.55f;//dist for standby animation to occur
        Vector2 rayDown         = transform.TransformDirection(Vector2.down);

        int          groundLayerMaskIgnore = ~LayerMask.GetMask("Mechs");
        RaycastHit2D groundHit             = Physics2D.Raycast(transform.position, rayDown, 20.0f, groundLayerMaskIgnore);

        //Debug.DrawRay(transform.position, rayDown, Color.green);

        /*if (groundHit)
         * {
         *  if(groundHit.collider)
         *  {
         *      GroundDist = groundHit.distance;//dist to ground
         *      Debug.Log("collider hit " + groundHit.collider.gameObject.name);
         *      Debug.Log("Distance to Ground " + GroundDist);
         *      Debug.DrawRay(transform.position, rayDown, Color.green);
         *  }
         * }*/
        //Debug.Log("HERE NOW  " + GroundDist + " " + minDistToGround);
        //if (GroundDist<= minDistToGround)
        if (mechScript.isOnGround)
        {
            anim.SetBool(onGroundHash, true);
        }
        else
        {
            anim.SetBool(onGroundHash, false);
        }

        if (mechInUse)
        {
            anim.speed = 1;
            anim.SetBool(mechInUseHash, true);
        }
        else
        {
            anim.speed = 0;
        }

        //if (GroundDist <= minDistToGround && mechInUse && !inputUp && !inputDown && (inputLeft || inputRight))//mechScript.inUse
        if (mechScript.isOnGround && mechInUse && !inputUp && !inputDown && (inputLeft || inputRight))//mechScript.inUse
        {
            walk = walkSpeed;
            //Debug.Log("inputLeft " + inputLeft + " inputUp" + inputUp + " inputDown" + inputDown);
            anim.SetFloat("walk", walk);
        }
        else
        {
            walk = 0.0f;
            anim.SetFloat("walk", walk);
        }

        //swing Sword Animation. Missile Shot takes precedence to swing sword
        swordSwing();
        animPlayingTag = anim.GetCurrentAnimatorStateInfo(0).tagHash;
        //Debug.Log("Anim playing " + animPlayingTag + " TagID_SwordSwing"  + swordSwingTag + "Current State Anim " + anim.GetCurrentAnimatorStateInfo(0).normalizedTime);
        if (animPlayingTag == swordSwingTag && anim.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1 || anim.GetBool(onGroundHash) == false || missileShot == true)
        {
            Debug.Log("Switching off Swing Sword");
            anim.SetBool(swingAtReachHash, false);
        }

        //Missile Animations
        if (weaponMgr.launcherMounted && launcherOn == false)
        {
            missileLauncher = GetComponentInChildren <MissileLauncher>();
            launcherOn      = true;
        }

        //Debug.Log("launcher is On " + launcherOn);
        //Debug.Log("Missile Shot is on " + missileShot);

        //Debug.Log("Launcher Mounted NOW " + weaponMgr.launcherMounted);

        if (weaponMgr.launcherMounted)
        {
            //TODO: need to move this outside update
            //render off for missile launcher cos mech already has missile shooter
            GameObject   missileLauncherGO     = GameObject.FindGameObjectWithTag("missileLauncher");
            MeshRenderer missileLauncherRender = missileLauncherGO.GetComponent <MeshRenderer>();
            missileLauncherRender.enabled = false;

            missileShot = missileLauncher.hasShotMissile;
            //Debug.Log("MissileShot Flag is " + missileShot);

            if (missileShot)
            {
                animPlayingTag = anim.GetCurrentAnimatorStateInfo(0).tagHash;
                anim.SetBool(missileShotHash, true);

                //decide anim to play
                if (positionLocked)
                {
                    missleLauncherLocationY = missileLauncherLocation.transform.position.y;
                    //Debug.Log("I'm inside positionLocked and the var is " + positionLocked);
                    lasserAnimDirection(missleLauncherLocationY);
                    //play missile particles to hide wrong exit of missile
                    missileFireParticles.Play();
                }
                //Debug.Log("Now PositionLocked is " + positionLocked);
                //Debug.Log("missileShot " + missileShot + " ////AnimPlayingTag " + animPlayingTag + "missileShotStraight1Tag " + missileShotStraight1Tag + " Straigh2 " + missileShotStraight2Tag  + " ShotUp " + missileShotUpTag + " ShotDown " + missileShotDownTag);
                //Debug.Log("Bool for Shooting Anim " + anim.GetBool(missileShotHash) + " time to end anim " + anim.GetCurrentAnimatorStateInfo(0).normalizedTime + " AnimPlayingTag " + animPlayingTag);
                //Debug.Log("Current Anim playing before flag to False " + animPlayingTag);
                if (anim.GetBool(missileShotHash) && anim.GetCurrentAnimatorStateInfo(0).normalizedTime >= 1)//(animPlayingTag==missileShotStraight1Tag || animPlayingTag==missileShotStraight2Tag || animPlayingTag==missileShotUpTag || animPlayingTag==missileShotDownTag)
                {
                    //Debug.Log("Has finished playing Anim");
                    //Debug.Log("We flag to false now : Bool for Shooting Anim " + anim.GetBool(missileShotHash) + " time to end anim " + anim.GetCurrentAnimatorStateInfo(0).normalizedTime + " AnimPlayingTag " + animPlayingTag);
                    if (animPlayingTag == missileShotStraight1Tag)
                    {
                        //missileShotStraight1 = false;
                        anim.SetBool(missileShotStraight1Hash, false);
                    }
                    else if (animPlayingTag == missileShotStraight2Tag)
                    {
                        //missileShotStraight2 = false;
                        anim.SetBool(missileShotStraight2Hash, false);
                    }
                    else if (animPlayingTag == missileShotUpTag)
                    {
                        anim.SetBool(missileShotUpHash, false);
                    }
                    else if (animPlayingTag == missileShotDownTag)
                    {
                        anim.SetBool(missileShotDownHash, false);
                    }
                    else
                    {
                        //  Debug.Log("Unrecognized AnimPlayingTag" + " AnimPlayingTag " + animPlayingTag);
                    }
                    missileLauncher.hasShotMissile = false;
                    anim.SetBool(missileShotHash, false);
                    //disable particles missile launch
                    missileFireParticles.Stop();
                }
            }
        }
    }
Example #24
0
        void Awake()
        {
            if (!vessel)
            {
                vessel = GetComponent <Vessel>();
            }
            if (!vessel)
            {
                Debug.Log("TargetInfo was added to a non-vessel");
                Destroy(this);
                return;
            }

            //destroy this if a target info is already attached to the vessel
            foreach (var otherInfo in vessel.gameObject.GetComponents <TargetInfo>())
            {
                if (otherInfo != this)
                {
                    Destroy(this);
                    return;
                }
            }

            team = BDArmorySettings.BDATeams.None;

            bool foundMf = false;

            foreach (var mf in vessel.FindPartModulesImplementing <MissileFire>())
            {
                foundMf       = true;
                team          = BDATargetManager.BoolToTeam(mf.team);
                weaponManager = mf;
                break;
            }
            if (!foundMf)
            {
                foreach (var ml in vessel.FindPartModulesImplementing <MissileLauncher>())
                {
                    isMissile     = true;
                    missileModule = ml;
                    team          = BDATargetManager.BoolToTeam(ml.team);
                    break;
                }
            }

            if (team != BDArmorySettings.BDATeams.None)
            {
                if (!BDATargetManager.TargetDatabase[BDATargetManager.OtherTeam(team)].Contains(this))
                {
                    BDATargetManager.TargetDatabase[BDATargetManager.OtherTeam(team)].Add(this);
                }
            }

            friendliesEngaging = new List <MissileFire>();

            vessel.OnJustAboutToBeDestroyed += AboutToBeDestroyed;
            lifeRoutine = StartCoroutine(LifetimeRoutine());
            //add delegate to peace enable event
            BDArmorySettings.OnPeaceEnabled += OnPeaceEnabled;

            if (!isMissile && team != BDArmorySettings.BDATeams.None)
            {
                massRoutine = StartCoroutine(MassRoutine());
            }
        }
Example #25
0
    public static void Load(string path)
    {
        DataStructure saved = DataStructure.Load(path);
        DataStructure general_information = saved.GetChild("GeneralInformation");
        DataStructure original_file       = DataStructure.Load(general_information.Get <string>("original_path"), is_general: true);

        FileReader.FileLog("Begin Loading", FileLogType.loader);
        GameObject       placeholder = GameObject.Find("Placeholder");
        GeneralExecution general     = placeholder.GetComponent <GeneralExecution>();

        general.battle_path = path;

        // Initiate Operating system
        general.os = new NMS.OS.OperatingSystem(Object.FindObjectOfType <ConsoleBehaviour>(), null);

        // Initiate mission core
        Loader partial_loader = new Loader(original_file);

        general.mission_core = new MissionCore(general.console, partial_loader);

        general.mission_core.in_level_progress = (short)general_information.Get <int>("in level progress");
        general.mission_core.in_stage_progress = (short)general_information.Get <int>("in stage progress");
        DeveloppmentTools.Log("start loading");
        partial_loader.LoadEssentials();

        DataStructure objects = saved.GetChild("ObjectStates");

        Debug.Log(objects);
        foreach (DataStructure child in objects.AllChildren)
        {
            int id = child.Get <ushort>("type", 1000, quiet: true);
            switch (id)
            {
            case 0:
                // Ship
                Dictionary <string, Turret[]> weapon_arrays = new Dictionary <string, Turret[]>();

                string     config_path  = child.Get <string>("config path");
                bool       is_friendly  = child.Get <bool>("friendly");
                bool       is_player    = child.Get <bool>("player");
                int        given_id     = child.Get <int>("id");
                GameObject ship_chassis = Loader.SpawnShip(config_path, is_friendly, is_player, false, pre_id: given_id);

                //LowLevelAI ai = Loader.EnsureComponent<LowLevelAI>(ship_chassis);
                //ai.HasHigherAI = !is_player;

                ShipControl ship_control = ship_chassis.GetComponent <ShipControl>();
                Ship        ship         = ship_control.myship;
                //ship.control_script.ai_low = ai;
                //ship.low_ai = ai;

                int netID = child.Get("parent network", is_friendly ? 1 : 2);
                if (SceneObject.TotObjectList.ContainsKey(netID) && SceneObject.TotObjectList [netID] is Network)
                {
                    ship.high_ai.Net = SceneObject.TotObjectList [netID] as Network;
                }

                ship.Position        = child.Get <Vector3>("position");
                ship.Orientation     = child.Get <Quaternion>("orientation");
                ship.Velocity        = child.Get <Vector3>("velocity");
                ship.AngularVelocity = child.Get <Vector3>("angular velocity");

                foreach (DataStructure child01 in child.AllChildren)
                {
                    switch (child01.Get <ushort>("type", 9, quiet:true))
                    {
                    case 1:                     // weapon
                        Weapon.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 3:                     // fuel tank
                        FuelTank.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 4:                     // engine
                        Engine.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 10:                     // ammo box
                        AmmoBox.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 11:                     // missile launcher
                        MissileLauncher.GetFromDS(child01.GetChild("description"), child01, ship.Transform);
                        break;

                    case 12:                     // armor
                        Armor.GetFromDS(child01, ship);
                        break;

                    default:
                        if (child01.Name.StartsWith("turr-"))
                        {
                            var tg = TurretGroup.Load(child01, ship);
                            weapon_arrays [child01.Name.Substring(5)] = tg.TurretArray;
                            ship_control.turretgroup_list.Add(new TurretGroup(Target.None, tg.TurretArray, tg.name)
                            {
                                own_ship = ship
                            });
                        }
                        break;
                    }
                }


                // Initializes parts
                foreach (BulletCollisionDetection part in ship_chassis.GetComponentsInChildren <BulletCollisionDetection>())
                {
                    part.Initialize();
                }
                ship_control.turrets = weapon_arrays;

                ship.os.cpu.Execute(child.Get <ulong []>("code"));

                if (is_player)
                {
                    SceneGlobals.Player = ship;
                    SceneGlobals.ui_script.Start_();
                }

                break;

            case 1:             // Missile
                Missile.SpawnFlying(child);
                break;

            case 2:             // Bullet
                Bullet.Spawn(
                    Globals.ammunition_insts [child.Get <string>("ammunition")],
                    child.Get <Vector3>("position"),
                    Quaternion.FromToRotation(Vector3.forward, child.Get <Vector3>("velocity")),
                    child.Get <Vector3>("velocity"),
                    child.Get <bool>("is_friend")
                    );
                break;

            case 3:             // Destroyable target
                DestroyableTarget.Load(child);
                break;

            case 4:             // Explosion

                break;
            }
        }

        general.os.Attached = SceneGlobals.Player;

        ReferenceSystem ref_sys;

        if (general_information.Contains <Vector3>("RS position"))
        {
            ref_sys = new ReferenceSystem(general_information.Get <Vector3>("RS position"));
        }
        else
        {
            int parent_id = general_information.Get <int>("RS parent");
            if (SceneObject.TotObjectList.ContainsKey(parent_id))
            {
                ref_sys = new ReferenceSystem(SceneObject.TotObjectList [parent_id]);
            }
            else
            {
                ref_sys = new ReferenceSystem(Vector3.zero);
            }
            ref_sys.Offset = general_information.Get <Vector3>("RS offset");
        }
        SceneGlobals.ReferenceSystem = ref_sys;
    }
        void CamWindow(int windowID)
        {
            if (!TargetingCamera.Instance)
            {
                return;
            }

            windowIsOpen = true;

            GUI.DragWindow(new Rect(0, 0, camImageSize + 16, camImageSize + 8));

            Rect imageRect = new Rect(8, 20, camImageSize, camImageSize);

            GUI.DrawTexture(imageRect, TargetingCamera.Instance.targetCamRenderTexture, ScaleMode.StretchToFill, false);
            GUI.DrawTexture(imageRect, TargetingCamera.Instance.ReticleTexture, ScaleMode.StretchToFill, true);

            float controlsStartY = 24 + camImageSize + 4;

            //slew buttons
            float slewStartX    = 8;
            float slewSize      = (controlPanelHeight / 3) - 8;
            Rect  slewUpRect    = new Rect(slewStartX + slewSize, controlsStartY, slewSize, slewSize);
            Rect  slewDownRect  = new Rect(slewStartX + slewSize, controlsStartY + (2 * slewSize), slewSize, slewSize);
            Rect  slewLeftRect  = new Rect(slewStartX, controlsStartY + slewSize, slewSize, slewSize);
            Rect  slewRightRect = new Rect(slewStartX + (2 * slewSize), controlsStartY + slewSize, slewSize, slewSize);

            if (GUI.RepeatButton(slewUpRect, "^", HighLogic.Skin.button))
            {
                //SlewCamera(Vector3.up);
                slewInput.y = 1;
            }
            if (GUI.RepeatButton(slewDownRect, "v", HighLogic.Skin.button))
            {
                //SlewCamera(Vector3.down);
                slewInput.y = -1;
            }
            if (GUI.RepeatButton(slewLeftRect, "<", HighLogic.Skin.button))
            {
                //SlewCamera(Vector3.left);
                slewInput.x = -1;
            }
            if (GUI.RepeatButton(slewRightRect, ">", HighLogic.Skin.button))
            {
                //SlewCamera(Vector3.right);
                slewInput.x = 1;
            }

            //zoom buttons
            float    zoomStartX    = 8 + (3 * slewSize) + 4;
            Rect     zoomInRect    = new Rect(zoomStartX, controlsStartY, 3 * slewSize, slewSize);
            Rect     zoomOutRect   = new Rect(zoomStartX, controlsStartY + (2 * slewSize), 3 * slewSize, slewSize);
            GUIStyle disabledStyle = new GUIStyle();

            disabledStyle.alignment        = TextAnchor.MiddleCenter;
            disabledStyle.normal.textColor = Color.white;
            if (currentFovIndex < zoomFovs.Length - 1)
            {
                if (GUI.Button(zoomInRect, "In", HighLogic.Skin.button))
                {
                    ZoomIn();
                }
            }
            else
            {
                GUI.Label(zoomInRect, "(In)", disabledStyle);
            }
            if (currentFovIndex > 0)
            {
                if (GUI.Button(zoomOutRect, "Out", HighLogic.Skin.button))
                {
                    ZoomOut();
                }
            }
            else
            {
                GUI.Label(zoomOutRect, "(Out)", disabledStyle);
            }
            Rect     zoomInfoRect  = new Rect(zoomStartX, controlsStartY + slewSize, 3 * slewSize, slewSize);
            GUIStyle zoomInfoStyle = new GUIStyle(HighLogic.Skin.box);

            zoomInfoStyle.fontSize = 12;
            zoomInfoStyle.wordWrap = false;
            GUI.Label(zoomInfoRect, "Zoom " + (currentFovIndex + 1).ToString(), zoomInfoStyle);

            GUIStyle dataStyle = new GUIStyle();

            dataStyle.alignment        = TextAnchor.MiddleCenter;
            dataStyle.normal.textColor = Color.white;

            //groundStablize button
            float stabilStartX  = zoomStartX + zoomInRect.width + 4;
            Rect  stabilizeRect = new Rect(stabilStartX, controlsStartY, 3 * slewSize, 3 * slewSize);

            if (!groundStabilized)
            {
                if (GUI.Button(stabilizeRect, "Lock\nTarget", HighLogic.Skin.button))
                {
                    GroundStabilize();
                }
            }
            else
            {
                if (GUI.Button(new Rect(stabilizeRect.x, stabilizeRect.y, stabilizeRect.width, stabilizeRect.height / 2), "Unlock", HighLogic.Skin.button))
                {
                    ClearTarget();
                }
                if (weaponManager)
                {
                    GUIStyle gpsStyle = new GUIStyle(HighLogic.Skin.button);
                    gpsStyle.fontSize = 10;
                    if (GUI.Button(new Rect(stabilizeRect.x, stabilizeRect.y + (stabilizeRect.height / 2), stabilizeRect.width, stabilizeRect.height / 2), "Send GPS", gpsStyle))
                    {
                        SendGPS();
                    }
                }

                if (!gimbalLimitReached)
                {
                    //open square
                    float oSqrSize = (24f / 512f) * camImageSize;
                    Rect  oSqrRect = new Rect(imageRect.x + (camImageSize / 2) - (oSqrSize / 2), imageRect.y + (camImageSize / 2) - (oSqrSize / 2), oSqrSize, oSqrSize);
                    GUI.DrawTexture(oSqrRect, BDArmorySettings.Instance.openWhiteSquareTexture, ScaleMode.StretchToFill, true);
                }

                //geo data
                Rect   geoRect  = new Rect(imageRect.x, (camImageSize * 0.94f), camImageSize, 14);
                string geoLabel = Misc.FormattedGeoPos(bodyRelativeGTP, false);
                GUI.Label(geoRect, geoLabel, dataStyle);

                //target data
                dataStyle.fontSize = 16;
                float  dataStartX      = stabilStartX + stabilizeRect.width + 8;
                Rect   targetRangeRect = new Rect(imageRect.x, (camImageSize * 0.94f) - 18, camImageSize, 18);
                float  targetRange     = Vector3.Distance(groundTargetPosition, transform.position);
                string rangeString     = "Range: " + targetRange.ToString("0.0") + "m";
                GUI.Label(targetRangeRect, rangeString, dataStyle);

                //laser ranging indicator
                dataStyle.fontSize = 18;
                string lrLabel = surfaceDetected ? "LR" : "NO LR";
                Rect   lrRect  = new Rect(imageRect.x, imageRect.y + (camImageSize * 0.65f), camImageSize, 20);
                GUI.Label(lrRect, lrLabel, dataStyle);

                //azimuth and elevation indicator //UNFINISHED

                /*
                 * Vector2 azielPos = TargetAzimuthElevationScreenPos(imageRect, groundTargetPosition, 4);
                 * Rect azielRect = new Rect(azielPos.x, azielPos.y, 4, 4);
                 * GUI.DrawTexture(azielRect, BDArmorySettings.Instance.whiteSquareTexture, ScaleMode.StretchToFill, true);
                 */

                //DLZ
                if (weaponManager && weaponManager.selectedWeapon != null)
                {
                    if (weaponManager.selectedWeapon.GetWeaponClass() == WeaponClasses.Missile)
                    {
                        MissileLauncher currMissile = weaponManager.currentMissile;
                        if (currMissile.targetingMode == MissileLauncher.TargetingModes.GPS || currMissile.targetingMode == MissileLauncher.TargetingModes.Laser)
                        {
                            MissileLaunchParams dlz = MissileLaunchParams.GetDynamicLaunchParams(currMissile, Vector3.zero, groundTargetPosition);
                            float dlzWidth          = 12 * (imageRect.width / 360);
                            float lineWidth         = 2;
                            Rect  dlzRect           = new Rect(imageRect.x + imageRect.width - (3 * dlzWidth) - lineWidth, imageRect.y + (imageRect.height / 4), dlzWidth, imageRect.height / 2);
                            float scaleDistance     = Mathf.Max(Mathf.Max(8000f, currMissile.maxStaticLaunchRange * 2), targetRange);
                            float rangeToPixels     = (1f / scaleDistance) * dlzRect.height;


                            GUI.BeginGroup(dlzRect);

                            float dlzX = 0;

                            BDGUIUtils.DrawRectangle(new Rect(0, 0, dlzWidth, dlzRect.height), Color.black);

                            Rect maxRangeVertLineRect = new Rect(dlzRect.width - lineWidth, Mathf.Clamp(dlzRect.height - (dlz.maxLaunchRange * rangeToPixels), 0, dlzRect.height), lineWidth, Mathf.Clamp(dlz.maxLaunchRange * rangeToPixels, 0, dlzRect.height));
                            BDGUIUtils.DrawRectangle(maxRangeVertLineRect, Color.white);


                            Rect maxRangeTickRect = new Rect(dlzX, maxRangeVertLineRect.y, dlzWidth, lineWidth);
                            BDGUIUtils.DrawRectangle(maxRangeTickRect, Color.white);

                            Rect minRangeTickRect = new Rect(dlzX, Mathf.Clamp(dlzRect.height - (dlz.minLaunchRange * rangeToPixels), 0, dlzRect.height), dlzWidth, lineWidth);
                            BDGUIUtils.DrawRectangle(minRangeTickRect, Color.white);

                            Rect rTrTickRect = new Rect(dlzX, Mathf.Clamp(dlzRect.height - (dlz.rangeTr * rangeToPixels), 0, dlzRect.height), dlzWidth, lineWidth);
                            BDGUIUtils.DrawRectangle(rTrTickRect, Color.white);

                            Rect noEscapeLineRect = new Rect(dlzX, rTrTickRect.y, lineWidth, minRangeTickRect.y - rTrTickRect.y);
                            BDGUIUtils.DrawRectangle(noEscapeLineRect, Color.white);


                            GUI.EndGroup();

                            float targetDistIconSize = 6;
                            float targetDistY        = dlzRect.y + dlzRect.height - (targetRange * rangeToPixels);
                            Rect  targetDistanceRect = new Rect(dlzRect.x - (targetDistIconSize / 2), targetDistY, (targetDistIconSize / 2) + dlzRect.width, targetDistIconSize);
                            BDGUIUtils.DrawRectangle(targetDistanceRect, Color.white);
                        }
                    }
                }
            }



            //gimbal limit
            dataStyle.fontSize = 24;
            if (gimbalLimitReached)
            {
                Rect gLimRect = new Rect(imageRect.x, imageRect.y + (camImageSize * 0.15f), camImageSize, 28);
                GUI.Label(gLimRect, "GIMBAL LIMIT", dataStyle);
            }


            //reset button
            float resetStartX = stabilStartX + stabilizeRect.width + 4;
            Rect  resetRect   = new Rect(resetStartX, controlsStartY + (2 * slewSize), 3 * slewSize, slewSize - 1);

            if (GUI.Button(resetRect, "Reset", HighLogic.Skin.button))
            {
                ResetCameraButton();
            }


            //CoM lock
            Rect     comLockRect = new Rect(resetRect.x, controlsStartY, 3 * slewSize, slewSize - 1);
            GUIStyle comStyle    = new GUIStyle(CoMLock ? HighLogic.Skin.box : HighLogic.Skin.button);

            comStyle.fontSize = 10;
            comStyle.wordWrap = false;
            if (GUI.Button(comLockRect, "CoM Track", comStyle))
            {
                CoMLock = !CoMLock;
            }


            //radar slave
            Rect     radarSlaveRect  = new Rect(comLockRect.x + comLockRect.width + 4, comLockRect.y, 3 * slewSize, slewSize - 1);
            GUIStyle radarSlaveStyle = radarLock ? HighLogic.Skin.box : HighLogic.Skin.button;

            if (GUI.Button(radarSlaveRect, "Radar", radarSlaveStyle))
            {
                radarLock = !radarLock;
            }

            //slave turrets button
            Rect slaveRect = new Rect(resetStartX, controlsStartY + slewSize, (3 * slewSize), slewSize - 1);

            if (!slaveTurrets)
            {
                if (GUI.Button(slaveRect, "Turrets", HighLogic.Skin.button))
                {
                    SlaveTurrets();
                }
            }
            else
            {
                if (GUI.Button(slaveRect, "Turrets", HighLogic.Skin.box))
                {
                    UnslaveTurrets();
                }
            }

            //point to gps button
            Rect toGpsRect = new Rect(resetRect.x + slaveRect.width + 4, slaveRect.y, 3 * slewSize, slewSize - 1);

            if (GUI.Button(toGpsRect, "To GPS", HighLogic.Skin.button))
            {
                PointToGPSTarget();
            }


            //nv button
            float    nvStartX = resetStartX + resetRect.width + 4;
            Rect     nvRect   = new Rect(nvStartX, resetRect.y, 3 * slewSize, slewSize - 1);
            string   nvLabel  = nvMode ? "NV Off" : "NV On";
            GUIStyle nvStyle  = nvMode ? HighLogic.Skin.box : HighLogic.Skin.button;

            if (GUI.Button(nvRect, nvLabel, nvStyle))
            {
                ToggleNV();
            }

            //off button
            float offStartX = nvStartX + nvRect.width + 4;
            Rect  offRect   = new Rect(offStartX, controlsStartY, slewSize * 1.5f, 3 * slewSize);

            if (GUI.Button(offRect, "O\nF\nF", HighLogic.Skin.button))
            {
                DisableCamera();
            }


            float   indicatorSize   = Mathf.Clamp(64 * (camImageSize / 360), 64, 128);
            float   indicatorBorder = imageRect.width * 0.056f;
            Vector3 vesForward      = vessel.ReferenceTransform.up;
            Vector3 upDirection     = (transform.position - FlightGlobals.currentMainBody.transform.position).normalized;
            //horizon indicator
            float   horizY   = imageRect.y + imageRect.height - indicatorSize - indicatorBorder;
            Vector3 hForward = Vector3.ProjectOnPlane(vesForward, upDirection);
            float   hAngle   = -Misc.SignedAngle(hForward, vesForward, upDirection);

            horizY -= (hAngle / 90) * (indicatorSize / 2);
            Rect horizonRect = new Rect(indicatorBorder + imageRect.x, horizY, indicatorSize, indicatorSize);

            GUI.DrawTexture(horizonRect, BDArmorySettings.Instance.horizonIndicatorTexture, ScaleMode.StretchToFill, true);

            //roll indicator
            Rect rollRect = new Rect(indicatorBorder + imageRect.x, imageRect.y + imageRect.height - indicatorSize - indicatorBorder, indicatorSize, indicatorSize);

            GUI.DrawTexture(rollRect, rollReferenceTexture, ScaleMode.StretchToFill, true);
            Vector3 localUp = vessel.ReferenceTransform.InverseTransformDirection(upDirection);

            localUp = Vector3.ProjectOnPlane(localUp, Vector3.up).normalized;
            float rollAngle = -Misc.SignedAngle(-Vector3.forward, localUp, Vector3.right);

            GUIUtility.RotateAroundPivot(rollAngle, rollRect.center);
            GUI.DrawTexture(rollRect, rollIndicatorTexture, ScaleMode.StretchToFill, true);
            GUI.matrix = Matrix4x4.identity;

            //target direction indicator
            float angleToTarget = Misc.SignedAngle(hForward, Vector3.ProjectOnPlane(targetPointPosition - transform.position, upDirection), Vector3.Cross(upDirection, hForward));

            GUIUtility.RotateAroundPivot(angleToTarget, rollRect.center);
            GUI.DrawTexture(rollRect, BDArmorySettings.Instance.targetDirectionTexture, ScaleMode.StretchToFill, true);
            GUI.matrix = Matrix4x4.identity;



            //resizing
            Rect resizeRect = new Rect(camWindowRect.width - 20, camWindowRect.height - 20, 20, 20);

            if (GUI.RepeatButton(resizeRect, "//"))
            {
                resizing = true;
            }

            if (resizing)
            {
                camImageSize += Mouse.delta.x / 4;
                camImageSize += Mouse.delta.y / 4;

                camImageSize = Mathf.Clamp(camImageSize, 360, 800);


                RefreshWindowSize();
            }

            if (Input.GetMouseButtonUp(0))
            {
                resizing = false;
            }
        }
Example #27
0
        public void UpdateMissileChildren()
        {
            missileCount = 0;

            //setup com dictionary
            if (comOffsets == null)
            {
                comOffsets = new Dictionary <string, Vector3>();
            }

            //destroy the existing reference transform objects
            if (missileReferenceTransforms != null)
            {
                for (int i = 0; i < missileReferenceTransforms.Length; i++)
                {
                    if (missileReferenceTransforms[i])
                    {
                        Destroy(missileReferenceTransforms[i].gameObject);
                    }
                }
            }

            List <MissileLauncher> msl  = new List <MissileLauncher>();
            List <Transform>       mtfl = new List <Transform>();
            List <Transform>       mrl  = new List <Transform>();

            List <Part> .Enumerator child = part.children.GetEnumerator();
            while (child.MoveNext())
            {
                if (child.Current == null)
                {
                    continue;
                }
                if (child.Current.parent != part)
                {
                    continue;
                }

                MissileLauncher ml = child.Current.FindModuleImplementing <MissileLauncher>();

                if (!ml)
                {
                    continue;
                }

                Transform mTf = child.Current.FindModelTransform("missileTransform");
                //fix incorrect hierarchy
                if (!mTf)
                {
                    Transform modelTransform = ml.part.partTransform.FindChild("model");

                    mTf = new GameObject("missileTransform").transform;
                    Transform[] tfchildren = new Transform[modelTransform.childCount];
                    for (int i = 0; i < modelTransform.childCount; i++)
                    {
                        tfchildren[i] = modelTransform.GetChild(i);
                    }
                    mTf.parent        = modelTransform;
                    mTf.localPosition = Vector3.zero;
                    mTf.localRotation = Quaternion.identity;
                    mTf.localScale    = Vector3.one;
                    IEnumerator <Transform> t = tfchildren.AsEnumerable().GetEnumerator();
                    while (t.MoveNext())
                    {
                        if (t.Current == null)
                        {
                            continue;
                        }
                        if (BDArmorySettings.DRAW_DEBUG_LABELS)
                        {
                            Debug.Log("[BDArmory] : MissileTurret moving transform: " + t.Current.gameObject.name);
                        }
                        t.Current.parent = mTf;
                    }
                    t.Dispose();
                }

                if (!ml || !mTf)
                {
                    continue;
                }
                msl.Add(ml);
                mtfl.Add(mTf);
                Transform mRef = new GameObject().transform;
                mRef.position = mTf.position;
                mRef.rotation = mTf.rotation;
                mRef.parent   = finalTransform;
                mrl.Add(mRef);

                ml.MissileReferenceTransform = mTf;
                ml.missileTurret             = this;

                ml.decoupleForward = true;
                ml.dropTime        = 0;

                if (!comOffsets.ContainsKey(ml.part.name))
                {
                    comOffsets.Add(ml.part.name, ml.part.CoMOffset);
                }

                missileCount++;
            }
            child.Dispose();

            missileChildren            = msl.ToArray();
            missileTransforms          = mtfl.ToArray();
            missileReferenceTransforms = mrl.ToArray();
        }
Example #28
0
        public void UpdateMissileChildren()
        {
            missileCount = 0;

            //setup com dictionary
            if (comOffsets == null)
            {
                comOffsets = new Dictionary <Part, Vector3>();
            }

            //destroy the existing reference transform objects
            if (missileReferenceTransforms != null)
            {
                for (int i = 0; i < missileReferenceTransforms.Length; i++)
                {
                    if (missileReferenceTransforms[i])
                    {
                        Destroy(missileReferenceTransforms[i].gameObject);
                    }
                }
            }

            List <MissileLauncher> msl  = new List <MissileLauncher>();
            List <Transform>       mtfl = new List <Transform>();
            List <Transform>       mrl  = new List <Transform>();

            List <Part> .Enumerator child = part.children.GetEnumerator();
            while (child.MoveNext())
            {
                if (child.Current == null)
                {
                    continue;
                }
                if (child.Current.parent != part)
                {
                    continue;
                }

                MissileLauncher ml = child.Current.FindModuleImplementing <MissileLauncher>();

                if (!ml)
                {
                    continue;
                }

                Transform mTf = child.Current.FindModelTransform("missileTransform");
                //fix incorrect hierarchy
                if (!mTf)
                {
                    Transform modelTransform = ml.part.partTransform.Find("model");

                    mTf = new GameObject("missileTransform").transform;
                    Transform[] tfchildren = new Transform[modelTransform.childCount];
                    for (int i = 0; i < modelTransform.childCount; i++)
                    {
                        tfchildren[i] = modelTransform.GetChild(i);
                    }
                    mTf.parent        = modelTransform;
                    mTf.localPosition = Vector3.zero;
                    mTf.localRotation = Quaternion.identity;
                    mTf.localScale    = Vector3.one;
                    IEnumerator <Transform> t = tfchildren.AsEnumerable().GetEnumerator();
                    while (t.MoveNext())
                    {
                        if (t.Current == null)
                        {
                            continue;
                        }
                        //Debug.Log("MissileTurret moving transform: " + tfchildren[i].gameObject.name);
                        t.Current.parent = mTf;
                    }
                    t.Dispose();
                }

                if (!mTf)
                {
                    continue;
                }
                msl.Add(ml);
                mtfl.Add(mTf);
                Transform mRef = new GameObject().transform;
                mRef.position = mTf.position;
                mRef.rotation = mTf.rotation;
                mRef.parent   = rotationTransforms[0];
                mrl.Add(mRef);

                ml.MissileReferenceTransform = mTf;
                ml.rotaryRail = this;

                ml.decoupleForward = false;
                //ml.decoupleSpeed = Mathf.Max(ml.decoupleSpeed, 4); //removing clamp as some weapons want greater decouple speeds
                ml.dropTime = Mathf.Max(ml.dropTime, 0.2f);

                if (!comOffsets.ContainsKey(ml.part))
                {
                    comOffsets.Add(ml.part, ml.part.CoMOffset);
                }
            }
            child.Dispose();

            missileChildren            = msl.ToArray();
            missileCount               = missileChildren.Length;
            missileTransforms          = mtfl.ToArray();
            missileReferenceTransforms = mrl.ToArray();

            UpdateIndexDictionary();
        }
Example #29
0
    public void Initialize(int pregiven_id = -1)
    {
        //Read the data
        DataStructure data = data_ == null ? data_ = DataStructure.Load(config_path, "data", null) : data_;

        // Variables used to place weapons
        Dictionary <string, Turret[]> weapon_arrays = new Dictionary <string, Turret[]> ();

        //First set up some basic things
        Ship own_ship = new Ship(gameObject, friendly, data.Get <string>("name"), pregiven_id);

        ShipControl ship_control = Loader.EnsureComponent <ShipControl> (gameObject);
        RCSFiring   rcs_comp     = Loader.EnsureComponent <RCSFiring> (gameObject);

        own_ship.control_script = ship_control;
        own_ship.rcs_script     = rcs_comp;
        own_ship.config_path    = config_path;
        own_ship.TurretAim      = own_ship.Target = Target.None;

        ship_control.myship = own_ship;

        // AI
        LowLevelAI ai = Loader.EnsureComponent <LowLevelAI>(gameObject);

        ai.Start_();
        ai.HasHigherAI = !player;

        HighLevelAI high_ai = own_ship.high_ai;

        //high_ai.Load(child.GetChild("ai data"));

        high_ai.low_ai = ai;

        // Instantiates normal UI marker
        TgtMarker.Instantiate(own_ship, 1);

        foreach (KeyValuePair <string, DataStructure> child_pair in data_.children)
        {
            // Do this for each "command" in the datafile
            DataStructure child     = child_pair.Value;
            string        comp_name = child.Name;

            DataStructure part_data;
            if (child.Contains <string>("part"))
            {
                string part_name = child.Get <string>("part");
                part_data = Globals.parts.Get <DataStructure>(part_name);
            }
            else
            {
                part_data = child;
            }
            switch (comp_name)
            {
            case "rcs":
                ship_control.RCS_ISP = child.Get <float>("isp");

                rcs_comp.rcs_mesh           = child.Get <GameObject>("mesh");
                rcs_comp.strength           = child.Get <float>("thrust");
                rcs_comp.angular_limitation = child.Get <float>("angular limitation", 1);
                rcs_comp.positions          = child.Get <Vector3[]>("positions");
                rcs_comp.directions         = child.Get <Quaternion[]>("orientations");
                break;

            case "ship":
                if (rcs_comp != null)
                {
                    rcs_comp.center_of_mass = child.Get <Vector3>("centerofmass");
                }
                own_ship.offset = child.Get <Vector3>("centerofmass");
                break;

            case "AI":
                high_ai.Load(child.GetChild("ai data"));
                break;

            case "engine":
                if (!include_parts)
                {
                    break;
                }
                Engine.GetFromDS(part_data, child, transform);
                break;

            case "tank":
                if (!include_parts)
                {
                    break;
                }
                FuelTank.GetFromDS(part_data, child, transform);
                break;

            case "fix weapon":
                if (!include_parts)
                {
                    break;
                }
                Weapon.GetFromDS(part_data, child, transform);
                break;

            case "ammobox":
                if (!include_parts)
                {
                    break;
                }
                AmmoBox.GetFromDS(part_data, child, transform);
                break;

            case "missiles":
                if (!include_parts)
                {
                    break;
                }
                MissileLauncher.GetFromDS(part_data, child, transform);
                break;

            case "armor":
                if (!include_parts)
                {
                    break;
                }
                Armor.GetFromDS(child, own_ship);
                break;

            default:
                if (comp_name.StartsWith("turr-"))
                {
                    if (!include_parts)
                    {
                        break;
                    }
                    var tg = TurretGroup.Load(child, own_ship);
                    weapon_arrays [comp_name.Substring(5)] = tg.TurretArray;
                    ship_control.turretgroup_list.Add(new TurretGroup(Target.None, tg.TurretArray, tg.name)
                    {
                        own_ship = own_ship
                    });
                }
                break;
            }
        }

        // Initializes parts
        foreach (BulletCollisionDetection part in GetComponentsInChildren <BulletCollisionDetection>())
        {
            part.Initialize();
        }
        ship_control.turrets = weapon_arrays;
    }