public override void OnFixedUpdate()
        {
            //Restore the saved target when we are made active vessel
            if (!wasActiveVessel && vessel.isActiveVessel)
            {
                if (target != null && target.GetVessel() != null)
                {
                    FlightGlobals.fetch.SetVesselTarget(target);
                }
            }

            //notice when the user switches targets
            if (vessel.isActiveVessel && target != FlightGlobals.fetch.VesselTarget)
            {
                target = FlightGlobals.fetch.VesselTarget;
                if (target is Vessel && ((Vessel)target).LandedOrSplashed && (((Vessel)target).mainBody == vessel.mainBody))
                {
                    targetBody      = vessel.mainBody;
                    targetLatitude  = vessel.mainBody.GetLatitude(target.GetTransform().position);
                    targetLongitude = vessel.mainBody.GetLongitude(target.GetTransform().position);
                }
            }

            //Update targets that need updating:
            if (target is DirectionTarget)
            {
                ((DirectionTarget)target).Update(targetDirection);
            }
            else if (target is PositionTarget)
            {
                ((PositionTarget)target).Update(targetBody, targetLatitude, targetLongitude);
            }

            wasActiveVessel = vessel.isActiveVessel;
        }
 /// <summary>
 /// Returns facing (or anti-facing) vector of a ITargetable
 /// </summary>
 /// <param name="target"></param>
 /// <param name="targetMode"></param>
 /// <returns>Vector3</returns>
 public static Vector3 getAttitude(this ITargetable target, SmartDockingAid.TargetMode targetMode)
 {
     if (targetMode == SmartDockingAid.TargetMode.PARALLEL_NEGATIVE)
     {
         if (target is ModuleDockingNode)
         {
             return(-target.GetTransform().forward);
         }
         else
         {
             return(-target.GetTransform().up);
         }
     }
     else
     {
         if (target is ModuleDockingNode)
         {
             return(target.GetTransform().forward);
         }
         else
         {
             return(target.GetTransform().up);
         }
     }
 }
        public void UpdateCoordinates(CelestialBody body)
        {
            if (target == null)
            {
                return;
            }
            Name = target.GetName();
            switch (TargetInfo.targetType)
            {
            case ProtoTargetInfo.Type.Vessel:
                var v = target as Vessel;
                if (v == null)
                {
                    break;
                }
                set_coordinates(v);
                return;

            case ProtoTargetInfo.Type.PartModule:
                var m = target as PartModule;
                if (m == null || m.vessel == null)
                {
                    break;
                }
                set_coordinates(m.vessel);
                return;

            case ProtoTargetInfo.Type.Part:
                // There may be ITargetable Part derivatives in some mods
                // ReSharper disable once SuspiciousTypeConversion.Global
                var p = target as Part;
                if (p == null || p.vessel == null)
                {
                    // ProtoTargetInfo.FindTarget() may return a Vessel when the Type == Part
                    goto case ProtoTargetInfo.Type.Vessel;
                }
                set_coordinates(p.vessel);
                return;

            case ProtoTargetInfo.Type.Generic:
                var t = target.GetTransform();
                if (t == null)
                {
                    break;
                }
                var position = t.position;
                set_coordinates(body.GetLatitude(position),
                                body.GetLongitude(position),
                                body.GetAltitude(position));
                return;
            }
            TargetInfo.targetType = ProtoTargetInfo.Type.Null;
            target = null;
            Valid  = false;
        }
        public void UpdateCoordinates(CelestialBody body)
        {
            if (target == null)
            {
                return;
            }
            Name = target.GetName();
            switch (TargetInfo.targetType)
            {
            case ProtoTargetInfo.Type.Vessel:
                var v = target as Vessel;
                if (v == null)
                {
                    break;
                }
                set_coordinates(v);
                return;

            case ProtoTargetInfo.Type.PartModule:
                var m = target as PartModule;
                if (m == null || m.vessel == null)
                {
                    break;
                }
                set_coordinates(m.vessel);
                return;

            case ProtoTargetInfo.Type.Part:
                var p = target as Part;
                if (p == null || p.vessel == null)
                {
                    break;
                }
                set_coordinates(p.vessel);
                return;

            case ProtoTargetInfo.Type.Generic:
                var t = target.GetTransform();
                if (t == null)
                {
                    break;
                }
                set_coordinates(body.GetLatitude(t.position),
                                body.GetLongitude(t.position));
                return;

//			case ProtoTargetInfo.Type.CelestialBody:
            default:
                break;
            }
            TargetInfo.targetType = ProtoTargetInfo.Type.Null;
            Name  += " last location";
            target = null;
        }
Esempio n. 5
0
 public void Update()
 {
     if (target != null)
     {
         if (Time.timeSinceLevelLoad >= nextAttackTime)
         {
             if (Vector3.Distance(transform.position, target.GetTransform().position) <= range)
             {
                 Shoot();
             }
         }
     }
 }
Esempio n. 6
0
        public static void SetTarget(ITargetable target, bool show = true)
        {
            if (indicator == null)
            {
                indicator = UIManager._instance.CreateTargetIndicator(target.getGridPosition(), Color.red, true);
            }
            else
            {
                indicator.SetTarget(target.getGridPosition());
                indicator.SetColor(Color.red);
                indicator.SetShow(show);
            }

            currentTarget       = target;
            currentPosition     = target.getGridPosition();
            CameraFollow.target = target.GetTransform();

            if (Character.GetCharacterAtTile(currentPosition) != null)
            {
                BattleUIContainer.RefreshUnitView(Character.GetCharacterAtTile(currentPosition));
            }

            if (currentTargetList != null && currentTargetList.Contains(target))
            {
                SelectedIndex = currentTargetList.IndexOf(target);
            }
        }
Esempio n. 7
0
        private void UpdateTarget()
        {
            activeTarget = FlightGlobals.fetch.VesselTarget;
            if (activeTarget != null)
            {
                targetDisplacement = activeTarget.GetTransform().position - vessel.GetTransform().position;
                targetDirection    = targetDisplacement.normalized;

                targetRelativeVelocity = vessel.obt_velocity - activeTarget.GetObtVelocity();
                targetCmpSpeed         = -1.0;
                targetDockingTransform = null;

                if (activeTarget is Vessel)
                {
                    targetType = ((activeTarget as Vessel).vesselType == VesselType.SpaceObject) ? TargetType.Asteroid : TargetType.Vessel;
                }
                else if (activeTarget is CelestialBody)
                {
                    targetType = TargetType.CelestialBody;
                }
                else if (activeTarget is ModuleDockingNode)
                {
                    targetType             = TargetType.DockingPort;
                    targetDockingTransform = (activeTarget as ModuleDockingNode).GetTransform();
                }
                else if (activeTarget is PositionTarget)
                {
                    targetType = TargetType.PositionTarget;
                }
                else
                {
                    Utility.LogError(this, "UpdateTarget() - unable to classify target {0}", activeTarget.GetType().Name);
                    targetType = TargetType.None;
                }

                if (targetType == TargetType.Vessel || targetType == TargetType.DockingPort)
                {
                    UpdateTargetDockingPorts();
                }

                targetName  = activeTarget.GetName();
                targetOrbit = activeTarget.GetOrbit();
            }
            else
            {
                targetCmpSpeed         = 0.0;
                targetType             = TargetType.None;
                targetDisplacement     = Vector3.zero;
                targetRelativeVelocity = Vector3d.zero;
                targetDirection        = forward;
                targetDockingTransform = null;
                targetName             = string.Empty;
                targetOrbit            = null;
                if (targetDockingPorts.Length > 0)
                {
                    targetDockingPorts = new ModuleDockingNode[0];
                }
            }
            approachSolver.ResetComputation();
        }
        public override void OnFixedUpdate()
        {
            //Restore the saved target when we are made active vessel
            if (!wasActiveVessel && vessel.isActiveVessel)
            {
                if (target != null && target.GetVessel() != null)
                {
                    vessel.targetObject = target;
                }
            }

            //notice when the user switches targets
            if (target != vessel.targetObject)
            {
                target = vessel.targetObject;
                if (target is Vessel && ((Vessel)target).LandedOrSplashed && (((Vessel)target).mainBody == vessel.mainBody))
                {
                    targetBody      = vessel.mainBody;
                    targetLatitude  = vessel.mainBody.GetLatitude(target.GetTransform().position);
                    targetLongitude = vessel.mainBody.GetLongitude(target.GetTransform().position);
                }
                if (target is CelestialBody)
                {
                    targetBody = (CelestialBody)target;
                }
            }

            // .23 temp fix until I understand better what's going on
            if (targetBody == null)
            {
                targetBody = vessel.mainBody;
            }

            //Update targets that need updating:
            if (target is DirectionTarget)
            {
                ((DirectionTarget)target).Update(targetDirection);
            }
            else if (target is PositionTarget)
            {
                ((PositionTarget)target).Update(targetBody, targetLatitude, targetLongitude);
            }

            wasActiveVessel = vessel.isActiveVessel;
        }
