public PlayerBuyWindow(Hangar mh, Hangar guh, Hangar vp, Hangar jh)
 {
     mechHangar = mh;
     groundUnitHangar = guh;
     airUnitHangar = vp;
     jetHangar = jh;
 }
        public static void Main()
        {
            var grafIgnatievo = new Hangar<Airplane>();

            var equipment1 = grafIgnatievo.GetAircraft();
            equipment1.PilotName = "Bubi Hartmann";
            Console.WriteLine(
                "Airplane 1 ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used by {1}",
                equipment1.RequestedAt,
                equipment1.PilotName);
            Thread.Sleep(2000);

            var equipment2 = grafIgnatievo.GetAircraft();
            equipment1.PilotName = "Chuck DeBellevue";
            Console.WriteLine(
                "Airplane 2 ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used by {1}",
                equipment2.RequestedAt,
                equipment1.PilotName);
            Thread.Sleep(2000);

            grafIgnatievo.ReleaseEquipment(equipment1);

            equipment1.PilotName = "Ilmari Juutilainen";
            Console.WriteLine(
                "Airplane 3 ordered on {0:MM/dd/yyyy hh:mm:ss.fff tt} used by {1}",
                equipment1.RequestedAt,
                equipment1.PilotName);
            Thread.Sleep(2000);
        }
Exemple #3
0
 void buildHandler(int button, int building)
 {
     switch(building)
     {
         case 0:
             buildings[button] = new Barracks(currentTurn, this);
             buttonDescriptions[button] = buildings[button].getBuildingInfo();
             break;
         case 1:
             buildings[button] = new Factory(currentTurn, this);
             buttonDescriptions[button] = buildings[button].getBuildingInfo();
             break;
         case 2:
             buildings[button] = new Hangar(currentTurn, this);
             buttonDescriptions[button] = buildings[button].getBuildingInfo();
             break;
     }
 }
Exemple #4
0
        public void HangarRemoveResources()
        {
            Hangar h = new Hangar(station, corporation);

            ResourceElement elem1  = new ResourceElement(ResourceElement.ResourceType.Wastes, station, 100, 1);
            ResourceStack   stack1 = new ResourceStack(elem1);

            h.Add(stack1);

            ResourceElement elem2  = new ResourceElement(ResourceElement.ResourceType.Wastes, station, 100, 2);
            ResourceElement elem3  = new ResourceElement(ResourceElement.ResourceType.Wastes, station, 100, 3);
            ResourceStack   stack2 = new ResourceStack(elem2);

            stack2.Add(elem3);
            h.Add(stack2);

            ResourceStack outStack = h.GetStack(ResourceElement.ResourceType.Wastes, 50);

            Assert.NotNull(outStack);
            Assert.AreEqual(50, outStack.Qte);
            Assert.AreEqual(ResourceElement.ResourceType.Wastes, outStack.Type);
            Assert.AreEqual(250, h.GetResourceQte(ResourceElement.ResourceType.Wastes));
        }
Exemple #5
0
        public override void DisposeScreen()
        {
            CancelAsync();

            AnimatedThreadWorker.Dispose();

            if (_itemPrintReportHistory != null)
            {
                _itemPrintReportHistory.Dispose();
            }
            if (_itemPrintReportRecords != null)
            {
                _itemPrintReportRecords.Dispose();
            }
            if (_buttonPrintMenuStrip != null)
            {
                _buttonPrintMenuStrip.Dispose();
            }

            _currentItem = null;

            Dispose(true);
        }
Exemple #6
0
    public bool RemoveResourceToHangar(int hangarID, int resType, int qte)
    {
        Hangar h      = _container._hangars[hangarID];
        int    tmpQte = 0;
        List <ResourceStack> stacks = new List <ResourceStack>();

        foreach (int i in h.StacksIDs)
        {
            ResourceStack r = _container._resourceStacks[i];
            if (r.Type == resType)
            {
                tmpQte += r.Qte;
                stacks.Add(r);
            }
        }

        if (tmpQte >= qte)
        {
            while (qte > 0)
            {
                if (stacks[0].Qte > qte)
                {
                    stacks[0].Qte -= qte;
                    qte            = 0;
                }
                else
                {
                    qte -= stacks[0].Qte;
                    _container._resourceStacks.Remove(stacks[0].ID);
                    h.StacksIDs.Remove(stacks[0].ID);
                    stacks.RemoveAt(0);
                }
            }
            return(true);
        }
        return(false);
    }
