Ejemplo n.º 1
0
        public static T CreateEntity <T>(MyObjectBuilder_Base builder) where T : MyEntity
        {
            T entity = m_objectFactory.CreateInstance <T>(builder.TypeId);

            AddScriptGameLogic(entity, builder.GetType(), builder.SubtypeName);
            MyEntities.RaiseEntityCreated(entity);
            return(entity);
        }
Ejemplo n.º 2
0
        public static T CreateEntity <T>(MyObjectBuilder_Base builder) where T : MyEntity
        {
            ProfilerShort.Begin("MyEntityFactory.CreateEntity(...)");
            T entity = m_objectFactory.CreateInstance <T>(builder.TypeId);

            AddScriptGameLogic(entity, builder.GetType(), builder.SubtypeName);
            ProfilerShort.End();
            return(entity);
        }
Ejemplo n.º 3
0
        public static T CreateEntity <T>(MyObjectBuilder_Base builder, bool readyForReplication = true) where T : MyEntity
        {
            ProfilerShort.Begin("MyEntityFactory.CreateEntity(...)");
            T entity = m_objectFactory.CreateInstance <T>(builder.TypeId);

            AddScriptGameLogic(entity, builder.GetType(), builder.SubtypeName);
            entity.IsReadyForReplication = readyForReplication;
            ProfilerShort.End();
            MyEntities.RaiseEntityCreated(entity);
            return(entity);
        }
        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);
        }
Ejemplo n.º 5
0
        public static T CreateEntity <T>(MyObjectBuilder_Base builder) where T : MyEntity
        {
            ProfilerShort.Begin("MyEntityFactory.CreateEntity(...)");
            T   entity        = m_objectFactory.CreateInstance <T>(builder.TypeId);
            var scriptManager = Sandbox.Game.World.MyScriptManager.Static;
            var builderType   = builder.GetType();

            if (scriptManager != null && scriptManager.EntityScripts.ContainsKey(builderType))
            {
                entity.GameLogic = (MyGameLogicComponent)Activator.CreateInstance(scriptManager.EntityScripts[builderType]);
            }
            ProfilerShort.End();
            return(entity);
        }
        /// <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));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Replacement for MyObjectBuilderSerializer that lets you set compression level.
        /// </summary>
        /// <param name="writeTo"></param>
        /// <param name="obj"></param>
        /// <param name="level"></param>
        /// <param name="bufferSize"></param>
        private static void SerializeZipped(Stream writeTo, MyObjectBuilder_Base obj, CompressionLevel level, int bufferSize = 0x8000)
        {
            var           ms         = new MemoryStream(bufferSize);
            Stopwatch     stopwatch  = Stopwatch.StartNew();
            XmlSerializer serializer = MyXmlSerializerManager.GetSerializer(obj.GetType());

            serializer.Serialize(ms, obj);
            stopwatch.Stop();
            Log.Info($"Serialization took {stopwatch.Elapsed.TotalMilliseconds}ms");
            ms.Position = 0;
            Log.Info($"Wrote {Utilities.FormatDataSize(ms.Length)}");
            _lastSize = Math.Max(_lastSize, (int)ms.Length);
            stopwatch.Restart();
            using (var gz = new GZipStream(writeTo, level))
            {
                ms.CopyTo(gz);
            }
            stopwatch.Stop();
            Log.Info($"Compression took {stopwatch.Elapsed.TotalMilliseconds}ms");
            ms.Close();
        }
Ejemplo n.º 8
0
        public override bool Invoke(ulong steamId, long playerId, string messageText)
        {
            MyObjectBuilder_Base content = null;

            string[] options;
            decimal  amount = 1;

            var match = Regex.Match(messageText, @"/invadd\s{1,}(?:(?<Key>.+)\s(?<Value>[+-]?((\d+(\.\d*)?)|(\.\d+)))|(?<Key>.+))", RegexOptions.IgnoreCase);

            if (match.Success)
            {
                var itemName  = match.Groups["Key"].Value;
                var strAmount = match.Groups["Value"].Value;
                if (!decimal.TryParse(strAmount, out amount))
                {
                    amount = 1;
                }

                if (!Support.FindPhysicalParts(_oreNames, _ingotNames, _physicalItemNames, _physicalItems, itemName, out content, out options) && options.Length > 0)
                {
                    MyAPIGateway.Utilities.ShowMessage("Did you mean", String.Join(", ", options) + " ?");
                    return(true);
                }
            }

            if (content != null)
            {
                if (amount < 0)
                {
                    amount = 1;
                }

                if (content.TypeId != typeof(MyObjectBuilder_Ore) && content.TypeId != typeof(MyObjectBuilder_Ingot))
                {
                    // must be whole numbers.
                    amount = Math.Round(amount, 0);
                }

                if (!MyAPIGateway.Multiplayer.MultiplayerActive)
                {
                    var definitionId = new MyDefinitionId(content.GetType(), content.SubtypeName);
                    if (!Support.InventoryAdd((MyEntity)MyAPIGateway.Session.Player.GetCharacter(), (MyFixedPoint)amount, definitionId))
                    {
                        MyAPIGateway.Utilities.ShowMessage("Failed", "Inventory full. Could not add the item.");
                    }
                }
                else
                {
                    ConnectionHelper.SendMessageToServer(new MessageSyncCreateObject()
                    {
                        EntityId    = ((IMyEntity)MyAPIGateway.Session.Player.GetCharacter()).EntityId,
                        Type        = SyncCreateObjectType.Inventory,
                        TypeId      = content.TypeId.ToString(),
                        SubtypeName = content.SubtypeName,
                        Amount      = amount
                    });
                }
                return(true);
            }

            MyAPIGateway.Utilities.ShowMessage("Unknown Item", "Could not find the specified name.");
            return(true);
        }
        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 (!MyFinalBuildConstants.IS_OFFICIAL)
                {
                    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);
                        }
                    }
                }

                sizeInBytes = 0;

                return(false);
            }
            return(true);
        }
        private static void SerializeXMLInternal(Stream writeTo, MyObjectBuilder_Base objectBuilder, Type serializeAsType = null)
        {
            XmlSerializer serializer = m_serializersByType[serializeAsType ?? objectBuilder.GetType()];

            serializer.Serialize(writeTo, objectBuilder);
        }