Пример #1
0
        public bool CreateServers()
        {
            //Need to attempt server
            try
            {
                Server = new SimpleTcpServer().Start(_Port);
                Hangar.Debug("Initilized Server on port: " + _Port);

                _Market.IsHostServer = true;
                Server.DataReceived += Server_DataReceived;

                //Server.DelimiterDataReceived += (sender, msg) => {
                //Console.WriteLine("From client: "+msg.MessageString);
                //CrossServerMessage RecievedData = new CrossServerMessage();
                //RecievedData.GridDefinition = Main.GridDefinition;
                //RecievedData.List = Main.GridList;
                //RecievedData.BalanceUpdate = Main.PlayerAccountUpdate;
                //msg.Reply(JsonConvert.SerializeObject(RecievedData));
                //};
            }
            catch (System.InvalidOperationException)
            {
                //Server already created, create client
                Client = new SimpleTcpClient().Connect("127.0.0.1", _Port);
                Hangar.Debug("Initilized Client on port: " + _Port);

                _Market.IsHostServer          = false;
                Client.DelimiterDataReceived += Client_DelimiterDataReceived;
            }
            catch (Exception a)
            {
                Hangar.Debug("Hangar CrossServer Network Error!", a, Hangar.ErrorType.Fatal);
                //Some weird shit
                return(false);
            }
            return(true);
        }
