Пример #1
0
        public static MyObjectBuilder_Definitions LoadWorkshopPrefab(string archive, ulong?publishedItemId)
        {
            if (!File.Exists(archive) || publishedItemId == null)
            {
                return(null);
            }
            var subItem = MyGuiBlueprintScreen.m_subscribedItemsList.Find(item => item.PublishedFileId == publishedItemId);

            if (subItem == null)
            {
                return(null);
            }

            var extracted = MyZipArchive.OpenOnFile(archive);
            var stream    = extracted.GetFile("bp.sbc").GetStream();

            if (stream == null)
            {
                return(null);
            }

            MyObjectBuilder_Definitions objectBuilder = null;
            var success = MyObjectBuilderSerializer.DeserializeXML(stream, out objectBuilder);

            stream.Close();
            extracted.Dispose();

            if (success)
            {
                objectBuilder.ShipBlueprints[0].Description = subItem.Description;
                objectBuilder.ShipBlueprints[0].CubeGrids[0].DisplayName = subItem.Title;
                return(objectBuilder);
            }
            return(null);
        }
 private static bool TryGetGridsFromDefinition(MyObjectBuilder_Definitions Definition, out IEnumerable <MyObjectBuilder_CubeGrid> Grids)
 {
     //Should be able to load shipdef and prefabs that people load/drag in
     Grids = new List <MyObjectBuilder_CubeGrid>();
     if (Definition.Prefabs != null && Definition.Prefabs.Count() != 0)
     {
         foreach (var prefab in Definition.Prefabs)
         {
             Grids = Grids.Concat(prefab.CubeGrids);
         }
         return(true);
     }
     else if (Definition.ShipBlueprints != null && Definition.ShipBlueprints.Count() != 0)
     {
         foreach (var shipBlueprint in Definition.ShipBlueprints)
         {
             Grids = Grids.Concat(shipBlueprint.CubeGrids);
         }
         return(true);
     }
     else
     {
         Log.Error("Invalid Definition file!");
         return(false);
     }
 }
Пример #3
0
        public void LoadParticlesLibrary(string file)
        {
            if (file.Contains(".mwl"))
            {
                MyParticlesLibrary.Deserialize(file);
            }
            else
            {
                ProfilerShort.Begin("Verify Integrity");
                MyDataIntegrityChecker.HashInFile(file);
                MyObjectBuilder_Definitions builder = null;

                ProfilerShort.BeginNextBlock("Parse");
                MyObjectBuilderSerializer.DeserializeXML <MyObjectBuilder_Definitions>(file, out builder);

                if (builder == null || builder.ParticleEffects == null)
                {
                    return;
                }
                else
                {
                    MyParticlesLibrary.Close();
                    foreach (var classDef in builder.ParticleEffects)
                    {
                        MyParticleEffect effect = MyParticlesManager.EffectsPool.Allocate();
                        effect.DeserializeFromObjectBuilder(classDef);
                        MyParticlesLibrary.AddParticleEffect(effect);
                    }
                }

                //definitionBuilders.Add(new Tuple<MyObjectBuilder_Definitions, string>(builder, file));
                ProfilerShort.End();
            }
        }
Пример #4
0
        public bool Save()
        {
            if (!Changed)
            {
                return(false);
            }
            if (!IsMutable)
            {
                return(false);
            }
            if (FileInfo == null)
            {
                return(false);
            }

            MyObjectBuilder_Definitions definitionsContainer = new MyObjectBuilder_Definitions();

            if (m_definitionsContainerField == null)
            {
                throw new GameInstallationInfoException(GameInstallationInfoExceptionState.Invalid, "Failed to find matching definitions field in the given file.");
            }

            //Save the source data into the definitions container
            m_definitionsContainerField.SetValue(definitionsContainer, ExtractBaseDefinitions().ToArray());

            //Save the definitions container out to the file
            SaveContentFile <MyObjectBuilder_Definitions, MyObjectBuilder_DefinitionsSerializer>(definitionsContainer, m_fileInfo);

            return(true);
        }
        private bool SaveGridToFile(string path, string filename, List <MyObjectBuilder_CubeGrid> objectBuilders)
        {
            MyObjectBuilder_ShipBlueprintDefinition definition =
                MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>();

            definition.Id = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)),
                                               filename);
            definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray();

            /* Reset ownership as it will be different on the new server anyway */
            foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids)
            {
                foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks)
                {
                    cubeBlock.Owner   = 0L;
                    cubeBlock.BuiltBy = 0L;
                }
            }

            MyObjectBuilder_Definitions builderDefinition =
                MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>();

            builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition };


            return(MyObjectBuilderSerializer.SerializeXML(path, false, builderDefinition));
        }
