protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiParentedSkeletonComponentDefinition)def;

            AutomaticMapping = ob.AutomaticMapping ?? false;
            MoveToOrigin     = ob.MoveToOrigin ?? true;
            ExplicitMapping.Clear();
            if (ob.Mapping == null)
            {
                return;
            }

            foreach (var k in ob.Mapping)
            {
                if (string.IsNullOrWhiteSpace(k.Source))
                {
                    MyDefinitionErrors.Add(Package, $"Null or empty mapping source bone", LogSeverity.Warning);
                    continue;
                }

                if (string.IsNullOrWhiteSpace(k.Dest))
                {
                    MyDefinitionErrors.Add(Package, $"Null or empty mapping destination bone", LogSeverity.Warning);
                    continue;
                }

                ExplicitMapping[k.Dest] = k.Source;
            }
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            var ob = (MyObjectBuilder_EdgePlacerBehaviorDefinition)builder;

            Layer = ob.Layer;
            if (string.IsNullOrWhiteSpace(Layer))
            {
                MyDefinitionErrors.Add(builder.Package, $"{nameof(EdgePlacerBehaviorDefinition)} {builder.GetId()} has {nameof(Layer)} that is null",
                                       LogSeverity.Error);
            }
            Placed = ob.Placed;
            if (Placed.TypeId.IsNull)
            {
                MyDefinitionErrors.Add(builder.Package, $"{nameof(EdgePlacerBehaviorDefinition)} {builder.GetId()} has {nameof(Placed)} that is null",
                                       LogSeverity.Error);
            }
            CrosshairPrefix = ob.CrosshairPrefix;

            CrosshairPlace              = Create("Place", MyCrosshairIconInfo.IconPosition.TopLeftCorner);
            CrosshairPlaceNoPermission  = Create("PlaceNoPerm", MyCrosshairIconInfo.IconPosition.TopLeftCorner);
            CrosshairQuestion           = Create("Question", MyCrosshairIconInfo.IconPosition.Center);
            CrosshairRemove             = Create("Remove", MyCrosshairIconInfo.IconPosition.TopRightCorner);
            CrosshairRemoveNoPermission = Create("RemoveNoPerm", MyCrosshairIconInfo.IconPosition.TopRightCorner);
        }
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_RailSwitchInternalComponentDefinition)def;


            _switchablesByDummy.Clear();
            if (ob.Switchables == null || ob.Switchables.Length == 0)
            {
                Switchables = new RailSegmentSwitchable[0];
            }
            else
            {
                Switchables = ob.Switchables.Select(x => new RailSegmentSwitchable(x)).ToArray();
                for (var index = 0; index < Switchables.Length; index++)
                {
                    var k = Switchables[index];
                    if (string.IsNullOrWhiteSpace(k.Dummy))
                    {
                        MyDefinitionErrors.Add(ob.Package, $"Switchable has no dummy name, will not be interactable", LogSeverity.Warning);
                        continue;
                    }

                    if (_switchablesByDummy.ContainsKey(k.Dummy))
                    {
                        MyDefinitionErrors.Add(ob.Package, $"Switchable has duplicated dummy name, will not operate", LogSeverity.Error);
                        continue;
                    }

                    _switchablesByDummy.Add(k.Dummy, index);
                }
            }
        }
示例#4
0
        private void TryAddEntityScripts(Assembly assembly)
        {
            var gameLogicType = typeof(MyGameLogicComponent);
            var builderType   = typeof(MyObjectBuilder_Base);

            foreach (var type in assembly.GetTypes())
            {
                var descriptorArray = type.GetCustomAttributes(typeof(MyEntityComponentDescriptor), false);
                if (descriptorArray != null && descriptorArray.Length > 0)
                {
                    var descriptor = (MyEntityComponentDescriptor)descriptorArray[0];
                    var component  = (MyGameLogicComponent)Activator.CreateInstance(type);
                    if (gameLogicType.IsAssignableFrom(type) && builderType.IsAssignableFrom(descriptor.EntityBuilderType))
                    {
                        if (EntityScripts.Remove(descriptor.EntityBuilderType))
                        {
                            var msg = string.Format("Entity script overwritten: {0}", descriptor.EntityBuilderType.Name);
                            Debug.Fail(msg);
                            var c = new MyModContext();
                            c.Init(assembly.FullName, assembly.FullName);
                            MyDefinitionErrors.Add(c, msg, ErrorSeverity.Notice);
                        }
                        EntityScripts.Add(descriptor.EntityBuilderType, type);
                    }
                }
            }
        }
示例#5
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_BogieComponentDefinition)def;

            if (!ob.VerticalOffset.HasValue)
            {
                MyDefinitionErrors.Add(Package, $"Bogie {Id} has no {nameof(VerticalOffset)}", LogSeverity.Critical);
            }
            if (!ob.CoefficientOfFriction.HasValue)
            {
                MyDefinitionErrors.Add(Package, $"Bogie {Id} has no {nameof(CoefficientOfFriction)}", LogSeverity.Critical);
            }
            if (!ob.DetachDistance.HasValue)
            {
                MyDefinitionErrors.Add(Package, $"Bogie {Id} has no {nameof(DetachDistance)}", LogSeverity.Critical);
            }

            VerticalOffset = ob.VerticalOffset ?? 0;
            Layer          = ob.Layer;
            MaxVelocity    = ob.MaxVelocity ?? 0;
            BrakingCoefficientOfFriction = ob.BrakingCoefficientOfFriction ?? 0.2f;
            MaxForce                               = ob.MaxForce ?? 0;
            DetachDistance                         = ob.DetachDistance ?? 1.5f;
            CoefficientOfFriction                  = ob.CoefficientOfFriction ?? 0.01f;
            OrientationConvergenceFactor           = ob.OrientationConvergenceFactor ?? 1f;
            OrientationConvergenceFactorHorizontal = ob.OrientationConvergenceFactorHorizontal ?? OrientationConvergenceFactor;
            NeedsPower                             = ob.NeedsPower ?? PowerObserver.RequiredPowerEnum.None;
        }