Пример #2
0
        public static bool TryUpdatePlayerBalance(PlayerAccount Account)
        {
            try
            {
                long IdentityID = MySession.Static.Players.TryGetIdentityId(Account.SteamID);

                if (IdentityID == 0)
                {
                    return(false);
                }


                if (Account.AccountAdjustment)
                {
                    MyBankingSystem.ChangeBalance(IdentityID, Account.AccountBalance);
                    return(true);
                }


                long OriginalBalance = MyBankingSystem.GetBalance(IdentityID);
                long BalanceAdjuster = Account.AccountBalance - OriginalBalance;

                if (BalanceAdjuster == 0)
                {
                    return(true);
                }

                MyBankingSystem.ChangeBalance(IdentityID, BalanceAdjuster);
                Hangar.Debug("Player " + IdentityID + " account has been updated! ");

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Пример #3
0
        public static void FormatGridName(PlayerInfo Data, Result result)
        {
            Hangar.Debug("F");

            try
            {
                string GridName = FileSaver.CheckInvalidCharacters(result.biggestGrid.DisplayName);
                result.GridName = GridName;
                if (Data.Grids.Any(x => x.GridName.Equals(GridName, StringComparison.OrdinalIgnoreCase)))
                {
                    //There is already a grid with that name!
                    bool NameCheckDone = false;
                    int  a             = 0;
                    while (!NameCheckDone)
                    {
                        a++;
                        if (!Data.Grids.Any(x => x.GridName.Equals(GridName + " [" + a + "]", StringComparison.OrdinalIgnoreCase)))
                        {
                            NameCheckDone = true;
                            break;
                        }
                    }
                    //Main.Debug("Saving grid name: " + GridName);
                    GridName = GridName + "[" + a + "]";
                    result.grids[0].DisplayName    = GridName;
                    result.biggestGrid.DisplayName = GridName;
                    result.GridName = GridName;
                }
            }
            catch (Exception e)
            {
                Hangar.Debug("eeerror", e);
            }

            Hangar.Debug("G");
        }
Пример #4
0
        private bool BeginAlignToGravity(MyObjectBuilder_CubeGrid[] AllGrids, Vector3D position, Vector3D direction, Vector3D vector3D)
        {
            //Create WorldMatrix
            MatrixD worldMatrix = MatrixD.CreateWorld(position, direction, vector3D);

            int     num    = 0;
            MatrixD matrix = MatrixD.Identity;

            //Find biggest grid and get their postion matrix
            Parallel.For(0, AllGrids.Length, i =>
            {
                //Option to clone the BP
                //array[i] = (MyObjectBuilder_CubeGrid)TotalGrids[i].Clone();
                if (AllGrids[i].CubeBlocks.Count > num)
                {
                    num    = AllGrids[i].CubeBlocks.Count;
                    matrix = (AllGrids[i].PositionAndOrientation.HasValue ? AllGrids[i].PositionAndOrientation.Value.GetMatrix() : MatrixD.Identity);
                }
            });

            MatrixD matrix2;


            //Align to Main/Biggest grid
            Vector3D value = Vector3D.Zero;

            if (AllGrids[0].PositionAndOrientation.HasValue)
            {
                value = AllGrids[0].PositionAndOrientation.Value.Position;
            }
            matrix2 = MatrixD.CreateWorld(-value, direction, vector3D);


            //Huh? (Keen does this so i guess i will too) My guess so it can create large entities
            MyEntities.IgnoreMemoryLimits = true;

            //Update each grid in the array
            Parallel.For(0, AllGrids.Length, j =>
            {
                MatrixD newWorldMatrix;

                if (AllGrids[j].PositionAndOrientation.HasValue)
                {
                    MatrixD matrix3 = AllGrids[j].PositionAndOrientation.Value.GetMatrix() * MatrixD.Invert(matrix);
                    newWorldMatrix  = matrix3 * worldMatrix;
                    AllGrids[j].PositionAndOrientation = new MyPositionAndOrientation(newWorldMatrix);
                }
                else
                {
                    newWorldMatrix = worldMatrix;
                    AllGrids[j].PositionAndOrientation = new MyPositionAndOrientation(worldMatrix);
                }
            });


            /* Where do we want to paste the grids? Lets find out. based from the character/position */
            var pos = FindPastePosition(AllGrids, position);

            if (pos == null)
            {
                Hangar.Debug("No free Space found!");


                chat.Respond("No free space available!");

                return(false);
            }

            var newPosition = pos.Value;

            /* Update GridsPosition via xyz. (We already have the orientation correct) if that doesnt work get out of here. */
            if (!UpdateGridsPosition(AllGrids, newPosition))
            {
                chat.Respond("The File to be imported does not seem to be compatible with the server!");

                return(false);
            }


            //Remap to prevent bad stuff
            MyEntities.RemapObjectBuilderCollection(AllGrids);

            //Use Rexxars spciy spaghetti code for parallel spawning of ALL grids
            ParallelSpawner spawner = new ParallelSpawner(AllGrids);

            spawner.Start();

            //Return completeted
            return(true);
        }
Пример #5
0
        private bool CalculateGridPosition()
        {
            List <MyObjectBuilder_CubeGrid> TotalGrids = new List <MyObjectBuilder_CubeGrid>();
            List <MyObjectBuilder_Cockpit>  cockpits   = new List <MyObjectBuilder_Cockpit>();
            Vector3D direction = _PlayerPosition;



            //Get all cockpit blkocks on the grid
            foreach (var shipBlueprint in _ShipBlueprints)
            {
                TotalGrids.AddRange(shipBlueprint.CubeGrids.ToList());
                foreach (MyObjectBuilder_CubeGrid grid in shipBlueprint.CubeGrids)
                {
                    cockpits.AddRange(grid.CubeBlocks.OfType <MyObjectBuilder_Cockpit>().ToList());
                }
            }

            MyObjectBuilder_CubeGrid[] array = TotalGrids.ToArray();
            if (array.Length == 0)
            {
                //Simple grid/objectbuilder null check. If there are no gridys then why continue?
                return(false);
            }
            Hangar.Debug("Total Grids to be pasted: " + array.Count());

            if (cockpits.Count > 0)
            {
                //Main.Debug("Cockpits found!");
                foreach (MyObjectBuilder_Cockpit Block in cockpits)
                {
                    if (Block.IsMainCockpit)
                    {
                        Hangar.Debug("Main cockpit found! Attempting to Align!");
                        direction = new Vector3D(Block.Orientation.x, Block.Orientation.y, Block.Orientation.z);
                        break;
                    }
                }
            }
            else
            {
                Hangar.Debug("No Cockpits. Continuing based off of grid pivot point!");
            }


            //Attempt to get gravity/Artificial gravity to align the grids to
            Vector3D position = _PlayerPosition;

            //Here you can adjust the offset from the surface and rotation.
            //Unfortunatley we move the grid again after this to find a free space around the character. Perhaps later i can incorporate that into
            //LordTylus's existing grid checkplament method
            float gravityOffset   = 0f;
            float gravityRotation = 0f;

            Vector3 vector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(position);

            if (vector == Vector3.Zero)
            {
                vector = MyGravityProviderSystem.CalculateArtificialGravityInPoint(position);
            }
            Vector3D vector3D;

            if (vector != Vector3.Zero)
            {
                Hangar.Debug("Attempting to correct grid orientation!");
                vector.Normalize();
                vector3D  = -vector;
                position += vector * gravityOffset;
                if (direction == Vector3D.Zero)
                {
                    direction = Vector3D.CalculatePerpendicularVector(vector);
                    if (gravityRotation != 0f)
                    {
                        MatrixD matrixa = MatrixD.CreateFromAxisAngle(vector3D, gravityRotation);
                        direction = Vector3D.Transform(direction, matrixa);
                    }
                }
            }
            else if (direction == Vector3D.Zero)
            {
                direction = Vector3D.Right;
                vector3D  = Vector3D.Up;
            }
            else
            {
                vector3D = Vector3D.CalculatePerpendicularVector(-direction);
            }


            return(BeginAlignToGravity(array, position, direction, vector3D));
        }
Пример #6
0
        public bool SaveGrids(List <MyCubeGrid> grids, string GridName, Hangar Plugin)
        {
            List <MyObjectBuilder_CubeGrid> objectBuilders = new List <MyObjectBuilder_CubeGrid>();

            foreach (MyCubeGrid grid in grids)
            {
                /* Remove characters from cockpits */

                Action P = delegate
                {
                    foreach (var blck in grid.GetFatBlocks().OfType <MyCockpit>())
                    {
                        if (blck.Pilot != null)
                        {
                            blck.RemovePilot();
                        }
                    }
                };

                Task KickPlayers = GameEvents.InvokeActionAsync(P);
                KickPlayers.Wait(5000);



                /* What else should it be? LOL? */
                if (!(grid.GetObjectBuilder() is MyObjectBuilder_CubeGrid objectBuilder))
                {
                    throw new ArgumentException(grid + " has a ObjectBuilder thats not for a CubeGrid");
                }

                objectBuilders.Add(objectBuilder);
            }



            try
            {
                //Need To check grid name

                string GridSavePath = Path.Combine(FolderPath, GridName + ".sbc");

                //Log.Info("SavedDir: " + pathForPlayer);
                bool saved = SaveGridToFile(GridSavePath, GridName, objectBuilders);

                try
                {
                    MyIdentity IDentity = MySession.Static.Players.TryGetPlayerIdentity(new MyPlayer.PlayerId(SteamID));

                    if (Plugin.GridBackup != null)
                    {
                        Plugin.GridBackup.GetType().GetMethod("BackupGridsManuallyWithBuilders", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new Type[2] {
                            typeof(List <MyObjectBuilder_CubeGrid>), typeof(long)
                        }, null).Invoke(Plugin.GridBackup, new object[] { objectBuilders, IDentity.IdentityId });
                        Log.Warn("Successfully BackedUp grid!");
                    }
                }
                catch (Exception e)
                {
                    Log.Fatal(e);
                }

                if (saved)
                {
                    DisposeGrids(grids);
                }


                return(saved);
            }
            catch (Exception e)
            {
                Hangar.Debug("Saving Grid Failed!", e, Hangar.ErrorType.Fatal);
                return(false);
            }
        }
Пример #7
0
        private bool LoadShipBlueprint(MyObjectBuilder_ShipBlueprintDefinition shipBlueprint, Vector3D GridSaveLocation, Vector3D PlayerLocation, bool keepOriginalLocation, Chat chat, Hangar Plugin, bool force = false)
        {
            var grids = shipBlueprint.CubeGrids;

            if (grids == null || grids.Length == 0)
            {
                chat.Respond("No grids in blueprint!");
                return(false);
            }

            try
            {
                MyIdentity IDentity = MySession.Static.Players.TryGetPlayerIdentity(new MyPlayer.PlayerId(SteamID));

                if (Plugin.GridBackup != null)
                {
                    Plugin.GridBackup.GetType().GetMethod("BackupGridsManuallyWithBuilders", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new Type[2] {
                        typeof(List <MyObjectBuilder_CubeGrid>), typeof(long)
                    }, null).Invoke(Plugin.GridBackup, new object[] { grids.ToList(), IDentity.IdentityId });
                    Log.Warn("Successfully BackedUp grid!");
                }
            }
            catch (Exception e)
            {
                Log.Fatal(e);
            }

            Vector3D TargetLocation;
            bool     AlignToGravity = false;

            if (keepOriginalLocation)
            {
                TargetLocation = GridSaveLocation;
            }
            else
            {
                AlignToGravity = true;
                TargetLocation = PlayerLocation;
            }

            ParallelSpawner Spawner = new ParallelSpawner(grids, chat, AlignToGravity);

            Log.Info("Attempting Grid Spawning @" + TargetLocation.ToString());
            return(Spawner.Start(keepOriginalLocation, TargetLocation));
        }
Пример #8
0
        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))
                {
                    var shipBlueprints = myObjectBuilder_Definitions.ShipBlueprints;


                    if (shipBlueprints == null)
                    {
                        Hangar.Debug("No ShipBlueprints in File '" + path + "'");
                        chat.Respond("There arent any Grids in your file to import!");
                        return(false);
                    }

                    if (!HangarChecker.BlockLimitChecker(shipBlueprints))
                    {
                        Hangar.Debug("Block Limiter Checker Failed");
                        return(false);
                    }

                    if (Config.OnLoadTransfer)
                    {
                        Log.Warn("Target player: " + 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;
                                }
                            }
                        }
                    }

                    //If the configs have keep originial position on, we dont want to align this to gravity.

                    foreach (var shipBlueprint in shipBlueprints)
                    {
                        Vector3D TargetSpawnPos = Vector3D.Zero;
                        if (Player != null)
                        {
                            TargetSpawnPos = Player.PositionComp.GetPosition();
                        }


                        if (!LoadShipBlueprint(shipBlueprint, GridSaveLocation, TargetSpawnPos, keepOriginalLocation, chat, Plugin))
                        {
                            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);
        }
