internal void Initialize()
        {
            shipItems = new Dictionary <int, ShipItem>();
            List <Part> parts          = player.Parts;
            int         activeBoxIndex = 0;
            IDs         id             = IDs.RECTHULLPART;

            shipItems.Add(0, new ShipItem(new Vector2(WindowSize.Width / 2, WindowSize.Height / 2), 0, null, player.Parts[0], id));      //not 100% centered   + hull = null  + linkpos = 0
            RectangularHull currentHull = (RectangularHull)parts[0];

            for (int i = 1; i < parts.Count; i++)
            {
                Part            currentPart = parts[i];
                RectangularHull carrier     = (RectangularHull)currentPart.Carrier;
                if (currentHull != carrier)
                {
                    activeBoxIndex = parts.IndexOf(carrier);
                    currentHull    = carrier;
                    AddEmptyParts(currentHull, shipItems[activeBoxIndex], false);
                }
                Vector2 itemPos = shipItems[activeBoxIndex].Position;
                Vector2 v       = LinkPosition(currentPart.LinkPosition, itemPos);

                ShipItem shipItem = CreateShipItem(currentPart, currentPart.LinkPosition, v, currentHull);
                shipItems.Add(i, shipItem);
            }
            RenewEmptyBoxes();
        }
 private void PlacePart(ShipItem pressedItem, RectangularHull hull, Part newPart)
 {
     Particles.GenerateDeathParticles(newPart.Sprite, pressedItem.Position, 2, 0, false);
     hull.AddPart(newPart, pressedItem.LinkPosition);
     player.Parts.Add(newPart);
     newPart.Carrier = hull; //REDUNDANCY
 }
Example #3
0
 public PowerSim(SimObject obj, PowerArchetype arch, ShipItem item)
 {
     Object   = obj;
     Item     = item;
     _arch    = arch;
     Capacity = _arch.Capacity;
 }
 /// <summary>
 ///     FLPACKET_SERVER_SETREMOVEITEM
 /// </summary>
 /// <param name="player"></param>
 /// <param name="item"></param>
 public static void SendRemoveItem(Player player, ShipItem item)
 {
     player.Log.AddLog(LogType.FL_MSG, "tx FLPACKET_SERVER_SETREMOVEITEM hpid={0}", item.hpid);
     byte[] omsg = { 0x2F, 0x02 };
     FLMsgType.AddUInt32(ref omsg, item.hpid);
     FLMsgType.AddUInt32(ref omsg, 0);
     FLMsgType.AddUInt32(ref omsg, 0);
     player.SendMsgToClient(omsg);
 }
Example #5
0
        private void Convert(ShipItem shipContainer, Dictionary <ulong, ItemBase> items)
        {
            if (items != null && items.Count != 0)
            {
                foreach (var item in items)
                {
                    ShipItem shipItem = new ShipItem();
                    shipItem.SetUID(item.Value.UID);
                    shipItem.SetTID(item.Value.TID);
                    shipItem.SetReference(item.Value.Reference);
                    shipItem.SetBaseConfig(item.Value.ItemConfig);
                    switch (item.Value.MainType)
                    {
                    case Category.Package:
                        shipItem.SetCurrentSizeMax((item.Value as ItemContainer).CurrentSizeMax);
                        shipContainer.AddContainer((item.Value as ItemContainer).ContainerType, shipItem);
                        Convert(shipItem, (item.Value as ItemContainer).Items);
                        break;

                    case Category.Weapon:
                        shipItem.SetLv((item.Value as ItemWeaponVO).Lv);
                        shipItem.SetItemPos(item.Value.Position);
                        shipContainer.AddItem(shipItem);
                        Convert(shipItem, (item.Value as ItemContainer).Items);
                        break;

                    case Category.EquipmentMod:
                        shipItem.SetLv((item.Value as ItemModVO).Lv);
                        shipItem.SetItemPos(item.Value.Position);
                        shipContainer.AddItem(shipItem);
                        break;

                    case Category.Equipment:
                        shipItem.SetLv((item.Value as ItemEquipmentVO).Lv);
                        shipItem.SetItemPos(item.Value.Position);
                        shipContainer.AddItem(shipItem);
                        break;

                    case Category.Reformer:
                        shipItem.SetLv((item.Value as ItemReformerVO).Lv);
                        shipContainer.AddItem(shipItem);
                        break;

                    default:
                        shipContainer.AddItem(shipItem);
                        break;
                    }

                    if (m_AllItem.ContainsKey(shipItem.GetUID()))
                    {
                        m_AllItem.Remove(shipItem.GetUID());
                    }
                    m_AllItem.Add(shipItem.GetUID(), shipItem);
                }
            }
        }
        public void Reset()
        {
            ShipItem motherBoard = shipItems[0];

            ((RectangularHull)motherBoard.Part).ResetLinks();
            shipItems = new Dictionary <int, ShipItem>();
            shipItems.Add(0, motherBoard);
            AddEmptyParts((RectangularHull)motherBoard.Part, shipItems[0], false);
            UpgradeBar.Reset();
            IsModified = false;
        }
Example #7
0
        public void UseItem(uint hpid)
        {
            //TODO: move healing of bats/bots to cfg?
            const float HIT_PTS_PER_BAT = 300;
            const float HIT_PTS_PER_BOT = 600;

            ShipItem item = player.Ship.FindByHpid(hpid);

            if (item == null)
            {
                return;
            }

            // Calculate the number of shield bats needed to fully recharge the shield and if possible
            // repair the shield and use the items.
            if (item.arch is ShieldBatteryArchetype && Shield != null && Shield.Health < 1.0f)
            {
                uint bats_needed = 1 + (uint)(((1.0f - Shield.Health) * Shield.Arch.MaxCapacity) / HIT_PTS_PER_BAT);
                if (bats_needed > item.count)
                {
                    bats_needed = item.count;
                }

                if (bats_needed > 0)
                {
                    Items[item.hpid].count -= bats_needed;
                    if (player != null)
                    {
                        Packets.SendUseItem(player, Objid, item.hpid, bats_needed);
                    }
                    RepairShield(bats_needed * HIT_PTS_PER_BAT);
                }
            }
            // Otherwise try to repair the hull
            else if (item.arch is RepairKitArchetype && Health < 1.0f)
            {
                uint bots_needed = 1 + (uint)(((1.0f - Health) * Arch.HitPts) / HIT_PTS_PER_BOT);
                if (bots_needed > item.count)
                {
                    bots_needed = item.count;
                }

                if (bots_needed > 0)
                {
                    Items[item.hpid].count -= bots_needed;
                    if (player != null)
                    {
                        Packets.SendUseItem(player, Objid, item.hpid, bots_needed);
                    }
                    RepairHull(bots_needed * HIT_PTS_PER_BOT);
                }
            }
        }
 private void FixLinkPosition(ShipItem fixItem)
 {
     for (int i = 0; i < 4; i++)
     {
         Vector2  v       = LinkPosition(i, new Vector2(fixItem.BoundBox.Left, fixItem.BoundBox.Top)); //dependablse [i] not removable
         ShipItem newHull = HullPresent(v);
         if (newHull != null && newHull.Part == fixItem.Hull)
         {
             fixItem.LinkPosition = (i + 2) % 4; //!!!!
         }
     }
 }
        //refactor buying out of this method
        private void AddPart(Part newPart)
        {
            if (newPart != null)
            {
                IsModified = true;
            }

            bool notEnoughMoney = false;  // only used to see if

            if (shipItems[activeSelection].id == IDs.RECTHULLPART)
            {
            }
            else if (activeSelection != 0)
            {
                ShipItem        pressedItem = shipItems[activeSelection];
                RectangularHull hull        = null;
                hull = pressedItem.Hull;
                // now redundant - graveyard functionality
                //if (pressedItem.id == IDs.RECTHULLPART)
                //{
                //    RemoveHull(pressedItem);
                //    FixLinkPosition(pressedItem); //!!!!!
                //}

                if (newPart == null)
                {
                    PlaceEmptyBox(pressedItem, hull);
                    UpgradeBar.SpentResource -= EntityConstants.PRICE[(int)pressedItem.id];
                }
                else
                {
                    float newPartPrice = EntityConstants.GetStatsFromID(EntityConstants.PRICE, EntityConstants.TypeToID(newPart.GetType()));
                    if (UpgradeBar.Resource >= newPartPrice)
                    {
                        PlacePart(pressedItem, hull, newPart);
                        UpgradeBar.SpentResource += newPartPrice;
                        UpgradeBar.SpentResource -= EntityConstants.PRICE[(int)pressedItem.id];
                    }
                    else
                    {
                        notEnoughMoney = true;
                    }
                }
                if (!notEnoughMoney)
                {
                    Vector2  v = pressedItem.Position;
                    ShipItem s = CreateShipItem(newPart, pressedItem.LinkPosition, v, (RectangularHull)hull);
                    shipItems[activeSelection] = s;
                    RenewEmptyBoxes();
                }
            }
        }