Пример #6
0
        public static bool SaveGrid(string path, string filename, bool keepOriginalOwner, bool keepProjection, List <MyObjectBuilder_CubeGrid> objectBuilders)
        {
            MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>();

            definition.Id        = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), filename);
            definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray();

            /* Reset ownership as it will be different on the new server anyway */
            foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids)
            {
                foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks)
                {
                    if (!keepOriginalOwner)
                    {
                        cubeBlock.Owner   = 0L;
                        cubeBlock.BuiltBy = 0L;
                    }

                    /* Remove Projections if not needed */
                    if (!keepProjection)
                    {
                        if (cubeBlock is MyObjectBuilder_ProjectorBase projector)
                        {
                            projector.ProjectedGrids = null;
                        }
                    }

                    /* Remove Pilot and Components (like Characters) from cockpits */
                    if (cubeBlock is MyObjectBuilder_Cockpit cockpit)
                    {
                        cockpit.Pilot = null;

                        if (cockpit.ComponentContainer != null)
                        {
                            var components = cockpit.ComponentContainer.Components;

                            if (components != null)
                            {
                                for (int i = components.Count - 1; i >= 0; i--)
                                {
                                    var component = components[i];

                                    if (component.TypeId == "MyHierarchyComponentBase")
                                    {
                                        components.RemoveAt(i);
                                        continue;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>();

            builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition };

            return(MyObjectBuilderSerializer.SerializeXML(path, false, builderDefinition));
        }
Пример #7
0
        public static MyObjectBuilder_Definitions SaveProgram(string path, MyObjectBuilder_Definitions definitions, long entityid, string program)
        {
            try
            {
                string backup = String.Format("{0}.bak", path);
                if (!File.Exists(backup))
                {
                    File.Copy(path, backup);
                }
                else
                {
                    FileInfo source = new FileInfo(path);
                    FileInfo dest   = new FileInfo(path);

                    if (source.LastWriteTime > dest.LastWriteTime)
                    {
                        File.Copy(path, backup, true);
                    }
                }

                foreach (MyObjectBuilder_ShipBlueprintDefinition blueprints in definitions.ShipBlueprints)
                {
                    foreach (MyObjectBuilder_CubeGrid cubegrid in blueprints.CubeGrids)
                    {
                        foreach (MyObjectBuilder_CubeBlock block in cubegrid.CubeBlocks)
                        {
                            if (block is MyObjectBuilder_MyProgrammableBlock)
                            {
                                if (block.EntityId == entityid)
                                {
                                    MyObjectBuilder_MyProgrammableBlock prog = (MyObjectBuilder_MyProgrammableBlock)block;
                                    prog.Program = program;
                                }
                            }
                        }
                    }
                }

                MyObjectBuilderSerializer.SerializeXML(path, false, definitions);
            }
            catch (Exception ex)
            {
                string message = String.Format(
                    "{0} ({1}){2}{2}{3}",
                    "There was an error saving the blueprint",
                    ex.Message,
                    Environment.NewLine,
                    ex.StackTrace
                    );

                System.Windows.MessageBox.Show(
                    message,
                    "SE Workbench",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error
                    );
            }

            return(definitions);
        }
Пример #8
0
        bool CopySelectedItemToClipboard()
        {
            if (!ValidateSelecteditem())
            {
                return(false);
            }

            var path = "";
            MyObjectBuilder_Definitions prefab = null;

            if ((m_selectedItem.UserData as MyBlueprintItemInfo).Type == MyBlueprintTypeEnum.LOCAL)
            {
                path = Path.Combine(m_localBlueprintFolder, m_selectedItem.Text.ToString(), "bp.sbc");
                if (File.Exists(path))
                {
                    prefab = LoadPrefab(path);
                }
            }
            else if ((m_selectedItem.UserData as MyBlueprintItemInfo).Type == MyBlueprintTypeEnum.STEAM)
            {
                var id = (m_selectedItem.UserData as MyBlueprintItemInfo).PublishedItemId;
                path = Path.Combine(m_workshopBlueprintFolder, id.ToString() + m_workshopBlueprintSuffix);
                if (File.Exists(path))
                {
                    prefab = LoadWorkshopPrefab(path, id);
                }
            }
            else if ((m_selectedItem.UserData as MyBlueprintItemInfo).Type == MyBlueprintTypeEnum.SHARED)
            {
                return(false);
            }
            else if ((m_selectedItem.UserData as MyBlueprintItemInfo).Type == MyBlueprintTypeEnum.DEFAULT)
            {
                path = Path.Combine(m_defaultBlueprintFolder, m_selectedItem.Text.ToString(), "bp.sbc");
                if (File.Exists(path))
                {
                    prefab = LoadPrefab(path);
                }
            }

            if (prefab != null)
            {
                if (MySandboxGame.Static.SessionCompatHelper != null)
                {
                    MySandboxGame.Static.SessionCompatHelper.CheckAndFixPrefab(prefab);
                }
                return(CopyBlueprintPrefabToClipboard(prefab, m_clipboard));
            }
            else
            {
                MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                           buttonType: MyMessageBoxButtonsType.OK,
                                           styleEnum: MyMessageBoxStyleEnum.Error,
                                           messageCaption: new StringBuilder("Error"),
                                           messageText: new StringBuilder("Failed to load the blueprint file.")
                                           ));
                return(false);
            }
        }
        protected static void SavePrefabToFile(MyObjectBuilder_Definitions prefab, string name, bool replace = false, MyBlueprintTypeEnum type = MyBlueprintTypeEnum.LOCAL)
        {
            //if (name == null)
            //{
            //    name = MyUtils.StripInvalidChars(MyCubeBuilder.Static.Clipboard.CopiedGridsName);
            //}

            Debug.Assert(name != null, "Name cannot be null");

            string file = "";

            if (type == MyBlueprintTypeEnum.LOCAL)
            {
                file = Path.Combine(m_localBlueprintFolder, name);
            }
            else
            {
                file = Path.Combine(m_workshopBlueprintFolder, "temp", name);
            }
            string filePath = "";
            int    index    = 1;

            try
            {
                if (!replace)
                {
                    while (MyFileSystem.DirectoryExists(file))
                    {
                        file = Path.Combine(m_localBlueprintFolder, name + "_" + index);
                        index++;
                    }
                    if (index > 1)
                    {
                        name += new StringBuilder("_" + (index - 1));
                    }
                }
                filePath = file + "\\bp.sbc";
                var success = MyObjectBuilderSerializer.SerializeXML(filePath, false, prefab);

                Debug.Assert(success, "falied to write blueprint to file");
                if (!success)
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                               buttonType: MyMessageBoxButtonsType.OK,
                                               styleEnum: MyMessageBoxStyleEnum.Error,
                                               messageCaption: new StringBuilder("Error"),
                                               messageText: new StringBuilder("There was a problem with saving blueprint")
                                               ));
                    if (Directory.Exists(file))
                    {
                        Directory.Delete(file, true);
                    }
                }
            }
            catch (Exception e)
            {
                MySandboxGame.Log.WriteLine(String.Format("Failed to write prefab at file {0}, message: {1}, stack:{2}", filePath, e.Message, e.StackTrace));
            }
        }
