Inheritance: ICritterState
Ejemplo n.º 1
0
    // Update is called once per frame

    void FixedUpdate()
    {
        if (GameObject.FindGameObjectWithTag("Manager").GetComponent <Pauser>().Paused == false)
        {
            if (isActive)
            {
                transform.position = new Vector3(Mathf.Lerp(transform.position.x, TargetTrans.position.x, 0.01f), transform.position.y, Mathf.Lerp(transform.position.z, TargetTrans.position.z, 0.05f));

                if (HandleGroundedAnim)
                {
                    PlayerState = TargetTrans.gameObject.GetComponent <PlaneControl>().State;

                    if (PlayerState == FlightState.Starting || PlayerState == FlightState.Idle)
                    {
                        MixFac = TargetTrans.position.y / TargetTrans.GetComponent <PlaneControl>().MaxHeight;
                    }
                    else if (PlayerState == FlightState.Game)
                    {
                        MixFac = 1;

                        GetComponentInChildren <Animator>().SetBool("isFlying", true);
                    }

                    GetComponentInChildren <Animator>().SetFloat("MixFac", MixFac);
                }
            }
        }
    }
Ejemplo n.º 2
0
    /// <summary>
    /// handles common state like hinge angles, lander position, lander enabled
    /// </summary>
    /// <param name="state"></param>
    private void SetState(FlightState state)
    {
        Data.State = state;

        Lander.gameObject.SetActive(state != FlightState.Disabled);

        Quaternion effectiveLanderHingeLocalRotation = Quaternion.identity;
        Vector3    effectiveLanderLocalPosition      = Vector3.zero;

        switch (state)
        {
        case FlightState.Landing:
            effectiveLanderHingeLocalRotation = Quaternion.Euler(airborneLanderHinge);
            effectiveLanderLocalPosition      = airborneLanderPosition;
            break;

        case FlightState.Landed:
            effectiveLanderHingeLocalRotation = Quaternion.Euler(landedLanderHinge);
            effectiveLanderLocalPosition      = landedLanderLocalPosition;
            break;

        case FlightState.TakingOff:
            effectiveLanderHingeLocalRotation = Quaternion.Euler(landedLanderHinge);
            effectiveLanderLocalPosition      = landedLanderLocalPosition;
            break;
        }

        LanderHinge.localRotation = effectiveLanderHingeLocalRotation;
        Lander.localPosition      = effectiveLanderLocalPosition;
    }
        private void FlightGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            // Clear the row error in case the user presses ESC.
            //FlightGridView.Rows[e.RowIndex].ErrorText = String.Empty;

            DataGridViewRow            row   = FlightGridView.Rows[e.RowIndex];
            DataGridViewCellCollection cells = row.Cells;

            Guid flightID = Guid.Parse(cells["ID"].Value.ToString());

            string departureDateStr = cells["ActualDepartureDate"].Value.ToString();
            Nullable <DateTime> actualDepartureDate = null;

            if (departureDateStr != "")
            {
                actualDepartureDate = DateTime.ParseExact(departureDateStr, "yyyy/mm/dd hh:mm:ss", CultureInfo.InvariantCulture);
            }


            string actualArrivalDateStr           = cells["ActualArrivalDate"].Value.ToString();
            Nullable <DateTime> actualArrivalDate = null;

            if (actualArrivalDateStr != "")
            {
                actualArrivalDate = DateTime.ParseExact(actualArrivalDateStr, "yyyy/mm/dd hh:mm:ss", CultureInfo.InvariantCulture);
            }

            FlightState state = PersianStringToFlightState(cells["StateComboBox"].Value.ToString());

            reservationSystem.UpdateFlight(flightID, state, actualArrivalDate, actualArrivalDate);

            reservationSystem.UpdateTables();
            RefereshTables();
        }
Ejemplo n.º 4
0
 public Plane(string Name, DateTime ActionDate, int waitingTime, FlightState flightState)
 {
     this.Name        = Name;
     this.ActionDate  = ActionDate;
     this.waitingTime = waitingTime;
     this.flightState = flightState;
 }
Ejemplo n.º 5
0
    void OnTargetReached()
    {
        FlightState old = target;

        target = targetSelector.OnTargetReached(target);
        Debug.Log($"Target switched from {old.parentBody}-{old.flightState} to {target.parentBody}-{target.flightState}");
    }
Ejemplo n.º 6
0
 void FlyToPlayer()
 {
     if (!hasPlayerOneWon)
     {
         flightdirection = -1;
         if (transform.position.x < playerOneSpawn.transform.position.x)
         {
             state = FlightState.dropItem;
             foreach (Rigidbody2D rb in GetComponentsInChildren <Rigidbody2D>())
             {
                 rb.gravityScale = 1;
             }
         }
     }
     else
     {
         flightdirection = 1;
         if (transform.position.x > playerTwoSpawn.transform.position.x)
         {
             state = FlightState.dropItem;
             foreach (Rigidbody2D rb in GetComponentsInChildren <Rigidbody2D>())
             {
                 rb.gravityScale = 1;
             }
         }
     }
     transform.position += Vector3.right * Time.deltaTime * flightdirection * speed * radiusModifier;
 }