Example #10
0
#pragma warning restore 0649

    public override void SpawnList()
    {
        shipsPopup.infoText.gameObject.SetActive(false);
        foreach (ShipListItem listItem in listItems)
        {
            ShipListItem item  = listItem;
            GameObject   panel = pool.RequestAnObject();
            panel.transform.SetParent(contentPanel);

            ShipItem shipItem = panel.GetComponent <ShipItem>();
            shipItem.Init(item);
        }
    }
Example #11
0
        public void AddItem(ItemContainer item)
        {
            ShipItem shipItem = new ShipItem();

            shipItem.SetUID(item.UID);
            shipItem.SetTID(item.TID);
            shipItem.SetReference(item.Reference);
            switch (item)
            {
            case ItemWeaponVO val:
                shipItem.SetLv(val.Lv);
                shipItem.SetItemPos(val.Position);
                m_AllItem[item.ParentUID].AddItem(shipItem);
                break;

            case ItemReformerVO val:
                shipItem.SetLv(val.Lv);
                m_AllItem[item.ParentUID].AddItem(shipItem);
                break;

            case ItemEquipmentVO val:
                shipItem.SetLv(val.Lv);
                shipItem.SetItemPos(val.Position);
                m_AllItem[item.ParentUID].AddItem(shipItem);
                break;

            case ItemModVO val:
                shipItem.SetLv(val.Lv);
                shipItem.SetItemPos(val.Position);
                m_AllItem[item.ParentUID].AddItem(shipItem);
                break;

            case ItemSkillVO val:
                shipItem.SetItemPos(val.Position);
                m_AllItem[item.ParentUID].AddItem(shipItem);
                break;

            case ItemContainer val:
                shipItem.SetCurrentSizeMax(val.CurrentSizeMax);
                m_AllItem[item.ParentUID].AddContainer(val.ContainerType, shipItem);
                break;
            }
            shipItem.SetBaseConfig(item.ItemConfig);
            Convert(shipItem, item.Items);

            if (m_AllItem.ContainsKey(shipItem.GetUID()))
            {
                m_AllItem.Remove(shipItem.GetUID());
            }
            m_AllItem.Add(shipItem.GetUID(), shipItem);
        }
Example #12
0
            public ShipItemCollection(kcsapi_start2 initData, int beginNo, int endNo)
            {
                var list = new List <ShipItem>();

                initData.api_mst_ship.Where(x => x.api_sortno >= beginNo && x.api_sortno <= endNo).ToList()
                .ForEach(x =>
                {
                    var ship = new ShipItem(x);
                    initData.api_mst_ship.Where(y => y.api_id >= 900 && y.api_yomi == x.api_yomi).ToList()     // 查找节日立绘
                    .ForEach(y => ship.AddGraph(y.api_id));
                    list.Add(ship);
                });

                this.api_list = list.Count > 0 ? list.ToArray() : null;
            }
Example #13
0
 public override void RefreshList()
 {
     while (contentPanel.childCount > 0)
     {
         GameObject toRemove = transform.GetChild(0).gameObject;
         ShipItem   element  = toRemove.GetComponent <ShipItem>();
         if (element != null)
         {
             element.Remove();
         }
         pool.StoreInPool(toRemove);
     }
     if (listItems != null)
     {
         listItems.Clear();
     }
 }
Example #14
0
        public ShipVM(string shipId, ShipItemVM[] shipCargo)
        {
            ShipId = shipId;

            if (ShipItem == null)
            {
                ShipItem = new ObservableCollection <ShipItemVM>();
            }
            foreach (var cargo in shipCargo)
            {
                ShipItem.Add(cargo);
            }

            foreach (var ship in ShipItem)
            {
                sum += ship.Weight;
            }
            ;
        }
Example #15
0
        /// <summary>
        ///     Repair equipment by hpid if it exists
        /// </summary>
        /// <param name="hpid"></param>
        /// <param name="hit_pts"></param>
        public void RepairEquipment(uint hpid, float hit_pts)
        {
            if (hit_pts <= 0)
            {
                return;
            }

            // Repair equipment if we can find it.
            ShipItem item = FindByHpid(hpid);

            if (item != null && item.arch is EquipmentArchetype && item.health > 0)
            // fixme: change to external equipment
            {
                item.health += hit_pts / item.arch.HitPts;
                if (item.health > 1.0f)
                {
                    item.health = 1.0f;
                }
                Runner.NotifyOnSetHitPoints(Objid, item.hpid, item.health * item.arch.HitPts, false);
            }
        }
Example #16
0
        public CounterMeasure(DPGameRunner runner, Ship.Ship owner, CounterMeasureDropperArchetype gun_arch,
                              ShipItem launcher, uint hpid)
            : base(runner)
        {
            munition_arch = gun_arch.ProjectileArch as CounterMeasureArchetype;
            Arch          = munition_arch;

            Position    = owner.InterpolatedPosition();
            Position   += owner.Orientation * owner.Arch.Hardpoints[launcher.hpname.ToLowerInvariant()].Position;
            Orientation = Matrix.TurnAround(owner.Orientation);
            velocity    = Orientation * gun_arch.MuzzleVelocity + owner.EstimatedVelocity;
            owner_objid = owner.Objid;
            this.hpid   = hpid;

            lifetime        = munition_arch.Lifetime;
            owner_safe_time = munition_arch.OwnerSafeTime;

            Throttle = 1; // (float)(this.velocity.Length() / this.max_speed);

            angular_velocity = new Vector(rand.NextDouble() * 10 - 5, rand.NextDouble() * 10 - 5, rand.NextDouble() * 10 - 5);
        }
 private void AddEmptyParts(RectangularHull hull, ShipItem current, bool inMenu)
 {
     bool[] taken = hull.TakenPositions;
     for (int j = 0; j < taken.Length; j++)
     {
         if (!taken[j])
         {
             if (inMenu)
             {
                 Vector2 v = LinkPosition(j, current.Position);
                 if (PositionIsFree(v))
                 {
                     shipItems.Add(emptyPartIndex++, new ShipItem(new Vector2(v.X, v.Y), j, hull, null, IDs.EMPTYPART)); //secondary constructor for empty parts /!!! null
                 }
             }
             else
             {
                 Vector2 v = LinkPosition(j, current.Position);
                 shipItems.Add(emptyPartIndex++, new ShipItem(new Vector2(v.X, v.Y), j, hull, null, IDs.EMPTYPART)); //secondary constructor for empty parts /!!! null
             }
         }
     }
 }
Example #18
0
        public Missile(DPGameRunner runner, Ship.Ship owner, GunArchetype gun_arch, ShipItem launcher, Vector target_position,
                       uint hpid)
            : base(runner)
        {
            munition_arch = gun_arch.ProjectileArch as MunitionArchetype;
            Arch          = munition_arch;

            Position        = owner.InterpolatedPosition();
            Position       += owner.Orientation * owner.Arch.Hardpoints[launcher.hpname.ToLowerInvariant()].Position;
            Orientation     = Matrix.CreateLookAt(Position, target_position);
            velocity        = Orientation * gun_arch.MuzzleVelocity + owner.EstimatedVelocity;
            owner_objid     = owner.Objid;
            target_objid    = owner.TargetObjID;
            target_subobjid = owner.target_subobjid;
            this.hpid       = hpid;

            lifetime = munition_arch.Lifetime;

            motor_accel        = munition_arch.MotorArch.Accel;
            motor_lifetime_max = motor_lifetime = munition_arch.MotorArch.Lifetime;
            motor_delay        = munition_arch.MotorArch.Delay;

            seek = (munition_arch.Seeker.ToUpper() == "LOCK") && (target_objid != 0);
            if (seek)
            {
                seeker_fov   = munition_arch.SeekerFovDeg * Math.PI / 180;
                seeker_range = munition_arch.SeekerRange;

                time_to_lock         = munition_arch.TimeToLock;
                max_angular_velocity = munition_arch.MaxAngularVelocity * Math.PI / 180;
            }

            max_speed = velocity.Length() + motor_accel * motor_lifetime_max;

            Throttle = 1; // (float)(this.velocity.Length() / this.max_speed);
        }