Пример #10
0
            public int GetHashCode(object o)
            {
                var definitions = o as MyObjectBuilder_Definitions;

                if (definitions != null)
                {
                    Def = definitions;
                }
                return(0);
            }
Пример #11
0
        public static bool SaveGrid(string path, string filename, string ip, bool keepOriginalOwner, bool keepProjection, List <MyObjectBuilder_CubeGrid> objectBuilders)
        {
            MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>();

            definition.Id        = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), filename);
            definition.CubeGrids = objectBuilders.Select(x => (MyObjectBuilder_CubeGrid)x.Clone()).ToArray();
            List <ulong> playerIds = new List <ulong>();

            /* Reset ownership as it will be different on the new server anyway */
            foreach (MyObjectBuilder_CubeGrid cubeGrid in definition.CubeGrids)
            {
                foreach (MyObjectBuilder_CubeBlock cubeBlock in cubeGrid.CubeBlocks)
                {
                    if (!keepOriginalOwner)
                    {
                        cubeBlock.Owner   = 0L;
                        cubeBlock.BuiltBy = 0L;
                    }

                    /* Remove Projections if not needed */
                    if (!keepProjection)
                    {
                        if (cubeBlock is MyObjectBuilder_ProjectorBase projector)
                        {
                            projector.ProjectedGrids = null;
                        }
                    }

                    /* Remove Pilot and Components (like Characters) from cockpits */
                    if (cubeBlock is MyObjectBuilder_Cockpit cockpit)
                    {
                        if (cockpit.Pilot != null)
                        {
                            var playersteam = cockpit.Pilot.PlayerSteamId;
                            var player      = PlayerUtils.GetIdentityByNameOrId(playersteam.ToString());
                            playerIds.Add(playersteam);
                            ModCommunication.SendMessageTo(new JoinServerMessage(ip), playersteam);
                        }
                    }
                }
            }

            MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>();

            builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition };
            foreach (var playerId in playerIds)
            {
                var player = PlayerUtils.GetIdentityByNameOrId(playerId.ToString());
                player.Character.EnableBag(false);
                Sandbox.Game.MyVisualScriptLogicProvider.SetPlayersHealth(player.IdentityId, 0);
                player.Character.Delete();
            }
            return(MyObjectBuilderSerializer.SerializeXML(path, false, builderDefinition));
        }
Пример #12
0
        private bool LoadBlueprint(string path)
        {
            bool success = false;
            MyObjectBuilder_Definitions blueprint = MyGuiBlueprintScreenBase.LoadPrefab(path);

            if (blueprint != null)
            {
                success = MyGuiBlueprintScreen.CopyBlueprintPrefabToClipboard(blueprint, m_clipboard);
            }

            OnBlueprintScreen_Closed(null);
            return(success);
        }
Пример #13
0
        public static void SaveEnvironmentDefinition()
        {
            EnvironmentDefinition.SunProperties       = SunProperties;
            EnvironmentDefinition.FogProperties       = FogProperties;
            EnvironmentDefinition.SSAOSettings        = SSAOSettings;
            EnvironmentDefinition.HBAOSettings        = HBAOSettings;
            EnvironmentDefinition.PostProcessSettings = MyPostprocessSettingsWrapper.Settings;
            EnvironmentDefinition.ShadowSettings.CopyFrom(ShadowSettings);

            var save = new MyObjectBuilder_Definitions();

            save.Environments = new MyObjectBuilder_EnvironmentDefinition[] { (MyObjectBuilder_EnvironmentDefinition)EnvironmentDefinition.GetObjectBuilder() };
            save.Save(Path.Combine(MyFileSystem.ContentPath, "Data", "Environment.sbc"));
        }
 /// <summary>
 /// Method to serialize a configuration file.
 /// </summary>
 /// <param name="definitions">The definition to serialize.</param>
 public void Serialize(MyObjectBuilder_Definitions definitions)
 {
     XmlWriterSettings settings = new XmlWriterSettings()
     {
         CloseOutput = true,
         Indent = true,
         ConformanceLevel = ConformanceLevel.Auto,
         NewLineHandling = NewLineHandling.Entitize
     };
     XmlWriter writer = XmlWriter.Create(_configFileInfo.FullName, settings);
     MyObjectBuilder_DefinitionsSerializer serializer = (MyObjectBuilder_DefinitionsSerializer)Activator.CreateInstance(typeof(MyObjectBuilder_DefinitionsSerializer));
     serializer.Serialize(writer,definitions);
     writer.Close();
 }
Пример #15
0
        public static MyObjectBuilder_Definitions LoadPrefab(string filePath)
        {
            MyObjectBuilder_Definitions loadedPrefab = null;

            if (MyFileSystem.FileExists(filePath))
            {
                var success = MyObjectBuilderSerializer.DeserializeXML(filePath, out loadedPrefab);
                if (!success)
                {
                    return(null);
                }
            }
            return(loadedPrefab);
        }