Esempio n. 9
0
        string CalcTargetDistance(ITargetable obj)
        {
            // from Docking Port Alignment Indicator
            Transform selfTransform   = FlightGlobals.ActiveVessel.ReferenceTransform;
            Transform targetTransform = obj.GetTransform();
            Vector3   targetToOwnship = selfTransform.position - targetTransform.position;
            float     distance        = targetToOwnship.magnitude;

            return(Formatter.Distance_short(distance) + " ");
        }
Esempio n. 10
0
    void LateUpdate()
    {
        if (this.navBall == null)
        {
            this.navBall = FindObjectOfType <NavBall>();
        }
        if (FlightGlobals.fetch != null &&
            FlightGlobals.ready &&
            FlightGlobals.fetch.activeVessel != null &&
            FlightGlobals.fetch.VesselTarget != null &&
            FlightGlobals.fetch.VesselTarget.GetTargetingMode() == VesselTargetModes.DirectionVelocityAndOrientation)
        {
            /// Targeted a Port if I am not mistaken o__o

            if (this.indicator == null)
            {
                SetupIndicator();
            }


            #region "legacy" Code
            ITargetable targetPort      = FlightGlobals.fetch.VesselTarget;
            Transform   targetTransform = targetPort.GetTransform();
            Transform   selfTransform   = FlightGlobals.ActiveVessel.ReferenceTransform;

            // Position
            Vector3 targetPortOutVector       = targetTransform.forward.normalized;
            Vector3 rotatedTargetPortInVector = navBall.attitudeGymbal * -targetPortOutVector;
            this.indicator.transform.localPosition = rotatedTargetPortInVector * navBall.progradeVector.localPosition.magnitude;

            // Rotation
            Vector3 v1  = Vector3.Cross(selfTransform.up, -targetTransform.up);
            Vector3 v2  = Vector3.Cross(selfTransform.up, selfTransform.forward);
            float   ang = Vector3.Angle(v1, v2);
            if (Vector3.Dot(selfTransform.up, Vector3.Cross(v1, v2)) < 0)
            {
                ang = -ang;
            }
            this.indicator.transform.rotation = Quaternion.Euler(90 + ang, 90, 270);
            #endregion

            // Set opacity
            float value = Vector3.Dot(indicator.transform.localPosition.normalized, Vector3.forward);
            value = Mathf.Clamp01(value);
            this.indicator.GetComponent <MeshRenderer>().materials[0].SetFloat("_Opacity", value);

            this.indicator.SetActive(indicator.transform.localPosition.z > 0.0d);
            return;
        }

        if (this.indicator != null)
        {
            this.indicator.SetActive(false);
        }
    }
Esempio n. 11
0
    public void LateUpdate()
    {
        if (FlightGlobals.ready == false)
        {
            return;
        }

        if (FlightGlobals.fetch != null)
        {
            if (FlightGlobals.fetch.VesselTarget != null)
            {
                if (FlightGlobals.fetch.VesselTarget.GetTargetingMode() == VesselTargetModes.DirectionVelocityAndOrientation)
                {
                    ITargetable targetPort      = FlightGlobals.fetch.VesselTarget;
                    Transform   targetTransform = targetPort.GetTransform();
                    Transform   selfTransform   = FlightGlobals.ActiveVessel.ReferenceTransform;

                    //indicator position
                    Vector3 targetPortOutVector       = targetTransform.forward.normalized;
                    Vector3 targetPortInVector        = -targetPortOutVector;
                    Vector3 rotatedTargetPortInVector = navBallBehaviour.attitudeGymbal * targetPortInVector;
                    indicator.transform.localPosition = rotatedTargetPortInVector * navBallBehaviour.progradeVector.localPosition.magnitude;

                    //indicator rotation
                    Vector3 v1  = Vector3.Cross(selfTransform.up, -targetTransform.up);
                    Vector3 v2  = Vector3.Cross(selfTransform.up, selfTransform.forward);
                    float   ang = Vector3.Angle(v1, v2);
                    if (Vector3.Dot(selfTransform.up, Vector3.Cross(v1, v2)) < 0)
                    {
                        ang = -ang;
                    }
                    indicator.transform.rotation = Quaternion.Euler(90 + ang, 90, 270);

                    //indicator visibility (invisible if on back half sphere)
                    indicator.SetActive(indicator.transform.localPosition.z > 0.0d);

                    return;
                }
            }
        }

        //no docking port is currently selected
        indicator.SetActive(false);
        return;
    }
Esempio n. 12
0
        private void updateVesselCourse()
        {
            ITargetable targetObject = this.part.vessel.targetObject;

            //First check to see if the vessel has selected a target.
            if (targetObject != null)
            {
                vesselCourse   = targetObject.GetDisplayName().Replace("^N", "");
                targetDistance = Math.Abs((part.vessel.GetWorldPos3D() - (Vector3d)targetObject.GetTransform().position).magnitude);

                // Light-years
                if (targetDistance > (kGigaMeter * 1000))
                {
                    targetDistance /= kLightYear;
                    Fields["targetDistance"].guiUnits = "Ly";
                }

                // Giga-meters
                else if (targetDistance > (kMegaMeter * 1000))
                {
                    targetDistance /= kGigaMeter;
                    Fields["targetDistance"].guiUnits = "Gm";
                }

                // Mega-meters
                else if (targetDistance > 1000 * 1000)
                {
                    targetDistance /= kMegaMeter;
                    Fields["targetDistance"].guiUnits = "Mm";
                }

                else
                {
                    targetDistance /= 1000;
                    Fields["targetDistance"].guiUnits = "Km";
                }
            }
            else
            {
                vesselCourse   = "None";
                targetDistance = 0;
                Fields["targetDistance"].guiUnits = "m";
            }
        }
Esempio n. 13
0
    private void UpdateHealthBar()
    {
        if (_user == null || _user.Equals(null))
        {
            OnDestroyed();
            return;
        }

        //Convert the position of the entity to a viewpoint
        Vector2 viewport = Camera.main.WorldToViewportPoint(_user.GetTransform().position);

        //Calculate the position of the health bar to be above the entity.
        Vector2 position = new Vector2(
            ((viewport.x * _canvas.sizeDelta.x) - (_canvas.sizeDelta.x * 0.5f)),
            ((viewport.y * _canvas.sizeDelta.y) - (_canvas.sizeDelta.y * 0.5f)) + _offset);


        HealthBarRect.anchoredPosition = position;
    }
Esempio n. 14
0
        Vector3 GetOrientationDeviation(ITargetable obj)
        {
            Transform selfTransform   = FlightGlobals.ActiveVessel.ReferenceTransform;
            Transform targetTransform = obj.GetTransform();

            Vector3 targetPortOutVector           = targetTransform.forward.normalized;
            Vector3 targetPortRollReferenceVector = -targetTransform.up;

            Vector3 orientationDeviation = new Vector3
            {
                x = AngleAroundNormal(-targetPortOutVector, selfTransform.up, selfTransform.forward),
                y = AngleAroundNormal(-targetPortOutVector, selfTransform.up, -selfTransform.right),
                z = AngleAroundNormal(targetPortRollReferenceVector, selfTransform.forward, selfTransform.up)
            };

            orientationDeviation.x = (360 + orientationDeviation.x) % 360;  // -90..270
            orientationDeviation.y = (360 + orientationDeviation.y) % 360;
            orientationDeviation.z = (360 - orientationDeviation.z) % 360;
            return(orientationDeviation);
        }