Example #19
0
    public void Start()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        if (this != Instance)
        {
            Destroy(this.gameObject);
        }
        orbitCenter = new Vector3(0, 0, 0);

        ShipItems          = new List <ShipItem>();
        ShipItemsCatalogue = new List <ShipItem>(ShipItemsCatalogueSerializable.shipItemList);
        InventoryItems     = new List <KeyValuePair <InventoryItem, ItemType> >();
        //Add all the zero cost default items from the catalogue to the ship, and add them to the ship
        for (int i = ShipItemsCatalogue.Count - 1; i >= 0; i--)
        {
            ShipItem shipItem = ShipItemsCatalogue[i];
            if (shipItem.price == 0)
            {
                ShipItems.Add(shipItem);
                ShipItemsCatalogue.RemoveAt(i);
            }
        }
        //Initialize the stats of the ship based on the assigned parts.
        foreach (ShipItem shipItem in ShipItems)
        {
            ShipItemSize    += shipItem.size;
            FuelMax         += shipItem.fuelCapacityBonus;
            FuelConsumption += shipItem.fuelConsumptionRate;
            Speed           += shipItem.speedBonus;
        }
        Fuel = FuelMax;
        transform.position += new Vector3(orbitRadius, 0, 0);
    }
 private bool RotatePart(ShipItem current)
 {
     if (current.id.Equals(IDs.RECTHULLPART) || current.id.Equals(IDs.EMPTYPART))
     {
         return(false);
     }
     for (int i = 0; i < 4; i++)
     {
         int      newPos = (current.LinkPosition + i) % 4;
         Vector2  v      = LinkPosition(newPos, new Vector2(current.BoundBox.Left, current.BoundBox.Top));
         ShipItem s      = HullPresent(v);
         if (s != null && current.Hull != s.Part)     //&& current.id !=IDs.EMPTYPART) ///current?
         {
             ((RectangularHull)s.Part).AddPart(current.Part, (newPos + 2) % 4);
             current.Hull.RemovePart(current.Part);     //restore hull ????????!!!!!!!!!!!!!!!!!!!!!!!! in parts also, not only shipItem
             //((RectangularHull)removable.Part).Carrier = removable.Hull; //ALSO WHEN ADDPART?
             current.Hull         = (RectangularHull)s.Part;
             current.LinkPosition = newPos;
             current.UpdateRotation();
             return(true);
         }
     }
     return(false);
 }
Example #21
0
 public ShipCtxControl_AI(ShipItem ship)
     : base(ship.gameObject, uniqueSubmenusReqd: Constants.Zero, menuPosition: MenuPositionMode.Offset) {
     _shipMenuOperator = ship;
 }
Example #22
0
 /// <summary>
 /// Removes the 'fleet is now aligned' callback a ship may have requested by providing the ship's
 /// delegate that registered the callback. Returns <c>true</c> if the callback was removed, <c>false</c> otherwise.
 /// </summary>
 /// <param name="shipCallbackDelegate">The callback delegate from the ship. Can be null.</param>
 /// <param name="ship">The ship.</param>
 internal void RemoveFleetIsAlignedCallback(Action shipCallbackDelegate, ShipItem ship) {
     D.AssertNotNull(shipCallbackDelegate);
     _navigator.RemoveFleetIsAlignedCallback(shipCallbackDelegate, ship);
 }
Example #23
0
    void AssumingFormation_UponOrderOutcome(ShipDirective directive, ShipItem ship, bool isSuccess, IShipNavigable target, UnitItemOrderFailureCause failCause) {
        LogEvent();
        if (directive != ShipDirective.AssumeStation) {
            D.Warn("{0} State {1} erroneously received OrderOutcome callback with {2} {3}.", DebugName, CurrentState.GetValueName(), typeof(ShipDirective).Name, directive.GetValueName());
            return;
        }

        D.AssertNull(target);
        if (isSuccess) {
            _fsmShipWaitForOnStationCount--;
        }
        else {
            switch (failCause) {
                case UnitItemOrderFailureCause.UnitItemNeedsRepair:
                    // Ship will get repaired, but even if it goes to its formationStation to do so
                    // it won't communicate its success back to Cmd since Captain ordered it, not Cmd
                    _fsmShipWaitForOnStationCount--;
                    break;
                case UnitItemOrderFailureCause.UnitItemDeath:
                    _fsmShipWaitForOnStationCount--;
                    break;
                case UnitItemOrderFailureCause.TgtDeath:
                case UnitItemOrderFailureCause.TgtRelationship:
                case UnitItemOrderFailureCause.TgtUncatchable:
                case UnitItemOrderFailureCause.TgtUnreachable:
                case UnitItemOrderFailureCause.None:
                default:
                    throw new NotImplementedException(ErrorMessages.UnanticipatedSwitchValue.Inject(failCause));
            }
        }
        if (_fsmShipWaitForOnStationCount == Constants.Zero) {
            Return();
        }
    }
Example #24
0
 private void OnFleetElementDestroyed(ShipItem ship) {
     if (ship.gameObject.GetSafeInterface<ICameraFocusable>().IsFocus) {
         // our fleet's ship that was just destroyed was the focus, so change the focus to the fleet
         (View as ICameraFocusable).IsFocus = true;
     }
 }