Пример #16
0
        private static bool SaveGridToFile(string Path, string Name, IEnumerable <MyObjectBuilder_CubeGrid> GridBuilders)
        {
            MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>();

            definition.Id        = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), Name);
            definition.CubeGrids = GridBuilders.ToArray();
            PrepareGridForSave(definition);

            MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>();

            builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition };

            return(MyObjectBuilderSerializer.SerializeXML(Path, false, builderDefinition));
        }
Пример #17
0
        /// <summary>
        /// Method to serialize a configuration file.
        /// </summary>
        /// <param name="definitions">The definition to serialize.</param>
        public void Serialize(MyObjectBuilder_Definitions definitions)
        {
            XmlWriterSettings settings = new XmlWriterSettings()
            {
                CloseOutput      = true,
                Indent           = true,
                ConformanceLevel = ConformanceLevel.Auto,
                NewLineHandling  = NewLineHandling.Entitize
            };
            XmlWriter writer = XmlWriter.Create(_configFileInfo.FullName, settings);
            MyObjectBuilder_DefinitionsSerializer serializer = (MyObjectBuilder_DefinitionsSerializer)Activator.CreateInstance(typeof(MyObjectBuilder_DefinitionsSerializer));

            serializer.Serialize(writer, definitions);
            writer.Close();
        }
Пример #18
0
        public void Load(FileInfo sourceFile)
        {
            m_fileInfo = sourceFile;

            //Get the definitions content from the file
            MyObjectBuilder_Definitions definitionsContainer = LoadContentFile <MyObjectBuilder_Definitions, MyObjectBuilder_DefinitionsSerializer>(m_fileInfo);

            if (m_definitionsContainerField == null)
            {
                throw new SEConfigurationException(SEConfigurationExceptionState.InvalidConfigurationFile, "Failed to find matching definitions field in the specified file.");
            }

            //Get the data from the definitions container
            MyObjectBuilder_Base[] baseDefinitions = (MyObjectBuilder_Base[])m_definitionsContainerField.GetValue(definitionsContainer);

            Load(baseDefinitions);
        }
        private static bool SaveGridToFile(string SavePath, string GridName, IEnumerable <MyObjectBuilder_CubeGrid> GridBuilders)
        {
            MyObjectBuilder_ShipBlueprintDefinition definition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_ShipBlueprintDefinition>();

            definition.Id        = new MyDefinitionId(new MyObjectBuilderType(typeof(MyObjectBuilder_ShipBlueprintDefinition)), GridName);
            definition.CubeGrids = GridBuilders.ToArray();
            //PrepareGridForSave(definition);

            MyObjectBuilder_Definitions builderDefinition = MyObjectBuilderSerializer.CreateNewObject <MyObjectBuilder_Definitions>();

            builderDefinition.ShipBlueprints = new MyObjectBuilder_ShipBlueprintDefinition[] { definition };



            Log.Warn("Saving grid @" + Path.Combine(SavePath, GridName + ".sbc"));
            return(MyObjectBuilderSerializer.SerializeXML(Path.Combine(SavePath, GridName + ".sbc"), false, builderDefinition));
        }
Пример #20
0
        private static MyBehaviorDefinition LoadBehaviorTreeFromFile(string path)
        {
            MyObjectBuilder_Definitions objectBuilder = null;

            MyObjectBuilderSerializer.DeserializeXML <MyObjectBuilder_Definitions>(path, out objectBuilder);
            if (((objectBuilder == null) || (objectBuilder.AIBehaviors == null)) || (objectBuilder.AIBehaviors.Length == 0))
            {
                return(null);
            }
            MyObjectBuilder_BehaviorTreeDefinition builder = objectBuilder.AIBehaviors[0];
            MyModContext modContext = new MyModContext();

            modContext.Init("BehaviorDefinition", Path.GetFileName(path), null);
            MyBehaviorDefinition definition1 = new MyBehaviorDefinition();

            definition1.Init(builder, modContext);
            return(definition1);
        }
        private static MyBehaviorDefinition LoadBehaviorTreeFromFile(string path)
        {
            MyObjectBuilder_Definitions allDefinitions = null;

            MyObjectBuilderSerializer.DeserializeXML(path, out allDefinitions);

            if (allDefinitions != null && allDefinitions.AIBehaviors != null && allDefinitions.AIBehaviors.Length > 0)
            {
                var firstDef = allDefinitions.AIBehaviors[0]; // only one tree can be uploaded at one time

                MyBehaviorDefinition behaviorDefinition = new MyBehaviorDefinition();
                MyModContext         context            = new MyModContext();
                context.Init("BehaviorDefinition", Path.GetFileName(path));
                behaviorDefinition.Init(firstDef, context);
                return(behaviorDefinition);
            }
            return(null);
        }