Esempio n. 15
0
 public void Update()
 {
     if (TVcam != null && CameraManager.Instance.currentCameraMode == CameraManager.CameraMode.IVA)
     {
         TVcam.transform.rotation = originalRotation;
         if (FlightGlobals.fetch.vesselTargetMode != VesselTargetModes.None)
         {
             ITargetable target = FlightGlobals.fetch.VesselTarget;
             TVcam.transform.LookAt(target.GetTransform(), Firespitter.Tools.WorldUp(vessel));
             //TVcam.transform.localRotation = Quaternion.Euler(new Vector3(TVcam.transform.localRotation.eulerAngles.x, TVcam.transform.localRotation.eulerAngles.z, 0f));
             TVcam.fieldOfView = Mathf.Lerp(TVcam.fieldOfView, 5f, lerpProgress);
             if (lerpProgress < 1f)
             {
                 lerpProgress += 0.01f;
             }
         }
         else
         {
             TVcam.fieldOfView = 100f;
             lerpProgress      = 0f;
         }
         TVcam.Render();
     }
 }
        private void FetchCommonData()
        {
            localGeeASL = vessel.orbit.referenceBody.GeeASL * gee;
            coM = vessel.findWorldCenterOfMass();
            localGeeDirect = FlightGlobals.getGeeForceAtPosition(coM).magnitude;
            up = (coM - vessel.mainBody.position).normalized;
            forward = vessel.GetTransform().up;
            right = vessel.GetTransform().right;
            north = Vector3d.Exclude(up, (vessel.mainBody.position + vessel.mainBody.transform.up * (float)vessel.mainBody.Radius) - coM).normalized;
            rotationSurface = Quaternion.LookRotation(north, up);
            rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);

            velocityVesselOrbit = vessel.orbit.GetVel();
            velocityVesselSurface = velocityVesselOrbit - vessel.mainBody.getRFrmVel(coM);

            speedVertical = Vector3d.Dot(velocityVesselSurface, up);
            speedVerticalRounded = Math.Ceiling(speedVertical * 20) / 20;
            target = FlightGlobals.fetch.VesselTarget;
            node = vessel.patchedConicSolver.maneuverNodes.Count > 0 ? vessel.patchedConicSolver.maneuverNodes[0] : null;
            time = Planetarium.GetUniversalTime();
            FetchAltitudes();
            terrainHeight = altitudeASL - altitudeTrue;
            if (time >= lastTimePerSecond + 1) {
                terrainDelta = terrainHeight - lastTerrainHeight;
                lastTerrainHeight = terrainHeight;
                lastTimePerSecond = time;
            }

            horzVelocity = (velocityVesselSurface - (speedVertical * up)).magnitude;
            horzVelocityForward = Vector3d.Dot(velocityVesselSurface, forward);
            horzVelocityRight = Vector3d.Dot(velocityVesselSurface, right);

            atmPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);
            dynamicPressure = 0.5 * velocityVesselSurface.sqrMagnitude * vessel.atmDensity;

            if (target != null) {
                targetSeparation = vessel.GetTransform().position - target.GetTransform().position;
                targetOrientation = target.GetTransform().rotation;

                targetVessel = target as Vessel;
                targetBody = target as CelestialBody;
                targetDockingNode = target as ModuleDockingNode;

                targetDistance = Vector3.Distance(target.GetTransform().position, vessel.GetTransform().position);

                // This is kind of messy.
                targetOrbitSensibility = false;
                // All celestial bodies except the sun have orbits that make sense.
                targetOrbitSensibility |= targetBody != null && targetBody != Planetarium.fetch.Sun;

                if (targetVessel != null)
                    targetOrbitSensibility = JUtil.OrbitMakesSense(targetVessel);
                if (targetDockingNode != null)
                    targetOrbitSensibility = JUtil.OrbitMakesSense(target.GetVessel());

                if (targetOrbitSensibility)
                    targetOrbit = target.GetOrbit();

                // TODO: Actually, there's a lot of nonsensical cases here that need more reasonable handling.
                // Like what if we're targeting a vessel landed on a moon of another planet?...
                if (targetOrbit != null) {
                    velocityRelativeTarget = vessel.orbit.GetVel() - target.GetOrbit().GetVel();
                } else {
                    velocityRelativeTarget = vessel.orbit.GetVel();
                }

                // If our target is somehow our own celestial body, approach speed is equal to vertical speed.
                if (targetBody == vessel.mainBody)
                    approachSpeed = speedVertical;
                // In all other cases, that should work. I think.
                approachSpeed = Vector3d.Dot(velocityRelativeTarget, (target.GetTransform().position - vessel.GetTransform().position).normalized);
            } else {
                velocityRelativeTarget = targetSeparation = Vector3d.zero;
                targetOrbit = null;
                targetDistance = 0;
                approachSpeed = 0;
                targetBody = null;
                targetVessel = null;
                targetDockingNode = null;
                targetOrientation = vessel.GetTransform().rotation;
                targetOrbitSensibility = false;
            }
            orbitSensibility = JUtil.OrbitMakesSense(vessel);
            if (vessel.situation == Vessel.Situations.SUB_ORBITAL || vessel.situation == Vessel.Situations.FLYING) {
                // Mental note: the local g taken from vessel.mainBody.GeeASL will suffice.
                //  t = (v+sqrt(v²+2gd))/g or something.

                // What is the vertical component of current acceleration?
                double accelUp = Vector3d.Dot(vessel.acceleration, up);

                double altitude = altitudeTrue;
                if (vessel.mainBody.ocean && altitudeASL > 0.0) {
                    // AltitudeTrue shows distance above the floor of the ocean,
                    // so use ASL if it's closer in this case, and we're not
                    // already below SL.
                    altitude = Math.Min(altitudeASL, altitudeTrue);
                }

                if (accelUp < 0.0 || speedVertical >= 0.0 || Planetarium.TimeScale > 1.0) {
                    // If accelUp is negative, we can't use it in the general
                    // equation for finding time to impact, since it could
                    // make the term inside the sqrt go negative.
                    // If we're going up, we can use this as well, since
                    // the precision is not critical.
                    // If we are warping, accelUp is always zero, so if we
                    // do not use this case, we would fall to the simple
                    // formula, which is wrong.
                    secondsToImpact = (speedVertical + Math.Sqrt(speedVertical * speedVertical + 2 * localGeeASL * altitude)) / localGeeASL;
                } else if (accelUp > 0.005) {
                    // This general case takes into account vessel acceleration,
                    // so estimates on craft that include parachutes or do
                    // powered descents are more accurate.
                    secondsToImpact = (speedVertical + Math.Sqrt(speedVertical * speedVertical + 2 * accelUp * altitude)) / accelUp;
                } else {
                    // If accelUp is small, we get floating point precision
                    // errors that tend to make secondsToImpact get really big.
                    secondsToImpact = altitude / -speedVertical;
                }

                // MOARdV: I think this gets the computation right.  High thrust will
                // result in NaN, which is already handled.
                /*
                double accelerationAtMaxThrust = localG - (totalMaximumThrust / totalShipWetMass);
                double timeToImpactAtMaxThrust = (speedVertical + Math.Sqrt(speedVertical * speedVertical + 2 * accelerationAtMaxThrust * altitude)) / accelerationAtMaxThrust;
                bestPossibleSpeedAtImpact = speedVertical - accelerationAtMaxThrust * timeToImpactAtMaxThrust;
                if (double.IsNaN(bestPossibleSpeedAtImpact))
                    bestPossibleSpeedAtImpact = 0;
                */
                bestPossibleSpeedAtImpact = SpeedAtImpact(totalMaximumThrust, totalShipWetMass, localGeeASL, speedVertical, altitude);
                expectedSpeedAtImpact = SpeedAtImpact(totalCurrentThrust, totalShipWetMass, localGeeASL, speedVertical, altitude);

            } else {
                secondsToImpact = Double.NaN;
                bestPossibleSpeedAtImpact = 0;
                expectedSpeedAtImpact = 0;
            }
        }
        public override void OnUpdate()
        {
            /*
             * Line_Forward.SetPosition(0, transform.position); Line_Forward.SetPosition(1, transform.position + vessel.vesselTransform.forward);
             * Line_Up.SetPosition(0, transform.position); Line_Up.SetPosition(1, transform.position + vessel.vesselTransform.up);
             * Line_Right.SetPosition(0, transform.position); Line_Right.SetPosition(1, transform.position + vessel.vesselTransform.right);
             */

            vTarget      = FlightGlobals.fetch.VesselTarget;
            vIsActive    = vessel.isActiveVessel;
            foundTarget  = vTarget != null;
            loadedTarget = foundTarget && vTarget.GetVessel() != null && vTarget.GetVessel().loaded;


            if (!toggle || !vIsActive || !foundTarget || !loadedTarget)
            {
                Line_Dock.SetPosition(0, Vector3.zero); Line_Dock.SetPosition(1, Vector3.zero);
                Line_Velocity.SetPosition(0, Vector3.zero); Line_Velocity.SetPosition(1, Vector3.zero);

                Line_V_Up.SetPosition(0, Vector3.zero); Line_V_Right.SetPosition(0, Vector3.zero); Line_V_Diff.SetPosition(0, Vector3.zero);
                Line_V_Up.SetPosition(1, Vector3.zero); Line_V_Right.SetPosition(1, Vector3.zero); Line_V_Diff.SetPosition(1, Vector3.zero);
                alignment = 0f;
                return;
            }

            velocity_smoothed = (velocity_smoothed * 0.9f + (vessel.rootPart.Rigidbody.velocity - vTarget.GetVessel().rootPart.Rigidbody.velocity) * Time.deltaTime * 0.1f) / 10f; // Sliding window

            arrow_point = vessel.GetTransform().position + velocity_smoothed.normalized;

            alignment = 100f * Vector3.Dot(velocity_smoothed.normalized, (vTarget.GetTransform().transform.position - vessel.GetTransform().position).normalized);
            if (alignment > 99.9f)
            {
                setLineColors(Line_Dock, Color_Velocity);
                setLineColors(Line_V_Diff, Color_Velocity);
                arrow_to_point = arrow_point;
            }
            else
            {
                setLineColors(Line_Dock, Color_Dock);
                setLineColors(Line_V_Diff, Color_Diff);
                arrow_to_point = Vector3.ProjectOnPlane(((vTarget.GetTransform().transform.position - vessel.GetTransform().position).normalized - arrow_point + vessel.GetTransform().position), vessel.GetTransform().up).normalized + arrow_point;
            }

            Line_Dock.SetPosition(0, vessel.GetTransform().position);  // GetTransform returns the point being controlled from
            Line_Dock.SetPosition(1, vTarget.GetTransform().position); // This is the other dock port
            Line_Velocity.SetPosition(0, vessel.GetTransform().position);
            if (velocity_smoothed.magnitude > 0.00001f)
            {
                Line_Velocity.SetPosition(1, arrow_point);
                // Line_V_Down.SetPosition(0, arrow_point); Line_V_Down.SetPosition(1, arrow_point + vessel.GetTransform().up * -1f);
                Line_V_Up.SetPosition(1, arrow_point + vessel.GetTransform().forward * -1f); // Weird right? "Up" is actually "Back" on a Kerbin ship
                // Line_V_Left.SetPosition(0, arrow_point); Line_V_Left.SetPosition(1, arrow_point + vessel.GetTransform().right * -1f);
                Line_V_Right.SetPosition(1, arrow_point + vessel.GetTransform().right);
                Line_V_Diff.SetPosition(1, arrow_to_point);
            }
            else
            {
                Line_Velocity.SetPosition(1, vessel.GetTransform().position);
                Line_V_Up.SetPosition(1, arrow_point); Line_V_Right.SetPosition(1, arrow_point); Line_V_Diff.SetPosition(1, arrow_point);
            }
            Line_V_Up.SetPosition(0, arrow_point);
            Line_V_Right.SetPosition(0, arrow_point);
            Line_V_Diff.SetPosition(0, arrow_point);
            // print("Velocity is " + part.Rigidbody.velocity * Time.deltaTime);
        }