Ejemplo n.º 7
0
        public byte Tick(SensorUpdate sensors, FlightState state)
        {
            if (state != lastState)
            {
                // Trigger ignition with state change
                if (state == FlightState.LAUNCH)
                {
                    flightStatusController.RequestFlightStateChange(FlightState.ASCENT_PHASE);
                    lastState = state;
                    return(Ignition(0x01, true));
                }
            }
            switch (state)
            {
            case FlightState.DESCENT_PHASE:
                return(HandleDescent(sensors));

            case FlightState.ASCENT_PHASE:
            case FlightState.LAUNCH:
            case FlightState.MISSION_ENDED:
            case FlightState.ON_PAD:
            default:
                return(Pyros);
            }
        }
Ejemplo n.º 8
0
        private void Drone_StateChanged(FlightState state)
        {
            lock (stateLock)
            {
                try
                {
                    flightState = new FlightState(state.Altitude, state.Yaw, state.Pitch, state.Roll, state.Vx, state.Vy, state.Vz, state.IsFlying, state.Error);

                    var first = Values.DefaultIfEmpty(0).FirstOrDefault();

                    Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        if (Values.Count >= MaxRecordNumber)
                        {
                            Values.Remove(first);
                        }

                        if (Values.Count < MaxRecordNumber)
                        {
                            Values.Add(flightState.Yaw);
                        }
                    }).AsTask().Wait();

                    Count = Values.Count;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.ToString());
                }
            }
        }
Ejemplo n.º 9
0
        public async Task <IHttpActionResult> PutFlightState(int id, FlightStateDTO flightStateDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != flightStateDto.Id)
            {
                return(BadRequest());
            }
            FlightState flightState = Mapper.Map <FlightState>(flightStateDto);

            db.Entry(flightState).State = System.Data.Entity.EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!FlightStateExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
Ejemplo n.º 10
0
 void Start()
 {
     radiusModifier  = 0.1f;
     flightdirection = 1;
     playerOneSpawn  = GameObject.Find("playerOneSpawn");
     playerTwoSpawn  = GameObject.Find("playerTwoSpawn");
     state           = FlightState.undecided;
 }