Пример #22
0
        void OnSave(MyGuiControlButton button)
        {
            var ob = new MyObjectBuilder_Definitions();

            var sounds = MyDefinitionManager.Static.GetSoundDefinitions();

            ob.Sounds = new MyObjectBuilder_AudioDefinition[sounds.Count];
            int i = 0;

            foreach (var sound in sounds)
            {
                ob.Sounds[i++] = (MyObjectBuilder_AudioDefinition)sound.GetObjectBuilder();
            }

            var path = Path.Combine(MyFileSystem.ContentPath, @"Data\Audio.sbc");

            MyObjectBuilderSerializer.SerializeXML(path, false, ob);
        }
        public static bool CopyBlueprintPrefabToClipboard(MyObjectBuilder_Definitions prefab, MyGridClipboard clipboard, bool setOwner = true)
        {
            if (prefab.ShipBlueprints == null)
            {
                return(false);
            }

            var cubeGrids = prefab.ShipBlueprints[0].CubeGrids;

            if (cubeGrids == null || cubeGrids.Count() == 0)
            {
                return(false);
            }

            var localBB = MyCubeGridExtensions.CalculateBoundingSphere(cubeGrids[0]);

            var posAndOrient            = cubeGrids[0].PositionAndOrientation.Value;
            var worldMatrix             = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up);
            var invertedNormalizedWorld = Matrix.Normalize(Matrix.Invert(worldMatrix));

            var worldBB = localBB.Transform(worldMatrix);

            var dragVector   = Vector3.TransformNormal((Vector3)(Vector3D)posAndOrient.Position - worldBB.Center, invertedNormalizedWorld);
            var dragDistance = localBB.Radius + 10f;

            //Reset ownership to local player
            if (setOwner)
            {
                foreach (var gridBuilder in cubeGrids)
                {
                    foreach (var block in gridBuilder.CubeBlocks)
                    {
                        if (block.Owner != 0)
                        {
                            block.Owner = MySession.LocalPlayerId;
                        }
                    }
                }
            }

            clipboard.SetGridFromBuilders(cubeGrids, dragVector, dragDistance);
            clipboard.Deactivate();
            return(true);
        }
        /// <summary>
        /// Method to deserialize a configuration file.
        /// </summary>
        /// <returns>The deserialized definition.</returns>
        public MyObjectBuilder_Definitions Deserialize()
        {
            if (!_configFileInfo.Exists)
            {
                throw new SEConfigurationException(SEConfigurationExceptionState.InvalidFileInfo, "The file pointed by configFileInfo does not exists." + "\r\n" + "Cannot deserialize: " + _configFileInfo.FullName);
            }

            XmlReaderSettings settings = new XmlReaderSettings();
            XmlReader         reader   = XmlReader.Create(_configFileInfo.FullName, settings);
            MyObjectBuilder_DefinitionsSerializer serializer = (MyObjectBuilder_DefinitionsSerializer)Activator.CreateInstance(typeof(MyObjectBuilder_DefinitionsSerializer));

            if (!serializer.CanDeserialize(reader))
            {
                throw new SEConfigurationException(SEConfigurationExceptionState.InvalidConfigurationFile, "The file pointed by configFileInfo cannot be deserialized: " + _configFileInfo.FullName);
            }
            MyObjectBuilder_Definitions definitions = (MyObjectBuilder_Definitions)serializer.Deserialize(reader);

            reader.Close();
            return(definitions);
        }
Пример #25
0
        /// <summary>
        /// Method to deserialize a configuration file.
        /// </summary>
        /// <returns>The deserialized definition.</returns>
        /// <exception cref="FileNotFoundException">Config file specified does not exist.</exception>
        /// <exception cref="PathTooLongException">The fully qualified path and file name is 260 or more characters.</exception>
        /// <exception cref="SecurityException">The caller does not have the required permission. </exception>
        /// <exception cref="TargetInvocationException">The constructor being called throws an exception. </exception>
        /// <exception cref="MethodAccessException">The caller does not have permission to call the specified constructor. </exception>
        /// <exception cref="MemberAccessException">Cannot create an instance of an <see langword="abstract"/> class, or this member was invoked with a late-binding mechanism. </exception>
        /// <exception cref="MissingMethodException">No matching public constructor was found.</exception>
        /// <exception cref="SerializationException">Unable to de-serialize file.</exception>
        public MyObjectBuilder_Definitions Deserialize()
        {
            if (!_configFileInfo.Exists)
            {
                throw new FileNotFoundException(string.Format("The file specified in configFileInfo does not exists.\r\nCannot deserialize: {0}", _configFileInfo.FullName), _configFileInfo.FullName);
            }

            XmlReaderSettings settings = new XmlReaderSettings();
            XmlReader         reader   = XmlReader.Create(_configFileInfo.FullName, settings);
            MyObjectBuilder_DefinitionsSerializer serializer = (MyObjectBuilder_DefinitionsSerializer)Activator.CreateInstance(typeof(MyObjectBuilder_DefinitionsSerializer));

            if (!serializer.CanDeserialize(reader))
            {
                throw new SerializationException(string.Format("The file specified in configFileInfo cannot be deserialized: {0}", _configFileInfo.FullName));
            }
            MyObjectBuilder_Definitions definitions = (MyObjectBuilder_Definitions)serializer.Deserialize(reader);

            reader.Close();
            return(definitions);
        }
Пример #26
0
        public void Load(FileInfo sourceFile)
        {
            m_fileInfo = sourceFile;

            //Get the definitions content from the file
            MyObjectBuilder_Definitions definitionsContainer = LoadContentFile <MyObjectBuilder_Definitions, MyObjectBuilder_DefinitionsSerializer>(m_fileInfo);

            if (m_definitionsContainerField == null)
            {
                throw new SEConfigurationException(SEConfigurationExceptionState.InvalidConfigurationFile, "Failed to find matching definitions field in the specified file.");
            }

            //Get the data from the definitions container
            T[] baseDefinitions = (T[])m_definitionsContainerField.GetValue(definitionsContainer);

            //Copy the data into the manager
            GetInternalData().Clear();
            foreach (T definition in baseDefinitions)
            {
                NewEntry(definition);
            }
        }