Esempio n. 18
0
        public void FixedUpdate()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            if (!JUtil.IsActiveVessel(vessel))
            {
                return;
            }

            ITargetable target = FlightGlobals.fetch.VesselTarget;

            if (radarEnabled)
            {
                bool powered = true;
                // Resources check
                if (resourceAmount > 0.0f)
                {
                    double requested = resourceAmount * TimeWarp.fixedDeltaTime;
                    double supplied  = part.RequestResource(resourceId, requested);
                    if (supplied < requested * 0.5)
                    {
                        powered = false;
                    }
                }

                if (target == null)
                {
                    if (!powered)
                    {
                        JUtil.LogMessage(this, "Want to scan, but there's no power");
                        return;
                    }

                    // Scan
                    ScanForTargets();
                }
                else
                {
                    if (!trackWhileOff && !powered)
                    {
                        JUtil.LogMessage(this, "Radar ran out of power and trackWhileOff is false, so clearing target");
                        FlightGlobals.fetch.SetVesselTarget(null);
                        return;
                    }

                    // Target locked; tracking
                    if (restrictTracking)
                    {
                        Vector3 vectorToTarget = (target.GetTransform().position - scanTransform.position);
                        if (vectorToTarget.sqrMagnitude > maxRangeMetersSquared)
                        {
                            JUtil.LogMessage(this, "Target is out of range, losing lock");
                            FlightGlobals.fetch.SetVesselTarget(null);
                            return;
                        }
                        float angle = Vector3.Angle(vectorToTarget.normalized, (scanTransformIsDockingNode) ? scanTransform.forward : scanTransform.up);
                        if (angle > scanAngle)
                        {
                            JUtil.LogMessage(this, "Target is out of scan angle, losing lock");
                            FlightGlobals.fetch.SetVesselTarget(null);
                            return;
                        }
                    }

                    if (powered && targetDockingPorts && (target is Vessel) && !(target as Vessel).packed)
                    {
                        // Attempt to refine our target.
                        ModuleDockingNode closestNode     = null;
                        float             closestDistance = float.MaxValue;
                        var l = (target as Vessel).FindPartModulesImplementing <ModuleDockingNode>();
                        if (l != null)
                        {
                            for (int i = 0; i < l.Count; ++i)
                            {
                                if (l[i].state == "Ready" && (string.IsNullOrEmpty(nodeType) || nodeType == l[i].nodeType))
                                {
                                    Vector3 vectorToTarget = (l[i].part.transform.position - scanTransform.position);
                                    if (vectorToTarget.sqrMagnitude < closestDistance)
                                    {
                                        closestDistance = vectorToTarget.sqrMagnitude;
                                        closestNode     = l[i];
                                    }
                                }
                            }
                        }

                        if (closestNode != null)
                        {
                            // This seems to be triggering continuously for
                            // ranges > 0.2km.  How do I determine
                            // programmatically that I can target a docking
                            // port?
                            //JUtil.LogMessage(this, "Refining target to {1} at {0:0.000} km.", Mathf.Sqrt(closestDistance) * 0.001f, closestNode.vessel.vesselName);
                            FlightGlobals.fetch.SetVesselTarget(closestNode);
                        }
                    }
                }
            }
            else if (target != null)
            {
                if (!trackWhileOff)
                {
                    JUtil.LogMessage(this, "Radar is off and trackWhileOff is false, so clearing target");
                    FlightGlobals.fetch.SetVesselTarget(null);
                    return;
                }

                if (restrictTracking)
                {
                    Vector3 vectorToTarget = (target.GetTransform().position - scanTransform.position);
                    if (vectorToTarget.sqrMagnitude > maxRangeMetersSquared)
                    {
                        JUtil.LogMessage(this, "Target is out of range, losing lock");
                        FlightGlobals.fetch.SetVesselTarget(null);
                        return;
                    }
                    float angle = Vector3.Angle(vectorToTarget.normalized, (scanTransformIsDockingNode) ? scanTransform.forward : scanTransform.up);
                    if (angle > scanAngle)
                    {
                        JUtil.LogMessage(this, "Target is out of scan angle, losing lock");
                        FlightGlobals.fetch.SetVesselTarget(null);
                        return;
                    }
                }
            }
        }