Example #25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShipHelm" /> class.
        /// </summary>
        /// <param name="ship">The ship.</param>
        /// <param name="shipRigidbody">The ship rigidbody.</param>
        internal ShipHelm(ShipItem ship, Rigidbody shipRigidbody) {
            ApCourse = new List<IShipNavigable>();
            //_gameMgr = GameManager.Instance;
            _gameTime = GameTime.Instance;
            _jobMgr = JobManager.Instance;

            _ship = ship;
            _shipData = ship.Data;
            _engineRoom = new EngineRoom(ship, shipRigidbody);
            Subscribe();
        }
        /// <summary>
        ///     Load the specified character file, resetting all character specific
        ///     content for this player and notifying all players of the name.
        /// </summary>
        /// <param name="account">Player account</param>
        /// <param name="log"></param>
        /// <returns>Returns null on successful load otherwise returns error message as a string.</returns>
        public string LoadCharFile(Account account, ILogController log)
        {
            if (account == null)
            {
                log.AddLog(LogType.ERROR, "Broken account found!");
                return("Account is null!");
            }
            //null checks made earlier
            // ReSharper disable once PossibleInvalidOperationException
            PlayerAccount = account;
            Wgrp          = new WeaponGroup();

// ReSharper disable once PossibleNullReferenceException
            Name  = PlayerAccount.CharName;
            Money = PlayerAccount.Money;

            var arch = ArchetypeDB.Find(PlayerAccount.Ship);

            if (arch is ShipArchetype)
            {
                Ship.Arch = arch;
            }
            else
            {
                return("invalid ship");
            }

            if (ShipState.RepGroup == "")
            {
                Ship.faction = new Faction();
            }
            else
            {
                Ship.faction = UniverseDB.FindFaction(ShipState.RepGroup);
                if (Ship.faction == null)
                {
                    return("invalid faction");
                }
            }

            Ship.System = UniverseDB.FindSystem(PlayerAccount.System);
            if (Ship.System == null)
            {
                return("invalid system");
            }

            if (ShipState.Base == null)
            {
                Ship.Basedata = null;
            }
            else
            {
                Ship.Basedata = UniverseDB.FindBase(ShipState.Base);
                if (Ship.Basedata == null)
                {
                    return("invalid base");
                }
            }

            if (ShipState.LastBase == "")
            {
                Ship.RespawnBasedata = null;
                return("no respawn base");
            }

            Ship.RespawnBasedata = UniverseDB.FindBase(ShipState.LastBase);
            if (Ship.RespawnBasedata == null)
            {
                return("invalid respawn base");
            }



            if (Ship.Basedata == null)
            {
                if (ShipState.Position != null)
                {
                    Ship.Position = ShipState.Position;
                }

                if (ShipState.Rotate != null)
                {
                    Ship.Orientation = Matrix.EulerDegToMatrix(ShipState.Rotate);
                }
            }

            //TODO: why ShipState.Hull is always true
            Ship.Health = ShipState.Hull;
            if (Ship.Health <= 0)
            {
                Ship.Health = 0.05f;
            }

            Ship.voiceid = FLUtility.CreateID(Appearance.Voice);

            //TODO: calculate rank
// ReSharper disable once PossibleNullReferenceException
            Ship.Rank = PlayerAccount.Rank;

            Ship.com_body      = Appearance.Body;
            Ship.com_head      = Appearance.Head;
            Ship.com_lefthand  = Appearance.LeftHand;
            Ship.com_righthand = Appearance.RightHand;

            Ship.Items.Clear();

            uint hpid = 34;

            foreach (var set in Equipment)
            {
                var si = new ShipItem
                {
                    arch    = ArchetypeDB.Find(set.Arch),
                    hpname  = set.HpName,
                    health  = set.Health,
                    count   = 1,
                    mission = false,
                    mounted = true,
                    hpid    = hpid++
                };
                Ship.Items[si.hpid] = si;
            }

            foreach (var set in Cargo)
            {
                var si = new ShipItem
                {
                    arch    = ArchetypeDB.Find(set.Arch),
                    hpname  = "",
                    count   = set.Count,
                    health  = 1.0f,
                    mission = false,
                    mounted = false,
                    hpid    = hpid++
                };
                Ship.Items[si.hpid] = si;
            }

            Ship.Reps.Clear();


            foreach (var set in RepDictionary)
            {
                float rep     = set.Value;
                var   faction = UniverseDB.FindFaction(set.Key);
                if (faction == null)
                {
// ReSharper disable once PossibleNullReferenceException
                    log.AddLog(LogType.ERROR, "error: faction not found char={0} faction={1}", account.CharName,
                               set.Value);
                }
                else
                {
                    Ship.Reps[faction] = rep;
                }
            }


            //Visits.Clear();
            //foreach (var set in Visits)
            //{
            //    Visits[set.Key] = set.Value;
            //}

            Ship.CurrentAction = null;

            return(null);
        }
Example #27
0
 private bool RequestFormationStationChange(ShipItem ship, AFormationManager.FormationStationSelectionCriteria stationSelectionCriteria, ref int iterateCount) {
     if (FormationMgr.IsSlotAvailable(stationSelectionCriteria)) {
         //D.Log(ShowDebugLog, "{0} request for formation station change has been approved.", ship.DebugName);
         FormationMgr.AddAndPositionNonHQElement(ship, stationSelectionCriteria);
         return true;
     }
     iterateCount++;
     return false;
 }
Example #28
0
 /// <summary>
 /// Removes the 'fleet is now aligned' callback a ship may have requested by providing the ship's
 /// delegate that registered the callback. Returns <c>true</c> if the callback was removed, <c>false</c> otherwise.
 /// </summary>
 /// <param name="shipCallbackDelegate">The callback delegate from the ship. Can be null.</param>
 /// <param name="shipName">Name of the ship for debugging.</param>
 /// <returns></returns>
 internal void RemoveFleetIsAlignedCallback(Action shipCallbackDelegate, ShipItem ship) {
     D.AssertNotNull(_fleetIsAlignedCallbacks); // method only called if ship knows it has an active callback -> not null
     D.AssertNotNull(_waitForFleetToAlignJob);
     D.Assert(_fleetIsAlignedCallbacks.GetInvocationList().Contains(shipCallbackDelegate));
     _fleetIsAlignedCallbacks = Delegate.Remove(_fleetIsAlignedCallbacks, shipCallbackDelegate) as Action;
     bool isShipRemoved = _shipsWaitingForFleetAlignment.Remove(ship);
     D.Assert(isShipRemoved);
     if (_fleetIsAlignedCallbacks == null) {
         // delegate invocation list is now empty
         KillWaitForFleetToAlignJob();
     }
 }
Example #29
0
 private void TransferShip(ShipItem ship, FleetCmdItem fleetToJoin) {
     // UNCLEAR does this ship need to be in ShipState.None while these changes take place?
     RemoveElement(ship);
     ship.IsHQ = false; // Needed - RemoveElement never changes HQ Element as the TransferCmd is dead as soon as ship removed
     fleetToJoin.AddElement(ship);
 }
Example #30
0
 /// <summary>
 /// Handles the situation where the provided ship has either successfully explored the
 /// provided target in the system, or the exploration of the target failed because the
 /// target is dead. Returns <c>true</c> if a new exploration target was assigned to the
 /// ship, <c>false</c> otherwise. If the ship received no new assignment, it has been
 /// instructed to gather at a nearby assembly station.
 /// </summary>
 /// <param name="ship">The ship.</param>
 /// <param name="exploreTgt">The explore TGT.</param>
 /// <returns></returns>
 private bool HandleSystemTargetExploredOrDead(ShipItem ship, IShipExplorable exploreTgt) {
     _shipSystemExploreTgtAssignments.Remove(exploreTgt);
     bool isNowAssigned = AssignShipToExploreSystemTgt(ship);
     if (!isNowAssigned) {
         if (ship.IsHQ) {
             // no point in telling HQ to assume station, but with no more explore assignment, it should
             // return to the closest Assembly station so the other ships assume station there
             IFleetExplorable fleetExploreTgt = CurrentOrder.Target as IFleetExplorable;
             var closestLocalAssyStation = GameUtility.GetClosest(Position, fleetExploreTgt.LocalAssemblyStations);
             var speed = Speed.Standard;
             float standoffDistance = Constants.ZeroF;   // AssyStation can't be owned by anyone
             bool isFleetwideMove = false;
             ship.CurrentOrder = new ShipMoveOrder(OrderSource.CmdStaff, closestLocalAssyStation, speed, isFleetwideMove, standoffDistance);
         }
         else {
             ShipOrder assumeStationOrder = new ShipOrder(ShipDirective.AssumeStation, OrderSource.CmdStaff);
             ship.CurrentOrder = assumeStationOrder;
         }
     }
     return isNowAssigned;
 }
Example #31
0
 /// <summary>
 /// Handles the results of the ship's attempt to execute the provided directive.
 /// </summary>
 /// <param name="directive">The directive.</param>
 /// <param name="ship">The ship.</param>
 /// <param name="isSuccess">if set to <c>true</c> the directive was successfully completed. May still be ongoing.</param>
 /// <param name="target">The target. Can be null.</param>
 /// <param name="failCause">The failure cause if not successful.</param>
 internal void HandleOrderOutcome(ShipDirective directive, ShipItem ship, bool isSuccess, IShipNavigable target = null, UnitItemOrderFailureCause failCause = UnitItemOrderFailureCause.None) {
     UponOrderOutcome(directive, ship, isSuccess, target, failCause);
 }
Example #32
0
 /// <summary>
 /// Assigns the ship to explore any remaining unexplored targets in the System
 /// that don't already have an assigned ship. Returns <c>true</c> if the ship
 /// was assigned, <c>false</c> if not which means all unexplored remaining targets
 /// in the system, if any, have assigned ships.
 /// </summary>
 /// <param name="ship">The ship.</param>
 /// <returns></returns>
 private bool AssignShipToExploreSystemTgt(ShipItem ship) {
     D.Assert(!_shipSystemExploreTgtAssignments.Values.Contains(ship));
     var tgtsWithoutAssignedShip = _shipSystemExploreTgtAssignments.Where(kvp => kvp.Value == null).Select(kvp => kvp.Key);
     if (tgtsWithoutAssignedShip.Any()) {
         var closestExploreTgt = tgtsWithoutAssignedShip.MinBy(tgt => Vector3.SqrMagnitude(tgt.Position - ship.Position));
         if (closestExploreTgt.IsFullyExploredBy(Owner)) {
             // in interim, target could have been fully explored by another fleet's ship of ours
             return HandleSystemTargetExploredOrDead(ship, closestExploreTgt);
         }
         AssignShipToExploreItem(ship, closestExploreTgt);
         _shipSystemExploreTgtAssignments[closestExploreTgt] = ship;
         return true;
     }
     return false;
 }