Пример #27
0
        private MyObjectBuilder_Definitions LoadAllDefinitionsZip(string stockContentPath, string zipModFile, ref Dictionary <string, ContentDataPath> contentData)
        {
            var zipFiles    = ZipTools.ExtractZipContentList(zipModFile, null);
            var definitions = new MyObjectBuilder_Definitions();

            if (!zipFiles.Any(f => Path.GetDirectoryName(f).Equals("Data", StringComparison.InvariantCultureIgnoreCase)))
            {
                return(definitions);
            }

            var files = zipFiles.Where(f => Path.GetDirectoryName(f).Equals("Data", StringComparison.InvariantCultureIgnoreCase) && Path.GetExtension(f).Equals(".sbc", StringComparison.InvariantCultureIgnoreCase)).ToArray();

            foreach (var filePath in files)
            {
                MyObjectBuilder_Definitions stockTemp = null;
                try
                {
                    using (var stream = ZipTools.ExtractZipFileToSteam(zipModFile, null, filePath))
                    {
                        stockTemp = SpaceEngineersApi.ReadSpaceEngineersFile <MyObjectBuilder_Definitions>(stream);
                    }
                }
                catch (Exception ex)
                {
                    // ignore errors, keep on trucking just like SE.
                    // write event log warning of any files not loaded.
                    DiagnosticsLogging.LogWarning(string.Format(Res.ExceptionState_CorruptContentFile, filePath), ex);
                }

                if (stockTemp != null)
                {
                    MergeDefinitions(ref definitions, stockTemp);
                }
            }

            LoadContent(stockContentPath, null, zipModFile, zipFiles, definitions, ref contentData);

            return(definitions);
        }
Пример #28
0
        private void MergeDefinitions(ref MyObjectBuilder_Definitions baseDefinitions, MyObjectBuilder_Definitions newDefinitions)
        {
            var fields = newDefinitions.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance);

            foreach (var field in fields)
            {
                var readValues = field.GetValue(newDefinitions);
                if (readValues != null)
                {
                    var currentValues = field.GetValue(baseDefinitions);
                    if (currentValues == null || !field.FieldType.IsArray)
                    {
                        field.SetValue(baseDefinitions, readValues);
                    }
                    else
                    {
                        // Merge together multiple values from seperate files.
                        var newArray = ArrayHelper.MergeGenericArrays(currentValues, readValues);
                        field.SetValue(baseDefinitions, newArray);
                    }
                }
            }
        }
Пример #29
0
 public void LoadParticlesLibrary(string file)
 {
     if (file.Contains(".mwl"))
     {
         MyParticlesLibrary.Deserialize(file);
     }
     else
     {
         MyDataIntegrityChecker.HashInFile(file);
         MyObjectBuilder_Definitions objectBuilder = null;
         MyObjectBuilderSerializer.DeserializeXML <MyObjectBuilder_Definitions>(file, out objectBuilder);
         if ((objectBuilder != null) && (objectBuilder.ParticleEffects != null))
         {
             MyParticlesLibrary.Close();
             foreach (MyObjectBuilder_ParticleEffect effect in objectBuilder.ParticleEffects)
             {
                 MyParticleEffect local1 = MyParticlesManager.EffectsPool.Allocate(false);
                 local1.DeserializeFromObjectBuilder(effect);
                 MyParticlesLibrary.AddParticleEffect(local1);
             }
         }
     }
 }
Пример #30
0
        private MyObjectBuilder_Definitions LoadAllDefinitions(string stockContentPath, string modContentPath, ref Dictionary <string, ContentDataPath> contentData)
        {
            var searchPath  = Path.Combine(modContentPath, "Data");
            var definitions = new MyObjectBuilder_Definitions();

            if (!Directory.Exists(searchPath))
            {
                return(definitions);
            }

            var files = Directory.GetFiles(searchPath, "*.sbc");

            foreach (var filePath in files)
            {
                MyObjectBuilder_Definitions stockTemp = null;
                try
                {
                    bool isCompressed;
                    stockTemp = SpaceEngineersApi.ReadSpaceEngineersFile <MyObjectBuilder_Definitions>(filePath, out isCompressed);
                }
                catch (Exception ex)
                {
                    // ignore errors, keep on trucking just like SE.
                    // write event log warning of any files not loaded.
                    DiagnosticsLogging.LogWarning(string.Format(Res.ExceptionState_CorruptContentFile, filePath), ex);
                }

                if (stockTemp != null)
                {
                    MergeDefinitions(ref definitions, stockTemp);
                }
            }

            LoadContent(stockContentPath, modContentPath, null, null, definitions, ref contentData);

            return(definitions);
        }
Пример #31
0
        public bool Save()
        {
            if (!this.Changed)
            {
                return(false);
            }
            if (!this.IsMutable)
            {
                return(false);
            }
            if (this.FileInfo == null)
            {
                return(false);
            }

            MyObjectBuilder_Definitions definitionsContainer = new MyObjectBuilder_Definitions();

            if (m_definitionsContainerField == null)
            {
                throw new GameInstallationInfoException(GameInstallationInfoExceptionState.Invalid, "Failed to find matching definitions field in the given file.");
            }

            List <MyObjectBuilder_Base> baseDefs = new List <MyObjectBuilder_Base>();

            foreach (var baseObject in GetInternalData().Values)
            {
                baseDefs.Add(baseObject.ObjectBuilder);
            }

            //Save the source data into the definitions container
            m_definitionsContainerField.SetValue(definitionsContainer, baseDefs.ToArray());

            //Save the definitions container out to the file
            SaveContentFile <MyObjectBuilder_Definitions, MyObjectBuilder_DefinitionsSerializer>(definitionsContainer, m_fileInfo);

            return(true);
        }