Esempio n. 19
0
        private void UpdateVP()
        {
            List <Part> ActiveEngines = new List <Part>();

            ActiveEngines = GetListOfActivatedEngines(AV);

            VP.FlightStatus = (byte)AV.situation;

            //Orbit
            VP.CurrentOrbit = OrbUtil.GetOrbitData(AV.orbit);

            VP.VVI = (float)AV.verticalSpeed;
            VP.G   = (float)AV.geeForce;

            double ASL = AV.mainBody.GetAltitude(AV.CoM);
            double AGL = (ASL - AV.terrainAltitude);

            if (AGL < ASL)
            {
                VP.RAlt = (float)AGL;
            }
            else
            {
                VP.RAlt = (float)ASL;
            }

            VP.Alt   = (float)ASL;
            VP.Vsurf = (float)AV.srfSpeed;
            VP.Lat   = (float)AV.latitude;
            VP.Lon   = (float)AV.longitude;

            TempR            = GetResourceTotal(AV, "LiquidFuel");
            VP.LiquidFuelTot = TempR.Max;
            VP.LiquidFuel    = TempR.Current;

            VP.LiquidFuelTotS = (float)ProspectForResourceMax("LiquidFuel", ActiveEngines);
            VP.LiquidFuelS    = (float)ProspectForResource("LiquidFuel", ActiveEngines);

            TempR          = GetResourceTotal(AV, "Oxidizer");
            VP.OxidizerTot = TempR.Max;
            VP.Oxidizer    = TempR.Current;

            VP.OxidizerTotS = (float)ProspectForResourceMax("Oxidizer", ActiveEngines);
            VP.OxidizerS    = (float)ProspectForResource("Oxidizer", ActiveEngines);

            TempR           = GetResourceTotal(AV, "ElectricCharge");
            VP.EChargeTot   = TempR.Max;
            VP.ECharge      = TempR.Current;
            TempR           = GetResourceTotal(AV, "MonoPropellant");
            VP.MonoPropTot  = TempR.Max;
            VP.MonoProp     = TempR.Current;
            TempR           = GetResourceTotal(AV, "IntakeAir");
            VP.IntakeAirTot = TempR.Max;
            VP.IntakeAir    = TempR.Current;
            TempR           = GetResourceTotal(AV, "SolidFuel");
            VP.SolidFuelTot = TempR.Max;
            VP.SolidFuel    = TempR.Current;
            TempR           = GetResourceTotal(AV, "XenonGas");
            VP.XenonGasTot  = TempR.Max;
            VP.XenonGas     = TempR.Current;

            VP.MissionTime = (float)AV.missionTime;
            VP.UT          = (float)Planetarium.GetUniversalTime();

            VP.VOrbit = (float)AV.orbit.GetVel().magnitude;

            VP.MNTime     = 0;
            VP.MNDeltaV   = 0;
            VP.TargetDist = 0;
            VP.TargetV    = 0;

            VP.HasTarget = (byte)(HasTarget() ? 1 : 0);

            //mathy stuff
            Quaternion rotationSurface;

            CoM   = AV.CoM;
            up    = (CoM - AV.mainBody.position).normalized;
            north = Vector3d.Exclude(up, (AV.mainBody.position + AV.mainBody.transform.up * (float)AV.mainBody.Radius) - CoM).normalized;

            east = Vector3d.Cross(up, north);

            rotationSurface = Quaternion.LookRotation(north, up);

            Vector3d attitude = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(AV.GetTransform().rotation) * rotationSurface).eulerAngles;

            VP.Roll    = (float)((attitude.z > 180) ? (attitude.z - 360.0) : attitude.z);
            VP.Pitch   = (float)((attitude.x > 180) ? (360.0 - attitude.x) : -attitude.x);
            VP.Heading = (float)attitude.y;

            Vector3d prograde = new Vector3d(0, 0, 0);

            switch (FlightGlobals.speedDisplayMode)
            {
            case FlightGlobals.SpeedDisplayModes.Surface:
                prograde = AV.srf_velocity.normalized;
                break;

            case FlightGlobals.SpeedDisplayModes.Orbit:
                prograde = AV.obt_velocity.normalized;
                break;

            case FlightGlobals.SpeedDisplayModes.Target:
                prograde = FlightGlobals.ship_tgtVelocity;
                break;
            }

            VP.Prograde = WorldVecToNavHeading(up, north, east, prograde);

            if (HasTarget())
            {
                ITargetable t = AV.targetObject;

                VP.Target     = WorldVecToNavHeading(up, north, east, t.GetTransform().position - AV.transform.position);
                VP.TargetDist = (float)Vector3.Distance(t.GetTransform().position, AV.transform.position);
                VP.TargetV    = (float)FlightGlobals.ship_tgtVelocity.magnitude;

                if (t is Vessel)
                {
                    attitude = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(t.GetVessel().GetTransform().rotation) * rotationSurface).eulerAngles;
                    VP.TargetRotation.Pitch   = (float)((attitude.x > 180) ? (360.0 - attitude.x) : -attitude.x);
                    VP.TargetRotation.Heading = (float)attitude.y;
                }
                else if (t is ModuleDockingNode)
                {
                    VP.TargetRotation = WorldVecToNavHeading(up, north, east, t.GetFwdVector());
                }
            }

            if (AV.patchedConicSolver != null)
            {
                if (AV.patchedConicSolver.maneuverNodes != null)
                {
                    if (AV.patchedConicSolver.maneuverNodes.Count > 0)
                    {
                        VP.MNTime   = (UInt32)Math.Round(AV.patchedConicSolver.maneuverNodes[0].UT - Planetarium.GetUniversalTime());
                        VP.MNDeltaV = (float)AV.patchedConicSolver.maneuverNodes[0].GetBurnVector(AV.patchedConicSolver.maneuverNodes[0].patch).magnitude; //Added JS

                        VP.Maneuver = WorldVecToNavHeading(up, north, east, AV.patchedConicSolver.maneuverNodes[0].GetBurnVector(AV.patchedConicSolver.maneuverNodes[0].patch));
                    }
                }
            }

            VP.MainControls = CalcMainControls();

            VP.ActionGroups = CalcActionGroups();

            VP.MaxOverHeat = GetMaxOverHeat(AV);
            VP.IAS         = (float)AV.indicatedAirSpeed;

            VP.CurrentStage = (byte)StageManager.CurrentStage;
            VP.TotalStage   = (byte)StageManager.StageCount;

            VP.SpeedMode = (byte)(FlightGlobals.speedDisplayMode + 1);
            VP.SASMode   = GetSASMode(true);

            VP.timeWarpRateIndex = GetTimeWarpIndex();
        }
        // This is honestly very badly written code, probably the worst of what I have in this project.
        // Much of it dictated by the fact that I barely, if at all, understand what am I doing in vector mathematics,
        // the rest is because the problem is all built out of special cases.
        // Sorry. :)
        public bool RenderPFD(RenderTexture screen, float aspect)
        {
            if (screen == null || !startupComplete || HighLogic.LoadedSceneIsEditor)
            {
                return(false);
            }

            // Analysis disable once CompareOfFloatsByEqualityOperator
            if (aspect != cameraAspect)
            {
                cameraAspect      = aspect;
                ballCamera.aspect = cameraAspect;
            }
            GL.Clear(true, true, backgroundColorValue);

            ballCamera.targetTexture = screen;


            Vector3d coM = vessel.findWorldCenterOfMass();
            Vector3d up  = (coM - vessel.mainBody.position).normalized;
            Vector3d velocityVesselOrbit       = vessel.orbit.GetVel();
            Vector3d velocityVesselOrbitUnit   = velocityVesselOrbit.normalized;
            Vector3d velocityVesselSurface     = velocityVesselOrbit - vessel.mainBody.getRFrmVel(coM);
            Vector3d velocityVesselSurfaceUnit = velocityVesselSurface.normalized;
            Vector3d radialPlus = Vector3d.Exclude(velocityVesselOrbit, up).normalized;
            Vector3d normalPlus = -Vector3d.Cross(radialPlus, velocityVesselOrbitUnit);

            //Vector3d targetDirection = -FlightGlobals.fetch.vesselTargetDirection.normalized;
            Vector3d targetDirection = FlightGlobals.ship_tgtVelocity.normalized;

            navBall.transform.rotation = MirrorX(stockNavBall.navBall.rotation);

            if (heading != null)
            {
                Vector3d   north                 = Vector3d.Exclude(up, (vessel.mainBody.position + (Vector3d)vessel.mainBody.transform.up * vessel.mainBody.Radius) - coM).normalized;
                Quaternion rotationSurface       = Quaternion.LookRotation(north, up);
                Quaternion rotationVesselSurface = Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);
                heading.renderer.material.SetTextureOffset("_MainTex",
                                                           new Vector2(JUtil.DualLerp(0f, 1f, 0f, 360f, rotationVesselSurface.eulerAngles.y) - headingSpan / 2f, 0));
            }

            Quaternion gymbal = stockNavBall.attitudeGymbal;

            switch (FlightUIController.speedDisplayMode)
            {
            case FlightUIController.SpeedDisplayModes.Surface:
                MoveMarker(markerPrograde, velocityVesselSurfaceUnit, progradeColorValue, gymbal);
                MoveMarker(markerRetrograde, -velocityVesselSurfaceUnit, progradeColorValue, gymbal);
                break;

            case FlightUIController.SpeedDisplayModes.Target:
                MoveMarker(markerPrograde, targetDirection, progradeColorValue, gymbal);
                MoveMarker(markerRetrograde, -targetDirection, progradeColorValue, gymbal);
                break;

            case FlightUIController.SpeedDisplayModes.Orbit:
                MoveMarker(markerPrograde, velocityVesselOrbitUnit, progradeColorValue, gymbal);
                MoveMarker(markerRetrograde, -velocityVesselOrbitUnit, progradeColorValue, gymbal);
                break;
            }
            MoveMarker(markerNormal, normalPlus, normalColorValue, gymbal);
            MoveMarker(markerNormalMinus, -normalPlus, normalColorValue, gymbal);

            MoveMarker(markerRadial, radialPlus, radialColorValue, gymbal);
            MoveMarker(markerRadialMinus, -radialPlus, radialColorValue, gymbal);

            if (vessel.patchedConicSolver != null && vessel.patchedConicSolver.maneuverNodes.Count > 0)
            {
                Vector3d burnVector = vessel.patchedConicSolver.maneuverNodes[0].GetBurnVector(vessel.orbit);
                MoveMarker(markerManeuver, burnVector.normalized, maneuverColorValue, gymbal);
                MoveMarker(markerManeuverMinus, -burnVector.normalized, maneuverColorValue, gymbal);
                ShowHide(true, markerManeuver, markerManeuverMinus);
            }

            ITargetable target = FlightGlobals.fetch.VesselTarget;

            if (target != null)
            {
                Vector3 targetSeparation = (vessel.GetTransform().position - target.GetTransform().position).normalized;
                MoveMarker(markerTarget, targetSeparation, targetColorValue, gymbal);
                MoveMarker(markerTargetMinus, -targetSeparation, targetColorValue, gymbal);
                var targetPort = target as ModuleDockingNode;
                if (targetPort != null)
                {
                    // Thanks to Michael Enßlin
                    Transform targetTransform         = targetPort.transform;
                    Transform selfTransform           = vessel.ReferenceTransform;
                    Vector3   targetOrientationVector = -targetTransform.up.normalized;

                    Vector3 v1    = Vector3.Cross(selfTransform.up, targetTransform.forward);
                    Vector3 v2    = Vector3.Cross(selfTransform.up, selfTransform.forward);
                    float   angle = Vector3.Angle(v1, v2);
                    if (Vector3.Dot(selfTransform.up, Vector3.Cross(v1, v2)) < 0)
                    {
                        angle = -angle;
                    }
                    MoveMarker(markerDockingAlignment, targetOrientationVector, dockingColorValue, gymbal);
                    markerDockingAlignment.transform.Rotate(Vector3.up, -angle);
                    ShowHide(true, markerDockingAlignment);
                }
                ShowHide(true, markerTarget, markerTargetMinus);
            }


            // This dirty hack reduces the chance that the ball might get affected by internal cabin lighting.
            int backupQuality = QualitySettings.pixelLightCount;

            QualitySettings.pixelLightCount = 0;

            ShowHide(true,
                     cameraBody, navBall, overlay, heading, markerPrograde, markerRetrograde,
                     markerNormal, markerNormalMinus, markerRadial, markerRadialMinus);
            ballCamera.Render();
            QualitySettings.pixelLightCount = backupQuality;
            ShowHide(false,
                     cameraBody, navBall, overlay, heading, markerPrograde, markerRetrograde,
                     markerManeuver, markerManeuverMinus, markerTarget, markerTargetMinus,
                     markerNormal, markerNormalMinus, markerRadial, markerRadialMinus, markerDockingAlignment);

            return(true);
        }
        public override void OnFixedUpdate()
        {
            //Restore the saved target when we are made active vessel
            if (!wasActiveVessel && vessel.isActiveVessel)
            {
                if (target != null && target.GetVessel() != null)
                {                    
                    FlightGlobals.fetch.SetVesselTarget(target);
                }
            }

            //notice when the user switches targets
            if (vessel.isActiveVessel && target != FlightGlobals.fetch.VesselTarget)
            {
                target = FlightGlobals.fetch.VesselTarget;
                if (target is Vessel && ((Vessel)target).LandedOrSplashed && (((Vessel)target).mainBody == vessel.mainBody))
                {
                    targetBody = vessel.mainBody;
                    targetLatitude = vessel.mainBody.GetLatitude(target.GetTransform().position);
                    targetLongitude = vessel.mainBody.GetLongitude(target.GetTransform().position);
                }
            }


            // .23 temp fix until I understand better what's going on
            if (targetBody == null)
                targetBody = vessel.mainBody;
            
            //Update targets that need updating:
            if (target is DirectionTarget) ((DirectionTarget)target).Update(targetDirection);
            else if (target is PositionTarget) ((PositionTarget)target).Update(targetBody, targetLatitude, targetLongitude);

            wasActiveVessel = vessel.isActiveVessel;
        }