Пример #9
0
        private bool CalculateGridPosition()
        {
            List <MyObjectBuilder_CubeGrid> TotalGrids = new List <MyObjectBuilder_CubeGrid>();
            List <MyObjectBuilder_Cockpit>  cockpits   = new List <MyObjectBuilder_Cockpit>();
            Vector3D forwardVector = Vector3D.Zero;



            //Get all cockpit blkocks on the grid
            foreach (var shipBlueprint in _ShipBlueprints)
            {
                TotalGrids.AddRange(shipBlueprint.CubeGrids.ToList());
            }

            MyObjectBuilder_CubeGrid[] array = TotalGrids.ToArray();
            if (array.Length == 0)
            {
                //Simple grid/objectbuilder null check. If there are no gridys then why continue?
                return(false);
            }
            Hangar.Debug("Total Grids to be pasted: " + array.Count());

            //Attempt to get gravity/Artificial gravity to align the grids to
            Vector3D position = _PlayerPosition;

            //Here you can adjust the offset from the surface and rotation.
            //Unfortunatley we move the grid again after this to find a free space around the character. Perhaps later i can incorporate that into
            //LordTylus's existing grid checkplament method
            float gravityOffset   = 0f;
            float gravityRotation = 0f;

            Vector3 gravityDirectionalVector = MyGravityProviderSystem.CalculateNaturalGravityInPoint(position);

            if (gravityDirectionalVector == Vector3.Zero)
            {
                gravityDirectionalVector = MyGravityProviderSystem.CalculateArtificialGravityInPoint(position);
            }
            Vector3D upDirectionalVector;

            if (gravityDirectionalVector != Vector3.Zero)
            {
                Hangar.Debug("Attempting to correct grid orientation!");
                gravityDirectionalVector.Normalize();
                upDirectionalVector = -gravityDirectionalVector;
                position           += gravityDirectionalVector * gravityOffset;
                if (forwardVector == Vector3D.Zero)
                {
                    forwardVector = Vector3D.CalculatePerpendicularVector(gravityDirectionalVector);
                    if (gravityRotation != 0f)
                    {
                        MatrixD matrixa = MatrixD.CreateFromAxisAngle(upDirectionalVector, gravityRotation);
                        forwardVector = Vector3D.Transform(forwardVector, matrixa);
                    }
                }
            }
            else if (forwardVector == Vector3D.Zero)
            {
                forwardVector       = Vector3D.Right;
                upDirectionalVector = Vector3D.Up;
            }
            else
            {
                upDirectionalVector = Vector3D.CalculatePerpendicularVector(-forwardVector);
            }

            return(BeginAlignToGravity(array, forwardVector, upDirectionalVector));
        }