Пример #32
0
        void OnSave(MyGuiControlButton button)
        {
            var ob = new MyObjectBuilder_Definitions();

            var sounds = MyDefinitionManager.Static.GetSoundDefinitions();
            ob.Sounds = new MyObjectBuilder_AudioDefinition[sounds.Count];
            int i = 0;
            foreach (var sound in sounds)
            {
                ob.Sounds[i++] = (MyObjectBuilder_AudioDefinition)sound.GetObjectBuilder();
            }

            var path = Path.Combine(MyFileSystem.ContentPath, @"Data\Audio.sbc");
            MyObjectBuilderSerializer.SerializeXML(path, false, ob);
        }
Пример #33
0
 public void CallLoadPrefab(WorkData workData)
 {
     m_prefab = LoadPrefab(m_path);
     CallOnPrefabLoaded();
 }
Пример #34
0
 public void CallLoadWorkshopPrefab(WorkData workData)
 {
     m_prefab = LoadWorkshopPrefab(m_path, m_id);
     CallOnPrefabLoaded();
 }
Пример #35
0
 internal void OnPrefabLoaded(MyObjectBuilder_Definitions prefab)
 {
     if (prefab != null)
     {
         if (MySandboxGame.Static.SessionCompatHelper != null)
         {
             MySandboxGame.Static.SessionCompatHelper.CheckAndFixPrefab(prefab);
         }
         if (CheckBlueprintForMods(prefab) == false)
         {
             MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                    buttonType: MyMessageBoxButtonsType.YES_NO,
                    styleEnum: MyMessageBoxStyleEnum.Info,
                    messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionWarning),
                    messageText: MyTexts.Get(MyCommonTexts.MessageBoxTextDoYouWantToPasteGridWithMissingBlocks),
                    callback: result =>
                    {
                        if (result == MyGuiScreenMessageBox.ResultEnum.YES)
                        {
                            if (CopyBlueprintPrefabToClipboard(prefab, m_clipboard))
                            {
                                CloseScreen();
                            }
                        }
                    }));
         }
         else
         {
             if (CopyBlueprintPrefabToClipboard(prefab, m_clipboard))
                 CloseScreen();
         }
     }
     else
     {
         MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                     buttonType: MyMessageBoxButtonsType.OK,
                     styleEnum: MyMessageBoxStyleEnum.Error,
                     messageCaption: new StringBuilder("Error"),
                     messageText: new StringBuilder("Failed to load the blueprint file.")
                     ));
     }
 }
        public static void Publish(MyObjectBuilder_Definitions prefab, string blueprintName, Action<ulong> publishCallback = null)
        {
            string file = Path.Combine(m_localBlueprintFolder, blueprintName);
            string title = prefab.ShipBlueprints[0].CubeGrids[0].DisplayName;
            string description = prefab.ShipBlueprints[0].Description;
            ulong publishId = prefab.ShipBlueprints[0].WorkshopId;
            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                styleEnum: MyMessageBoxStyleEnum.Info,
                buttonType: MyMessageBoxButtonsType.YES_NO,
                messageCaption: new StringBuilder("Publish"),
                messageText: new StringBuilder("Do you want to publish this blueprint?"),
                callback: delegate(MyGuiScreenMessageBox.ResultEnum val)
                {
                    if (val == MyGuiScreenMessageBox.ResultEnum.YES)
                    {
                        Action<MyGuiScreenMessageBox.ResultEnum, string[]> onTagsChosen = delegate(MyGuiScreenMessageBox.ResultEnum tagsResult, string[] outTags)
                        {
                            if (tagsResult == MyGuiScreenMessageBox.ResultEnum.YES)
                            {
                                MySteamWorkshop.PublishBlueprintAsync(file, title, description, publishId, outTags, SteamSDK.PublishedFileVisibility.Public,
                                    callbackOnFinished: delegate(bool success, Result result, ulong publishedFileId)
                                    {
                                        if (success)
                                        {
                                            if (publishCallback != null)
                                                publishCallback(publishedFileId);

                                            prefab.ShipBlueprints[0].WorkshopId = publishedFileId;
                                            SavePrefabToFile(prefab, blueprintName, true);
                                            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                styleEnum: MyMessageBoxStyleEnum.Info,
                                                messageText: MyTexts.Get(MyCommonTexts.MessageBoxTextWorldPublished),
                                                messageCaption: new StringBuilder("BLUEPRINT PUBLISHED"),
                                                callback: (a) =>
                                                {
                                                    MySteam.API.OpenOverlayUrl(string.Format("http://steamcommunity.com/sharedfiles/filedetails/?id={0}", publishedFileId));
                                                }));
                                        }
                                        else
                                        {
                                            MyStringId error;
                                            switch (result)
                                            {
                                                case Result.AccessDenied:
                                                    error = MyCommonTexts.MessageBoxTextPublishFailed_AccessDenied;
                                                    break;
                                                default:
                                                    error = MyCommonTexts.MessageBoxTextWorldPublishFailed;
                                                    break;
                                            }

                                            MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                                                messageText: MyTexts.Get(error),
                                                messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionWorldPublishFailed)));
                                        }
                                    });
                            }
                        };

                        if (MySteamWorkshop.BlueprintCategories.Length > 0)
                            MyGuiSandbox.AddScreen(new MyGuiScreenWorkshopTags(MySteamWorkshop.WORKSHOP_BLUEPRINT_TAG, MySteamWorkshop.BlueprintCategories, null, onTagsChosen));
                        else
                            onTagsChosen(MyGuiScreenMessageBox.ResultEnum.YES, new string[] { MySteamWorkshop.WORKSHOP_BLUEPRINT_TAG });
                    }
                }));

        }
        protected static void SavePrefabToFile(MyObjectBuilder_Definitions prefab, string name, bool replace = false, MyBlueprintTypeEnum type = MyBlueprintTypeEnum.LOCAL)
        { 
            //if (name == null)
            //{
            //    name = MyUtils.StripInvalidChars(MyCubeBuilder.Static.Clipboard.CopiedGridsName);
            //}

            Debug.Assert(name != null, "Name cannot be null");

            string file = "";
            if (type == MyBlueprintTypeEnum.LOCAL)
            {
                file = Path.Combine(m_localBlueprintFolder, name);
            }
            else 
            {
                file = Path.Combine(m_workshopBlueprintFolder, "temp", name);
            }
            string filePath = "";
            int index = 1;

            try
            {
                if (!replace)
                {
                    while (MyFileSystem.DirectoryExists(file))
                    {
                        file = Path.Combine(m_localBlueprintFolder, name + "_" + index);
                        index++;
                    }
                    if (index > 1)
                    {
                        name += new StringBuilder("_" + (index - 1));
                    }
                }
                filePath = file + "\\bp.sbc";
                var success = MyObjectBuilderSerializer.SerializeXML(filePath, false, prefab);

                Debug.Assert(success, "falied to write blueprint to file");
                if (!success)
                {
                    MyGuiSandbox.AddScreen(MyGuiSandbox.CreateMessageBox(
                        buttonType: MyMessageBoxButtonsType.OK,
                        styleEnum: MyMessageBoxStyleEnum.Error,
                        messageCaption: new StringBuilder("Error"),
                        messageText: new StringBuilder("There was a problem with saving blueprint")
                        ));
                    if (Directory.Exists(file))
                        Directory.Delete(file, true);
                }

            }
            catch (Exception e)
            {
                MySandboxGame.Log.WriteLine(String.Format("Failed to write prefab at file {0}, message: {1}, stack:{2}", filePath, e.Message, e.StackTrace));
            }
        }
		/// <summary>
		/// Method to serialize a configuration file.
		/// </summary>
		/// <param name="definitions">The definition to serialize.</param>
		public void Serialize(MyObjectBuilder_Definitions definitions)
		{
			MyObjectBuilderSerializer.SerializeXML( _configFileInfo.FullName, false, definitions );
		}