Esempio n. 22
0
        public bool RenderCamera(RenderTexture screen, float cameraAspect)
        {
            // Just in case.
            if (HighLogic.LoadedSceneIsEditor)
            {
                return(false);
            }

            if (cameras.Count < 1)
            {
                return(false);
            }

            var activeCamera = cameras[currentCamera];

            if (string.IsNullOrEmpty(activeCamera.cameraTransform))
            {
                return(false);
            }

            if (cameraObject == null)
            {
                cameraObject = new FlyingCamera(part, cameraAspect);
                cameraObject.PointCamera(activeCamera.cameraTransform, activeCamera.currentFoV);
            }

            cameraObject.FOV = activeCamera.currentFoV;

            if (rentexWidth == 0)
            {
                rentexWidth  = screen.width;
                rentexHeight = screen.height;

                // Note to self: when rentex dims != screen dims, the FOV seems to be wrong (like FOV is smaller).
            }
            if (renderTex == null)
            {
                renderTex = new RenderTexture(rentexWidth, rentexHeight, screen.depth);
                renderTex.Create();
            }

            // Negate pitch - the camera object treats a negative pitch as "up"
            if (cameraObject.Render(renderTex, activeCamera.currentYaw, -activeCamera.currentPitch))
            {
                if (cameraEffectMaterial != null)
                {
                    cameraEffectMaterial.SetVector("_ImageDims", new Vector4((float)renderTex.width, (float)renderTex.height, 1.0f / (float)renderTex.width, 1.0f / (float)renderTex.height));

                    for (int i = 0; i < ceVariables.Count; ++i)
                    {
                        float value = ceVariables[i].value.AsFloat();
                        cameraEffectMaterial.SetFloat(ceVariables[i].variable, value);
                    }

                    Graphics.Blit(renderTex, screen, cameraEffectMaterial);
                }
                else
                {
                    Graphics.Blit(renderTex, screen);
                }
                renderTex.DiscardContents();

                ITargetable target = FlightGlobals.fetch.VesselTarget;

                bool drawSomething = ((gizmoTexture != null && target != null && showTargetIcon) || homeCrosshairMaterial.color.a > 0);

                if (drawSomething)
                {
                    GL.PushMatrix();
                    GL.LoadPixelMatrix(0, screen.width, screen.height, 0);
                }

                if (gizmoTexture != null && target != null && showTargetIcon)
                {
                    // Figure out which direction the target is.
                    Vector3 targetDisplacement = target.GetTransform().position - cameraObject.GetTransform().position;
                    targetDisplacement.Normalize();

                    // Transform it using the active camera's rotation.
                    var targetDisp = GetNormalizedScreenPosition(activeCamera, targetDisplacement, cameraAspect);

                    var iconCenter = new Vector2(screen.width * targetDisp.x, screen.height * targetDisp.y);

                    // Apply some clamping values to force the icon to stay on screen
                    iconCenter.x = Math.Max(iconPixelSize * 0.5f, iconCenter.x);
                    iconCenter.x = Math.Min(screen.width - iconPixelSize * 0.5f, iconCenter.x);
                    iconCenter.y = Math.Max(iconPixelSize * 0.5f, iconCenter.y);
                    iconCenter.y = Math.Min(screen.height - iconPixelSize * 0.5f, iconCenter.y);

                    var position = new Rect(iconCenter.x - iconPixelSize * 0.5f, iconCenter.y - iconPixelSize * 0.5f, iconPixelSize, iconPixelSize);

                    Graphics.DrawTexture(position, gizmoTexture, GizmoIcons.GetIconLocation(GizmoIcons.IconType.TARGETPLUS), 0, 0, 0, 0, iconMaterial);
                }

                if (homeCrosshairMaterial.color.a > 0)
                {
                    // Mihara: Reference point cameras are different enough to warrant it.
                    var cameraForward   = cameraObject.GetTransformForward();
                    var crossHairCenter = GetNormalizedScreenPosition(activeCamera, cameraForward, cameraAspect);
                    crossHairCenter.x *= screen.width;
                    crossHairCenter.y *= screen.height;
                    crossHairCenter.x  = Math.Max(iconPixelSize * 0.5f, crossHairCenter.x);
                    crossHairCenter.x  = Math.Min(screen.width - iconPixelSize * 0.5f, crossHairCenter.x);
                    crossHairCenter.y  = Math.Max(iconPixelSize * 0.5f, crossHairCenter.y);
                    crossHairCenter.y  = Math.Min(screen.height - iconPixelSize * 0.5f, crossHairCenter.y);

                    float zoomAdjustedIconSize = iconPixelSize * Mathf.Tan(Mathf.Deg2Rad * activeCamera.fovLimits.y * 0.5f) / Mathf.Tan(Mathf.Deg2Rad * activeCamera.currentFoV * 0.5f);

                    homeCrosshairMaterial.SetPass(0);
                    GL.Begin(GL.LINES);
                    GL.Vertex3(crossHairCenter.x - zoomAdjustedIconSize * 0.5f, crossHairCenter.y, 0.0f);
                    GL.Vertex3(crossHairCenter.x + zoomAdjustedIconSize * 0.5f, crossHairCenter.y, 0.0f);
                    GL.Vertex3(crossHairCenter.x, crossHairCenter.y - zoomAdjustedIconSize * 0.5f, 0.0f);
                    GL.Vertex3(crossHairCenter.x, crossHairCenter.y + zoomAdjustedIconSize * 0.5f, 0.0f);
                    GL.End();
                }

                if (drawSomething)
                {
                    GL.PopMatrix();
                }

                return(true);
            }
            else if (skipMissingCameras)
            {
                // This will handle cameras getting ejected while in use.
                SelectNextCamera();
            }

            return(false);
        }