示例#6
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiPlayerAttachmentComponentDefinition)def;

            if (ob.Anchor.HasValue)
            {
                Register(new ImmutableAttachmentInfo(ob));
            }
            if (ob.Attachments != null)
            {
                foreach (var k in ob.Attachments)
                {
                    Register(new ImmutableAttachmentInfo(ob, k));
                }
            }
            ImmutableAttachmentInfo wildcard = null;

            foreach (var v in _attachmentPointsByName.Values)
            {
                if (v.Dummies.Count == 0)
                {
                    if (wildcard != null)
                    {
                        MyDefinitionErrors.Add(Package, $"Attachments {wildcard.Name} and {v.Name} both are wildcard attachments", LogSeverity.Critical);
                    }
                    wildcard = v;
                }
            }

            _wildcardAttachment = wildcard;
        }
示例#7
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            _triggersByEvent.Clear();
            foreach (var trig in Triggers)
            {
                if (trig.To == MyStringHash.NullOrEmpty)
                {
                    MyDefinitionErrors.Add(Package, $"Trigger {trig} in {Id} has no to state", LogSeverity.Critical);
                }

                TriggerData trigs;
                if (!_triggersByEvent.TryGetValue(trig.Event, out trigs))
                {
                    _triggersByEvent.Add(trig.Event, trigs = new TriggerData());
                }

                if (trig.From == MyStringHash.NullOrEmpty && trigs.AnySourceTrigger != null)
                {
                    MyDefinitionErrors.Add(Package, $"Trigger {trig} trying to overwrite {trigs.AnySourceTrigger}", LogSeverity.Warning);
                }

                if (trig.From == MyStringHash.NullOrEmpty)
                {
                    trigs.AnySourceTrigger = trig;
                }
                else
                {
                    trigs.Triggers.Add(trig);
                }
            }
        }
示例#8
0
        private void ShowModErrorsMessageBox()
        {
            var errors = MyDefinitionErrors.GetErrors();

            if (m_currentModErrorsMessageBox != null)
            {
                RemoveScreen(m_currentModErrorsMessageBox);
            }

            var errorMessage = MyTexts.Get(MyCommonTexts.MessageBoxErrorModLoadingFailure);

            errorMessage.Append("\n");

            foreach (var error in errors)
            {
                if (error.Severity == TErrorSeverity.Critical && error.ModName != null)
                {
                    errorMessage.Append("\n");
                    errorMessage.Append(error.ModName);
                }
            }
            errorMessage.Append("\n");

            m_currentModErrorsMessageBox = MyGuiSandbox.CreateMessageBox(messageText: errorMessage, messageCaption: MyTexts.Get(MyCommonTexts.MessageBoxCaptionError));
            AddScreen(m_currentModErrorsMessageBox);
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            var b = (MyObjectBuilder_EquiVoxelEffectComponentDefinition)builder;

            SourceBone = b.SourceBone;
            var tmp = new Dictionary <MyDefinitionId, IReadOnlyCollection <MyDefinitionId> >();

            if (b.Effects != null)
            {
                foreach (var e in b.Effects)
                {
                    IReadOnlyCollection <MyDefinitionId> eft;
                    if (!tmp.TryGetValue(e.Material, out eft))
                    {
                        tmp.Add(e.Material, eft = new HashSet <MyDefinitionId>());
                    }
                    ((ICollection <MyDefinitionId>)eft).Add(e.Effect);
                }
            }

            if (tmp.Count == 0)
            {
                MyDefinitionErrors.Add(Package, $"Voxel effect component {Id} has no effects", LogSeverity.Error);
            }

            Effects = tmp;
        }
