public static bool SerializeXML(Stream writeTo, MyObjectBuilder_Base objectBuilder, XmlCompression compress = XmlCompression.Uncompressed, Type serializeAsType = null)
 {
     try
     {
         if (compress == XmlCompression.Gzip)
         {
             SerializeGZippedXMLInternal(writeTo, objectBuilder, serializeAsType);
         }
         else if (compress == XmlCompression.Uncompressed)
         {
             SerializeXMLInternal(writeTo, objectBuilder, serializeAsType);
         }
         else
         {
             Debug.Assert(false, "Unhandled XML compression type during object builder serialization");
         }
     }
     catch (Exception e)
     {
         MyLog.Default.WriteLine("Error during serialization.");
         MyLog.Default.WriteLine(e.ToString());
         return(false);
     }
     return(true);
 }
        public static bool DeserializeXML(string path, out MyObjectBuilder_Base objectBuilder, Type builderType)
        {
            bool result = false;

            objectBuilder = null;
            using (var fileStream = MyFileSystem.OpenRead(path))
            {
                if (fileStream != null)
                {
                    using (var readStream = fileStream.UnwrapGZip())
                    {
                        if (readStream != null)
                        {
                            result = DeserializeXML(readStream, out objectBuilder, builderType);
                        }
                    }
                }
            }

            if (!result)
            {
                MyLog.Default.WriteLine(string.Format("Failed to deserialize file '{0}'", path));
            }

            return(result);
        }
        /// <param name="typeOverrideMap">Allows override of the type of the definition. Refer to MyDefinitionXmlSerializer</param>
        internal static bool DeserializeXML(Stream reader, out MyObjectBuilder_Base objectBuilder, Type builderType, Dictionary <string, string> typeOverrideMap)
        {
            Debug.Assert(typeof(MyObjectBuilder_Base).IsAssignableFrom(builderType));
            Debug.Assert(reader != null);
            Debug.Assert(builderType != null);

            objectBuilder = null;
            try
            {
                XmlSerializer serializer = MyXmlSerializerManager.GetSerializer(builderType);
                Debug.Assert(serializer != null);

                XmlReaderSettings settings = new XmlReaderSettings()
                {
                    CheckCharacters = true
                };
                MyXmlTextReader xmlReader = new MyXmlTextReader(reader, settings);
                xmlReader.DefinitionTypeOverrideMap = typeOverrideMap;

                objectBuilder = (MyObjectBuilder_Base)serializer.Deserialize(xmlReader);
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine("ERROR: Exception during objectbuilder read! (xml): " + builderType.Name);
                MyLog.Default.WriteLine(e);
                //if (Debugger.IsAttached)
                //    Debugger.Break();
                return(false);
            }

            return(true);
        }
        private static bool DeserializeXML(Stream reader, out MyObjectBuilder_Base objectBuilder, Type builderType)
        {
            Debug.Assert(typeof(MyObjectBuilder_Base).IsAssignableFrom(builderType));
            Debug.Assert(reader != null);
            Debug.Assert(builderType != null);

            objectBuilder = null;
            try
            {
                XmlSerializer serializer = m_serializersByType[builderType];
                Debug.Assert(serializer != null);
                objectBuilder = (MyObjectBuilder_Base)serializer.Deserialize(XmlReader.Create(reader, new XmlReaderSettings()
                {
                    CheckCharacters = false
                }));
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine("ERROR: Exception during objectbuilder read! (xml): " + builderType.Name);
                MyLog.Default.WriteLine(e);
                if (Debugger.IsAttached)
                {
                    Debugger.Break();
                }
                return(false);
            }

            return(true);
        }