Esempio n. 23
0
        public void FixedUpdate()
        {
            if (HighLogic.LoadedSceneIsEditor)
            {
                return;
            }

            ITargetable target = FlightGlobals.fetch.VesselTarget;

            if (radarEnabled)
            {
                bool powered = true;
                // Resources check
                if (resourceAmount > 0.0f)
                {
                    float requested = resourceAmount * TimeWarp.fixedDeltaTime;
                    float supplied  = part.RequestResource(resourceId, requested);
                    if (supplied < requested * 0.5f)
                    {
                        powered = false;
                    }
                }

                if (target == null)
                {
                    if (!powered)
                    {
                        JUtil.LogMessage(this, "Want to scan, but there's no power");
                        return;
                    }

                    // Scan
                    ScanForTargets();
                }
                else
                {
                    if (!trackWhileOff && !powered)
                    {
                        JUtil.LogMessage(this, "Radar ran out of power and trackWhileOff is false, so clearing target");
                        FlightGlobals.fetch.SetVesselTarget(null);
                        return;
                    }

                    // Target locked; tracking
                    if (restrictTracking)
                    {
                        Vector3 vectorToTarget = (target.GetTransform().position - scanTransform.position);
                        if (vectorToTarget.sqrMagnitude > maxRangeMetersSquared)
                        {
                            JUtil.LogMessage(this, "Target is out of range, losing lock");
                            FlightGlobals.fetch.SetVesselTarget(null);
                            return;
                        }
                        float dotAngle = Vector3.Dot(vectorToTarget.normalized, (scanTransformIsDockingNode) ? scanTransform.forward : scanTransform.up);
                        if (dotAngle < scanDotValue)
                        {
                            JUtil.LogMessage(this, "Target is out of scan angle, losing lock");
                            FlightGlobals.fetch.SetVesselTarget(null);
                            return;
                        }
                    }

                    if (powered && targetDockingPorts && (target is Vessel))
                    {
                        // Attempt to refine our target.
                    }
                }
            }
            else if (target != null)
            {
                if (!trackWhileOff)
                {
                    JUtil.LogMessage(this, "Radar is off and trackWhileOff is false, so clearing target");
                    FlightGlobals.fetch.SetVesselTarget(null);
                    return;
                }

                if (restrictTracking)
                {
                    Vector3 vectorToTarget = (target.GetTransform().position - scanTransform.position);
                    if (vectorToTarget.sqrMagnitude > maxRangeMetersSquared)
                    {
                        JUtil.LogMessage(this, "Target is out of range, losing lock");
                        FlightGlobals.fetch.SetVesselTarget(null);
                        return;
                    }
                    float dotAngle = Vector3.Dot(vectorToTarget.normalized, (scanTransformIsDockingNode) ? scanTransform.forward : scanTransform.up);
                    if (dotAngle < scanDotValue)
                    {
                        JUtil.LogMessage(this, "Target is out of scan angle, losing lock");
                        FlightGlobals.fetch.SetVesselTarget(null);
                        return;
                    }
                }
            }
        }