Пример #10
0
        private bool CalculateSafePositionAndSpawn(bool keepOriginalLocation, Vector3D Target)
        {
            //This has to be ran on the main game thread!
            if (keepOriginalLocation)
            {
                var BoundingBox = FindBoundingBox(_grids);



                //sphere.Center = Target;
                List <MyEntity> entities = new List <MyEntity>();
                MyGamePruningStructure.GetAllEntitiesInOBB(ref BoundingBox, entities);


                Hangar.Debug(BoundingBox.ToString());

                Hangar.Debug(entities.Count.ToString());
                bool PotentialGrids = false;
                foreach (var entity in entities)
                {
                    if (entity is MyCubeGrid)
                    {
                        PotentialGrids = true;

                        BoundingBox     Box  = entity.PositionComp.LocalAABB;
                        ContainmentType Type = BoundingBox.Contains(ref Box);

                        Hangar.Debug(entity.DisplayName + " is intersecting spawn area! Containment Type: " + Type.ToString());


                        _Response.Respond("There are potentially other grids in the way. Attempting to spawn around the location to avoid collisions.");
                        break;
                    }
                }


                if (PotentialGrids)
                {
                    var pos = FindPastePosition(Target);
                    if (!pos.HasValue)
                    {
                        _Response.Respond("No free spawning zone found! Stopping load!");
                        return(false);
                    }

                    UpdateGridsPosition(pos.Value);
                    return(true);
                }
                else
                {
                    return(true);
                }
            }


            //Everything else is loading for near point
            if (!keepOriginalLocation)
            {
                /* Where do we want to paste the grids? Lets find out. */
                var pos = FindPastePosition(Target);
                if (pos == null)
                {
                    _Response.Respond("No free spawning zone found! Stopping load!");
                    return(false);
                }

                var newPosition = pos.Value;

                /* Update GridsPosition if that doesnt work get out of here. */
                if (!UpdateGridsPosition(newPosition))
                {
                    _Response.Respond("The File to be imported does not seem to be compatible with the server!");
                    return(false);
                }
            }
            return(true);
        }