示例#5
0
        public virtual void Init(MyObjectBuilder_Base objectBuilder)
        {
            var builder = (MyObjectBuilder_EntityStat) objectBuilder;

            MyEntityStatDefinition definition;
            MyDefinitionManager.Static.TryGetDefinition<MyEntityStatDefinition>(new MyDefinitionId(builder.TypeId, builder.SubtypeId), out definition);

            Debug.Assert(definition != null);
            StatDefinition = definition;

            System.Diagnostics.Debug.Assert(!float.IsNaN(definition.MaxValue) && !float.IsNaN(definition.MinValue) && !float.IsNaN(definition.DefaultValue), "Invalid values in stat definition!");

            m_maxValue = definition.MaxValue;
            m_minValue = definition.MinValue;
            m_currentValue = builder.Value * m_maxValue;
            m_defaultValue = definition.DefaultValue;
            
            m_lastSyncValue = m_currentValue;
            m_statId = MyStringHash.GetOrCompute(definition.Name);

            m_regenAmountMultiplier = builder.StatRegenAmountMultiplier;
            m_regenAmountMultiplierDuration = builder.StatRegenAmountMultiplierDuration;
            m_regenAmountMultiplierTimeStart = MySandboxGame.TotalGamePlayTimeInMilliseconds;
            m_regenAmountMultiplierTimeAlive = 0;
            m_regenAmountMultiplierActive = m_regenAmountMultiplierDuration > 0;

            ClearEffects();
            if (builder.Effects != null)
            {
                foreach (var effectBuilder in builder.Effects)
                {
                    AddEffect(effectBuilder);
                }
            }
        }