Example #33
0
 private void UponOrderOutcome(ShipDirective directive, ShipItem ship, bool isSuccess, IShipNavigable target = null, UnitItemOrderFailureCause failCause = UnitItemOrderFailureCause.None) {
     RelayToCurrentState(directive, ship, isSuccess, target, failCause);
 }
Example #34
0
 void ExecuteAttackOrder_UponOrderOutcome(ShipDirective directive, ShipItem ship, bool isSuccess, IShipNavigable target, UnitItemOrderFailureCause failCause) {
     LogEvent();
     if (directive != ShipDirective.Attack) {
         D.Warn("{0} State {1} erroneously received OrderOutcome callback with {2} {3}.", DebugName, CurrentState.GetValueName(), typeof(ShipDirective).Name, directive.GetValueName());
         return;
     }
     // TODO keep track of results to make better resulting decisions about what to do as battle rages
     // IShipAttackable attackedTgt = target as IShipAttackable;    // target can be null if ship failed and didn't have a target: Disengaged...
 }
Example #35
0
 /// <summary>
 /// Called when this menu is right clicked while an Item is selected, returns <c>true</c> if the Item selected is a user-owned, remote ship.
 /// Default implementation is to return false. Derived classes should override this behaviour to enable the type of access their menu supports.
 /// </summary>
 /// <param name="selected">The Item currently selected.</param>
 /// <param name="selectedShip">The user-owned, selected ship.</param>
 /// <returns></returns>
 protected virtual bool TryIsSelectedItemUserRemoteShip(ISelectable selected, out ShipItem selectedShip) {
     selectedShip = null;
     return false;
 }
Example #36
0
 private ShipCategory GetShipHull(ShipItem ship) {
     return Enums<ShipCategory>.Parse(ship.gameObject.name);
 }
Example #37
0
 private ShipCategory DeriveCategory(ShipItem element) {
     return Enums<ShipCategory>.Parse(element.gameObject.name);
 }
Example #38
0
 /// <summary>
 /// Requests a change in the ship's formation station assignment based on the stationSelectionCriteria provided.
 /// Returns <c>true</c> if the ship's formation station assignment was changed, <c>false</c> otherwise.
 /// </summary>
 /// <param name="ship">The ship.</param>
 /// <param name="stationSelectionCriteria">The station selection criteria.</param>
 /// <returns></returns>
 public bool RequestFormationStationChange(ShipItem ship, AFormationManager.FormationStationSelectionCriteria stationSelectionCriteria) {
     int iterateCount = Constants.Zero;
     while (iterateCount < 3) {
         if (RequestFormationStationChange(ship, stationSelectionCriteria, ref iterateCount)) {
             return true;
         }
         // TODO modify stationSelectionCriteria here to search for criteria that fits an available slot
     }
     return false;
 }
Example #39
0
 /// <summary>
 /// Waits for the ships in the fleet to align with the requested heading, then executes the provided callback.
 /// <remarks>
 /// Called by each of the ships in the fleet when they are preparing for collective departure to a destination
 /// ordered by FleetCmd. This single coroutine replaces a similar coroutine previously run by each ship.
 /// </remarks>
 /// </summary>
 /// <param name="fleetIsAlignedCallback">The fleet is aligned callback.</param>
 /// <param name="ship">The ship.</param>
 internal void WaitForFleetToAlign(Action fleetIsAlignedCallback, ShipItem ship) {
     //D.Log(ShowDebugLog, "{0} adding ship {1} to list waiting for fleet to align.", DebugName, ship.Name);
     if (__waitForFleetToAlignJobIsExecuting) {
         D.Error("{0}: Attempt to add {1} during WaitForFleetToAlign Job execution.", DebugName, ship.DebugName);
     }
     _fleetIsAlignedCallbacks += fleetIsAlignedCallback;
     bool isAdded = _shipsWaitingForFleetAlignment.Add(ship);
     D.Assert(isAdded, ship.DebugName);
     if (_waitForFleetToAlignJob == null) {
         string jobName = "{0}.WaitForFleetToAlignJob".Inject(DebugName);
         _waitForFleetToAlignJob = _jobMgr.StartGameplayJob(WaitWhileShipsAlignToRequestedHeading(), jobName, isPausable: true, jobCompleted: (jobWasKilled) => {
             __waitForFleetToAlignJobIsExecuting = false;
             if (jobWasKilled) {
                 // 12.12.16 An AssertNull(_jobRef) here can fail as the reference can refer to a new Job, created 
                 // right after the old one was killed due to the 1 frame delay in execution of jobCompleted(). My attempts at allowing
                 // the AssertNull to occur failed. I believe this is OK as _jobRef is nulled from KillXXXJob() and, if 
                 // the reference is replaced by a new Job, then the old Job is no longer referenced which is the objective. Jobs Kill()ed
                 // centrally by JobManager won't null the reference, but this only occurs during scene transitions.
                 if (_gameMgr.IsRunning) {    // When launching new game from existing game JobManager kills most jobs
                     D.AssertNull(_fleetIsAlignedCallbacks);  // only killed when all waiting delegates from ships removed
                     D.AssertEqual(Constants.Zero, _shipsWaitingForFleetAlignment.Count);
                 }
             }
             else {
                 _waitForFleetToAlignJob = null;
                 D.AssertNotNull(_fleetIsAlignedCallbacks);  // completed normally so there must be a ship to notify
                 D.Assert(_shipsWaitingForFleetAlignment.Count > Constants.Zero);
                 //D.Log(ShowDebugLog, "{0} is now aligned and ready for departure.", _fleet.DebugName);
                 _fleetIsAlignedCallbacks();
                 _fleetIsAlignedCallbacks = null;
                 _shipsWaitingForFleetAlignment.Clear();
             }
         });
     }
 }
Example #40
0
        public ShipData AddNewSOShip(Vector3 position, Quaternion rotation, int item_id)
        {
            SpaceObject SO = AddNewSO(position, rotation, item_id);
            ShipData    retSOShipData;

            if (SO.Type == TypeSO.ship)
            {
                ShipItem _shipItem = serverManager.inventoryServer.GetShipItem(item_id);

                string qwery = @"insert into SO_shipdata (
                   SO_id,
                   max_speed,
                   rotation_speed,
                   acceleration_max,
                   newSpeed,
                   hull_full,
                   armor_full,
                   shield_full,
                   capasitor_full,
                   hull,
                   armor,
                   shield,
                   capasitor,
                   hull_restore,
                   armor_restore,
                   shield_restore,
                   capasitor_restore,
                   agr_distance,
                   vision_distance,
                   mob,
                   warpDriveStartTime,
                   warpSpeed" +
                               ") values (" +
                               SO.Id.ToString() + ", " +
                               _shipItem.max_speed.ToString() + ", " +
                               _shipItem.rotation_speed.ToString() + ", " +
                               _shipItem.acceleration_max.ToString() + ", " +
                               _shipItem.newSpeed.ToString() + ", " +
                               _shipItem.hull_full.ToString() + ", " +
                               _shipItem.armor_full.ToString() + ", " +
                               _shipItem.shield_full.ToString() + ", " +
                               _shipItem.capasitor_full.ToString() + ", " +
                               _shipItem.hull.ToString() + ", " +
                               _shipItem.armor.ToString() + ", " +
                               _shipItem.shield.ToString() + ", " +
                               _shipItem.capasitor.ToString() + ", " +
                               _shipItem.hull_restore.ToString() + ", " +
                               _shipItem.armor_restore.ToString() + ", " +
                               _shipItem.shield_restore.ToString() + ", " +
                               _shipItem.capasitor_restore.ToString() + ", " +
                               _shipItem.agr_distance.ToString() + ", " +
                               _shipItem.vision_distance.ToString() + ", " +
                               _shipItem.mob.ToString() + ", " +
                               _shipItem.warpDriveStartTime.ToString() + ", " +
                               _shipItem.warpSpeed.ToString() + ")";

                GetReader(qwery);
            }
            retSOShipData = GetSOShipData(SO.Id);
            return(retSOShipData);
        }