Пример #11
0
        private bool LoadShipBlueprint(MyObjectBuilder_ShipBlueprintDefinition shipBlueprint,
                                       Vector3D playerPosition, bool keepOriginalLocation, Chat chat, bool force = false)
        {
            var grids = shipBlueprint.CubeGrids;

            if (grids == null || grids.Length == 0)
            {
                Hangar.Debug("No grids in blueprint!");
                chat.Respond("No grids in blueprint!");

                return(false);
            }


            bool LoadNearPosition = false;
            //For loading in the same location

            ParallelSpawner Spawner  = new ParallelSpawner(grids);
            var             position = grids[0].PositionAndOrientation.Value;

            if (keepOriginalLocation)
            {
                var sphere = FindBoundingSphere(grids);



                sphere.Center = position.Position;

                List <MyEntity> entities = new List <MyEntity>();
                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref sphere, entities);

                foreach (var entity in entities)
                {
                    if (entity is MyCubeGrid)
                    {
                        chat.Respond("There are potentially other grids in the way. Loading near the original point.");

                        LoadNearPosition = true;
                    }
                }

                if (!LoadNearPosition)
                {
                    /* Remapping to prevent any key problems upon paste. */
                    MyEntities.RemapObjectBuilderCollection(grids);

                    Spawner.Start();

                    return(true);
                }
            }



            /*
             *  Everything else is loading for near player
             *
             *
             *
             */



            /* Where do we want to paste the grids? Lets find out. */
            var pos = FindPastePosition(grids, position.Position);

            if (pos == null)
            {
                Hangar.Debug("No free Space found!");
                chat.Respond("No free space available!");

                return(false);
            }

            var newPosition = pos.Value;

            /* Update GridsPosition if that doesnt work get out of here. */
            if (!UpdateGridsPosition(grids, newPosition))
            {
                chat.Respond("The File to be imported does not seem to be compatible with the server!");

                return(false);
            }


            MyEntities.RemapObjectBuilderCollection(grids);
            Spawner.Start();
            return(true);
        }
Пример #12
0
        public bool LoadGrid(string GridName, MyCharacter Player, long TargetPlayerID, bool keepOriginalLocation, Chat chat, bool force = 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);
            }


            if (MyObjectBuilderSerializer.DeserializeXML(path, out MyObjectBuilder_Definitions myObjectBuilder_Definitions))
            {
                var shipBlueprints = myObjectBuilder_Definitions.ShipBlueprints;


                if (shipBlueprints == null)
                {
                    Hangar.Debug("No ShipBlueprints in File '" + path + "'");
                    chat.Respond("There arent any Grids in your file to import!");
                    return(false);
                }

                if (!HangarChecker.BlockLimitChecker(shipBlueprints))
                {
                    Hangar.Debug("Block Limiter Checker Failed");
                    return(false);
                }



                if (Config.OnLoadTransfer)
                {
                    Log.Warn("Target player: " + 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;
                            }
                        }
                    }
                }



                if (keepOriginalLocation)
                {
                    foreach (var shipBlueprint in shipBlueprints)
                    {
                        if (!LoadShipBlueprint(shipBlueprint, Player.PositionComp.GetPosition(), true, chat))
                        {
                            Hangar.Debug("Error Loading ShipBlueprints from File '" + path + "'");
                            return(false);
                        }
                    }
                    File.Move(path, path + ".bak");
                    //File.Delete(path);
                    return(true);
                }
                else
                {
                    Hangar.Debug("Attempting to align grid to gravity!");
                    AlignToGravity GravityAligner = new AlignToGravity(shipBlueprints, Player.PositionComp.GetPosition(), chat);


                    if (GravityAligner.Start())
                    {
                        File.Move(path, Path.Combine(FolderPath, GridName + ".bak"));
                        //File.Delete(path);
                        return(true);
                    }
                }
            }

            return(false);
        }