示例#10
0
        private void Compile(IEnumerable <string> scriptFiles, string assemblyName, bool zipped, MyModContext context)
        {
#if XB1
            System.Diagnostics.Debug.Assert(false, "Unsupported runtime script compilation on XB1.");
#else
            Assembly assembly = null;
            bool     compiled = false;
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream  = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(context, string.Format("Cannot load {0}", Path.GetFileName(file)), TErrorSeverity.Error);
                        MyDefinitionErrors.Add(context, e.Message, TErrorSeverity.Error);
                    }
                }
                compiled = IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
            }
            else
            {
                compiled = IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
            }
            Debug.Assert(compiled == (assembly != null), "Compile results inconsistency!");
            if (assembly != null && compiled)
            {
                AddAssembly(context, MyStringId.GetOrCompute(assemblyName), assembly);
            }
            else
            {
                MyDefinitionErrors.Add(context, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var error in m_errors)
                {
                    MyDefinitionErrors.Add(context, error.ToString(), TErrorSeverity.Error);
                    Debug.Assert(false, error.ToString());
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
#endif
        }
示例#11
0
        private void TryAddEntityScripts(MyModContext context, Assembly assembly)
        {
            var gameLogicType = typeof(MyGameLogicComponent);
            var builderType   = typeof(MyObjectBuilder_Base);

            foreach (var type in assembly.GetTypes())
            {
                var descriptorArray = type.GetCustomAttributes(typeof(MyEntityComponentDescriptor), false);
                if (descriptorArray != null && descriptorArray.Length > 0)
                {
                    var descriptor = (MyEntityComponentDescriptor)descriptorArray[0];
                    try
                    {
                        var component = (MyGameLogicComponent)Activator.CreateInstance(type);

                        if (descriptor.EntityBuilderSubTypeNames != null && descriptor.EntityBuilderSubTypeNames.Length > 0)
                        {
                            foreach (string subTypeName in descriptor.EntityBuilderSubTypeNames)
                            {
                                if (gameLogicType.IsAssignableFrom(type) && builderType.IsAssignableFrom(descriptor.EntityBuilderType))
                                {
                                    if (!SubEntityScripts.ContainsKey(new Tuple <Type, string>(descriptor.EntityBuilderType, subTypeName)))
                                    {
                                        SubEntityScripts.Add(new Tuple <Type, string>(descriptor.EntityBuilderType, subTypeName), new HashSet <Type>());
                                    }
                                    else
                                    {
                                        MyDefinitionErrors.Add(context, "Possible entity type script logic collision", TErrorSeverity.Warning);
                                    }

                                    SubEntityScripts[new Tuple <Type, string>(descriptor.EntityBuilderType, subTypeName)].Add(type);
                                }
                            }
                        }
                        else
                        {
                            if (gameLogicType.IsAssignableFrom(type) && builderType.IsAssignableFrom(descriptor.EntityBuilderType))
                            {
                                if (!EntityScripts.ContainsKey(descriptor.EntityBuilderType))
                                {
                                    EntityScripts.Add(descriptor.EntityBuilderType, new HashSet <Type>());
                                }
                                else
                                {
                                    MyDefinitionErrors.Add(context, "Possible entity type script logic collision", TErrorSeverity.Warning);
                                }

                                EntityScripts[descriptor.EntityBuilderType].Add(type);
                            }
                        }
                    }
                    catch (Exception)
                    {
                        MySandboxGame.Log.WriteLine("Exception during loading of type : " + type.Name);
                    }
                }
            }
        }
示例#12
0
        private void Compile(IEnumerable <string> scriptFiles, string assemblyName, bool zipped)
        {
            Assembly assembly = null;
            var      c        = new MyModContext();

            c.Init(assemblyName, assemblyName);
            if (zipped)
            {
                var tmp = Path.GetTempPath();
                foreach (var file in scriptFiles)
                {
                    try
                    {
                        var newPath = string.Format("{0}{1}", tmp, Path.GetFileName(file));
                        var stream  = MyFileSystem.OpenRead(file);
                        using (var sr = new StreamReader(stream))
                        {
                            stream = MyFileSystem.OpenWrite(newPath);// (newPath);
                            using (var sw = new StreamWriter(stream))
                            {
                                sw.Write(sr.ReadToEnd()); //create file in tmp for debugging
                            }
                        }
                        m_cachedFiles.Add(newPath);
                    }
                    catch (Exception e)
                    {
                        MySandboxGame.Log.WriteLine(e);
                        MyDefinitionErrors.Add(c, string.Format("Cannot load {0}", Path.GetFileName(file)), ErrorSeverity.Error);
                        MyDefinitionErrors.Add(c, e.Message, ErrorSeverity.Error);
                    }
                }
                IlCompiler.CompileFileModAPI(assemblyName, m_cachedFiles.ToArray(), out assembly, m_errors);
            }
            else
            {
                IlCompiler.CompileFileModAPI(assemblyName, scriptFiles.ToArray(), out assembly, m_errors);
            }
            if (assembly != null)
            {
                AddAssembly(MyStringId.GetOrCompute(assemblyName), assembly);
            }
            else
            {
                MyDefinitionErrors.Add(c, string.Format("Compilation of {0} failed:", assemblyName), ErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var error in m_errors)
                {
                    MyDefinitionErrors.Add(c, error.ToString(), ErrorSeverity.Error);
                    Debug.Assert(false, error.ToString());
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            var b = (MyObjectBuilder_EquiComponentEffectDefinition)builder;

            if (!b.AddedComponent.HasValue)
            {
                MyDefinitionErrors.Add(Package, $"{Id} has AppliedEffect == null", LogSeverity.Error);
            }
//            else if (!typeof(MyObjectBuilder_EntityComponent).IsAssignableFrom(b.AddedComponent.Value.TypeId))
//                MyDefinitionErrors.Add(Package, $"{Id} has AppliedEffect that isn't an entity component", LogSeverity.Error);
        }
        public static void Init()
        {
            if (!MyPerGameSettings.EnableTutorials)
            {
                return;
            }
            var path = Path.Combine(MyFileSystem.ContentPath, Path.Combine("Data", "Tutorials.sbx"));

            if (!MyFileSystem.FileExists(path))
            {
                Debug.Fail("Tutorials.sbx not found");
                return;
            }
            MyDataIntegrityChecker.HashInFile(path);
            MyObjectBuilder_TutorialsHelper objBuilder = null;

            if (!MyObjectBuilderSerializer.DeserializeXML(path, out objBuilder))
            {
                Debug.Fail("Tutorials deserialize fail");
            }

            if (objBuilder == null)
            {
                MyDefinitionErrors.Add(MyModContext.BaseGame, "Tutorials: Cannot load definition file, see log for details", TErrorSeverity.Error);
                return;
            }
            m_tutorialUnlockedBy = new Dictionary <string, List <string> >();

            if (objBuilder.Tutorials != null)
            {
                foreach (var tut in objBuilder.Tutorials)
                {
                    List <string> list;
                    if (!m_tutorialUnlockedBy.TryGetValue(tut.Name, out list))
                    {
                        list = new List <string>();
                        m_tutorialUnlockedBy.Add(tut.Name, list);
                    }

                    if (tut.UnlockedBy != null)
                    {
                        foreach (var other in tut.UnlockedBy)
                        {
                            list.Add(other);
                        }
                    }
                }
            }

            RefreshUnlocked();
        }
示例#15
0
 private void EnsureMemorized()
 {
     if (_hasMemorized)
     {
         return;
     }
     _memorizedModifier = MyDefinitionManager.Get <EquiModifierBaseDefinition>(_modifierId);
     if (_memorizedModifier == null)
     {
         MyDefinitionErrors.Add(_owner.Package, $"Failed to find modifier {_modifierId} for {_owner.Id}", LogSeverity.Critical);
     }
     _memorizedData = _memorizedModifier?.CreateData(_modifierData);
     _hasMemorized  = true;
 }
示例#16
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiPowerStateTransitionDefinition)def;

            _triggersBySource.Clear();
            foreach (var t in ob.Triggers)
            {
                var trig = new Trigger(t);
                if (trig.To == MyStringHash.NullOrEmpty)
                {
                    MyDefinitionErrors.Add(Package, $"Trigger {trig} in {Id} has no to destination state", LogSeverity.Critical);
                }

                _triggersBySource.AddMulti(trig.From, trig);
            }
        }
示例#17
0
        public override void RecreateControls(bool constructor)
        {
            AddCaption(MySpaceTexts.ScreenDebugOfficial_ErrorLogCaption, captionOffset: new Vector2(0.0f, MyGuiConstants.SCREEN_CAPTION_DELTA_Y * -0.5f));

            m_currentPosition.Y += MyGuiConstants.SCREEN_CAPTION_DELTA_Y;

            var text = AddMultilineText(size: Size - new Vector2(0.0f, MyGuiConstants.SCREEN_CAPTION_DELTA_Y), offset: Size * -0.5f, textScale: 0.7f);

            if (MyDefinitionErrors.GetErrors().Count() == 0)
            {
                text.AppendText(MyTexts.Get(MySpaceTexts.ScreenDebugOfficial_NoErrorText));
            }
            foreach (var error in MyDefinitionErrors.GetErrors())
            {
                text.AppendText(error.ToString(), text.Font, text.TextScaleWithLanguage, error.GetSeverityColor().ToVector4());
                text.AppendLine();
                text.AppendLine(); // Extra newline to separate different errors
            }
        }
示例#18
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_RailSegmentDefinition)def;

            if (ob.Capabilities == null || ob.Capabilities.Length == 0)
            {
                MyDefinitionErrors.Add(def.Package, $"Definition {def.Id} has no defined capabilities, using default", LogSeverity.Warning);
                _caps = new[] { RailSegmentCaps.Default };
                return;
            }

            _caps = new RailSegmentCaps[ob.Capabilities.Length];
            for (var i = 0; i < ob.Capabilities.Length; i++)
            {
                _caps[i] = new RailSegmentCaps(ob.Capabilities[i]);
            }
            Array.Sort(_caps, (a, b) => Comparer <float> .Default.Compare(a.ActivationLevel, b.ActivationLevel));
        }