Ejemplo n.º 11
0
        void PostInitSC()
        {
            if (LastVessels.Count < 1)
            {
                FlightState _flightState = HighLogic.CurrentGame.flightState;
                if (_flightState != null)
                {
                    List <ProtoVessel> _pVessels = _flightState.protoVessels;
                    for (int _i = _pVessels.Count - 1; _i >= 0; --_i)
                    {
                        ProtoVessel _pVessel = _pVessels[_i];
                        if (_pVessel != null)
                        {
                            AddLastVessel(_pVessel);
                        }
                    }
                }
            }
            else
            {
                List <QData> _lastVessels = LastVessels;
                LastVessels = new List <QData> ();
                for (int _i = _lastVessels.Count - 1; _i >= 0; --_i)
                {
                    QData _lastVessel = _lastVessels[_i];
                    if (pVesselExists(_lastVessel.protoVessel))
                    {
                        LastVessels.Add(_lastVessel);
                    }
                    else
                    {
                        Warning("Remove from the last Vessels: " + _lastVessel.protoVessel.vesselName, "QGoTo");
                    }
                }
            }
            if (SavedGoTo != GoTo.None)
            {
                switch (SavedGoTo)
                {
                case GoTo.Administration:
                    administration();
                    break;

                case GoTo.AstronautComplex:
                    astronautComplex();
                    break;

                case GoTo.RnD:
                    RnD();
                    break;

                case GoTo.MissionControl:
                    missionControl();
                    break;
                }
                SavedGoTo = GoTo.None;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// ReplaceMent for finding vessels
        /// </summary>
        /// <param name="flightState"></param>
        /// <param name="landedAt"></param>
        /// <param name="count"></param>
        /// <param name="name"></param>
        /// <param name="idx"></param>
        /// <param name="vType"></param>
        public static void FindVesselsLandedAtKK(FlightState flightState, string landedAt, out int count, out string name, out int idx, out VesselType vType)
        {
            // Log.Normal("Called");
            float maxDistance = 100f;

            int          vesselIndex = 0;
            KKLaunchSite launchSite  = LaunchSiteManager.GetLaunchSiteByName(landedAt);

            count = 0;
            name  = string.Empty;
            idx   = 0;
            vType = VesselType.Debris;

            if (flightState != null)
            {
                foreach (ProtoVessel vessel in flightState.protoVessels)
                {
                    if (vessel == null)
                    {
                        continue;
                    }

                    if (launchSite == null || launchSite.isSquad)
                    {
                        if (vessel.landedAt.Contains(landedAt))
                        {
                            count++;
                            name  = vessel.vesselName;
                            idx   = vesselIndex;
                            vType = vessel.vesselType;
                            break;
                        }
                    }
                    else
                    {
                        //if (vessel.situation == Vessel.Situations.SPLASHED || vessel.situation == Vessel.Situations.LANDED || vessel.situation == Vessel.Situations.PRELAUNCH )
                        //                        {
                        ////                            Log.Normal("Body: "+ FlightGlobals.Bodies[vessel.orbitSnapShot.ReferenceBodyIndex].name);
                        CelestialBody body     = FlightGlobals.Bodies[vessel.orbitSnapShot.ReferenceBodyIndex];
                        Vector3       position = body.GetWorldSurfacePosition(vessel.latitude, vessel.longitude, vessel.altitude);
                        float         distance = Vector3.Distance(position, launchSite.staticInstance.gameObject.transform.position);
                        //Log.Normal("Vessel with distance: " + distance);
                        if (distance < maxDistance)
                        {
                            Log.Normal("Found Vessel at Launchsite with distance: " + distance);
                            count++;
                            name  = vessel.vesselName;
                            idx   = vesselIndex;
                            vType = vessel.vesselType;
                            break;
                        }
                        //}
                    }
                    vesselIndex++;
                }
            }
        }
Ejemplo n.º 13
0
        public Guid Add(FlightStateDTO flightStateDTO)
        {
            FlightState state = new FlightState {
                Name = flightStateDTO.Name
            };

            _airplaneContext.FlightStates.Add(state);
            _airplaneContext.SaveChanges();
            return(state.Id);
        }
Ejemplo n.º 14
0
        public bool pVesselExists(ProtoVessel pvessel)
        {
            FlightState _flightState = HighLogic.CurrentGame.flightState;

            if (_flightState != null)
            {
                return(_flightState.protoVessels.Exists(pv => pv.vesselID == pvessel.vesselID));
            }
            return(false);
        }
Ejemplo n.º 15
0
 private void EvaluateFlightState()
 {
     if (VRTK_bodyPhysics.OnGround())
     {
         flightState = FlightState.Ground;
     }
     else
     {
         flightState = FlightState.Falling;
     }
 }
        public void UpdateFlight(Guid flightID, FlightState newState, Nullable <DateTime> newActualDepartureDate, Nullable <DateTime> newActualArrivalDate)
        {
            Flight f = ServiceFactory.GetFlights().GetFlightByID(flightID);

            f.flightState         = newState;
            f.actualArrivalDate   = newActualArrivalDate;
            f.actualDepartureDate = newActualDepartureDate;

            DBFacade.UpdateFlight(flightID, newState.ToString(), newActualDepartureDate, newActualArrivalDate);
            MessageBox.Show(" بروزرسانی با موفقیت اضافه شد");
        }
Ejemplo n.º 17
0
 public override FlightState OnTargetReached(FlightState flightStateNow)
 {
     if (flightStateNow.flightState == a.flightState && flightStateNow.parentBody == a.parentBody)
     {
         return(new FlightState(b));
     }
     if (flightStateNow.flightState == b.flightState && flightStateNow.parentBody == b.parentBody)
     {
         return(new FlightState(a));
     }
     Debug.Log($"Pendler lost in state {flightStateNow.parentBody}-{flightStateNow.flightState}"); return(null);
 }
Ejemplo n.º 18
0
        public async Task <IHttpActionResult> PostFlightState(FlightState flightState)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.FlightStates.Add(flightState);
            await db.SaveChangesAsync();

            return(Ok(flightState));
        }
 private void Initial(Guid ID, Airplane airplane, Airport origin, Airport destination, DateTime departureDate, DateTime arrivalDate, Nullable<DateTime> actualDepartureDate, Nullable<DateTime> actualArrivalDate, FlightState state, uint cost)
 {
     this.ID = ID;
     this.airplane = airplane;
     this.origin = origin;
     this.destination = destination;
     this.departureDate = departureDate;
     this.arrivalDate = arrivalDate;
     this.actualArrivalDate = actualArrivalDate;
     this.actualDepartureDate = actualDepartureDate;
     this.flightState= state;
     this.cost = cost;
 }
Ejemplo n.º 20
0
        public async Task <IHttpActionResult> DeleteFlightState(int id)
        {
            FlightState flightState = await db.FlightStates.FindAsync(id);

            if (flightState == null)
            {
                return(NotFound());
            }

            db.FlightStates.Remove(flightState);
            await db.SaveChangesAsync();

            return(Ok(flightState));
        }
        public ArrowStateEngine(
            IConstArg arg
            )
        {
            thisArrow = arg.arrow;

            AbsState.IConstArg stateConstArg = new AbsState.ConstArg(
                thisArrow,
                this
                );
            thisNockedState      = new NockedState(stateConstArg);
            thisFlightState      = new FlightState(stateConstArg);
            thisDeactivatedState = new DeactivatedState(stateConstArg);
        }
        public void UpdateTable()
        {
            flightTable.Clear();
            flightTable = DBFacade.GetFlights();

            AllAirplanes allPlanes   = ServiceFactory.GetAirplanes();
            AllAirports  allAirports = ServiceFactory.GetAirports();

            for (int i = 0; i < flightTable.Rows.Count; i++)
            {
                Guid ID = Guid.Parse(flightTable.Rows[i]["ID"].ToString());

                Guid     planeID  = Guid.Parse(flightTable.Rows[i]["planeID"].ToString());
                Airplane airplane = allPlanes.GetPlaneByID(planeID);

                Guid    originID = Guid.Parse(flightTable.Rows[i]["originAirportID"].ToString());
                Airport origin   = allAirports.GetAirportByID(originID);

                Guid    destinationID = Guid.Parse(flightTable.Rows[i]["destinationAirportID"].ToString());
                Airport destination   = allAirports.GetAirportByID(destinationID);

                DateTime arrivalDate   = DateTime.Parse(flightTable.Rows[i]["arrivalDate"].ToString());
                DateTime departureDate = DateTime.Parse(flightTable.Rows[i]["departureDate"].ToString());

                String actualArrivalDateStr           = flightTable.Rows[i]["actualArrivalDate"].ToString();
                Nullable <DateTime> actualArrivalDate = null;
                if (!actualArrivalDateStr.Equals(""))
                {
                    actualArrivalDate = DateTime.Parse(actualArrivalDateStr);
                }



                String actualDepartureDateStr           = flightTable.Rows[i]["actualDepartureDate"].ToString();
                Nullable <DateTime> actualDepartureDate = null;
                if (!actualDepartureDateStr.Equals(""))
                {
                    actualDepartureDate = DateTime.Parse(actualDepartureDateStr);
                }


                String      flightStateStr = flightTable.Rows[i]["State"].ToString();
                FlightState flightState    = Utilities.StringToFlightState(flightStateStr);

                uint cost = uint.Parse(flightTable.Rows[i]["Cost"].ToString());

                flights.Add(new Flight(ID, airplane, origin, destination, departureDate, arrivalDate, actualDepartureDate, actualArrivalDate, flightState, cost));
            }
        }
Ejemplo n.º 23
0
        public async Task <IHttpActionResult> GetFlightState(int id)
        {
            FlightState flightState = await db.FlightStates.FindAsync(id);

            if (flightState == null)
            {
                return(NotFound());
            }

            FlightStateDTO dto = new FlightStateDTO();

            dto.buildDTO(flightState);

            return(Ok(dto));
        }
Ejemplo n.º 24
0
    public override void HandleStart()
    {
        base.HandleStart();

        // Calculate the journey length.

        flightState   = FlightState.Forward;
        startPosition = transform.position;


        if (clip != null)
        {
            sound.clip = clip;
        }
    }
Ejemplo n.º 25
0
        public override string ToString()
        {
            string ret =
                "Flight number : " + flightNumber + "\n" +
                "origin city : " + origin + "\n" +
                "Destination : " + destination + "\n" +
                "Departure Date : " + departueDate.ToShortDateString() + "\n" +
                "Flight status : " + FlightState.ToString() + "\n";

            if (retDate != new DateTime())
            {
                ret += "Return Date : " + retDate.ToShortDateString() + "\n";
            }
            ret += "Base Flight Fare : " + baseFlightFare;
            return(ret);
        }
Ejemplo n.º 26
0
        private string ToFormattedText(FlightState value)
        {
            var stringVal = value.ToString();
            var bld       = new StringBuilder();

            for (var i = 0; i < stringVal.Length; i++)
            {
                if (char.IsUpper(stringVal[i]))
                {
                    bld.Append(" ");
                }

                bld.Append(stringVal[i]);
            }

            return(bld.ToString());
        }
    private void Awake()
    {
        wanderState = new WanderState (this); // huntStart = new HuntState (this); May replace with this
        idleState = new IdleState (this); // huntStart = new HuntState (this); May replace with this
        forageState = new ForageState (this);
        flightState = new FlightState (this);
        pursuitState = new PursuitState (this);
        exitState = new ExitState (this);
        enterState = new EnterState (this);
        navMeshAgent = GetComponent<NavMeshAgent>();

        navMeshAgent.enabled = true;
        // navMeshObstacle.enabled = false;

        navMeshRadius = navMeshAgent.radius;

        navMeshAgent.avoidancePriority = Random.Range(0, 100);  // Randomly set the avoidance priority
    }
Ejemplo n.º 28
0
    public bool SetNextFlightState(FlightState next, InterpolatedOrbit newOrbit, double insertionDeltaV)
    {
        // inconsistent parent body
        if (parentBody != next.parentBody && next.flightState != StateEnum.InterplanetaryTransfer && flightState != StateEnum.InterplanetaryTransfer)
        {
            return(false);
        }
        if (next.parentBody == null)
        {
            Debug.Log("Attempt to start flight with null parent body"); return(false);
        }

        // from surface only to LO
        if (flightState == StateEnum.OnSurface && next.flightState != StateEnum.LO)
        {
            return(false);
        }

        if (next.flightState == StateEnum.InterplanetaryTransfer)
        {
            if (next.parentBody == null)
            {
                Debug.Log("Attempt to start interplanetary flight without specifiying the destination"); return(false);
            }
            if (newOrbit == null)
            {
                Debug.Log("Orbit required and not provided"); return(false);
            }

            parentShip.SetupOrbit(newOrbit);
        }

        if (flightState == StateEnum.InterplanetaryTransfer && next.flightState != StateEnum.InterplanetaryTransfer)
        {
            parentShip.DestroyOrbit();
        }

        parentShip.engine.BurnFuelByDeltaV(insertionDeltaV, 3600 / 2);
        flightState = next.flightState;
        parentBody  = next.parentBody;

        return(true);
    }
Ejemplo n.º 29
0
    public void UpdatePosition()
    {
        if (flightStarted == true)
        {
            // Distance moved equals elapsed time times speed..
            float distCovered = (Time.time - startTime) * speed;

            // Fraction of journey completed equals current distance divided by total distance.
            float fractionOfFlight = distCovered / flightDistance;

            if (flightState == FlightState.Reverse)
            {
                fractionOfFlight = 1 - fractionOfFlight;
            }

            // Set our position as a fraction of the distance between the markers.
            transform.position = Vector3.Lerp(startPosition, endPosition, fractionOfFlight);

            if (flightState == FlightState.Forward && fractionOfFlight > .99)
            {
                flightStarted = false;
                flightState   = FlightState.Reverse;
            }
            else if (flightState == FlightState.Reverse && fractionOfFlight < .01)
            {
                flightStarted = false;
                flightState   = FlightState.Forward;
            }
        }
        if (flightStarted == false)
        {
            float transformY = Mathf.Sin(Time.time * transformFrequency * speed + transformPhase) * transformAmplitude;
            if (flightState == FlightState.Forward)
            {
                translate.Set(startPosition.x, startPosition.y + transformY, startPosition.z);
            }
            else
            {
                translate.Set(endPosition.x, endPosition.y + transformY, endPosition.z);
            }
            this.transform.localPosition = translate;
        }
    }
Ejemplo n.º 30
0
        public static List <ProtoVessel> FindVesselsLandedAt2(FlightState flightState, string landedAt)
        {
            float maxDistance       = 100f;
            List <ProtoVessel> list = new List <ProtoVessel>();

            if (flightState != null)
            {
                KKLaunchSite launchSite = LaunchSiteManager.GetLaunchSiteByName(landedAt);

                foreach (ProtoVessel vessel in flightState.protoVessels)
                {
                    if (vessel == null)
                    {
                        continue;
                    }

                    if (launchSite == null || launchSite.isSquad)
                    {
                        if (vessel.landedAt.Contains(landedAt))
                        {
                            list.Add(vessel);
                        }
                    }
                    else
                    {
                        //if (vessel.situation == Vessel.Situations.SPLASHED || vessel.situation == Vessel.Situations.LANDED || vessel.situation == Vessel.Situations.PRELAUNCH)
                        //{
                        CelestialBody body     = FlightGlobals.Bodies[vessel.orbitSnapShot.ReferenceBodyIndex];
                        Vector3       position = body.GetWorldSurfacePosition(vessel.latitude, vessel.longitude, vessel.altitude);
                        float         distance = Vector3.Distance(position, launchSite.staticInstance.transform.position);

                        if (distance < maxDistance)
                        {
                            Log.Normal("Found Vessel at Launchsite with distance: " + distance);
                            list.Add(vessel);
                        }
                        //}
                    }
                }
            }
            return(list);
        }
Ejemplo n.º 31
0
        public Airplane CreateRandomAirplane()
        {
            Random          rand               = new Random();
            Array           values1            = Enum.GetValues(typeof(FlightState));
            FlightState     randomFlightState  = (FlightState)values1.GetValue(rand.Next(values1.Length));
            Array           values2            = Enum.GetValues(typeof(AirplaneCompany));
            AirplaneCompany randomCompany      = (AirplaneCompany)values2.GetValue(rand.Next(values2.Length));
            int             randomflightNumber = rand.Next(1000, 9000);
            Airplane        a = new Airplane()
            {
                Id              = id++,
                FlightState     = randomFlightState,
                AirplaneStatus  = AirplaneStatus.ReadyToMove,
                AirplaneCompany = randomCompany,
                FlightNumber    = randomflightNumber,
                EnteredStartingStationDateTime = DateTime.Now
            };

            return(a);
        }
Ejemplo n.º 32
0
    static public GameObject SetupInstance(GameObject source, GameObject dest)
    {
        GameObject template = (GameObject)Resources.Load("ShipPrefab", typeof(GameObject));

        GameObject newRen = Instantiate(template);

        newRen.name = $"Ship #{GameEvents.current.GetNextShipNr()}";

        newRen.transform.parent = source.transform.parent;
        newRen.transform.SetPositionAndRotation(source.transform.position, new Quaternion());

        Ship ship = newRen.GetComponent <Ship>();

        ship.flightState = new FlightState(source.GetComponent <Planet>(), FlightState.StateEnum.OnSurface, ship);

        FlightState autopilotTarget = new FlightState(dest.GetComponent <Planet>(), FlightState.StateEnum.OnSurface, ship);

        ship.autopilot        = new HohmannTransferPendlerAutopilot(ship, ship.flightState, autopilotTarget);
        ship.autopilot.target = autopilotTarget;

        // fuel and engine initialization
        RP1Resource rp1      = new RP1Resource();
        LOXResource lox      = new LOXResource();
        Fuel        fuel     = new RP1Fuel(rp1, lox);
        double      fuelMass = 100000;
        FuelTank    rp1Tank  = new FuelTank(fuelMass, rp1, fuelMass * 0.07);
        FuelTank    loxTank  = new FuelTank(fuelMass * rp1.oxidizer_ratio, lox, fuelMass * rp1.oxidizer_ratio * 0.07);

        ship.engine = new ChemicalEngine(fuel, fuelMass * 0.07, ship);
        ship.fuelTanks.Add(rp1Tank);
        ship.fuelTanks.Add(loxTank);
        ship.Refuel();

        ship.orbit         = null;
        ship.orbitRenderer = null;

        GameEvents.current.allShips.Add(newRen);
        GameEvents.current.UpdateScales();

        return(newRen);
    }
        public void UpdateFlight(Guid flightID, FlightState newState, Nullable<DateTime> newActualDepartureDate, Nullable<DateTime> newActualArrivalDate)
        {
            Flight f = ServiceFactory.GetFlights().GetFlightByID(flightID);
            f.flightState = newState;
            f.actualArrivalDate = newActualArrivalDate;
            f.actualDepartureDate = newActualDepartureDate;

            DBFacade.UpdateFlight(flightID, newState.ToString(), newActualDepartureDate, newActualArrivalDate);
            MessageBox.Show(" بروزرسانی با موفقیت اضافه شد");
        }
Ejemplo n.º 34
0
    //private List<Vessel> bases;
    // =====================================================================================================================================================
    // UI Functions
    private void WindowGUI(int windowID)
    {
        /*
         * ToDo:
         * can extend FileBrowser class to see currently highlighted file?
         * rslashphish says: public myclass(arg1, arg2) : base(arg1, arg2);
         * KSPUtil.ApplicationRootPath - gets KSPO root
         * expose m_files and m_selectedFile?
         * fileBrowser = new FileBrowser(new Rect(Screen.width / 2, 100, 350, 500), title, callback, true);
         *
         * Style declarations messy - how do I dupe them easily?
         */
        if (uis.init)
        {
            uis.init = false;
        }

        EditorLogic editor = EditorLogic.fetch;
        if (editor) return;

        GUIStyle mySty = new GUIStyle(GUI.skin.button);
        mySty.normal.textColor = mySty.focused.textColor = Color.white;
        mySty.hover.textColor = mySty.active.textColor = Color.yellow;
        mySty.onNormal.textColor = mySty.onFocused.textColor = mySty.onHover.textColor = mySty.onActive.textColor = Color.green;
        mySty.padding = new RectOffset(8, 8, 8, 8);

        GUIStyle redSty = new GUIStyle(GUI.skin.box);
        redSty.padding = new RectOffset(8, 8, 8, 8);
        redSty.normal.textColor = redSty.focused.textColor = Color.red;

        GUIStyle yelSty = new GUIStyle(GUI.skin.box);
        yelSty.padding = new RectOffset(8, 8, 8, 8);
        yelSty.normal.textColor = yelSty.focused.textColor = Color.yellow;

        GUIStyle grnSty = new GUIStyle(GUI.skin.box);
        grnSty.padding = new RectOffset(8, 8, 8, 8);
        grnSty.normal.textColor = grnSty.focused.textColor = Color.green;

        GUIStyle whiSty = new GUIStyle(GUI.skin.box);
        whiSty.padding = new RectOffset(8, 8, 8, 8);
        whiSty.normal.textColor = whiSty.focused.textColor = Color.white;

        GUIStyle labSty = new GUIStyle(GUI.skin.label);
        labSty.normal.textColor = labSty.focused.textColor = Color.white;
        labSty.alignment = TextAnchor.MiddleCenter;

        GUILayout.BeginVertical();

        GUILayout.BeginHorizontal("box");
        GUILayout.FlexibleSpace();
        // VAB / SPH selection
        if (GUILayout.Toggle(uis.showvab, "VAB", GUILayout.Width(80)))
        {
            uis.showvab = true;
            uis.showsph = false;
            uis.ct = crafttype.VAB;
        }
        if (GUILayout.Toggle(uis.showsph, "SPH"))
        {
            uis.showvab = false;
            uis.showsph = true;
            uis.ct = crafttype.SPH;
        }
        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();

        string strpath = HighLogic.CurrentGame.Title.Split(new string[] { " (Sandbox)" }, StringSplitOptions.None).First();

        if (GUILayout.Button("Select Craft", mySty, GUILayout.ExpandWidth(true)))//GUILayout.Button is "true" when clicked
        {
            uis.craftlist = new CraftBrowser(new Rect(Screen.width / 2, 100, 350, 500), uis.ct.ToString(), strpath, "Select a ship to load", craftSelectComplete, craftSelectCancel, HighLogic.Skin, EditorLogic.ShipFileImage, true);
            uis.showcraftbrowser = true;
        }

        if (uis.craftselected)
        {
            GUILayout.Box("Selected Craft:  " + uis.craftnode.GetValue("ship"), whiSty);

            // Resource requirements
            GUILayout.Label("Resources required to build:", labSty, GUILayout.Width(600));

            // Link LFO toggle

            uis.linklfosliders = GUILayout.Toggle(uis.linklfosliders, "Link RocketFuel sliders for LiquidFuel and Oxidizer");

            uis.resscroll = GUILayout.BeginScrollView(uis.resscroll, GUILayout.Width(600), GUILayout.Height(300));

            GUILayout.BeginHorizontal();

            // Headings
            GUILayout.Label("Resource", labSty, GUILayout.Width(120));
            GUILayout.Label("Fill Percentage", labSty, GUILayout.Width(300));
            GUILayout.Label("Required", labSty, GUILayout.Width(60));
            GUILayout.Label("Available", labSty, GUILayout.Width(60));
            GUILayout.EndHorizontal();

            uis.canbuildcraft = true;      // default to can build - if something is stopping us from building, we will set to false later

            // LFO = 55% oxidizer

            // Cycle through required resources
            foreach (KeyValuePair<string, float> pair in uis.requiredresources)
            {
                string resname = pair.Key;  // Holds REAL resource name. May neet to translate from "JetFuel" back to "LiquidFuel"
                string reslabel = resname;   // Resource name for DISPLAY purposes only. Internally the app uses pair.Key
                if (reslabel == "JetFuel")
                {
                    // Do not show JetFuel line if not being used
                    if (pair.Value == 0f)
                    {
                        continue;
                    }
                    //resname = "JetFuel";
                    resname = "LiquidFuel";
                }

                // ToDo: If you request an unknown resource type, does this crash the UI?
                List<PartResource> connectedresources = GetConnectedResources(this.part, resname);
                // If in link LFO sliders mode, rename Oxidizer to LFO (Oxidizer) and LiquidFuel to LFO (LiquidFuel)
                if (reslabel == "Oxidizer")
                {
                    reslabel = "RocketFuel (Ox)";
                }
                if (reslabel == "LiquidFuel")
                {
                    reslabel = "RocketFuel (LF)";
                }

                GUILayout.BeginHorizontal();

                // Resource name
                GUILayout.Box(reslabel, whiSty, GUILayout.Width(120), GUILayout.Height(40));

                // Add resource to Dictionary if it does not exist
                if (!uis.resourcesliders.ContainsKey(pair.Key))
                {
                    uis.resourcesliders.Add(pair.Key, 1);
                }

                GUIStyle tmpSty = new GUIStyle(GUI.skin.label);
                tmpSty.alignment = TextAnchor.MiddleCenter;
                tmpSty.margin = new RectOffset(0, 0, 0, 0);

                GUIStyle sliSty = new GUIStyle(GUI.skin.horizontalSlider);
                sliSty.margin = new RectOffset(0, 0, 0, 0);

                // Fill amount
                GUILayout.BeginVertical();
                {
                    if (pair.Key == "RocketParts")
                    {
                        // Partial Fill for RocketParts not allowed - Instead of creating a slider, hard-wire slider position to 100%
                        uis.resourcesliders[pair.Key] = 1;
                        GUILayout.FlexibleSpace();
                        GUILayout.Box("Must be 100%", GUILayout.Width(300), GUILayout.Height(20));
                        GUILayout.FlexibleSpace();

                    }
                    else
                    {
                        GUILayout.FlexibleSpace();
                        // limit slider to 0.5% increments
                        float tmp = (float)Math.Round(GUILayout.HorizontalSlider(uis.resourcesliders[pair.Key], 0.0F, 1.0F, sliSty, new GUIStyle(GUI.skin.horizontalSliderThumb), GUILayout.Width(300), GUILayout.Height(20)), 3);
                        tmp = (Mathf.Floor(tmp * 200)) / 200;

                        // Are we in link LFO mode?
                        if (uis.linklfosliders)
                        {

                            if (pair.Key == "Oxidizer")
                            {
                                uis.resourcesliders["LiquidFuel"] = tmp;
                            }
                            else if (pair.Key == "LiquidFuel")
                            {
                                uis.resourcesliders["Oxidizer"] = tmp;
                            }
                        }
                        // Assign slider value to variable
                        uis.resourcesliders[pair.Key] = tmp;
                        GUILayout.Box((tmp * 100).ToString() + "%", tmpSty, GUILayout.Width(300), GUILayout.Height(20));
                        GUILayout.FlexibleSpace();
                    }
                }
                GUILayout.EndVertical();

                // Calculate if we have enough resources to build
                double tot = 0;
                foreach (PartResource pr in connectedresources)
                {
                    tot += pr.amount;
                }

                // If LFO LiquidFuel exists and we are on LiquidFuel (Non-LFO), then subtract the amount used by LFO(LiquidFuel) from the available amount

                if (pair.Key == "JetFuel")
                {
                    tot -= uis.requiredresources["LiquidFuel"] * uis.resourcesliders["LiquidFuel"];
                }
                GUIStyle avail = new GUIStyle();
                if (tot < pair.Value * uis.resourcesliders[pair.Key])
                {
                    avail = redSty;
                    uis.canbuildcraft = false; // prevent building
                }
                else
                {
                    avail = grnSty;
                }

                // Required
                GUILayout.Box((Math.Round(pair.Value * uis.resourcesliders[pair.Key], 2)).ToString(), avail, GUILayout.Width(60), GUILayout.Height(40));
                // Available
                GUILayout.Box(((int)tot).ToString(), whiSty, GUILayout.Width(60), GUILayout.Height(40));

                // Flexi space to make sure any unused space is at the right-hand edge
                GUILayout.FlexibleSpace();

                GUILayout.EndHorizontal();
            }

            GUILayout.EndScrollView();

            // Build button
            if (uis.canbuildcraft)
            {
                if (GUILayout.Button("Build", mySty, GUILayout.ExpandWidth(true)))
                {

                    // build craft
                    FlightState state = new FlightState();
                    ShipConstruct nship = ShipConstruction.LoadShip(uis.craftfile);
                    ShipConstruction.PutShipToGround(nship, this.part.transform);
                    // is this line causing bug #11 ?
                    ShipConstruction.AssembleForLaunch(nship, "External Launchpad", HighLogic.CurrentGame.flagURL, state);
                    Staging.beginFlight();
                    nship.parts[0].vessel.ResumeStaging();
                    Staging.GenerateStagingSequence(nship.parts[0].localRoot);
                    Staging.RecalculateVesselStaging(nship.parts[0].vessel);

                    // use resources
                    foreach (KeyValuePair<string, float> pair in uis.requiredresources)
                    {
                        // If resource is "JetFuel", rename to "LiquidFuel"
                        string res = pair.Key;
                        if (pair.Key == "JetFuel")
                        {
                            res = "LiquidFuel";
                        }

                        // Calculate resource cost based on slider position - note use pair.Key NOT res! we need to use the position of the dedicated LF slider not the LF component of LFO slider
                        double tot = pair.Value * uis.resourcesliders[pair.Key];
                        // Remove the resource from the vessel doing the building
                        this.part.RequestResource(res, tot);

                        // If doing a partial fill, remove unfilled amount from the spawned ship
                        // ToDo: Only subtract LiquidFuel from a part when it does not also have Oxidizer in it - try to leave fuel tanks in a sane state!
                        double ptot = pair.Value - tot;
                        foreach (Part p in nship.parts)
                        {
                            if (ptot > 0)
                            {
                                ptot -= p.RequestResource(res, ptot);
                            }
                            else
                            {
                                break;
                            }
                        }
                        /*
                        foreach (Part p in nship.parts) {
                            if (tot>pair.Value*uis.resourcesliders[res]) {
                                tot -= p.RequestResource(res, tot-pair.Value);
                            } else {
                                break;
                            }
                        }
                        */
                    }

                    //Remove the kerbals who get spawned with the ship
                    foreach (Part p in nship.parts)
                    {
                        if (p.CrewCapacity > 0)
                        {
                            print("Part has crew");
                            foreach (ProtoCrewMember m in p.protoModuleCrew)
                            {
                                print("Removing crewmember:");
                                print(m.name);
                                p.RemoveCrewmember(m);
                                m.rosterStatus = ProtoCrewMember.RosterStatus.AVAILABLE;
                            }
                        }
                    }

                    // Reset the UI
                    uis.craftselected = false;
                    uis.requiredresources = null;
                    uis.resourcesliders = null;

                    // Close the UI
                    DisableBuildMenu();
                }
            }
            else
            {
                GUILayout.Box("You do not have the resources to build this craft", redSty);
            }
        }
        else
        {
            GUILayout.Box("You must select a craft before you can build", redSty);
        }
        GUILayout.EndVertical();

        GUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button("Close"))
        {
            DisableBuildMenu();
        }

        uis.showbuilduionload = GUILayout.Toggle(uis.showbuilduionload, "Show on StartUp");

        GUILayout.FlexibleSpace();
        GUILayout.EndHorizontal();
        //DragWindow makes the window draggable. The Rect specifies which part of the window it can by dragged by, and is
        //clipped to the actual boundary of the window. You can also pass no argument at all and then the window can by
        //dragged by any part of it. Make sure the DragWindow command is AFTER all your other GUI input stuff, or else
        //it may "cover up" your controls and make them stop responding to the mouse.
        GUI.DragWindow(new Rect(0, 0, 10000, 20));
    }
 public Flight(Guid ID, Airplane airplane, Airport origin, Airport destination, DateTime departureDate, DateTime arrivalDate, Nullable<DateTime> actualDepartureDate, Nullable<DateTime> actualArrivalDate, FlightState state, uint cost)
 {
     Initial(ID, airplane, origin, destination, departureDate, arrivalDate, actualDepartureDate, actualArrivalDate, state, cost);
 }
 public extern static string SaveFlightState(FlightState st, string saveFileName, string saveFolder, SaveMode saveMode);