Пример #13
0
        //Force update
        public bool Update(CrossServerMessage Message)
        {
            if (_Market.IsHostServer)
            {
                string MarketServerData = JsonConvert.SerializeObject(Message);
                //Write to file and broadcast to all clients!
                Hangar.Debug("Sending new market data to clients! " + Message.Type.ToString());
                if (Message.Type == MessageType.AddItem)
                {
                    //Main.Debug("Point1");
                    Server.BroadcastLine(MarketServerData);
                    //Main.Debug("Point2");
                    //Update server.
                    GridMarket.GridList.Add(Message.List[0]);
                    //Main.GridDefinition.Add(Message.GridDefinition[0]);


                    //Send update to clients on this game server!
                    Comms.AddSingleItem(Message.List[0]);
                    //Main.Debug("Point3");

                    //Save data to file (This is server!)
                    MarketData Data = new MarketData();
                    Data.List = GridMarket.GridList;
                    FileSaver.Save(Path.Combine(Hangar.Dir, "Market.json"), Data);
                }
                else if (Message.Type == MessageType.RemoveItem)
                {
                    Server.BroadcastLine(MarketServerData);

                    //Update server.
                    GridMarket.GridList.Remove(Message.List[0]);
                    //Main.GridDefinition.RemoveAll(Message.GridDefinition[0]);
                    //Main.GridDefinition.RemoveAll(x => x.name == Message.List[0].Name);

                    //Send update to clients on this game server!
                    Comms.RemoveSingleItem(Message.List[0]);


                    //Save data to file (This is server!)
                    MarketData Data = new MarketData();
                    Data.List = GridMarket.GridList;
                    FileSaver.Save(Path.Combine(Hangar.Dir, "Market.json"), Data);
                }
                else if (Message.Type == MessageType.PlayerAccountUpdated)
                {
                    //Do nothing. (Send data to server and wait for reply)

                    Server.BroadcastLine(MarketServerData);


                    foreach (PlayerAccount account in Message.BalanceUpdate)
                    {
                        Utils.TryUpdatePlayerBalance(account);

                        if (!GridMarket.PlayerAccounts.ContainsKey(account.SteamID))
                        {
                            if (!account.AccountAdjustment)
                            {
                                GridMarket.PlayerAccounts.Add(account.SteamID, account.AccountBalance);
                            }
                        }
                        else
                        {
                            if (!account.AccountAdjustment)
                            {
                                GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance;
                            }
                            else
                            {
                                //Add this to the general list
                                GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance + GridMarket.PlayerAccounts[account.SteamID];
                            }
                        }
                    }

                    Accounts accounts = new Accounts();
                    accounts.PlayerAccounts = GridMarket.PlayerAccounts;

                    FileSaver.Save(Path.Combine(Hangar.Dir, "PlayerAccounts.json"), accounts);
                }
                else if (Message.Type == MessageType.PlayerOnline)
                {
                    //Server found the player online! (By Joining)
                    //var first = Message.BalanceUpdate.First();
                    //ulong key = first.Key;


                    // Main.PlayerAccountUpdate.Remove(key);

                    //Broadcast to all clients!
                    Server.BroadcastLine(MarketServerData);
                }
                else if (Message.Type == MessageType.PurchasedGrid)
                {
                    var t = Task.Run(() => _Market.PurchaseGrid(Message.GridDefinition[0]));
                }
                //File.WriteAllText(Path.Combine(Main.Dir, "Market.json"), JsonConvert.SerializeObject(Data));
            }
            else
            {
                try
                {
                    string MarketClientData = JsonConvert.SerializeObject(Message);
                    //Send to server to get reply
                    Client.Write(MarketClientData);

                    if (Message.Type == MessageType.AddItem)
                    {
                        //Send update to clients on this game server!
                        Comms.AddSingleItem(Message.List[0]);
                    }
                    else if (Message.Type == MessageType.RemoveItem)
                    {
                        //Send update to clients on this game server!
                        Comms.RemoveSingleItem(Message.List[0]);
                    }
                }
                catch (System.IO.IOException e)
                {
                    //Server no longer responding? Perhaps it shutdown? Or restarted?
                    //This means THIS server needs to be the new server

                    //Or this is an old client needing to be re-connected to server. This means we need to redo/Reconnect everything!
                    Hangar.Debug("Server closed! Trying to Update!", e, Hangar.ErrorType.Warn);
                    //Remove client DataRecieved Event!
                    Client.DelimiterDataReceived -= Client_DelimiterDataReceived;

                    //Re run create servers and client class!
                    CreateServers();

                    //Re run the update
                    Update(Message);
                }
                catch (Exception g)
                {
                    Hangar.Debug("CrossServer Market Network Failed Fatally!", g, Hangar.ErrorType.Fatal);
                }
            }


            return(true);
        }
Пример #14
0
        //Client data recieved
        private void Client_DelimiterDataReceived(object sender, SimpleTCP.Message e)
        {
            //if we recieve data as client we need to update the market list from the one that the server sent
            try
            {
                //e.MessageString.TrimEnd(e.MessageString[e.MessageString.Length-1]);
                CrossServerMessage RecievedData = JsonConvert.DeserializeObject <CrossServerMessage>(e.MessageString);
                Hangar.Debug("Server Data Recieved! " + RecievedData.Type.ToString());

                if (RecievedData.Type == MessageType.AddItem)
                {
                    if (!GridMarket.GridList.Contains(RecievedData.List[0]))
                    {
                        //If its not already in the list, add it.
                        GridMarket.GridList.Add(RecievedData.List[0]);
                        //Main.GridDefinition.Add(RecievedData.GridDefinition[0]);

                        //Send update to clients on this game server!
                        Comms.AddSingleItem(RecievedData.List[0]);
                    }
                }
                else if (RecievedData.Type == MessageType.RemoveItem)
                {
                    if (GridMarket.GridList.Any(x => x.Name == RecievedData.List[0].Name))
                    {
                        Hangar.Debug("Removing: " + RecievedData.List[0].Name + " from market!");
                        GridMarket.GridList.RemoveAll(x => x.Name == RecievedData.List[0].Name);
                        //Main.GridDefinition.RemoveAll(x => x.name == RecievedData.List[0].Name);

                        //Send update to clients on this game server!
                        Comms.RemoveSingleItem(RecievedData.List[0]);
                    }
                }
                else if (RecievedData.Type == MessageType.PlayerAccountUpdated)
                {
                    foreach (PlayerAccount account in RecievedData.BalanceUpdate)
                    {
                        Utils.TryUpdatePlayerBalance(account);

                        if (!GridMarket.PlayerAccounts.ContainsKey(account.SteamID))
                        {
                            if (!account.AccountAdjustment)
                            {
                                GridMarket.PlayerAccounts.Add(account.SteamID, account.AccountBalance);
                            }
                        }
                        else
                        {
                            if (!account.AccountAdjustment)
                            {
                                GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance;
                            }
                            else
                            {
                                //Add this to the general list
                                GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance + GridMarket.PlayerAccounts[account.SteamID];
                            }
                        }
                    }
                }
                else if (RecievedData.Type == MessageType.PlayerOnline)
                {
                    //Player was online somewhere!
                    //var first = RecievedData.BalanceUpdate.First();
                    //ulong key = first.Key;

                    //Main.PlayerAccountUpdate.Remove(key);
                }
                else if (RecievedData.Type == MessageType.RequestAll && !RecievedInitialRequest)
                {
                    //Update everything! (New Server started!)
                    //Main.GridDefinition = RecievedData.GridDefinition;
                    GridMarket.GridList = RecievedData.List;
                    //Main.PlayerAccountUpdate = RecievedData.BalanceUpdate;
                    RecievedInitialRequest = true;
                }
                else if (RecievedData.Type == MessageType.PurchasedGrid)
                {
                    var t = Task.Run(() => _Market.PurchaseGrid(RecievedData.GridDefinition[0]));
                }

                MarketData Data = new MarketData();
                //Data.GridDefinition = Main.GridDefinition;
                Data.List = GridMarket.GridList;

                //Save
                //FileSaver.Save(Path.Combine(Main.Dir, "Market.json"), Data);
                //File.WriteAllText(Path.Combine(Main.Dir, "Market.json"), JsonConvert.SerializeObject(Data));
            }
            catch (Exception c)
            {
                Hangar.Debug("Client DeserializeObject Error! ", c, Hangar.ErrorType.Fatal);
            }
            //throw new NotImplementedException();
        }