示例#19
0
        private void Register(ImmutableAttachmentInfo attachment)
        {
            if (_attachmentPointsByName.ContainsKey(attachment.Name))
            {
                MyDefinitionErrors.Add(Package, $"Can't register {attachment.Name} twice", LogSeverity.Critical);
                return;
            }

            _attachmentPointsByName.Add(attachment.Name, attachment);
            foreach (var dum in attachment.Dummies)
            {
                if (_attachmentPointByDummy.ContainsKey(dum))
                {
                    MyDefinitionErrors.Add(Package, $"Can't register attachment for dummy {dum} twice", LogSeverity.Critical);
                    continue;
                }

                _attachmentPointByDummy.Add(dum, attachment);
            }
        }
        private void CopyErrorLogToClipboard(MyGuiControlButton obj)
        {
            StringBuilder text = new StringBuilder();

            if (MyDefinitionErrors.GetErrors().Count() == 0)
            {
                text.Append(MyTexts.Get(MySpaceTexts.ScreenDebugOfficial_NoErrorText));
            }
            foreach (var error in MyDefinitionErrors.GetErrors())
            {
                text.Append(error.ToString());
                text.AppendLine();
            }

            Thread thread = new Thread(() => System.Windows.Forms.Clipboard.SetText(text.ToString()));

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
        }