Example #41
0
    /// <summary>
    /// Handles the condition where a ship is no longer available to explore. Returns <c>true</c>
    /// if another ship was assigned to replace this one (not necessarily with the same explore target),
    /// <c>false</c> if no more ships are currently available.
    /// <remarks>Typically this occurs when a ship fails to complete its assigned exploration mission
    /// either because it dies or is so wounded that it needs to repair.</remarks>
    /// </summary>
    /// <param name="unavailableShip">The unavailable ship.</param>
    /// <param name="exploreTgt">The explore target.</param>
    /// <returns></returns>
    private bool HandleShipNoLongerAvailableToExplore(ShipItem unavailableShip, IShipExplorable exploreTgt) {
        bool isExploringSystem = false;
        if (_shipSystemExploreTgtAssignments.ContainsKey(exploreTgt)) {
            isExploringSystem = true;
            if (_shipSystemExploreTgtAssignments.Values.Contains(unavailableShip)) {
                // ship had explore assignment in system so remove it
                var deadShipTgt = _shipSystemExploreTgtAssignments.Single(kvp => kvp.Value == unavailableShip).Key;
                _shipSystemExploreTgtAssignments[deadShipTgt] = null;
            }
        }

        bool isNewShipAssigned;
        IList<ShipItem> ships;
        if (TryGetShips(out ships, availableOnly: true, avoidHQ: true, qty: 1, priorityCats: _desiredExplorationShipCategories)) {
            ShipItem newExploreShip = ships.First();
            if (isExploringSystem) {
                AssignShipToExploreSystemTgt(newExploreShip);
            }
            else {
                AssignShipToExploreItem(newExploreShip, exploreTgt);
            }
            isNewShipAssigned = true;
        }
        else {
            isNewShipAssigned = false;
            D.Warn("{0} found no available ships to explore {1} after {2} became unavailable.", DebugName, exploreTgt.DebugName, unavailableShip.DebugName);
        }
        return isNewShipAssigned;
    }
Example #42
0
 public EngineRoom(ShipItem ship, Rigidbody shipRigidbody) {
     _ship = ship;
     _shipData = ship.Data;
     _shipTransform = ship.transform;
     _shipRigidbody = shipRigidbody;
     _gameMgr = GameManager.Instance;
     _gameTime = GameTime.Instance;
     _jobMgr = JobManager.Instance;
     _driftCorrector = new DriftCorrector(ship.transform, shipRigidbody, DebugName);
     Subscribe();
 }
Example #43
0
        private static void LoadLoadout(string path, ILogController log)
        {
            var ini = new FLDataFile(path, true);

            foreach (FLDataFile.Section sec in ini.Sections)
            {
                string sectionName = sec.SectionName.ToLowerInvariant();
                if (sectionName == "loadout")
                {
                    var  loadout = new Loadout();
                    uint hpid    = 34;
                    foreach (FLDataFile.Setting set in sec.Settings)
                    {
                        if (set.SettingName == "nickname")
                        {
                            loadout.Nickname  = set.Str(0);
                            loadout.LoadoutID = FLUtility.CreateID(loadout.Nickname);
                        }
                        else if (set.SettingName == "equip")
                        {
                            var item = new ShipItem {
                                arch = ArchetypeDB.Find(FLUtility.CreateID(set.Str(0)))
                            };
                            if (item.arch == null)
                            {
                                continue; // TODO: log
                            }
                            item.hpname = "";
                            if (set.NumValues() > 1)
                            {
                                item.hpname = set.Str(1);
                            }
                            item.health  = 1.0f;
                            item.mission = false;
                            item.mounted = true;
                            item.count   = 1;
                            item.hpid    = hpid++;
                            loadout.Items.Add(item);
                        }
                        else if (set.SettingName == "cargo")
                        {
                            var item = new ShipItem {
                                arch = ArchetypeDB.Find(FLUtility.CreateID(set.Str(0)))
                            };
                            if (item.arch == null)
                            {
                                continue; // TODO: log
                            }
                            item.hpname  = "";
                            item.health  = 1.0f;
                            item.mission = false;
                            item.mounted = false;
                            item.count   = set.UInt(1);
                            item.hpid    = hpid++;
                            loadout.Items.Add(item);
                        }
                    }
                    Loadouts[loadout.LoadoutID] = loadout;
                }
            }
        }
Example #44
0
 public ShipCtxControl_AI(ShipItem ship)
     : base(ship.gameObject) {
     _shipMenuOperator = ship;
 }
Example #45
0
 internal void HandleHQElementChanging(ShipItem oldHQElement, ShipItem newHQElement) {
     if (oldHQElement != null) {
         oldHQElement.apTgtReached -= FlagshipReachedDestinationEventHandler;
     }
     if (_apNavJob != null) {   // if not engaged, this connection will be established when next engaged
         newHQElement.apTgtReached += FlagshipReachedDestinationEventHandler;
     }
 }
Example #46
0
 public void AddItem(ShipItem value)
 {
     m_Items.Add(value);
 }
Example #47
0
            public ShipItemCollection(kcsapi_start2 initData, int beginNo, int endNo)
            {
                var list = new List<ShipItem>();
                initData.api_mst_ship.Where(x => x.api_sortno >= beginNo && x.api_sortno <= endNo).ToList()
                    .ForEach(x =>
                    {
                        var ship = new ShipItem(x);
                        initData.api_mst_ship.Where(y => y.api_id >= 900 && y.api_yomi == x.api_yomi).ToList() // 查找节日立绘
                            .ForEach(y => ship.AddGraph(y.api_id));
                        list.Add(ship);
                    });

                this.api_list = list.Count > 0 ? list.ToArray() : null;
            }
Example #48
0
 public bool RequestPermissionToWithdraw(ShipItem ship, ShipItem.WithdrawPurpose purpose) {
     return true;    // TODO false if fight to the death...
 }