Пример #15
0
        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            //if we recieve data to server, this means we need to update clients, and save file to disk
            CrossServerMessage RecievedData = JsonConvert.DeserializeObject <CrossServerMessage>(e.MessageString);

            Hangar.Debug("Client Data Recieved! " + RecievedData.Type.ToString());



            if (RecievedData.Type == MessageType.AddItem)
            {
                Server.BroadcastLine(e.MessageString);

                //Now that we added our items... we need to save file
                //Main.GridDefinition.Add(RecievedData.GridDefinition[0]);
                GridMarket.GridList.Add(RecievedData.List[0]);


                //Send update to clients on this game server!
                Comms.AddSingleItem(RecievedData.List[0]);

                //Save data to file (This is server!)
                MarketData Data = new MarketData();
                Data.List = GridMarket.GridList;
                FileSaver.Save(Path.Combine(Hangar.Dir, "Market.json"), Data);
            }
            else if (RecievedData.Type == MessageType.RemoveItem)
            {
                Server.BroadcastLine(e.MessageString);

                //Just goahead and check to see if the list contains etc.
                if (GridMarket.GridList.Any(x => x.Name == RecievedData.List[0].Name))
                {
                    Hangar.Debug("Removing: " + RecievedData.List[0].Name + " from market!");
                    GridMarket.GridList.RemoveAll(x => x.Name == RecievedData.List[0].Name);
                    //Main.GridDefinition.RemoveAll(x => x.name == RecievedData.List[0].Name);

                    //Send update to clients on this game server!
                    Comms.RemoveSingleItem(RecievedData.List[0]);
                }

                //Save data to file (This is server!)
                MarketData Data = new MarketData();
                Data.List = GridMarket.GridList;
                FileSaver.Save(Path.Combine(Hangar.Dir, "Market.json"), Data);
            }
            else if (RecievedData.Type == MessageType.PlayerAccountUpdated)
            {
                Server.BroadcastLine(e.MessageString);


                //Store values
                foreach (PlayerAccount account in RecievedData.BalanceUpdate)
                {
                    Utils.TryUpdatePlayerBalance(account);

                    if (!GridMarket.PlayerAccounts.ContainsKey(account.SteamID))
                    {
                        if (!account.AccountAdjustment)
                        {
                            GridMarket.PlayerAccounts.Add(account.SteamID, account.AccountBalance);
                        }
                    }
                    else
                    {
                        if (!account.AccountAdjustment)
                        {
                            GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance;
                        }
                        else
                        {
                            //Add this to the general list
                            GridMarket.PlayerAccounts[account.SteamID] = account.AccountBalance + GridMarket.PlayerAccounts[account.SteamID];
                        }
                    }
                }

                Accounts accounts = new Accounts();
                accounts.PlayerAccounts = GridMarket.PlayerAccounts;

                try
                {
                    FileSaver.Save(Path.Combine(Hangar.Dir, "PlayerAccounts.json"), accounts);
                    //File.WriteAllText(Path.Combine(Main.Dir, "PlayerAccounts.json"), JsonConvert.SerializeObject(accounts));
                }
                catch (Exception a)
                {
                    Hangar.Debug("IO Exception!", a, Hangar.ErrorType.Warn);
                }



                /*
                 * //Need to check to see if the player is online!
                 * //var first = RecievedData.BalanceUpdate.First();
                 * //ulong key = first.Key;
                 * //long val = first.Value;
                 *
                 *
                 *
                 * List<IMyPlayer> Seller = new List<IMyPlayer>();
                 * //MyAPIGateway.Players.GetPlayers(Seller, x => x.SteamUserId == Item.Steamid);
                 * MyAPIGateway.Players.GetPlayers(Seller, x => x.SteamUserId == key);
                 *
                 * if (Seller.Count == 1)
                 * {
                 *  //Player is online! Attempt to change player balance!
                 *  Seller[0].RequestChangeBalance(val);
                 *
                 *  //Send message to server that play is online!
                 *  CrossServerMessage PlayerOnlineMessage = new CrossServerMessage();
                 *  PlayerOnlineMessage.Type = CrossServer.MessageType.PlayerOnline;
                 *  //PlayerOnlineMessage.BalanceUpdate.Add(key, val);
                 *
                 *  Update(PlayerOnlineMessage);
                 * }
                 * else
                 * {
                 *  //Player is offline. Check to see if this server already has the player! (Remove and add new!)
                 *  if (Main.PlayerAccountUpdate.ContainsKey(key))
                 *  {
                 *      //Remove old Key
                 *      Main.PlayerAccountUpdate.Remove(key);
                 *  }
                 *
                 *  Main.PlayerAccountUpdate.Add(key, val);
                 *
                 *  Server.BroadcastLine(e.MessageString);
                 * }
                 */
            }
            else if (RecievedData.Type == MessageType.RequestAll)
            {
                CrossServerMessage AllData = new CrossServerMessage();
                //AllData.GridDefinition = Main.GridDefinition;
                AllData.List = GridMarket.GridList;
                //AllData.BalanceUpdate = Main.PlayerAccounts;
                AllData.Type = MessageType.RequestAll;

                string AllDataString = JsonConvert.SerializeObject(AllData);

                Server.BroadcastLine(AllDataString);
            }



            //File.WriteAllText(Path.Combine(Main.Dir, "Market.json"), FileData);


            //throw new NotImplementedException();
        }