示例#21
0
            public ImmutableAttachmentInfo(MyObjectBuilder_EquiPlayerAttachmentComponentDefinition @base,
                                           MyObjectBuilder_EquiPlayerAttachmentComponentDefinition.AttachmentInfo ob)
            {
                Name               = ob.Name;
                Anchor             = ob.Anchor;
                _animations        = ob.Animations != null && ob.Animations.Length > 0 ? ob.Animations.Select(x => new AnimationDesc(x)).ToArray() : null;
                EmptyActionDesc    = (MyActionDescription)ob.EmptyAction;
                OccupiedActionDesc = (MyActionDescription)ob.OccupiedAction;
                _dummyNames.Clear();
                if (ob.DummyNames == null)
                {
                    return;
                }
                foreach (var d in ob.DummyNames)
                {
                    if (!string.IsNullOrWhiteSpace(d))
                    {
                        _dummyNames.Add(d);
                    }
                }

                var tmpOps = new List <ImmutableEffectOperations>();

                if (ob.EffectOperations != null)
                {
                    foreach (var eo in ob.EffectOperations)
                    {
                        var res = new ImmutableEffectOperations(eo);
                        if (res.IsValid)
                        {
                            tmpOps.Add(res);
                        }
                        else
                        {
                            MyDefinitionErrors.Add(@base.Package, $"{@base.Id} has an invalid effect operation", LogSeverity.Error);
                        }
                    }
                }

                EffectOperations = tmpOps;
            }
示例#22
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiEventStateDefinitionBase)def;

            Defer = ob.Defer;
            _events.Clear();
            foreach (var t in ob.Triggers)
            {
                var trig = new Trigger(t);
                if (string.IsNullOrEmpty(trig.Event))
                {
                    MyDefinitionErrors.Add(Package, $"Trigger {t} in {Id} has no event", LogSeverity.Critical);
                }
                if (trig.From == MyStringHash.NullOrEmpty && trig.To == MyStringHash.NullOrEmpty)
                {
                    MyDefinitionErrors.Add(Package, $"Trigger {t} in {Id} has no from and no to state", LogSeverity.Critical);
                }
                _triggers.Add(trig);
                _events.Add(trig.Event);
            }
        }
示例#23
0
            internal bool AssertValid(MyObjectBuilder_EquiPlayerAttachmentComponentDefinition parent)
            {
                var good = true;

                if (_operations.Count == 0)
                {
                    MyDefinitionErrors.Add(parent.Package, $"{parent.Id} has operation group with no operations", LogSeverity.Error);
                    good = false;
                }

                if (When == MyObjectBuilder_EquiPlayerAttachmentComponentDefinition.EffectOperationsInfo.TriggerTime.Continuous)
                {
                    if (IntervalMs <= 0)
                    {
                        MyDefinitionErrors.Add(parent.Package, $"{parent.Id} has operation group with continuous trigger and zero interval",
                                               LogSeverity.Error);
                        good = false;
                    }
                }
                else
                {
                    if (IntervalMs != 0)
                    {
                        MyDefinitionErrors.Add(parent.Package, $"{parent.Id} has operation group with non continuous trigger and non zero interval",
                                               LogSeverity.Error);
                        good = false;
                    }
                }

                // ReSharper disable once InvertIf
                if (When == MyObjectBuilder_EquiPlayerAttachmentComponentDefinition.EffectOperationsInfo.TriggerTime.Leave && DelayMs != 0)
                {
                    MyDefinitionErrors.Add(parent.Package, $"{parent.Id} has operation group with leave trigger and non zero delay", LogSeverity.Error);
                    good = false;
                }

                return(good);
            }
        private void CopyErrorLogToClipboard(MyGuiControlButton obj)
        {
#if !XB1
            StringBuilder text = new StringBuilder();

            if (MyDefinitionErrors.GetErrors().Count() == 0)
            {
                text.Append(MyTexts.Get(MyCommonTexts.ScreenDebugOfficial_NoErrorText));
            }
            foreach (var error in MyDefinitionErrors.GetErrors())
            {
                text.Append(error.ToString());
                text.AppendLine();
            }

            Thread thread = new Thread(() => System.Windows.Forms.Clipboard.SetText(text.ToString()));
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
#else // XB1
            System.Diagnostics.Debug.Assert(false, "XB1 TODO?");
#endif // XB1
        }
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_BendyShapeComponentDefinition)def;

            Width = ob.Width;
            if (Width <= 0)
            {
                MyDefinitionErrors.Add(def.Package, $"{GetType().Name} {def.GetId()} has {nameof(Width)}={Width} <= 0", LogSeverity.Warning);
            }
            Height = ob.Height;
            if (Height <= 0)
            {
                MyDefinitionErrors.Add(def.Package, $"{GetType().Name} {def.GetId()} has {nameof(Height)}={Height} <= 0", LogSeverity.Warning);
            }
            Segments = ob.Segments;
            if (Segments <= 0)
            {
                MyDefinitionErrors.Add(def.Package, $"{GetType().Name} {def.GetId()} has {nameof(Segments)}={Segments} <= 0", LogSeverity.Warning);
            }

            VolumeErrorTolerance = ob.VolumeErrorTolerance ?? 0.1f;
        }