示例#6
0
        public virtual void Init(MyObjectBuilder_Base objectBuilder)
        {
            var builder = (MyObjectBuilder_EntityStat) objectBuilder;

            MyEntityStatDefinition definition;
            MyDefinitionManager.Static.TryGetDefinition<MyEntityStatDefinition>(new MyDefinitionId(builder.TypeId, builder.SubtypeId), out definition);

            Debug.Assert(definition != null);
            StatDefinition = definition;

            m_maxValue = builder.MaxValue * 100.0f;
            m_minValue = 0.0f;
            m_currentValue = builder.Value * m_maxValue;
            
            m_lastSyncValue = m_currentValue;
            m_statId = MyStringHash.GetOrCompute(definition.Name);

            if (builder.Effects != null)
            {
                foreach (var effectBuilder in builder.Effects)
                {
                    AddEffect(effectBuilder);
                }
            }
        }
        public void Init(MyLogicalEnvironmentSectorBase sector, MyObjectBuilder_Base ob)
        {
            if (ob != null)
                m_disabledItems.UnionWith(((MyObjectBuilder_DummyEnvironmentModule)ob).DisabledItems);

            m_sector = sector;
        }
 private static void SerializeGZippedXMLInternal(Stream writeTo, MyObjectBuilder_Base objectBuilder, Type serializeAsType = null)
 {
     using (GZipStream gz = new GZipStream(writeTo, CompressionMode.Compress, true))
         using (BufferedStream buffer = new BufferedStream(gz, 0x8000))
         {
             SerializeXMLInternal(buffer, objectBuilder, serializeAsType);
         }
 }
        public static MyObjectBuilder_Base Clone(MyObjectBuilder_Base toClone)
        {
            MyObjectBuilder_Base clone = null;

            using (var stream = new MemoryStream())
            {
                SerializeXMLInternal(stream, toClone);

                stream.Position = 0;

                DeserializeXML(stream, out clone, toClone.GetType());
            }
            return(clone);
        }
        public static bool SerializeXML(string path, bool compress, MyObjectBuilder_Base objectBuilder, out ulong sizeInBytes, Type serializeAsType = null)
        {
            try
            {
                using (var fileStream = MyFileSystem.OpenWrite(path))
                    using (var writeStream = compress ? fileStream.WrapGZip() : fileStream)
                    {
                        long          startPos   = fileStream.Position;
                        XmlSerializer serializer = m_serializersByType[serializeAsType ?? objectBuilder.GetType()];
                        serializer.Serialize(writeStream, objectBuilder);
                        sizeInBytes = (ulong)(fileStream.Position - startPos); // Length of compressed stream
                    }
            }
            catch (Exception e)
            {
                MyLog.Default.WriteLine("Error: " + path + " failed to serialize.");
                MyLog.Default.WriteLine(e.ToString());

#if !XB1
#if DEBUG
                var io = e as IOException;
                if (io != null && io.IsFileLocked())
                {
                    MyLog.Default.WriteLine("Files is locked during saving.");
                    MyLog.Default.WriteLine("Xml file locks:");
                    try
                    {
                        foreach (var p in Win32Processes.GetProcessesLockingFile(path))
                        {
                            MyLog.Default.WriteLine(p.ProcessName);
                        }
                    }
                    catch (Exception e2)
                    {
                        MyLog.Default.WriteLine(e2);
                    }
                }
#endif
#endif // !XB1

                sizeInBytes = 0;

                return(false);
            }
            return(true);
        }
        public override unsafe void Init(MyLogicalEnvironmentSectorBase sector, MyObjectBuilder_Base ob)
        {
            base.Init(sector, ob);

            var penv = (MyPlanetEnvironmentComponent)sector.Owner;

            if (penv.CollisionCheckEnabled)
            {
                m_boxes = penv.GetCollidedBoxes(sector.Id);
                if (m_boxes != null) m_boxes = new List<MyOrientedBoundingBoxD>(m_boxes); // duplicate the list so the debug draw works
            }

            var builder = (MyObjectBuilder_StaticEnvironmentModule)ob;

            if (builder != null)
            {
                var newDisabled = builder.DisabledItems;

                foreach (var item in newDisabled)
                {
                    if (!m_disabledItems.Contains(item))
                        OnItemEnable(item, false);
                }

                m_disabledItems.UnionWith(newDisabled);

                if (builder.Boxes != null && builder.MinScanned > 0)
                {
                    m_boxes = builder.Boxes;
                    m_minScannedLod = builder.MinScanned;
                }
            }

            // Postprocess positions so they are local and simplify tests
            if (m_boxes != null)
            {
                var sWorldPos = sector.WorldPos;

                int cnt = m_boxes.Count;
                fixed (MyOrientedBoundingBoxD* bb = m_boxes.GetInternalArray())
                    for (int i = 0; i < cnt; ++i)
                    {
                        bb[i].Center -= sWorldPos;
                    }
            }
        }
		public virtual void Init(MyObjectBuilder_Base objectBuilder, MyEntityStat parentStat)
		{
			m_parentStat = parentStat;

			var builder = objectBuilder as MyObjectBuilder_EntityStatRegenEffect;

			if (builder == null)
				return;

			Debug.Assert(builder.Interval > 0f);
			if (builder.Interval <= 0f)
				return;

			m_amount = builder.TickAmount;
			m_interval = builder.Interval;
			m_maxRegenRatio = builder.MaxRegenRatio;
			m_minRegenRatio = builder.MinRegenRatio;
			m_duration = builder.Duration - builder.AliveTime;
		}
        /// <summary>
        /// Performs shallow copy of data between members of the same name and type from source to target.
        /// This method can be slow and inefficient, so use only when needed.
        /// </summary>
        public static void MemberwiseAssignment(MyObjectBuilder_Base source, MyObjectBuilder_Base target)
        {
            var sourceFields = source.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetField | BindingFlags.GetProperty);
            var targetFields = target.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetField | BindingFlags.SetProperty);

            foreach (var sourceField in sourceFields)
            {
                var targetField = targetFields.FirstOrDefault(delegate(FieldInfo fieldInfo)
                {
                    return(fieldInfo.FieldType == sourceField.FieldType &&
                           fieldInfo.Name == sourceField.Name);
                });
                if (targetField == default(FieldInfo))
                {
                    continue;
                }

                targetField.SetValue(target, sourceField.GetValue(source));
            }
        }
        public void Init(IMyEnvironmentOwner owner, ref Vector3D origin, ref Vector3D basisA, ref Vector3D basisB, double sectorSize, MyObjectBuilder_Base ob)
        {
            Debug.Assert(owner.EnvironmentDefinition is MyProceduralEnvironmentDefinition, "The procedural world environment provider requires a Procedural World Environment Definition.");

            Owner = owner;

            m_sectorSize = sectorSize;

            m_origin = origin;
            m_basisX = basisA;
            m_basisY = basisB;

            var builder = ob as MyObjectBuilder_ProceduralEnvironmentProvider;

            if (builder != null)
            {
                for (int i = 0; i < builder.Sectors.Count; i++)
                {
                    var sector = builder.Sectors[i];
                    m_savedSectors.Add(sector.SectorId, sector);
                }
            }
        }
 public override bool AddItems(MyFixedPoint amount, MyObjectBuilder_Base objectBuilder)
 {
     var maxAmount = ComputeAmountThatFits(objectBuilder.GetId());
     var restAmount = amount;
     if (amount <= maxAmount)
     {
         foreach (MyInventoryBase inventory in m_children.Reader)
         {
             var availableSpace = inventory.ComputeAmountThatFits(objectBuilder.GetId());
             if (availableSpace > restAmount)
             {
                 availableSpace = restAmount;
             }
             if (availableSpace > 0)
             {
                 if (inventory.AddItems(availableSpace, objectBuilder))
                 {
                     restAmount -= availableSpace;
                 }
             }
             if (restAmount == 0) break;
         }
     }
     return restAmount == 0;
 }
 public static MyGuiControlBase CreateGuiControl(MyObjectBuilder_Base builder)
 {
     return m_objectFactory.CreateInstance(builder.TypeId);
 }
        public static bool SerializeXML(string path, bool compress, MyObjectBuilder_Base objectBuilder, Type serializeAsType = null)
        {
            ulong sizeInBytes;

            return(SerializeXML(path, compress, objectBuilder, out sizeInBytes, serializeAsType));
        }
 public static bool DeserializeXML(Stream reader, out MyObjectBuilder_Base objectBuilder, Type builderType)
 {
     return(DeserializeXML(reader, out objectBuilder, builderType, null));
 }
        private static void SerializeXMLInternal(Stream writeTo, MyObjectBuilder_Base objectBuilder, Type serializeAsType = null)
        {
            XmlSerializer serializer = MyXmlSerializerManager.GetSerializer(serializeAsType ?? objectBuilder.GetType());

            serializer.Serialize(writeTo, objectBuilder);
        }
 //TODO: This should be deprecated, we shoud add IMyInventoryItems objects only , instead of items based on their objectbuilder
 /// <summary>
 /// Adds item to inventory
 /// </summary>
 /// <param name="amount"></param>
 /// <param name="objectBuilder"></param>
 /// <param name="index"></param>
 /// <returns>true if items were added, false if items didn't fit</returns>
 public abstract bool AddItems(MyFixedPoint amount, MyObjectBuilder_Base objectBuilder); 
        private static void SerializeXMLInternal(Stream writeTo, MyObjectBuilder_Base objectBuilder, Type serializeAsType = null)
        {
            XmlSerializer serializer = m_serializersByType[serializeAsType ?? objectBuilder.GetType()];

            serializer.Serialize(writeTo, objectBuilder);
        }
 //TODO: This should be deprecated, we shoud add IMyInventoryItems objects only , instead of items based on their objectbuilder
 /// <summary>
 /// Adds item to inventory
 /// </summary>
 /// <param name="amount"></param>
 /// <param name="objectBuilder"></param>
 /// <param name="index"></param>
 /// <returns>true if items were added, false if items didn't fit</returns>
 public abstract bool AddItems(MyFixedPoint amount, MyObjectBuilder_Base objectBuilder, int index = -1, bool stack = true);        
 public virtual void Init(MyLogicalEnvironmentSectorBase sector, MyObjectBuilder_Base ob)
 {
     Sector = sector;
 }