Пример #39
0
 public LoadPrefabData(MyObjectBuilder_Definitions prefab, string path, MyGuiBlueprintScreen blueprintScreen, ulong? id = null)
 {
     m_prefab = prefab;
     m_path = path;
     m_blueprintScreen = blueprintScreen;
     m_id = id;
 }
        static bool CheckBlueprintForMods(MyObjectBuilder_Definitions prefab)
        {
            if (prefab.ShipBlueprints == null)
                return true;

            var cubeGrids = prefab.ShipBlueprints[0].CubeGrids;

            if (cubeGrids == null || cubeGrids.Length == 0)
                return true;

            foreach (var gridBuilder in cubeGrids)
            {
                foreach (var block in gridBuilder.CubeBlocks)
                {
                    var defId = block.GetId();
                    MyCubeBlockDefinition blockDefinition = null;
                    if (MyDefinitionManager.Static.TryGetCubeBlockDefinition(defId, out blockDefinition) == false)
                    { 
                        return false;
                    }
                }
            }

            return true;
        }
 public virtual void CheckAndFixPrefab(MyObjectBuilder_Definitions prefab)
 { }
        public static bool CopyBlueprintPrefabToClipboard(MyObjectBuilder_Definitions prefab, MyGridClipboard clipboard, bool setOwner = true)
        {
            if (prefab.ShipBlueprints == null)
                return false;

            var cubeGrids = prefab.ShipBlueprints[0].CubeGrids;

            if (cubeGrids == null || cubeGrids.Length == 0)
                return false;

            var localBB = MyCubeGridExtensions.CalculateBoundingSphere(cubeGrids[0]);

            var posAndOrient = cubeGrids[0].PositionAndOrientation.Value;
            var worldMatrix = MatrixD.CreateWorld(posAndOrient.Position, posAndOrient.Forward, posAndOrient.Up);
            var invertedNormalizedWorld = Matrix.Normalize(Matrix.Invert(worldMatrix));

            var worldBB = localBB.Transform(worldMatrix);

            var dragVector = Vector3.TransformNormal((Vector3)(Vector3D)posAndOrient.Position - worldBB.Center, invertedNormalizedWorld);
            var dragDistance = localBB.Radius + 10f;

            //Reset ownership to local player
            if (setOwner)
            {
                foreach (var gridBuilder in cubeGrids)
                {
                    foreach (var block in gridBuilder.CubeBlocks)
                    {
                        if (block.Owner != 0)
                        {
                            block.Owner = MySession.Static.LocalPlayerId;
                        }
                    }
                }
            }

            // Blueprint can have old (deprecated) fractured blocks, they have to be converted to fracture components. There is no version in blueprints.
            if (MyFakes.ENABLE_FRACTURE_COMPONENT)
            {
                for (int i = 0; i < cubeGrids.Length; ++i)
                {
                    cubeGrids[i] = MyFracturedBlock.ConvertFracturedBlocksToComponents(cubeGrids[i]);
                }
            }

            clipboard.SetGridFromBuilders(cubeGrids, dragVector, dragDistance);
            clipboard.Deactivate();
            return true;
        }