Example #49
0
    void ExecuteExploreOrder_UponOrderOutcome(ShipDirective directive, ShipItem ship, bool isSuccess, IShipNavigable target,
        UnitItemOrderFailureCause failCause) {
        LogEvent();
        if (directive != ShipDirective.Explore) {
            D.Warn("{0} State {1} erroneously received OrderOutcome callback with {2} {3}.", DebugName, CurrentState.GetValueName(), typeof(ShipDirective).Name, directive.GetValueName());
            return;
        }

        IShipExplorable shipExploreTgt = target as IShipExplorable;
        D.AssertNotNull(shipExploreTgt);

        bool issueFleetRecall = false;
        if (IsShipExploreTargetPartOfSystem(shipExploreTgt)) {
            // exploreTgt is a planet or star
            D.Assert(_shipSystemExploreTgtAssignments.ContainsKey(shipExploreTgt));
            if (isSuccess) {
                HandleSystemTargetExploredOrDead(ship, shipExploreTgt);
            }
            else {
                bool isNewShipAssigned;
                bool testForAdditionalExploringShips = false;
                switch (failCause) {
                    case UnitItemOrderFailureCause.TgtRelationship:
                        // exploration failed so recall all ships
                        issueFleetRecall = true;
                        break;
                    case UnitItemOrderFailureCause.TgtDeath:
                        HandleSystemTargetExploredOrDead(ship, shipExploreTgt);
                        // This is effectively counted as a success and will show up during the _EnterState's
                        // continuous test System.IsFullyExplored. As not really a failure, no reason to issue a fleet recall.
                        break;
                    case UnitItemOrderFailureCause.UnitItemNeedsRepair:
                        isNewShipAssigned = HandleShipNoLongerAvailableToExplore(ship, shipExploreTgt);
                        if (!isNewShipAssigned) {
                            if (Elements.Count > 1) {
                                // This is not the last ship in the fleet, but the others aren't available. Since it usually takes 
                                // more than one ship to explore a System, the other ships might currently be exploring
                                testForAdditionalExploringShips = true;
                            }
                            else {
                                D.AssertEqual(Constants.One, Elements.Count);
                                // Damaged ship is only one left in fleet and it can't explore so exploration failed
                                issueFleetRecall = true;
                            }
                        }
                        break;
                    case UnitItemOrderFailureCause.UnitItemDeath:
                        isNewShipAssigned = HandleShipNoLongerAvailableToExplore(ship, shipExploreTgt);
                        if (!isNewShipAssigned) {
                            if (Elements.Count > 1) {    // >1 as dead ship has not yet been removed from fleet
                                                         // This is not the last ship in the fleet, but the others aren't available. Since it usually takes 
                                                         // more than one ship to explore a System, the other ships might currently be exploring
                                testForAdditionalExploringShips = true;
                            }
                            else {
                                D.AssertEqual(Constants.One, Elements.Count);  // dead ship has not yet been removed from fleet
                                // Do nothing as Unit is about to die
                            }
                        }
                        break;
                    case UnitItemOrderFailureCause.TgtUncatchable:
                    case UnitItemOrderFailureCause.TgtUnreachable:
                    case UnitItemOrderFailureCause.None:
                    default:
                        throw new NotImplementedException(ErrorMessages.UnanticipatedSwitchValue.Inject(failCause));
                }

                if (testForAdditionalExploringShips) {
                    var otherShipsCurrentlyExploring = Elements.Cast<ShipItem>().Except(ship).Where(s => s.IsCurrentOrderDirectiveAnyOf(ShipDirective.Explore));
                    if (otherShipsCurrentlyExploring.Any()) {
                        // Do nothing as there are other ships currently exploring so exploreTarget will eventually be assigned a ship
                    }
                    else {
                        // There are no remaining ships out exploring -> the exploration attempt has failed so issue recall
                        issueFleetRecall = true;
                    }
                }
            }
        }
        else {
            // exploreTgt is UCenter
            D.Assert(shipExploreTgt is UniverseCenterItem);
            if (isSuccess) {
                // exploration of UCenter has successfully completed so issue fleet recall
                issueFleetRecall = true;
            }
            else {
                bool isNewShipAssigned;
                switch (failCause) {
                    case UnitItemOrderFailureCause.UnitItemNeedsRepair:
                        isNewShipAssigned = HandleShipNoLongerAvailableToExplore(ship, shipExploreTgt);
                        if (!isNewShipAssigned) {
                            // No more ships are available to finish UCenter explore. Since it only takes one ship
                            // to explore UCenter, the other ships, if any, can't currently be exploring, so no reason to wait for them
                            // to complete their exploration. -> the exploration attempt has failed so issue recall
                            issueFleetRecall = true;
                        }
                        break;
                    case UnitItemOrderFailureCause.UnitItemDeath:
                        isNewShipAssigned = HandleShipNoLongerAvailableToExplore(ship, shipExploreTgt);
                        if (!isNewShipAssigned) {
                            if (Elements.Count > 1) {    // >1 as dead ship has not yet been removed from fleet
                                                         // This is not the last ship in the fleet, but the others aren't available. Since it only takes one ship
                                                         // to explore UCenter, the other ships can't currently be exploring, so no reason to wait for them
                                                         // to complete their exploration. -> the exploration attempt has failed so issue recall
                                issueFleetRecall = true;
                            }
                            else {
                                D.AssertEqual(Constants.One, Elements.Count);  // dead ship has not yet been removed from fleet
                                // Do nothing as Unit is about to die
                            }
                        }
                        break;
                    case UnitItemOrderFailureCause.TgtDeath:
                    case UnitItemOrderFailureCause.TgtRelationship:
                    case UnitItemOrderFailureCause.TgtUncatchable:
                    case UnitItemOrderFailureCause.TgtUnreachable:
                    case UnitItemOrderFailureCause.None:
                    default:
                        throw new NotImplementedException(ErrorMessages.UnanticipatedSwitchValue.Inject(failCause));
                }
            }
        }
        if (issueFleetRecall) {
            IFleetExplorable fleetExploreTgt = CurrentOrder.Target as IFleetExplorable;
            var closestLocalAssyStation = GameUtility.GetClosest(Position, fleetExploreTgt.LocalAssemblyStations);
            CurrentOrder = new FleetOrder(FleetDirective.AssumeFormation, OrderSource.CmdStaff, closestLocalAssyStation);
        }
    }
 protected override bool TryIsSelectedItemUserRemoteShip(ISelectable selected, out ShipItem selectedShip) {
     return base.TryIsSelectedItemUserRemoteShip(selected, out selectedShip);
 }
Example #51
0
 /// <summary>
 /// Waits for the ships in the fleet to align with the requested heading, then executes the provided callback.
 /// <remarks>
 /// Called by each of the ships in the fleet when they are preparing for collective departure to a destination
 /// ordered by FleetCmd. This single coroutine replaces a similar coroutine previously run by each ship.
 /// </remarks>
 /// </summary>
 /// <param name="fleetIsAlignedCallback">The fleet is aligned callback.</param>
 /// <param name="ship">The ship.</param>
 internal void WaitForFleetToAlign(Action fleetIsAlignedCallback, ShipItem ship) {
     D.AssertNotNull(fleetIsAlignedCallback);
     _navigator.WaitForFleetToAlign(fleetIsAlignedCallback, ship);
 }
Example #52
0
    public ShipItem GetShipItem(int item_id)
    {
        ShipItem returnShipItem = new ShipItem();
        string   qwery          = "SELECT item_id,max_speed,rotation_speed, acceleration_max,hull_full,armor_full,shield_full,capasitor_full,hull_restore,armor_restore,shield_restore,capasitor_restore,agr_distance,vision_distance,mob,warpDriveStartTime,warpSpeed  FROM ship_item  where item_id=" + item_id.ToString();

        GetReader(qwery);
        while (reader.Read())
        {
            if (!reader.IsDBNull(0))
            {
                returnShipItem.item_id = reader.GetInt32(0);
            }
            if (!reader.IsDBNull(1))
            {
                returnShipItem.max_speed = reader.GetFloat(1);
            }
            if (!reader.IsDBNull(2))
            {
                returnShipItem.rotation_speed = reader.GetFloat(2);
            }
            if (!reader.IsDBNull(3))
            {
                returnShipItem.acceleration_max = reader.GetFloat(3);
            }
            if (!reader.IsDBNull(4))
            {
                returnShipItem.hull_full = reader.GetFloat(4);
            }
            if (!reader.IsDBNull(5))
            {
                returnShipItem.armor_full = reader.GetFloat(5);
            }
            if (!reader.IsDBNull(6))
            {
                returnShipItem.shield_full = reader.GetFloat(6);
            }
            if (!reader.IsDBNull(7))
            {
                returnShipItem.capasitor_full = reader.GetFloat(7);
            }
            if (!reader.IsDBNull(8))
            {
                returnShipItem.hull_restore = reader.GetFloat(8);
            }
            if (!reader.IsDBNull(9))
            {
                returnShipItem.armor_restore = reader.GetFloat(9);
            }
            if (!reader.IsDBNull(10))
            {
                returnShipItem.shield_restore = reader.GetFloat(10);
            }
            if (!reader.IsDBNull(11))
            {
                returnShipItem.capasitor_restore = reader.GetFloat(11);
            }
            if (!reader.IsDBNull(12))
            {
                returnShipItem.agr_distance = reader.GetFloat(12);
            }
            if (!reader.IsDBNull(13))
            {
                returnShipItem.vision_distance = reader.GetFloat(13);
            }
            if (!reader.IsDBNull(14))
            {
                returnShipItem.mob = (reader.GetInt32(14) == 1);
            }
            if (!reader.IsDBNull(15))
            {
                returnShipItem.warpDriveStartTime = reader.GetFloat(15);
            }
            if (!reader.IsDBNull(16))
            {
                returnShipItem.warpSpeed = reader.GetFloat(16);
            }
        }
        return(returnShipItem);
    }