Пример #16
0
        private bool LoadShipBlueprint(MyObjectBuilder_ShipBlueprintDefinition shipBlueprint,
                                       Vector3D playerPosition, bool keepOriginalLocation, Chat chat, Hangar Plugin, bool force = false)
        {
            var grids = shipBlueprint.CubeGrids;

            if (grids == null || grids.Length == 0)
            {
                Hangar.Debug("No grids in blueprint!");
                chat.Respond("No grids in blueprint!");

                return(false);
            }

            try
            {
                MyIdentity IDentity = MySession.Static.Players.TryGetPlayerIdentity(new MyPlayer.PlayerId(SteamID));

                if (Plugin.GridBackup != null)
                {
                    Plugin.GridBackup.GetType().GetMethod("BackupGridsManuallyWithBuilders", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, null, new Type[2] {
                        typeof(List <MyObjectBuilder_CubeGrid>), typeof(long)
                    }, null).Invoke(Plugin.GridBackup, new object[] { grids.ToList(), IDentity.IdentityId });
                    Log.Warn("Successfully BackedUp grid!");
                }
            }
            catch (Exception e)
            {
                Log.Fatal(e);
            }


            bool LoadNearPosition = false;
            //For loading in the same location

            ParallelSpawner Spawner  = new ParallelSpawner(grids);
            var             position = grids[0].PositionAndOrientation.Value;

            if (keepOriginalLocation)
            {
                var sphere = FindBoundingSphere(grids);



                sphere.Center = position.Position;

                List <MyEntity> entities = new List <MyEntity>();
                MyGamePruningStructure.GetAllTopMostEntitiesInSphere(ref sphere, entities);

                foreach (var entity in entities)
                {
                    if (entity is MyCubeGrid)
                    {
                        chat.Respond("There are potentially other grids in the way. Loading near the original point.");

                        LoadNearPosition = true;
                    }
                }

                if (!LoadNearPosition)
                {
                    /* Remapping to prevent any key problems upon paste. */
                    MyEntities.RemapObjectBuilderCollection(grids);

                    Spawner.Start();

                    return(true);
                }
            }



            /*
             *  Everything else is loading for near player
             *
             *
             *
             */



            /* Where do we want to paste the grids? Lets find out. */
            var pos = FindPastePosition(grids, position.Position);

            if (pos == null)
            {
                Hangar.Debug("No free Space found!");
                chat.Respond("No free space available!");

                return(false);
            }

            var newPosition = pos.Value;

            /* Update GridsPosition if that doesnt work get out of here. */
            if (!UpdateGridsPosition(grids, newPosition))
            {
                chat.Respond("The File to be imported does not seem to be compatible with the server!");

                return(false);
            }


            MyEntities.RemapObjectBuilderCollection(grids);
            Spawner.Start();
            return(true);
        }