示例#26
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiStateAnimVarsDefinition)def;

            foreach (var state in ob.States)
            {
                foreach (var when in state.When)
                {
                    var stateKey = MyStringHash.GetOrCompute(when);
                    Dictionary <MyStringId, SetInstruction> instructions;
                    if (!_states.TryGetValue(stateKey, out instructions))
                    {
                        _states.Add(stateKey, instructions = new Dictionary <MyStringId, SetInstruction>());
                    }

                    foreach (var instruction in state.Instructions)
                    {
                        var   varKey = MyStringId.GetOrCompute(instruction.Key);
                        float valOutput;
                        if (!string.IsNullOrWhiteSpace(instruction.Value) && float.TryParse(instruction.Value, out valOutput))
                        {
                            instructions[varKey] = new SetInstruction(valOutput);
                        }
                        else if (instruction.Transform.HasValue)
                        {
                            var mat = instruction.Transform.Value.GetMatrix();
                            instructions[varKey] = new SetInstruction(new MyTransformD(in mat));
                        }
                        else
                        {
                            MyDefinitionErrors.Add(Package, $"State {when} instruction {varKey} has no value", LogSeverity.Warning);
                        }
                    }
                }
            }
        }
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            var def = (MyObjectBuilder_ConstructableComponentDefinition)builder;

            Components      = new ReadOnlyList <CcComponent>(def.Components.Select(x => new CcComponent(x)).ToList());
            TotalComponents = Components.Sum(x => x.Count);
            if (TotalComponents == 0)
            {
                MyDefinitionErrors.Add(Package, $"{nameof(MyObjectBuilder_ConstructableComponentDefinition.BuildProgressModels)} has no values",
                                       LogSeverity.Critical);
            }

            var models = def.BuildProgressModels.Select(x => new CcBuildModel(x)).ToList();

            models.Sort((a, b) => a.UpperBound.CompareTo(b.UpperBound));
            BuildModels = new ReadOnlyList <CcBuildModel>(models);
            if (BuildModels.Count == 0)
            {
                MyDefinitionErrors.Add(Package, $"{nameof(MyObjectBuilder_ConstructableComponentDefinition.BuildProgressModels)} has no values",
                                       LogSeverity.Critical);
            }

            if (!def.BuildTime.HasValue)
            {
                MyDefinitionErrors.Add(Package, $"{nameof(MyObjectBuilder_ConstructableComponentDefinition.BuildTime)} has no value", LogSeverity.Critical);
            }
            BuildTime = def.BuildTime != null ? (TimeSpan)def.BuildTime.Value : TimeSpan.Zero;

            if (!def.MaxIntegrity.HasValue)
            {
                MyDefinitionErrors.Add(Package, $"{nameof(MyObjectBuilder_ConstructableComponentDefinition.MaxIntegrity)} has no value",
                                       LogSeverity.Critical);
            }
            MaxIntegrity = def.MaxIntegrity ?? 0;
        }
示例#28
0
        protected override void Init(MyObjectBuilder_DefinitionBase def)
        {
            base.Init(def);
            var ob = (MyObjectBuilder_EquiHarvestableComponentDefinition)def;

            _lootTableByTag.Clear();
            _lootTableByItem.Clear();
            if (ob.Entries == null)
            {
                return;
            }
            foreach (var k in ob.Entries)
            {
                if (string.IsNullOrWhiteSpace(k.From))
                {
                    MyDefinitionErrors.Add(Package, $"{Id} has an entry with no from state", LogSeverity.Warning);
                    continue;
                }

                if (k.Harvesters == null || k.Harvesters.Length == 0)
                {
                    MyDefinitionErrors.Add(Package, $"{Id} has an entry with no harvesters", LogSeverity.Warning);
                    continue;
                }

                MyLootTableDefinition lootTable = null;
                if (k.LootTable.HasValue)
                {
                    lootTable = MyDefinitionManager.Get <MyLootTableDefinition>(k.LootTable.Value);
                    if (lootTable == null)
                    {
                        MyDefinitionErrors.Add(Package, $"{Id} has an entry from {k.From} referring to missing loot table {k.LootTable}",
                                               LogSeverity.Warning);
                        continue;
                    }
                }

                foreach (var item in k.Harvesters)
                {
                    if (!item.IsValid())
                    {
                        MyDefinitionErrors.Add(Package, $"{Id} has an entry with an invalid harvester", LogSeverity.Warning);
                    }
                }


                var sourceState = MyStringHash.GetOrCompute(k.From);
                var destState   = MyStringHash.GetOrCompute(k.To);
                var data        = new Data(lootTable, destState, k.RequiresPermission, k.ActionHint ?? "Harvest",
                                           MyStringHash.GetOrCompute(k.ActionIcon ?? "Pickup_Item"));

                foreach (var item in k.Harvesters)
                {
                    if (!item.IsValid())
                    {
                        continue;
                    }

                    if (!string.IsNullOrWhiteSpace(item.Tag))
                    {
                        _lootTableByTag[new TagKey(sourceState, MyStringHash.GetOrCompute(item.Tag))] = data;
                    }
                    else
                    {
                        _lootTableByItem[new DefinitionKey(sourceState, item)] = data;
                    }
                }
            }
        }