Example #53
0
        /// <summary>
        ///     Damage the ship, either the shield, external equipment or hull.
        /// Use shield damage to damage shield or drain power.
        /// Hull damage is absorbed by shield if it's on, anything left goes on hull.
        /// </summary>
        /// <param name="hpid">Subtarget taking damage</param>
        /// <param name="energy_damage">The energy damage in hitpts</param>
        /// <param name="hull_damage">The hull damage in hitpts</param>
        /// <param name="type">Weapon type.</param>
        /// <returns>Returns true if the ship or an equipment item was destroyed</returns>
        public bool Damage(uint hpid, float energy_damage, float hull_damage, DeathCause cause)
        {
            if (energy_damage < 0 || hull_damage < 0)
            {
                return(false);
            }

            if (energy_damage == 0 && hull_damage == 0)
            {
                return(false);
            }

            // If we have an active shield ignore hits on the hull or external equipment
            // and make them on the shield.
            if (Shield != null && (Shield.Health > 0 || hpid == 0xFFF1))
            {
                // Step 1: calculate shield damage from energy damage
                float relative_shield_damage = (energy_damage * 1.0f) / Shield.Arch.MaxCapacity;
                Shield.Health -= relative_shield_damage;
                if (Shield.Health <= 0)
                {
                    energy_damage = -Shield.Health * 1.0f * Shield.Arch.MaxCapacity;
                    Shield.Health = 0;
                }
                else
                {
                    energy_damage = 0;

                    // Step 2 : calculate shield damage from hull damage if the shield is still up
                    relative_shield_damage = (hull_damage * 0.5f) / Shield.Arch.MaxCapacity;
                    Shield.Health         -= relative_shield_damage;
                    if (Shield.Health < 0)
                    {
                        hull_damage   = -Shield.Health * 1.0f * Shield.Arch.MaxCapacity;
                        Shield.Health = 0;
                    }
                    else
                    {
                        hull_damage = 0;
                    }
                }

                if (Shield.Health < Shield.Arch.OfflineThreshold)
                {
                    Shield.OfflineTime = Shield.Arch.OfflineRebuildTime;
                }
                Runner.NotifyOnSetHitPoints(Objid, DamageListItem.SHIELD, Shield.Health * Shield.Arch.MaxCapacity, false);
            }

            // Any remaining energy damage hits the powerplant
            if (energy_damage > 0)
            {
                Powergen.CurrPower -= energy_damage;
                Runner.NotifyOnSetHitPoints(Objid, Powergen.Item.hpid, Powergen.CurrPower, false);
            }

            // Avoid running the rest if the shield absorbed all damage
            if (hull_damage <= 0)
            {
                return(false);
            }

            bool hasDestroyedSomething = false;

            // Otherwise if this is a hit on an external equipment item do the hit on that
            ShipItem item = FindByHpid(hpid);

            if (item != null && item.arch is ExternalEquipmentArechetype && item.health > 0)
            {
                item.health -= (hull_damage / item.arch.HitPts) * _armorDamageFactor;
                if (item.health < 0)
                {
                    hull_damage = -item.health * item.arch.HitPts / _armorDamageFactor;
                    item.health = 0;
                }

                if (item.health == 0)
                {
                    Runner.NotifyOnSetHitPoints(Objid, item.hpid, 0, true);
                    Items.Remove(item.hpid);
                    hasDestroyedSomething = true;
                }

                Runner.NotifyOnSetHitPoints(Objid, item.hpid, item.health * item.arch.HitPts, false);
            }

            // Avoid running the rest if the equipment absorbed all damage
            if (hull_damage <= 0)
            {
                return(hasDestroyedSomething);
            }

            // Otherwise this is a hull hit.
            Health -= (hull_damage / Arch.HitPts) * _armorDamageFactor;
            if (Health < 0)
            {
                Health = 0;
            }

            if (Health == 0)
            {
                Destroy(cause);
                return(true);
            }

            Runner.NotifyOnSetHitPoints(Objid, DamageListItem.HULL, Health * Arch.HitPts, false);
            return(hasDestroyedSomething);
        }
Example #54
0
            public override void HandleTimerEvent(double deltaSeconds)
            {
                if (runner.System == UniverseDB.FindSystem("li01"))
                {
                    //TODO: AI debug here
                    for (int i = 0; i < 1; i++)
                    {
                        var npc = new Old.Object.Ship.Ship(runner);
                        npc.AI   = new AI.DebugAI(npc);
                        npc.Arch = ArchetypeDB.Find(FLUtility.CreateID("dsy_csv"));
                        if (npc.Arch == null)
                        {
                            return;
                        }

                        npc.Position = new Vector(-30000 + i * 300, i * 100, -25000);
                        //npc.orientation = ;
                        npc.Rank    = 20;
                        npc.System  = runner.System;
                        npc.Health  = 1.0f;
                        npc.faction = UniverseDB.FindFaction("fc_wild");
                        Loadout loadout = UniverseDB.FindLoadout("fc_j_ge_csv_loadout01");
                        if (loadout != null)
                        {
                            uint hpid = 34;
                            foreach (ShipItem item in loadout.Items)
                            {
                                var new_item = new ShipItem();
                                new_item.arch    = item.arch;
                                new_item.count   = item.count;
                                new_item.health  = 1.0f;
                                new_item.hpid    = hpid++;
                                new_item.hpname  = item.hpname;
                                new_item.mounted = item.mounted;
                                npc.Items.Add(new_item.hpid, new_item);
                            }
                        }
                        npc.InitialiseEquipmentSimulation();
                        runner.CreateSimObject(npc);
                    }
                }
                //    int total = 0;
                //    if (runner.players.Count > 0)
                //    {
                //        if (delta_seconds > 1.5)
                //            runner.log.AddLog(LogType.FL_MSG, "bad delta " + delta_seconds);

                //        // wow, this'll really suck if there are lots of NPCs
                //        foreach (Zone z in runner.system.zones)
                //        {
                //            if (z.shape != null && z.density > 0)
                //            {
                //                while (z.interference < z.density) // borrow this
                //                {
                //                    Ship npc = new Ship(runner);
                //                    npc.position = z.shape.position;
                //                    npc.orientation = z.shape.orientation;
                //                    npc.rank = 20;
                //                    npc.arch = ArchetypeDB.Find(FLUtility.CreateID("dsy_csv"));
                //                    npc.system = runner.system;
                //                    npc.health = 1.0f;
                //                    runner.CreateSimObject(npc);

                //                    z.interference++;
                //                    total++;
                //                }
                //            }
                //        }

                //        int working_npcs = 0;
                //        foreach (SimObject o in runner.objects.Values)
                //        {
                //            if (o.health > 0)
                //            {
                //                working_npcs++;

                //                foreach (Player player in runner.players.Values)
                //                {
                //                    if (player.ship != o)
                //                    {
                //                        Vector position = player.ship.position;
                //                        position.x += rand.Next(100);
                //                        position.z += rand.Next(100);
                //                        o.SetUpdateObject(position, player.ship.orientation, 1.0f, 0);
                //                    }
                //                }
                //            }
                //        }

                //        runner.log.AddLog(LogType.GENERAL, "system={0} npcs={1} objects={2} running={3}",
                //            runner.system.nickname, total, runner.objects.Count, working_npcs));

                //    }

                //    ExpireAfter(1);
            }
Example #55
0
 public ThrusterSim(Ship ship, ShipItem item)
 {
     this.ship = ship;
     this.item = item;
     arch      = item.arch as ThrusterArchetype;
 }
Example #56
0
 public void RemoveItem(ShipItem item)
 {
     m_Items.Remove(item);
 }
Example #57
0
 public GunSim(Ship ship, ShipItem item)
 {
     this.ship = ship;
     this.item = item;
     arch      = item.arch as GunArchetype;
 }
Example #58
0
 private void __SetFtlDamagedState(ShipItem element) {
     element.Data.IsFtlDamaged = _ftlStartsDamaged;
 }
Example #59
0
 private void AssignShipToExploreItem(ShipItem ship, IShipExplorable item) {
     if (!item.IsExploringAllowedBy(Owner)) {
         D.Error("{0} attempting to assign {1} to illegally explore {2}.", DebugName, ship.DebugName, item.DebugName);
     }
     if (item.IsFullyExploredBy(Owner)) {
         D.Error("{0} attempting to assign {1} to explore {2} which is already explored.", DebugName, ship.DebugName, item.DebugName);
     }
     ShipOrder exploreOrder = new ShipOrder(ShipDirective.Explore, CurrentOrder.Source, toNotifyCmd: true, target: item);
     ship.CurrentOrder = exploreOrder;
 }