Esempio n. 24
0
        public bool RenderCamera(RenderTexture screen, float cameraAspect)
        {
            // Just in case.
            if (!HighLogic.LoadedSceneIsFlight)
            {
                return(false);
            }

            if (cameras.Count < 1)
            {
                return(false);
            }

            var activeCamera = cameras[currentCamera];

            if (string.IsNullOrEmpty(activeCamera.cameraTransform))
            {
                return(false);
            }

            if (cameraObject == null)
            {
                cameraObject = new FlyingCamera(part, screen, cameraAspect);
                cameraObject.PointCamera(activeCamera.cameraTransform, activeCamera.currentFoV);
            }

            cameraObject.FOV = activeCamera.currentFoV;

            // Negate pitch - the camera object treats a negative pitch as "up"
            if (cameraObject.Render(activeCamera.currentYaw, -activeCamera.currentPitch))
            {
                ITargetable target = FlightGlobals.fetch.VesselTarget;

                bool drawSomething = ((gizmoTexture != null && target != null && showTargetIcon) || homeCrosshairMaterial.color.a > 0);

                if (drawSomething)
                {
                    GL.PushMatrix();
                    GL.LoadPixelMatrix(0, screen.width, screen.height, 0);
                }

                if (gizmoTexture != null && target != null && showTargetIcon)
                {
                    // Figure out which direction the target is.
                    Vector3 targetDisplacement = target.GetTransform().position - cameraObject.GetTransform().position;
                    targetDisplacement.Normalize();

                    // Transform it using the active camera's rotation.
                    var targetDisp = GetNormalizedScreenPosition(activeCamera, targetDisplacement, cameraAspect);

                    var iconCenter = new Vector2(screen.width * targetDisp.x, screen.height * targetDisp.y);

                    // Apply some clamping values to force the icon to stay on screen
                    iconCenter.x = Math.Max(iconPixelSize * 0.5f, iconCenter.x);
                    iconCenter.x = Math.Min(screen.width - iconPixelSize * 0.5f, iconCenter.x);
                    iconCenter.y = Math.Max(iconPixelSize * 0.5f, iconCenter.y);
                    iconCenter.y = Math.Min(screen.height - iconPixelSize * 0.5f, iconCenter.y);

                    var position = new Rect(iconCenter.x - iconPixelSize * 0.5f, iconCenter.y - iconPixelSize * 0.5f, iconPixelSize, iconPixelSize);

                    Graphics.DrawTexture(position, gizmoTexture, GizmoIcons.GetIconLocation(GizmoIcons.IconType.TARGETPLUS), 0, 0, 0, 0, iconMaterial);
                }

                if (homeCrosshairMaterial.color.a > 0)
                {
                    // Mihara: Reference point cameras are different enough to warrant it.
                    var cameraForward   = cameraObject.GetTransformForward();
                    var crossHairCenter = GetNormalizedScreenPosition(activeCamera, cameraForward, cameraAspect);
                    crossHairCenter.x *= screen.width;
                    crossHairCenter.y *= screen.height;
                    crossHairCenter.x  = Math.Max(iconPixelSize * 0.5f, crossHairCenter.x);
                    crossHairCenter.x  = Math.Min(screen.width - iconPixelSize * 0.5f, crossHairCenter.x);
                    crossHairCenter.y  = Math.Max(iconPixelSize * 0.5f, crossHairCenter.y);
                    crossHairCenter.y  = Math.Min(screen.height - iconPixelSize * 0.5f, crossHairCenter.y);

                    float zoomAdjustedIconSize = iconPixelSize * Mathf.Tan(Mathf.Deg2Rad * activeCamera.fovLimits.y * 0.5f) / Mathf.Tan(Mathf.Deg2Rad * activeCamera.currentFoV * 0.5f);

                    homeCrosshairMaterial.SetPass(0);
                    GL.Begin(GL.LINES);
                    GL.Vertex3(crossHairCenter.x - zoomAdjustedIconSize * 0.5f, crossHairCenter.y, 0.0f);
                    GL.Vertex3(crossHairCenter.x + zoomAdjustedIconSize * 0.5f, crossHairCenter.y, 0.0f);
                    GL.Vertex3(crossHairCenter.x, crossHairCenter.y - zoomAdjustedIconSize * 0.5f, 0.0f);
                    GL.Vertex3(crossHairCenter.x, crossHairCenter.y + zoomAdjustedIconSize * 0.5f, 0.0f);
                    GL.End();
                }

                if (drawSomething)
                {
                    GL.PopMatrix();
                }

                return(true);
            }
            return(false);
        }
Esempio n. 25
0
        /// <summary>
        /// Forces the controller to pick a target to track. In order of preference:
        /// 1) A player-selected target.
        /// 2) A target vessel specified by the targetVessel variable.
        /// 3) A target celestial body specified by the targetBody variable.
        /// 4) A random target if trackRandomTargets is set to true.
        /// </summary>
        /// <returns></returns>
        public bool UpdateTarget()
        {
            ITargetable targetObject = this.part.vessel.targetObject;

            //chek for unset
            if (targetObject == null && targetObjectSet)
            {
                targetTransform = null;
                targetObjectSet = false;
            }

            //If we already have a target to track then we're good to go.
            if (targetTransform != null && targetObject == null)
            {
                return(true);
            }

            //First check to see if the vessel has selected a target.
            if (targetObject != null && canTrackPlayerTargets)
            {
                targetTransform = targetObject.GetTransform();
                trackingStatus  = targetObject.GetDisplayName().Replace("^N", "");
                targetName      = trackingStatus;
                targetObjectSet = true;
                return(true);
            }

            //Next check to see if we have a target vessel
            if (targetVessel != null)
            {
                targetTransform = targetVessel.vesselTransform;
                trackingStatus  = targetVessel.vesselName;
                targetName      = trackingStatus;
                return(true);
            }

            //Now check target planet
            if (targetBody != null)
            {
                targetTransform = targetBody.scaledBody.transform;
                trackingStatus  = targetBody.displayName.Replace("^N", "");
                targetName      = trackingStatus;
                return(true);
            }

            //Lastly, if random tracking is enabled and we don't have a target, then randomly select one from the unloaded vessels list.
            if (trackRandomObjects && targetTransform == null)
            {
                //get the tracking controllers on the vessel
                List <WBIBGTrackingServo> trackingControllers = this.part.vessel.FindPartModulesImplementing <WBIBGTrackingServo>();

                //If we aren't the first controller, then we're done.
                if (trackingControllers[0] != this)
                {
                    trackingStatus  = trackingControllers[0].trackingStatus;
                    targetTransform = trackingControllers[0].targetTransform;
                    targetName      = trackingStatus;
                    return(false);
                }

                //Find a random vessel to track
                int    vesselCount = FlightGlobals.VesselsUnloaded.Count;
                Vessel trackedVessel;
                for (int index = 0; index < vesselCount; index++)
                {
                    trackedVessel = FlightGlobals.VesselsUnloaded[UnityEngine.Random.Range(0, vesselCount - 1)];

                    //If we find a vessel we're interested in, tell all the other tracking controllers.
                    if (trackedVessel.vesselType != VesselType.Flag &&
                        trackedVessel.vesselType != VesselType.EVA &&
                        trackedVessel.vesselType != VesselType.Unknown)
                    {
                        int controllerCount = trackingControllers.Count;
                        for (int controllerIndex = 0; controllerIndex < controllerCount; controllerIndex++)
                        {
                            if (!trackingControllers[controllerIndex].trackRandomObjects)
                            {
                                continue;
                            }

                            trackingControllers[controllerIndex].targetTransform = trackedVessel.vesselTransform;
                            trackingControllers[controllerIndex].trackingStatus  = trackedVessel.vesselName;
                            trackingControllers[controllerIndex].targetName      = trackedVessel.vesselName;
                        }
                        return(true);
                    }
                }
            }

            //Nothing to track
            trackingStatus = kTrackingNone;
            targetName     = trackingStatus;
            return(false);
        }