示例#29
0
        /// <summary>
        /// Compiles the mod
        /// </summary>
        /// <returns></returns>
        public bool Compile()
        {
            // Compile
            if (m_compile)
            {
                if (m_type == WorkshopType.Mod)
                {
                    if (_compileMethod != null)
                    {
                        MySandboxGame.Log.WriteLineAndConsole("Compiling...");
#if SE
                        var mod = new MyModContext();

                        // Because of a regression in SE, we need to create a checkpoint ModItem to set the Id.
                        var modob = new MyObjectBuilder_Checkpoint.ModItem();
                        modob.Name = Path.GetFileName(m_modPath);

                        if (ModId.Length > 0)
                        {
                            modob.PublishedFileId      = m_workshopItems[m_modId[0]].Id;
                            modob.PublishedServiceName = m_workshopItems[m_modId[0]].ServiceName;
                            modob.FriendlyName         = m_workshopItems[m_modId[0]].Title;
                            modob.SetModData(m_workshopItems[m_modId[0]]);
                        }
                        else
                        {
                            // Fake it, so the compile still works
                            modob.PublishedFileId      = 0;
                            modob.PublishedServiceName = MyGameService.GetDefaultUGC().ServiceName;
                            modob.FriendlyName         = Title;
                        }
                        mod.Init(modob);

                        // Call init again, to make sure the path in set properly to the local mod directory
                        mod.Init(m_title, null, m_modPath);
#else
                        var workshopItem = new MyLocalWorkshopItem(new VRage.ObjectBuilders.SerializableModReference(Path.GetFileName(m_modPath), 0));
                        var mod          = new MyModContext(workshopItem, 0);
#endif
                        _compileMethod(
#if SE
                            m_modPath,
#endif
                            mod
                            );

                        // Process any errors
#if SE
                        var errors = MyDefinitionErrors.GetErrors();
#else
                        var compileMessages = _scriptManager.GetType().GetField("m_messages", BindingFlags.NonPublic | BindingFlags.Instance);
                        var errors          = (compileMessages.GetValue(_scriptManager) as List <MyScriptCompiler.Message>) ?? new List <MyScriptCompiler.Message>();
#endif
                        if (errors.Count > 0)
                        {
                            int errorCount   = 0;
                            int warningCount = 0;

                            // This is not efficient, but I'm lazy
                            foreach (var error in errors)
                            {
                                if (error.Severity >= TErrorSeverity.Error)
                                {
                                    errorCount++;
                                }
                                if (error.Severity == TErrorSeverity.Warning)
                                {
                                    warningCount++;
                                }
                            }

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile errors:", errorCount));
                            }
                            if (warningCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile warnings:", warningCount));
                            }

                            // Output raw message, which is usually in msbuild friendly format, for automated tools
                            foreach (var error in errors)
#if SE
                            { System.Console.WriteLine(error.Message); }
#else
                            { System.Console.WriteLine(error.Text); }
#endif

#if SE
                            MyDefinitionErrors.Clear();     // Clear old ones, so next mod starts fresh
#endif

                            if (errorCount > 0)
                            {
                                MySandboxGame.Log.WriteLineAndConsole("Compilation FAILED!");
                                return(false);
                            }
                        }
                        MySandboxGame.Log.WriteLineAndConsole("Compilation successful!");
                    }
                    else
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format(Constants.ERROR_Reflection, "LoadScripts"));
                    }
                }
#if SE
                else if (m_type == WorkshopType.IngameScript)
                {
                    // Load the ingame script from the disk
                    // I don't like this, but meh
                    var input   = new StreamReader(Path.Combine(m_modPath, "Script.cs"));
                    var program = input.ReadToEnd();
                    input.Close();
                    var scripts = new List <Script>();
                    scripts.Add(MyScriptCompiler.Static.GetIngameScript(program, "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name, "sealed partial"));

                    var messages = new List <Message>();
                    var assembly = MyVRage.Platform.Scripting.CompileIngameScriptAsync(Path.Combine(VRage.FileSystem.MyFileSystem.UserDataPath, "SEWT-Script" + Path.GetFileName(m_modPath)), program, out messages, "SEWT Compiled PB Script", "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name).Result;

                    if (messages.Count > 0)
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format("There are {0} compile messages:", messages.Count));
                        int errors = 0;
                        foreach (var msg in messages)
                        {
                            MySandboxGame.Log.WriteLineAndConsole(msg.Text);

                            if (msg.IsError)
                            {
                                errors++;
                            }
                        }
                        if (errors > 0)
                        {
                            return(false);
                        }
                    }

                    if (assembly == null)
                    {
                        return(false);
                    }
                }
#endif
                return(true);
            }
            return(true);
        }