Exemple #7
0
        public static void SaveOnlinePlayerAccounts(Hangar Plugin)
        {
            if (Plugin == null)
            {
                Hangar.Debug("Major Error! Plugin refrence is null!");
                return;
            }

            if (!Plugin.Config.PluginEnabled || !Plugin.Config.CrossServerEcon)
            {
                return;
            }
            //Saving all online player balances

            List <PlayerAccount> PAccounts = new List <PlayerAccount>();

            foreach (MyPlayer player in MySession.Static.Players.GetOnlinePlayers())
            {
                ulong ID = MySession.Static.Players.TryGetSteamId(player.Identity.IdentityId);

                //Check if steam id is null
                if (ID == 0)
                {
                    continue;
                }

                Utils.TryGetPlayerBalance(ID, out long balance);
                PAccounts.Add(new PlayerAccount(player.DisplayName, ID, balance));
            }
            Hangar.Debug("Saving all online player Accounts!");
            //Attempt to broadcast to server
            CrossServerMessage message = new CrossServerMessage();

            message.Type          = CrossServer.MessageType.PlayerAccountUpdated;
            message.BalanceUpdate = PAccounts;
            Plugin.Market.MarketServers.Update(message);
        }
        /// <summary>
        ///  Konstruktor klase World.
        /// </summary>
        public World(String scenePath, String sceneFileName, int width, int height)
        {
            this.m_balloon = new AssimpScene2(scenePath, sceneFileName);
            this.m_hangar = new Hangar(10.0f, 10.0f, 12.0f);
            this.m_terrain = new Terrain();
            //this.m_hangar = new Hangar(3.0f, 2.5f, 6.0f);
            this.m_width = width;
            this.m_height = height;

            try
            {
                // TODO 4.0: Podsavanje fonta Courier New, 11pt, bold, italic
                m_font = new OutlineFont("Courier New", 11, 0.02f, true, true, false, false);
                m_textures = new int[m_textureCount];
            }
            catch (Exception)
            {
                MessageBox.Show("Neuspesno kreirana instanca OpenGL fonta", "GRESKA", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            this.Initialize();  // Korisnicka inicijalizacija OpenGL parametara

            this.Resize();      // Podesi projekciju i viewport
        }
Exemple #9
0
        /// <summary>
        ///  Konstruktor klase World.
        /// </summary>
        public World(String scenePath, String sceneFileName, int width, int height)
        {
            this.m_balloon = new AssimpScene2(scenePath, sceneFileName);
            this.m_hangar  = new Hangar(10.0f, 10.0f, 12.0f);
            this.m_terrain = new Terrain();
            //this.m_hangar = new Hangar(3.0f, 2.5f, 6.0f);
            this.m_width  = width;
            this.m_height = height;

            try
            {
                // TODO 4.0: Podsavanje fonta Courier New, 11pt, bold, italic
                m_font     = new OutlineFont("Courier New", 11, 0.02f, true, true, false, false);
                m_textures = new int[m_textureCount];
            }
            catch (Exception)
            {
                MessageBox.Show("Neuspesno kreirana instanca OpenGL fonta", "GRESKA", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            this.Initialize();  // Korisnicka inicijalizacija OpenGL parametara

            this.Resize();      // Podesi projekciju i viewport
        }
    private void RedrawWindow()
    {
        int        statedCrystalsCount = 0, statedSuppliesCount = Expedition.MIN_SUPPLIES_COUNT;
        Color      redcolor = Color.red, whitecolor = Color.white;
        GameObject g;

        if (showingExpedition == null)
        {
            //подготовка новой экспедиции
            expLabel.text = Localization.GetExpeditionName(selectedDestination);
            bool readyToStart = true;

            PrepareCrewDropdown();
            if (selectedCrew != null)
            {
                readyToStart = selectedCrew.atHome;
                crewButton.SetActive(true);
            }
            else
            {
                readyToStart = false;
                crewButton.SetActive(false);
            }
            if (!crewDropdown.gameObject.activeSelf)
            {
                crewDropdown.gameObject.SetActive(true);
                crewStableName.enabled = false;
            }
            //supplies
            suppliesSlider.value = statedSuppliesCount;
            OnSuppliesSliderChanged(statedSuppliesCount);
            if (preparingMode != true)
            {
                suppliesSlider.gameObject.SetActive(true);
                suppliesStableValue.gameObject.SetActive(false);
            }
            //crystals
            crystalsSlider.value = statedCrystalsCount;
            OnCrystalsSliderChanged(statedCrystalsCount);
            if (preparingMode != true)
            {
                crystalsSlider.gameObject.SetActive(true);
                crystalsStableValue.gameObject.SetActive(false);
            }
            //transmitters:
            int c = QuantumTransmitter.GetFreeTransmittersCount();
            if (c > 0)
            {
                transmitterMarker.uvRect = UIController.GetIconUVRect(Icons.TaskCompleted);
                transmitterLabel.text    = Localization.GetPhrase(LocalizedPhrase.FreeTransmitters) + c.ToString();
                transmitterLabel.color   = whitecolor;
            }
            else
            {
                transmitterMarker.uvRect = UIController.GetIconUVRect(Icons.TaskFailed);
                transmitterLabel.text    = Localization.GetPhrase(LocalizedPhrase.NoTransmitters);
                transmitterLabel.color   = redcolor;
                readyToStart             = false;
            }
            //shuttles:
            c = Hangar.GetFreeShuttlesCount();
            if (c > 0)
            {
                shuttleMarker.uvRect = UIController.GetIconUVRect(Icons.TaskCompleted);
                shuttleLabel.text    = Localization.GetPhrase(LocalizedPhrase.FreeShuttles) + c.ToString();
                shuttleLabel.color   = whitecolor;
            }
            else
            {
                shuttleMarker.uvRect = UIController.GetIconUVRect(Icons.TaskFailed);
                shuttleLabel.text    = Localization.GetPhrase(LocalizedPhrase.NoShuttles);
                shuttleLabel.color   = redcolor;
                readyToStart         = false;
            }
            lastShuttlesListMarker = Hangar.listChangesMarkerValue;
            //fuel:
            if (FuelCheck() == false)
            {
                readyToStart = false;
            }
            if (preparingMode != true)
            {
                shuttleLine.gameObject.SetActive(true);
                fuelLine.gameObject.SetActive(true);
                minigameButton.SetActive(false);
            }
            //launch button
            launchButtonLabel.text    = Localization.GetWord(LocalizedWord.Launch);
            launchButton.interactable = readyToStart;
            launchButton.GetComponent <Image>().color = readyToStart ? lightcyan : Color.grey;
            launchButton.gameObject.SetActive(true);
            //
            preparingMode = true;
        }
        else
        {
            // отрисовка существующей
            expLabel.text          = Localization.GetExpeditionName(showingExpedition);
            statedCrystalsCount    = showingExpedition.crystalsCollected;
            statedSuppliesCount    = showingExpedition.suppliesCount;
            lastChangesMarkerValue = showingExpedition.changesMarkerValue;

            crewStableName.text = showingExpedition.crew.name;
            if (crewDropdown.gameObject.activeSelf)
            {
                crewDropdown.gameObject.SetActive(false);
                crewStableName.enabled = true;
            }
            //supplies
            suppliesStableValue.text  = statedSuppliesCount.ToString();
            suppliesStableValue.color = statedSuppliesCount > 0 ? whitecolor : redcolor;
            if (preparingMode != false)
            {
                suppliesSlider.gameObject.SetActive(false);
                suppliesStableValue.gameObject.SetActive(true);
            }
            //crystals
            crystalsStableValue.text = statedCrystalsCount.ToString();
            if (preparingMode != false)
            {
                crystalsSlider.gameObject.SetActive(false);
                crystalsStableValue.gameObject.SetActive(true);
            }
            //transmitter:
            if (showingExpedition.hasConnection)
            {
                transmitterMarker.uvRect = UIController.GetIconUVRect(Icons.TaskCompleted);
                transmitterLabel.text    = Localization.GetPhrase(LocalizedPhrase.ConnectionOK);
                transmitterLabel.color   = whitecolor;
            }
            else
            {
                transmitterMarker.uvRect = UIController.GetIconUVRect(Icons.TaskFailed);
                transmitterLabel.text    = Localization.GetPhrase(LocalizedPhrase.ConnectionLost);
                transmitterLabel.color   = redcolor;
            }
            //shuttle & fuel
            if (preparingMode != false)
            {
                shuttleLine.gameObject.SetActive(false);
                fuelLine.gameObject.SetActive(false);
            }
            //launchbutton
            if (showingExpedition.stage == Expedition.ExpeditionStage.OnMission | showingExpedition.stage == Expedition.ExpeditionStage.WayIn)
            {
                launchButtonLabel.text = Localization.GetPhrase(LocalizedPhrase.StopMission);
                launchButton.GetComponent <Image>().color = halfred;
                launchButton.interactable = true;
                launchButton.gameObject.SetActive(true);
            }
            else
            {
                launchButton.gameObject.SetActive(false);
            }

            minigameButton.SetActive(showingExpedition.stage == Expedition.ExpeditionStage.OnMission);

            preparingMode = false;
        }

        var edb = expDestinationButton;

        if (selectedDestination != null)
        {
            edb.transform.GetChild(0).GetComponent <RawImage>().uvRect = GlobalMapUI.GetMarkerRect(selectedDestination.type);
            edb.SetActive(workOnMainCanvas);
        }
        else
        {
            if (edb.activeSelf)
            {
                edb.SetActive(false);
            }
        }
    }
Exemple #11
0
        private void UpdatePublicOffers()
        {
            //Update all public offer market items!
            if (!Hangar.IsRunning)
            {
                return;
            }

            //Need to remove existing ones

            string PublicOfferPath = Plugin.Market.ServerOffersDir;

            //Clear list
            GridMarket.PublicOfferseGridList.Clear();


            foreach (PublicOffers offer in Plugin.Config.PublicOffers)
            {
                if (offer.Forsale && (offer.Name != null || offer.Name != ""))
                {
                    string GridFilePath = System.IO.Path.Combine(PublicOfferPath, offer.Name + ".sbc");
                    Hangar.Debug("Blueprint Path: " + GridFilePath);

                    MyObjectBuilderSerializer.DeserializeXML(GridFilePath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = null;
                    try
                    {
                        shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                    }
                    catch
                    {
                        Hangar.Debug("Error on BP: " + offer.Name + "! Most likely you put in the SBC5 file! Dont do that!");
                        continue;
                    }
                    MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];
                    byte[] Definition             = MyAPIGateway.Utilities.SerializeToBinary(grid);

                    HangarChecks.GetPublicOfferBPDetails(shipBlueprint, out GridStamp stamp);


                    //Straight up add new ones
                    MarketList NewList = new MarketList();
                    NewList.Steamid        = 0;
                    NewList.Name           = offer.Name;
                    NewList.Seller         = offer.Seller;
                    NewList.SellerFaction  = offer.SellerFaction;
                    NewList.Price          = offer.Price;
                    NewList.Description    = offer.Description;
                    NewList.GridDefinition = Definition;


                    NewList.GridBuiltPercent = stamp.GridBuiltPercent;
                    NewList.NumberofBlocks   = stamp.NumberofBlocks;
                    NewList.SmallGrids       = stamp.SmallGrids;
                    NewList.LargeGrids       = stamp.LargeGrids;
                    NewList.BlockTypeCount   = stamp.BlockTypeCount;


                    //Need to setTotalBuys
                    GridMarket.PublicOfferseGridList.Add(NewList);

                    Hangar.Debug("Adding new public offer: " + offer.Name);
                }
            }


            //Update Everything!
            Comms.SendListToModOnInitilize();

            MarketData Data = new MarketData();

            Data.List = GridMarket.PublicOfferseGridList;

            //Write to file
            FileSaver.Save(Plugin.Market.ServerMarketFileDir, Data);
            //File.WriteAllText(Main.ServerMarketFileDir, JsonConvert.SerializeObject(Data));
            //This will force the market to update the market items
        }
 public void Update(string id, Hangar hangarIn) =>
 _hangar.ReplaceOne(hangar => hangar.Id == id, hangarIn);
Exemple #13
0
 public void Sethangar(Hangar hangar)
 {
     this.hangar = hangar;
 }
Exemple #14
0
        public void InitilizeGridMarket()
        {
            //Initilize new market servers
            MarketServers = new CrossServer(Config.MarketPort, this);
            //Attempt to create market servers!
            if (MarketServers.CreateServers() == false)
            {
                Hangar.Debug("Unable to start market servers! Check logs & contact plugin dev!");
                Config.GridMarketEnabled = false;
            }



            Config.HostServer = IsHostServer;


            ServerOffersDir     = Path.Combine(_StoragePath, "HangarServerOffers");
            ServerMarketFileDir = Path.Combine(ServerOffersDir, "HangarServerOffers.json");
            Directory.CreateDirectory(ServerOffersDir);
            MarketData PublicData = new MarketData();


            if (File.Exists(ServerMarketFileDir))
            {
                using (StreamReader file = File.OpenText(ServerMarketFileDir))
                {
                    JsonSerializer serializer = new JsonSerializer();
                    PublicData = (MarketData)serializer.Deserialize(file, typeof(MarketData));
                }
            }

            if (IsHostServer)
            {
                MarketData Data               = new MarketData();
                Accounts   Accounts           = new Accounts();
                string     MarketPath         = Path.Combine(Config.FolderDirectory, "Market.json");
                string     PlayerAccountsPath = Path.Combine(Config.FolderDirectory, "PlayerAccounts.json");


                //Initilize loading of files!
                if (File.Exists(MarketPath))
                {
                    using (StreamReader file = File.OpenText(MarketPath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        Data = (MarketData)serializer.Deserialize(file, typeof(MarketData));
                    }
                }


                if (File.Exists(PlayerAccountsPath))
                {
                    using (StreamReader file = File.OpenText(PlayerAccountsPath))
                    {
                        JsonSerializer serializer = new JsonSerializer();
                        Accounts = (Accounts)serializer.Deserialize(file, typeof(Accounts));
                    }
                }


                //GridDefinition = Data.GridDefinition;
                PublicOfferseGridList = PublicData.List;
                GridList       = Data.List;
                PlayerAccounts = Accounts.PlayerAccounts;
            }
            else
            {
                Hangar.Debug("Requesting update!");

                //Client start. (Tell server to broadcast to all clients!)
                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.RequestAll;

                MarketServers.Update(SendMessage);
                Hangar.Debug("Initial Send Request");
            }
        }
Exemple #15
0
        //Forces refresh of all admin offered grids and syncs them to the blocks in the server
        public void UpdatePublicOffers()
        {
            //Update all public offer market items!


            //Need to remove existing ones
            for (int i = 0; i < GridList.Count; i++)
            {
                if (GridList[i].Steamid != 0)
                {
                    continue;
                }

                Hangar.Debug("Removing public offer: " + GridList[i].Name);
                GridList.RemoveAt(i);
            }

            string PublicOfferPath = ServerOffersDir;

            //Clear list
            PublicOfferseGridList.Clear();

            foreach (PublicOffers offer in Config.PublicOffers)
            {
                if (offer.Forsale)
                {
                    string GridFilePath = System.IO.Path.Combine(PublicOfferPath, offer.Name + ".sbc");


                    MyObjectBuilderSerializer.DeserializeXML(GridFilePath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = null;
                    try
                    {
                        shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                    }
                    catch
                    {
                        Hangar.Debug("Error on BP: " + offer.Name + "! Most likely you put in the SBC5 file! Dont do that!");
                        continue;
                    }
                    MyObjectBuilder_CubeGrid grid = shipBlueprint[0].CubeGrids[0];
                    byte[] Definition             = MyAPIGateway.Utilities.SerializeToBinary(grid);

                    //HangarChecks.GetPublicOfferBPDetails(shipBlueprint, out GridStamp stamp);


                    //Straight up add new ones
                    MarketList NewList = new MarketList();
                    NewList.Steamid        = 0;
                    NewList.Name           = offer.Name;
                    NewList.Seller         = offer.Seller;
                    NewList.SellerFaction  = offer.SellerFaction;
                    NewList.Price          = offer.Price;
                    NewList.Description    = offer.Description;
                    NewList.GridDefinition = Definition;
                    //NewList.GridBuiltPercent = stamp.GridBuiltPercent;
                    //NewList.NumberofBlocks = stamp.NumberofBlocks;
                    //NewList.SmallGrids = stamp.SmallGrids;
                    //NewList.LargeGrids = stamp.LargeGrids;
                    // NewList.BlockTypeCount = stamp.BlockTypeCount;

                    //Need to setTotalBuys
                    PublicOfferseGridList.Add(NewList);

                    Hangar.Debug("Adding new public offer: " + offer.Name);
                }
            }

            //Update Everything!
            Comms.SendListToModOnInitilize();

            MarketData Data = new MarketData();

            Data.List = PublicOfferseGridList;

            FileSaver.Save(ServerMarketFileDir, Data);
        }
Exemple #16
0
    public Hangar GetPlayerHangar()
    {
        Hangar _hangar = player.GetComponent <Hangar>();

        return(player.GetComponent <Hangar>());
    }
 /// <summary>
 /// Очищает все поля
 /// </summary>
 public void ClearFields()
 {
     textBoxShop.Text  = "";
     Hangar            = Hangar.Unknown;
     textBoxOther.Text = "";
 }
Exemple #18
0
        public IActionResult Create(Hangar nota)
        {
            _hangarBusiness.Create(nota);

            return(Ok(nota));
        }
Exemple #19
0
 public Barracuda(int id, string name, Hangar hangar, Faction factionId, Vector position, Spacemap spacemap, int maxHealth, int currentNanoHull,
                  int maxShield, int currentShield, int currentHealth, int damage, Reward reward, int respawnTime = 0, bool respawning = true, Npc motherShip = null) : base(id, name, hangar, factionId, position, spacemap, maxHealth, currentNanoHull, maxShield, currentShield, currentHealth, damage, reward, respawnTime, respawning, motherShip)
 {
 }
 private void Awake()
 {
     playerHangar = PersistantDataManager.Instance.GetPlayerHangar();
     computer     = FindObjectOfType <EnemyAi>();
 }
Exemple #21
0
 public void SetPlayerHangar(Hangar hangar)
 {
     player.GetComponent <Player>().Sethangar(hangar);
     Hangar _hangar = player.GetComponent <Hangar>();
 }
        public bool LoadGrid(string GridName, MyCharacter Player, long TargetPlayerID, bool keepOriginalLocation, Chat chat, Hangar Plugin, Vector3D GridSaveLocation, bool force = false, bool Admin = false)
        {
            string path = Path.Combine(FolderPath, GridName + ".sbc");

            if (!File.Exists(path))
            {
                Chat?.Respond("Grid doesnt exist! Admin should check logs for more information.");
                Log.Fatal("Grid doesnt exsist @" + path);
                return(false);
            }

            try
            {
                if (MyObjectBuilderSerializer.DeserializeXML(path, out MyObjectBuilder_Definitions myObjectBuilder_Definitions))
                {
                    MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprints = myObjectBuilder_Definitions.ShipBlueprints;
                    if (shipBlueprints == null)
                    {
                        Log.Warn("No ShipBlueprints in File '" + path + "'");
                        Chat?.Respond("There arent any Grids in your file to import!");
                        return(false);
                    }


                    /*
                     * if (!HangarChecker.BlockLimitChecker(shipBlueprints))
                     * {
                     *  Log.Warn("Block Limiter Checker Failed");
                     *  return false;
                     * }
                     */

                    if (Config.OnLoadTransfer)
                    {
                        Log.Warn("Transfering grid to: " + TargetPlayerID);
                        //Will transfer pcu to new player
                        foreach (MyObjectBuilder_ShipBlueprintDefinition definition in shipBlueprints)
                        {
                            foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                            {
                                foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                                {
                                    block.Owner   = TargetPlayerID;
                                    block.BuiltBy = TargetPlayerID;
                                }
                            }
                        }
                    }


                    Vector3D PlayerPosition = Player?.PositionComp.GetPosition() ?? Vector3D.Zero;


                    foreach (var shipBlueprint in shipBlueprints)
                    {
                        if (!LoadShipBlueprint(shipBlueprint, GridSaveLocation, PlayerPosition, keepOriginalLocation, chat))
                        {
                            //Hangar.Debug("Error Loading ShipBlueprints from File '" + path + "'");
                            return(false);
                        }
                    }

                    File.Delete(path);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Chat?.Respond("This ship failed to load. Contact staff & Check logs!");
                Log.Error(ex, "Failed to deserialize grid: " + path + " from file! Is this a shipblueprint?");
            }

            return(false);
        }
Exemple #23
0
        public void PurchaseGrid(GridsForSale grid)
        {
            //Need to check hangar of the person who bought the grid

            if (!Config.GridMarketEnabled)
            {
                return;
            }
            //Get Item from market list for price
            MarketList Item = null;

            List <MarketList> Allitems = new List <MarketList>();

            //Incluse all offers!
            Allitems.AddRange(GridList);
            Allitems.AddRange(PublicOfferseGridList);


            try
            {
                Item = Allitems.First(x => x.Name == grid.name);
            }
            catch
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Grid has been removed from market!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }


            MyPlayer.PlayerId BuyPlayer = new MyPlayer.PlayerId(grid.BuyerSteamid);
            MySession.Static.Players.TryGetPlayerById(BuyPlayer, out MyPlayer Buyer);

            GridMethods BuyerMethods = new GridMethods(grid.BuyerSteamid, Config.FolderDirectory);

            //string BuyerPath = GridMethods.CreatePathForPlayer(Config.FolderDirectory, grid.BuyerSteamid);

            if (Buyer == null)
            {
                Hangar.Debug("Unable to get steamID. Glitched player?");
                return;
                //Some kind of error message directed to player.
            }

            //Debug("Seller SteamID: " + Item.Steamid);
            MyCharacter Player = Buyer.Character;

            Hangar.Debug("Player Buying grid: " + Player.DisplayName + " [" + grid.BuyerSteamid + "]");

            //Start transfer of grids!
            int MaxStorage = Config.NormalHangarAmount;

            if (Player.PromoteLevel >= MyPromoteLevel.Scripter)
            {
                MaxStorage = Config.ScripterHangarAmount;
            }

            PlayerInfo BuyerData = new PlayerInfo();

            //Get PlayerInfo from file
            try
            {
                BuyerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json")));
                if (BuyerData.Grids.Count >= MaxStorage)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! No room in hangar!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }
            }
            catch
            {
                Hangar.Debug("Buyer doesnt have anything stored in their hangar! THIS IS NOT AN ERROR!");
                //ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", MyFontEnum.Red, grid.BuyerSteamid);
                //Debug("Deserialization error! Make sure files exist! \n" + e);
                //New player. Go ahead and create new. Should not have a timer.
            }



            //Adjust player prices (We need to check if buyer has enough moneyies hehe)
            bool RetrieveSuccessful = Utils.TryGetPlayerBalance(grid.BuyerSteamid, out long BuyerBallance);

            if (!RetrieveSuccessful || BuyerBallance < Item.Price)
            {
                _ChatManager.SendMessageAsOther("GridMarket", "Unable to purchase grid! Not enough credits!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                return;
            }



            string NewGridName    = Item.Name;
            bool   FileStilExists = true;
            int    i = 0;

            if (File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc")))
            {
                while (FileStilExists)
                {
                    i++;
                    if (!File.Exists(Path.Combine(BuyerMethods.FolderPath, NewGridName + "[" + i + "].sbc")))
                    {
                        FileStilExists = false;
                    }
                    //Turns out there is already a ship with that name in this players hangar!
                    if (i > 50)
                    {
                        _ChatManager.SendMessageAsOther("GridMarket", "Dude what the actual f**k do you need 50 of these for?", VRageMath.Color.Yellow, grid.BuyerSteamid);
                        Hangar.Debug("Dude what the actual f**k do you need 50 of these for? Will not continue due to... security reasons. @" + NewGridName);
                        return;
                    }
                }

                NewGridName = NewGridName + "[" + i + "]";
            }



            if (Item.Steamid == 0)
            {
                //Check to see if the item existis in the dir
                string PublicOfferPath = ServerOffersDir;
                string GridPath        = Path.Combine(PublicOfferPath, Item.Name + ".sbc");

                //Add counter just in case some idiot


                string BuyerGridPath = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                if (!File.Exists(GridPath))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Server Offer got manually deleted from folder! Blame admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Someone tried to buy a ship that doesnt exist! Did you delete it?? @" + GridPath);
                }

                //Need to check if player can buy
                PublicOffers Offer;
                int          Index;
                try
                {
                    Offer = Config.PublicOffers.First(x => x.Name == Item.Name);
                    Index = Config.PublicOffers.IndexOf(Offer);
                }
                catch (Exception e)
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Unknown error! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    Hangar.Debug("Unknown error! @" + GridPath, e, ErrorType.Fatal);
                    return;
                    //Something went wrong
                }



                if (Offer.TotalPerPlayer != 0 && !WithinPlayerLimits(Item.PlayerPurchases, grid.BuyerSteamid, Offer.TotalPerPlayer))
                {
                    _ChatManager.SendMessageAsOther("GridMarket", "Youve reached your buy limit on this grid!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                //File check complete!
                Hangar.Debug("Old Buyers Balance: " + BuyerBallance);

                //Create PlayerAccount
                PlayerAccount BuyerAccount = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);


                //Need to figure out HOW to get the data in here
                GridStamp stamp = new GridStamp();
                stamp.GridForSale = false;
                stamp.GridName    = NewGridName;


                //Add it to buyers info
                File.Copy(GridPath, BuyerGridPath);
                BuyerData.Grids.Add(stamp);


                //Update ALL blocks
                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);


                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);

                MarketServers.Update(SendAccountUpdate);

                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);

                //Write all files!
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));

                Offer.NumberOfBuys++;

                if (Offer.TotalPerPlayer != 0)
                {
                    AddPlayerPurchase(PublicOfferseGridList, Item, grid.BuyerSteamid);
                }

                //Check Total Limit
                if (Offer.NumberOfBuys >= Offer.TotalAmount)
                {
                    Config.PublicOffers[Index].Forsale = false;
                    //Update offers and refresh
                    UpdatePublicOffers();
                }
            }
            else
            {
                //This is a player offer

                GridMethods SellerMethods = new GridMethods(Item.Steamid, Dir);
                //string SellerPath = GridMethods.CreatePathForPlayer(Dir, Item.Steamid);
                Debug("Seller SteamID: " + Item.Steamid);


                PlayerInfo SellerData = new PlayerInfo();


                try
                {
                    SellerData = JsonConvert.DeserializeObject <PlayerInfo>(File.ReadAllText(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json")));
                }
                catch (Exception e)
                {
                    Hangar.Debug("Seller Hangar Playerinfo is missing! Did they get deleted by admin?", e, ErrorType.Warn);
                    _ChatManager.SendMessageAsOther("GridMarket", "Seller hangar info is missing! Contact admin!", VRageMath.Color.Yellow, grid.BuyerSteamid);
                    return;
                }



                CrossServerMessage SendMessage = new CrossServerMessage();
                SendMessage.Type = CrossServer.MessageType.RemoveItem;
                SendMessage.List.Add(Item);
                MarketServers.Update(SendMessage);


                PlayerAccount BuyerAccount  = new PlayerAccount(Player.DisplayName, grid.BuyerSteamid, BuyerBallance - Item.Price);
                PlayerAccount SellerAccount = new PlayerAccount(Item.Seller, Item.Steamid, Item.Price, true);



                //Get grids
                GridStamp gridsold = SellerData.Grids.FirstOrDefault(x => x.GridName == grid.name);
                //Reset grid for sale and remove it from the sellers hangarplayerinfo
                gridsold.GridForSale          = false;
                gridsold.ForceSpawnNearPlayer = true;
                SellerData.Grids.Remove(gridsold);
                gridsold.GridName = NewGridName;

                //Add it to buyers info
                BuyerData.Grids.Add(gridsold);

                //Move grid in folders!
                string SellerGridPath = Path.Combine(SellerMethods.FolderPath, grid.name + ".sbc");
                string BuyerGridPath  = Path.Combine(BuyerMethods.FolderPath, NewGridName + ".sbc");

                File.Move(SellerGridPath, BuyerGridPath);

                //After move we need to update all block owners and authors! this meanings opening up the grid and deserializing it to iterate the grid! (we dont want the seller to still be the author)

                MyObjectBuilderSerializer.DeserializeXML(BuyerGridPath, out MyObjectBuilder_Definitions myObjectBuilder_Definitions);

                MyObjectBuilder_ShipBlueprintDefinition[] shipBlueprint = myObjectBuilder_Definitions.ShipBlueprints;
                foreach (MyObjectBuilder_ShipBlueprintDefinition definition in myObjectBuilder_Definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid CubeGridDef in definition.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in CubeGridDef.CubeBlocks)
                        {
                            block.Owner   = Buyer.Identity.IdentityId;
                            block.BuiltBy = Buyer.Identity.IdentityId;
                            //Could turnoff warheads etc here
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(BuyerGridPath, false, myObjectBuilder_Definitions);

                //byte[] Definition = MyAPIGateway.Utilities.SerializeToBinary(grid);

                //Get grid definition of removed grid. (May not even need to get this lol)
                //GridsForSale RemovedGrid = Main.GridDefinition.FirstOrDefault(x => x.name == Item.Name);


                //We need to send to all to remove the item from the list

                CrossServerMessage SendAccountUpdate = new CrossServerMessage();
                SendAccountUpdate.Type = CrossServer.MessageType.PlayerAccountUpdated;
                SendAccountUpdate.BalanceUpdate.Add(BuyerAccount);
                SendAccountUpdate.BalanceUpdate.Add(SellerAccount);

                MarketServers.Update(SendAccountUpdate);
                _ChatManager.SendMessageAsOther("HangarMarket", Player.DisplayName + " just bought a " + grid.name, VRageMath.Color.Yellow);



                //Write all files!
                FileSaver.Save(Path.Combine(SellerMethods.FolderPath, "PlayerInfo.json"), SellerData);
                FileSaver.Save(Path.Combine(BuyerMethods.FolderPath, "PlayerInfo.json"), BuyerData);
                //File.WriteAllText(Path.Combine(SellerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(SellerData));
                //File.WriteAllText(Path.Combine(BuyerPath, "PlayerInfo.json"), JsonConvert.SerializeObject(BuyerData));
            }
            //Transfer Grid and transfer Author/owner!
        }
        public Hangar Create(Hangar hangar)
        {
            hangar.Id = Guid.NewGuid().ToString();

            return(_repository.Create(hangar));
        }
Exemple #25
0
        protected override void Update(GameTime gameTime)
        {
            lastMilliseconds = Environment.TickCount;

            needToDraw = false;
#if DEBUG
            countFPSUpdate(gameTime);
#endif
            input.update();

            if (state == nextState)
            {
                switch (state)
                {
                case states.mission:
                    mission.doLogic();
                    break;

                case states.mainMenu:
                    mainMenu.doLogic();
                    break;

                case states.hangar:
                    hangar.doLogic();
                    break;
                }
            }
            else if (loadScreenLoaded)
            {
                needToDraw = true;
                unloadContent(state);
                switch (nextState)
                {
                case states.mainMenu:
                    if (mainMenu == null)
                    {
                        mainMenu = new MainMenu();
                    }
                    if (mainMenu.load())
                    {
                        changeState();
                    }
                    break;

                case states.hangar:
                    if (hangar == null)
                    {
                        hangar = new Hangar();
                    }
                    if (hangar.load())
                    {
                        changeState();
                    }
                    break;

                case states.mission:
                    if (mission == null)
                    {
                        mission = new Mission();
                    }
                    if (mission.load())
                    {
                        changeState();
                    }
                    break;
                }
            }
            else
            {
                unloadContent(state);
                if (loadScreen == null)
                {
                    loadScreen = new LoadScreen();
                }
                loadScreenLoaded = loadScreen.load(Content);
            }

            if (nextState == states.quit)
            {
                this.Exit();
            }

            base.Update(gameTime);

            frameCount++;
#if DEBUG
            updateCount++;
#endif

            if (state == nextState)
            {
                if (!needToDraw)
                {
#if !DEBUG
                    Sleep();
                    this.SuppressDraw();
#else
                    drawCount--;
#endif
                }
            }
        }
        public HangarView()
        {
            InitializeComponent();

            Hangares = new List <Hangar>()
            {
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Cumbica", PrecoDiaria = 1000.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Cumbica", PrecoDiaria = 950.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Cumbica", PrecoDiaria = 1025
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Professor Urbano Ernesto Stumpf", PrecoDiaria = 1200.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Professor Urbano Ernesto Stumpf", PrecoDiaria = 1100.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Congonhas", PrecoDiaria = 1000.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Congonhas", PrecoDiaria = 1500.00
                },
                new Hangar {
                    NomeHangar = "hangar03", Airport = "Congonhas", PrecoDiaria = 1051.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Galeão", PrecoDiaria = 980.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Galeão", PrecoDiaria = 990.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Jacarepagua", PrecoDiaria = 1010.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Jacarepagua", PrecoDiaria = 1150.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Guararapes", PrecoDiaria = 1000.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Guararapes", PrecoDiaria = 880.00
                },
                new Hangar {
                    NomeHangar = "hangar03", Airport = "Guararapes", PrecoDiaria = 900.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Porto Alegre", PrecoDiaria = 940.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Pinto Martins Intl", PrecoDiaria = 998.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Bacacheri", PrecoDiaria = 1400.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Bacacheri", PrecoDiaria = 1350.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Viracopos", PrecoDiaria = 1130.00
                },
                new Hangar {
                    NomeHangar = "hangar02", Airport = "Viracopos", PrecoDiaria = 1125.00
                },
                new Hangar {
                    NomeHangar = "hangar03", Airport = "Viracopos", PrecoDiaria = 1500.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Confins", PrecoDiaria = 1410.00
                },
                new Hangar {
                    NomeHangar = "hangar01", Airport = "Brasília", PrecoDiaria = 1160.00
                },
            };

            Hangar h          = new Hangar();
            String NomeHangar = string.Format(h.NomeHangar + "   Diária  R$ {0}", h.PrecoDiaria);

            this.ListaHangar.ItemsSource = Hangares;
            // this.BindingContext = this;
        }
        public Hangar Create(Hangar hangar)
        {
            _hangar.InsertOne(hangar);

            return(hangar);
        }
 void StoreVessel()
 {
     Hangar.StoreVessel(FlightGlobals.ActiveVessel, hangar);
 }
 public void Remove(Hangar hangarIn) =>
 _hangar.DeleteOne(hangar => hangar.Id == hangarIn.Id);
Exemple #30
0
    public override int Update(ServerUpdate serverUpdate)
    {
        if (_data._currentFrame < _fleet.NextUpdateFrame)
        {
            return(_fleet.NextUpdateFrame);
        }

        string currentState = _fleet.FleetParams.GetString("currentState", "none");

        switch (currentState)
        {
        case "none": {
            Ship s1 = _data._ships[_fleet.ShipIDs[0]];
            _fleet.LastHangar = s1.Hangar;
            Hangar h = _data._hangars[s1.Hangar];
            _fleet.LastStation = h.Station;
            _fleet.NextHangar  = _fleet.LastHangar;

            StartUndock(serverUpdate);
        } break;

        case "undocking": {
            Undock(serverUpdate);

            //start moveTo
            NextUpdateFrame(100);

            foreach (int sID in _fleet.ShipIDs)
            {
                Ship ship = _data._ships[sID];
                ship.Hangar = -1;
                ship.Status = "Moving to explore site";
                serverUpdate.Add(ship);
            }
            _fleet.FleetParams.Set("currentState", "moveOut");
        } break;

        case "moveOut": {
            NextUpdateFrame(500);

            foreach (int sID in _fleet.ShipIDs)
            {
                Ship ship = _data._ships[sID];
                ship.Status = "Exploring";
                ship.AddLog("Moved to explore site");
                serverUpdate.Add(ship);
            }
            _fleet.FleetParams.Set("currentState", "explore");
        } break;

        case "explore": {
            NextUpdateFrame(200);

            //choisir un POI si possible
            bool      didFound = false;
            Random    r        = new Random();
            double    a        = r.NextDouble();
            NodeInfos n        = _nodes.nodes[_myID];
            int       sector   = n.nodeParams.GetInt("zone", 0);
            List <PointOfInterest> possible = _data._POIs.Values.Where(p => p.FindProba > a && p.Sector == sector).ToList();
            if (possible.Count > 0)
            {
                didFound = true;
                int             index = r.Next(possible.Count);
                PointOfInterest found = possible[index];

                Bookmark bookmark = new Bookmark(_data._bookmarkIDs++, index);
                bookmark.datas = found.DatasToBookmark();
                _data._bookmarks.Add(bookmark.ID, bookmark);

                n.nodeParams.Set("found", bookmark.ID);

/*
 *                  Corporation c = _container._corps[s.Corp];
 *                  SendMailRequest request = new SendMailRequest(-1, c.Owner);
 *                  request.Message = "You found something while exploring, congrat! \n\n" + found.Description;
 *                  request.Subject = "Exploration result";
 *                  _manager.SendRequest(request);
 */
            }

            foreach (int sID in _fleet.ShipIDs)
            {
                Ship ship = _data._ships[sID];
                ship.Status = "Moving back to station";
                ship.AddLog("Done with exploration");
                if (didFound)
                {
                    ship.AddLog("And found something...");
                }
                serverUpdate.Add(ship);
            }
            _fleet.FleetParams.Set("currentState", "moveIn");
        } break;

        case "moveIn": {
            StartDock(serverUpdate);
        } break;

        case "docking": {
            Dock(serverUpdate);
            StartFueling(serverUpdate);
        } break;

        case "fueling": {
            Fuel(serverUpdate);
        } break;

        case "doneFueling": {
            foreach (int sID in _fleet.ShipIDs)
            {
                Ship ship = _data._ships[sID];
                ship.Status = "Idle in station";
            }
            MoveFlow("ExploreOutput");
        }
        break;
        }

        return(_fleet.NextUpdateFrame);
    }
Exemple #31
0
        public static void HangarInterface(StaticInstance selectedFacility)
        {
            Hangar myHangar = selectedFacility.myFacilities[0] as Hangar;


            float fMaxMass = myHangar.FacilityMassCapacity;

            if (fMaxMass < 1)
            {
                fMaxMass = 25f;
            }

            int fMaxCrafts = myHangar.FacilityCraftCapacity;

            GUILayout.Space(2);
            GUILayout.Label("Where necessary craft are disassembled for storage or re-assembled before being rolled out. Please note that for game purposes, this procedure is instantaneous.", UIMain.LabelInfo);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Max Craft: " + fMaxCrafts.ToString("#0"), UIMain.LabelInfo);
            GUILayout.FlexibleSpace();
            GUILayout.Label("Max Mass/Craft: " + fMaxMass.ToString("#0") + " T", UIMain.LabelInfo);
            GUILayout.EndHorizontal();


            if (myHangar.storedVessels.Count == 0)
            {
                GUILayout.Label("");
                GUILayout.Label("No craft currently held in this facility.", UIMain.LabelInfo);
                GUILayout.Label("");
            }
            else
            {
                int iNumberCrafts = myHangar.storedVessels.Count;

                GUILayout.Box("Stored Craft (" + iNumberCrafts.ToString() + "/" + fMaxCrafts.ToString() + ")", UI.UIMain.Yellowtext);

                foreach (Hangar.StoredVessel vessel in myHangar.storedVessels)
                {
                    if (GUILayout.Button("" + vessel.vesselName, UIMain.ButtonKK, GUILayout.Height(20)))
                    {
                        // Empty the hangar
                        if (HangarwayIsClear(selectedFacility))
                        {
                            //Vessel newVessel = Hangar.RollOutVessel(vessel, myHangar);
                            //newVessel.Load();
                            //newVessel.MakeActive() ;
                            UI2.HangarKSCGUI.useFromFlight    = true;
                            UI2.HangarKSCGUI.selectedFacility = selectedFacility;
                            UI2.HangarKSCGUI.Open();
                        }
                        else
                        {
                            MiscUtils.HUDMessage("Cannot roll craft out. Clear the way first!", 10, 3);
                        }
                    }
                }
            }

            GUILayout.Space(5);


            GUILayout.Box("Store Vessel", UIMain.Yellowtext);

            bool bNearbyCraft = false;

            float vDistToCraft = Vector3.Distance(FlightGlobals.ActiveVessel.gameObject.transform.position, selectedFacility.position);

            if (vDistToCraft < KerbalKonstructs.instance.facilityUseRange)
            {
                bNearbyCraft = true;
            }

            GUI.enabled = bNearbyCraft;

            float fMass = FlightGlobals.ActiveVessel.GetTotalMass();

            if (fMass > fMaxMass)
            {
                GUILayout.Label("Vessel too heavy: " + Math.Round(fMass, 1).ToString() + "/" + fMaxMass);
                GUI.enabled = false;
            }
            if (myHangar.storedVessels.Count >= myHangar.FacilityCraftCapacity)
            {
                GUILayout.Label("Hangar is Full!", UIMain.LabelRed);
                GUI.enabled = false;
            }

            if (GUILayout.Button("Store Vessel" + FlightGlobals.ActiveVessel.vesselName, UIMain.ButtonKK, GUILayout.Height(23)))
            {
                Hangar.StoreVessel(FlightGlobals.ActiveVessel, myHangar);
            }
            GUI.enabled = true;
            if (!bNearbyCraft)
            {
                GUILayout.BeginHorizontal();
                {
                    GUILayout.Label("You are ", UIMain.LabelInfo);
                    GUILayout.Label(((int)vDistToCraft - KerbalKonstructs.instance.facilityUseRange).ToString(), UIMain.LabelRed);

                    GUILayout.Label("m", UIMain.LabelWhite);
                    GUILayout.Label(" too far away to store your craft!", UIMain.LabelInfo);
                }
                GUILayout.EndHorizontal();
            }


            GUILayout.FlexibleSpace();
        }
        public static void HangarInterface(StaticInstance selectedFacility)
        {
            Hangar myHangar = selectedFacility.myFacilities[0] as Hangar;

            DeadButton = new GUIStyle(GUI.skin.button);
            DeadButton.normal.background  = null;
            DeadButton.hover.background   = null;
            DeadButton.active.background  = null;
            DeadButton.focused.background = null;
            DeadButton.normal.textColor   = Color.white;
            DeadButton.hover.textColor    = Color.white;
            DeadButton.active.textColor   = Color.white;
            DeadButton.focused.textColor  = Color.white;
            DeadButton.fontSize           = 14;
            DeadButton.fontStyle          = FontStyle.Bold;

            DeadButtonRed = new GUIStyle(GUI.skin.button);
            DeadButtonRed.normal.background  = null;
            DeadButtonRed.hover.background   = null;
            DeadButtonRed.active.background  = null;
            DeadButtonRed.focused.background = null;
            DeadButtonRed.normal.textColor   = Color.red;
            DeadButtonRed.hover.textColor    = Color.yellow;
            DeadButtonRed.active.textColor   = Color.red;
            DeadButtonRed.focused.textColor  = Color.red;
            DeadButtonRed.fontSize           = 12;
            DeadButtonRed.fontStyle          = FontStyle.Bold;

            BoxNoBorder = new GUIStyle(GUI.skin.box);
            BoxNoBorder.normal.background = null;
            BoxNoBorder.normal.textColor  = Color.white;

            Yellowtext = new GUIStyle(GUI.skin.box);
            Yellowtext.normal.textColor  = Color.yellow;
            Yellowtext.normal.background = null;

            LabelInfo = new GUIStyle(GUI.skin.label);
            LabelInfo.normal.background = null;
            LabelInfo.normal.textColor  = Color.white;
            LabelInfo.fontSize          = 13;
            LabelInfo.fontStyle         = FontStyle.Bold;
            LabelInfo.padding.left      = 3;
            LabelInfo.padding.top       = 0;
            LabelInfo.padding.bottom    = 0;

            ButtonSmallText           = new GUIStyle(GUI.skin.button);
            ButtonSmallText.fontSize  = 12;
            ButtonSmallText.fontStyle = FontStyle.Normal;

            sInStorage  = myHangar.InStorage1;
            sInStorage2 = myHangar.InStorage2;
            sInStorage3 = myHangar.InStorage3;

            float fMaxMass = (float)selectedFacility.model.DefaultFacilityMassCapacity;

            if (fMaxMass < 1)
            {
                fMaxMass = 25f;
            }
            int fMaxCrafts = selectedFacility.model.DefaultFacilityCraftCapacity;

            if (fMaxCrafts < 1 || fMaxCrafts > 3)
            {
                fMaxCrafts = 2;
            }

            GUILayout.Space(2);
            GUILayout.Label("Where necessary craft are disassembled for storage or re-assembled before being rolled out. Please note that for game purposes, this procedure is instantaneous.", LabelInfo);
            GUILayout.BeginHorizontal();
            GUILayout.Label("Max Craft: " + fMaxCrafts.ToString("#0"), LabelInfo);
            GUILayout.FlexibleSpace();
            GUILayout.Label("Max Mass/Craft: " + fMaxMass.ToString("#0") + " T", LabelInfo);
            GUILayout.EndHorizontal();

            if (sInStorage == null || sInStorage == "")
            {
                sInStorage          = "None";
                myHangar.InStorage1 = "None";
            }
            if (sInStorage2 == null || sInStorage2 == "")
            {
                sInStorage2         = "None";
                myHangar.InStorage2 = "None";
            }
            if (sInStorage3 == null || sInStorage3 == "")
            {
                sInStorage3         = "None";
                myHangar.InStorage3 = "None";
            }

            if (sInStorage == "None" && sInStorage2 == "None" && sInStorage3 == "None")
            {
                GUILayout.Label("No craft currently held in this facility.", LabelInfo);
            }
            else
            {
                int iNumberCrafts = NumberCraftHangared(selectedFacility);

                GUILayout.Box("Stored Craft (" + iNumberCrafts.ToString() + "/" + fMaxCrafts.ToString("#0") + ")", Yellowtext);

                List <Vessel> lVessels = FlightGlobals.Vessels;

                foreach (Vessel vVesselStored in lVessels)
                {
                    if (vVesselStored.id.ToString() == sInStorage)
                    {
                        if (GUILayout.Button("" + vVesselStored.vesselName, ButtonSmallText, GUILayout.Height(20)))
                        {
                            // Empty the hangar
                            if (HangarwayIsClear(selectedFacility))
                            {
                                sInStorage = "None";
                                UnhangarCraft(vVesselStored, selectedFacility);
                                sInStorage = "None";
                            }
                            else
                            {
                                MiscUtils.HUDMessage("Cannot roll craft out. Clear the way first!", 10,
                                                     3);
                            }
                        }
                        break;
                    }
                }

                foreach (Vessel vVesselStored in lVessels)
                {
                    if (vVesselStored.id.ToString() == sInStorage2)
                    {
                        if (GUILayout.Button("" + vVesselStored.vesselName, ButtonSmallText, GUILayout.Height(20)))
                        {
                            // Empty the hangar
                            if (HangarwayIsClear(selectedFacility))
                            {
                                sInStorage2 = "None";
                                UnhangarCraft(vVesselStored, selectedFacility);
                                sInStorage2 = "None";
                            }
                            else
                            {
                                MiscUtils.HUDMessage("Cannot roll craft out. Clear the way first!", 10,
                                                     3);
                            }
                        }
                        break;
                    }
                }

                foreach (Vessel vVesselStored in lVessels)
                {
                    if (vVesselStored.id.ToString() == sInStorage3)
                    {
                        if (GUILayout.Button("" + vVesselStored.vesselName, ButtonSmallText, GUILayout.Height(20)))
                        {
                            // Empty the hangar
                            if (HangarwayIsClear(selectedFacility))
                            {
                                sInStorage3 = "None";
                                UnhangarCraft(vVesselStored, selectedFacility);
                                sInStorage3 = "None";
                            }
                            else
                            {
                                MiscUtils.HUDMessage("Cannot roll craft out. Clear the way first!", 10,
                                                     3);
                            }
                        }
                        break;
                    }
                }
            }

            GUILayout.Space(5);

            scrollNearbyCraft = GUILayout.BeginScrollView(scrollNearbyCraft);

            GUILayout.Box("Nearby Craft", Yellowtext);

            bool bNearbyCraft = false;

            foreach (Vessel vVessel in FlightGlobals.Vessels)
            {
                if (vVessel == null)
                {
                    continue;
                }
                if (!vVessel.loaded)
                {
                    continue;
                }
                if (vVessel.vesselType == VesselType.SpaceObject)
                {
                    continue;
                }
                if (vVessel.vesselType == VesselType.Debris)
                {
                    continue;
                }
                if (vVessel.vesselType == VesselType.EVA)
                {
                    continue;
                }
                if (vVessel.vesselType == VesselType.Flag)
                {
                    continue;
                }
                if (vVessel.vesselType == VesselType.Unknown)
                {
                    continue;
                }
                if (vVessel == FlightGlobals.ActiveVessel)
                {
                    continue;
                }
                if (vVessel.situation != Vessel.Situations.LANDED)
                {
                    continue;
                }
                if (vVessel.GetCrewCount() > 0)
                {
                    continue;
                }

                var vDistToCraft = Vector3.Distance(vVessel.gameObject.transform.position, selectedFacility.gameObject.transform.position);
                if (vDistToCraft > 250)
                {
                    continue;
                }

                bNearbyCraft = true;

                if (GUILayout.Button(" " + vVessel.vesselName + " ", ButtonSmallText, GUILayout.Height(20)))
                {
                    float fMass = vVessel.GetTotalMass();

                    if (fMass > fMaxMass)
                    {
                        MiscUtils.HUDMessage("Craft too heavy for this facility. Max " + fMaxMass.ToString("#0") + "T per craft.", 10,
                                             3);
                    }
                    else
                    {
                        float fMaxCraft = (float)selectedFacility.model.DefaultFacilityCraftCapacity;
                        if (fMaxCraft < 1 || fMaxCraft > 3)
                        {
                            fMaxCraft = 2;
                        }

                        int iNumberCraft = NumberCraftHangared(selectedFacility);

                        if (iNumberCraft < (int)fMaxCraft)
                        {
                            HangarCraft(vVessel, selectedFacility, (int)fMaxCraft);
                        }
                        else
                        {
                            MiscUtils.HUDMessage("This facility is full. Max craft: " + fMaxCraft.ToString("#0"), 10,
                                                 3);
                        }
                    }
                }
            }

            if (!bNearbyCraft)
            {
                GUILayout.Label("There are no craft close enough to store in this facility.", LabelInfo);
            }

            GUILayout.EndScrollView();

            GUILayout.FlexibleSpace();
        }
Exemple #33
0
 private void PublicOffers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
     Hangar.Debug(e.Action.ToString());
     //Plugin.Config.RefreshModel();
     //throw new NotImplementedException();
 }
        public static void CacheHangaredCraft(StaticInstance obj)
        {
            Hangar myHangar    = obj.myFacilities[0] as Hangar;
            string sInStorage  = myHangar.InStorage1;
            string sInStorage2 = myHangar.InStorage2;
            string sInStorage3 = myHangar.InStorage3;

            foreach (Vessel vVesselStored in FlightGlobals.Vessels)
            {
                if (vVesselStored == null)
                {
                    continue;
                }
                if (!vVesselStored.loaded)
                {
                    continue;
                }
                if (vVesselStored.vesselType == VesselType.SpaceObject)
                {
                    continue;
                }
                if (vVesselStored.vesselType == VesselType.Debris)
                {
                    continue;
                }
                if (vVesselStored.vesselType == VesselType.EVA)
                {
                    continue;
                }
                if (vVesselStored.vesselType == VesselType.Flag)
                {
                    continue;
                }
                if (vVesselStored.vesselType == VesselType.Unknown)
                {
                    continue;
                }

                string sHangarSpace = "None";
                // If a vessel is hangared
                if (vVesselStored.id.ToString() == sInStorage)
                {
                    sHangarSpace = "InStorage1";
                }
                if (vVesselStored.id.ToString() == sInStorage2)
                {
                    sHangarSpace = "InStorage2";
                }
                if (vVesselStored.id.ToString() == sInStorage3)
                {
                    sHangarSpace = "InStorage3";
                }

                if (sHangarSpace != "None")
                {
                    if (vVesselStored == FlightGlobals.ActiveVessel)
                    {
                        // Craft has been taken control
                        // Empty the hangar
                        typeof(Hangar).GetField(sHangarSpace).SetValue(myHangar, "None");
                    }
                    else
                    {
                        // Hide the vessel - it is in the hangar
                        if (vVesselStored != null)
                        {
                            foreach (Part p in vVesselStored.Parts)
                            {
                                if (p != null && p.gameObject != null)
                                {
                                    p.gameObject.SetActive(false);
                                }
                                else
                                {
                                    continue;
                                }
                            }

                            vVesselStored.MakeInactive();
                            vVesselStored.enabled = false;

                            if (vVesselStored.loaded)
                            {
                                vVesselStored.Unload();
                            }
                        }
                    }
                }
            }
        }