示例#30
0
        protected override void Init(MyObjectBuilder_DefinitionBase builder)
        {
            base.Init(builder);
            var def = (MyObjectBuilder_BendyComponentDefinition)builder;

            #region Config

            Layer = def.Layer;
            if (string.IsNullOrWhiteSpace(Layer))
            {
                MyDefinitionErrors.Add(def.Package,
                                       $"{nameof(BendyComponentDefinition)} {builder.GetId()} has {nameof(Layer)} that is null or whitespace",
                                       LogSeverity.Error);
            }

            var nodes = new ImmutableNode[def.Nodes?.Length ?? 0];
            if (def.Nodes != null)
            {
                for (var i = 0; i < def.Nodes.Length; i++)
                {
                    var n = def.Nodes[i];
                    var m = Matrix.CreateWorld(n.Position, n.Forward, n.Up);
                    if (Vector3.IsZero(m.Forward))
                    {
                        MyDefinitionErrors.Add(def.Package,
                                               $"{nameof(BendyComponentDefinition)} {builder.GetId()} node {i} has an invalid matrix forward",
                                               LogSeverity.Error);
                    }
                    if (Vector3.IsZero(m.Up))
                    {
                        MyDefinitionErrors.Add(def.Package,
                                               $"{nameof(BendyComponentDefinition)} {builder.GetId()} node {i} has an invalid matrix up",
                                               LogSeverity.Error);
                    }
                    if (Math.Abs(m.Forward.Dot(m.Up)) > 1e-3f)
                    {
                        MyDefinitionErrors.Add(def.Package,
                                               $"{nameof(BendyComponentDefinition)} {builder.GetId()} node {i} has an invalid matrix",
                                               LogSeverity.Error);
                    }
                    nodes[i] = new ImmutableNode(m, n.Movable);
                }
            }

            var edges = new ImmutableEdge[def.Edges?.Length ?? 0];
            if (edges.Length > 0 && nodes.Length == 0)
            {
                throw new Exception($"Component {builder.GetId()} has edges when it has no nodes.  Unrecoverable.");
            }
            if (def.Edges != null)
            {
                for (var i = 0; i < def.Edges.Length; i++)
                {
                    var e  = def.Edges[i];
                    var n0 = MathHelper.Clamp((int)e.From, 0, nodes.Length - 1);
                    var n1 = MathHelper.Clamp((int)e.To, 0, nodes.Length - 1);
                    if (n0 != e.From)
                    {
                        MyDefinitionErrors.Add(def.Package,
                                               $"{nameof(BendyComponentDefinition)} {builder.GetId()} edge {i} refers to an invalid from",
                                               LogSeverity.Error);
                    }
                    if (n1 != e.To)
                    {
                        MyDefinitionErrors.Add(def.Package,
                                               $"{nameof(BendyComponentDefinition)} {builder.GetId()} edge {i} refers to an invalid to",
                                               LogSeverity.Error);
                    }

                    var bones = e.Bones?.Split(null).Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();
                    edges[i] = new ImmutableEdge((uint)n0, (uint)n1, e.Mode, bones != null ? new ReadOnlyList <string>(bones) : null, e.Control1, e.Control2);
                }
            }

            Nodes = new ReadOnlyList <ImmutableNode>(nodes);
            Edges = new ReadOnlyList <ImmutableEdge>(edges);

            #endregion

            #region Bone Meta

            var tmp = new Dictionary <string, List <BoneEdgeMetadata> >();
            for (var i = 0; i < Edges.Count; i++)
            {
                var e = Edges[i];
                if (e.Bones == null || e.Bones.Count <= 0)
                {
                    continue;
                }
                for (var index = 0; index < e.Bones.Count; index++)
                {
                    var b = e.Bones[index];
                    List <BoneEdgeMetadata> src;
                    if (!tmp.TryGetValue(b, out src))
                    {
                        tmp.Add(b, src = new List <BoneEdgeMetadata>());
                    }
                    src.Add(new BoneEdgeMetadata((uint)i, index / (float)(e.Bones.Count - 1), 1f));
                }
            }

            BoneMetadata = tmp.ToDictionary(x => x.Key, x =>
            {
                var totalBoneWeight = x.Value.Sum(y => y.EdgeWeight);
                var dest            = new List <BoneEdgeMetadata>(x.Value.Count);
                foreach (var old in x.Value)
                {
                    if (old.EdgeWeight < 0)
                    {
                        continue;
                    }
                    dest.Add(new BoneEdgeMetadata(old.Edge, old.EdgeFactor, old.EdgeWeight / totalBoneWeight));
                }

                return((IReadOnlyList <BoneEdgeMetadata>) new ReadOnlyList <BoneEdgeMetadata>(dest));
            });

            #endregion

            #region Constraints

            Distance = def.Distance?.Immutable() ??
                       new ImmutableRange <float>(RailConstants.DefaultMinLength, RailConstants.DefaultMaxLength);
            if (Distance.Min > Distance.Max)
            {
                MyDefinitionErrors.Add(def.Package,
                                       $"{nameof(BendyComponentDefinition)} {builder.GetId()} distance has min > max",
                                       LogSeverity.Error);
            }
            PreferredDistance = def.PreferredDistance ?? ((Distance.Max + Distance.Min) / 2);
            MaxAngleDegrees   = def.MaxAngleDegrees ?? RailConstants.DefaultMaxAngleDegrees;
            if (MaxAngleDegrees < 0)
            {
                MyDefinitionErrors.Add(def.Package,
                                       $"{nameof(BendyComponentDefinition)} {builder.GetId()} max angle is less than zero",
                                       LogSeverity.Error);
            }
            MaxGradeRatio = def.MaxGradeRatio ?? RailConstants.DefaultMaxGradeRatio;
            if (MaxGradeRatio < 0)
            {
                MyDefinitionErrors.Add(def.Package,
                                       $"{nameof(BendyComponentDefinition)} {builder.GetId()} max grade ratio is less than zero",
                                       LogSeverity.Error);
            }

            #endregion
        }