コード例 #1
0
        public MyModContext GetModContext()
        {
            MyModContext modContext = new MyModContext();

            modContext.Init(new MyObjectBuilder_Checkpoint.ModItem(WorkshopId, "Steam"));
            modContext.Init(WorkshopId.ToString(), null, ModLocation);
            return(modContext);
        }
コード例 #2
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);
                    }
                }
            }
        }
コード例 #3
0
        private void Compile(IEnumerable <string> scriptFiles, string assemblyName, bool zipped)
        {
            Assembly assembly = null;
            bool     compiled = false;
            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)), TErrorSeverity.Error);
                        MyDefinitionErrors.Add(c, 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(MyStringId.GetOrCompute(assemblyName), assembly);
            }
            else
            {
                MyDefinitionErrors.Add(c, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
                foreach (var error in m_errors)
                {
                    MyDefinitionErrors.Add(c, error.ToString(), TErrorSeverity.Error);
                    Debug.Assert(false, error.ToString());
                }
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
        }
コード例 #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 (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
                                {
                                    var c = new MyModContext();
                                    c.Init(assembly.FullName, assembly.FullName);
                                    MyDefinitionErrors.Add(c, "Possible entity type script logic collision", ErrorSeverity.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
                            {
                                var c = new MyModContext();
                                c.Init(assembly.FullName, assembly.FullName);
                                MyDefinitionErrors.Add(c, "Possible entity type script logic collision", ErrorSeverity.Warning);
                            }

                            EntityScripts[descriptor.EntityBuilderType].Add(type);
                        }
                    }
                }
            }
        }
コード例 #5
0
        private void ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData)
        {
            MyExternalDebugStructures.ACReloadInGameMsg msgReload;
            if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload))
            {
                try
                {
                    string acAddress = msgReload.ACAddress;
                    string acName    = msgReload.ACName;

                    MyObjectBuilder_Definitions allDefinitions; // = null;
                    // load animation controller definition from SBC file
                    if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) &&
                        allDefinitions.Definitions != null &&
                        allDefinitions.Definitions.Length > 0)
                    {
                        var          firstDef = allDefinitions.Definitions[0];
                        MyModContext context  = new MyModContext();
                        context.Init("AnimationControllerDefinition", Path.GetFileName(acAddress));
                        MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition();
                        animationControllerDefinition.Init(firstDef, context);

                        // swap animation controller for each entity
                        foreach (MyEntity entity in MyEntities.GetEntities())
                        {
                            MyCharacter character = entity as MyCharacter;
                            if (character != null && character.Definition.AnimationController == acName)
                            {
                                character.AnimationController.InitFromDefinition(animationControllerDefinition);
                                character.ObtainBones();
                            }
                        }

                        // update in def. manager
                        MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName);
                        MyAnimationControllerDefinition animControllerDefInManager =
                            MyDefinitionManager.Static.GetDefinition <MyAnimationControllerDefinition>(animSubtypeNameHash);
                        animControllerDefInManager.Init(firstDef, context);
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                }
            }
        }
コード例 #6
0
        public void LoadData()
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyScriptManager.LoadData");
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - START");
            MySandboxGame.Log.IncreaseIndent();
            Static = this;
            Scripts.Clear();
            EntityScripts.Clear();
            SubEntityScripts.Clear();
            if (Sync.IsServer)
            {
                LoadScripts(MyFileSystem.ContentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.CurrentPath != null)
            {
                LoadScripts(MySession.Static.CurrentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.Mods != null)
            {
                foreach (var mod in MySession.Static.Mods)
                {
                    var mc = new MyModContext();
                    mc.Init(mod);
                    LoadScripts(Path.Combine(MyFileSystem.ModsPath, mod.Name), mc);
                }
            }

            foreach (var ass in Scripts.Values)
            {
#if XB1 // XB1_ALLINONEASSEMBLY
                System.Diagnostics.Debug.Assert(false, "XB1 TODO?");
#else // !XB1
                if (MyFakes.ENABLE_TYPES_FROM_MODS) // Highly experimental!
                {
                    MyGlobalTypeMetadata.Static.RegisterAssembly(ass);
                }

                MySandboxGame.Log.WriteLine(string.Format("Script loaded: {0}", ass.FullName));
#endif // !XB1
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - END");

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
コード例 #7
0
        public void LoadData()
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyScriptManager.LoadData");
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - START");
            MySandboxGame.Log.IncreaseIndent();
            Static = this;
            Scripts.Clear();
            EntityScripts.Clear();
            SubEntityScripts.Clear();
            if (Sync.IsServer)
            {
                LoadScripts(MyFileSystem.ContentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.CurrentPath != null)
            {
                LoadScripts(MySession.Static.CurrentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.Mods != null)
            {
                foreach (var mod in MySession.Static.Mods)
                {
                    var mc = new MyModContext();
                    mc.Init(mod);
                    LoadScripts(Path.Combine(MyFileSystem.ModsPath, mod.Name), mc);
                }
            }

            foreach (var ass in Scripts.Values)
            {
#if XB1 // XB1_ALLINONEASSEMBLY
                System.Diagnostics.Debug.Assert(false, "XB1 TODO?");
#else // !XB1
                if (MyFakes.ENABLE_TYPES_FROM_MODS) // Highly experimental!
                {
                    MyGlobalTypeMetadata.Static.RegisterAssembly(ass);
                }

                MySandboxGame.Log.WriteLine(string.Format("Script loaded: {0}", ass.FullName));
#endif // !XB1
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - END");

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
コード例 #8
0
        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);
        }
コード例 #9
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);
        }
コード例 #10
0
        public void LoadData()
        {
            VRageRender.MyRenderProxy.GetRenderProfiler().StartProfilingBlock("MyScriptManager.LoadData");
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - START");
            MySandboxGame.Log.IncreaseIndent();
            Static = this;
            Scripts.Clear();
            EntityScripts.Clear();
            SubEntityScripts.Clear();
            if (Sync.IsServer)
            {
                LoadScripts(MyFileSystem.ContentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.CurrentPath != null)
            {
                LoadScripts(MySession.Static.CurrentPath, MyModContext.BaseGame);
            }
            if (MySession.Static.Mods != null)
            {
                foreach (var mod in MySession.Static.Mods)
                {
                    var mc = new MyModContext();
                    mc.Init(mod);
                    LoadScripts(Path.Combine(MyFileSystem.ModsPath, mod.Name), mc);
                }
            }

            foreach (var ass in Scripts.Values)
            {
                if (MyFakes.ENABLE_TYPES_FROM_MODS) // Highly experimental!
                {
                    MyObjectFactories.RegisterFromAssembly(ass);
                }

                MySandboxGame.Log.WriteLine(string.Format("Script loaded: {0}", ass.FullName));
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("MyScriptManager.LoadData() - END");

            VRageRender.MyRenderProxy.GetRenderProfiler().EndProfilingBlock();
        }
コード例 #11
0
        private void Handle(ProfilerRequestType type)
        {
            var          ticks       = SampleTicks;
            var          top         = Top;
            long?        factionMask = null;
            long?        playerMask  = null;
            long?        entityMask  = null;
            MyModContext modFilter   = null;
            long?        reportGPS   = null;

            foreach (var arg in Context.Args)
            {
                if (arg.StartsWith("--ticks="))
                {
                    ticks = ulong.Parse(arg.Substring("--ticks=".Length));
                }
                else if (arg.StartsWith("--top="))
                {
                    top = int.Parse(arg.Substring("--top=".Length));
                }
                else if (arg.StartsWith("--faction="))
                {
                    var name = arg.Substring("--faction=".Length);
                    if (!ResolveFaction(name, out var id))
                    {
                        Context.Respond($"Failed to find faction {name}");
                        return;
                    }

                    factionMask = id?.FactionId ?? 0;
                }
                else if (arg.StartsWith("--player="))
                {
                    var name = arg.Substring("--player=".Length);
                    if (!ResolveIdentity(name, out var id))
                    {
                        Context.Respond($"Failed to find player {name}");
                        return;
                    }

                    playerMask = id?.IdentityId ?? 0;
                }
                else if (arg.StartsWith("--entity="))
                {
                    var id  = long.Parse(arg.Substring("--entity=".Length));
                    var ent = MyEntities.GetEntityById(id);
                    if (ent == null)
                    {
                        Context.Respond($"Failed to find entity with ID={id}");
                        return;
                    }

                    entityMask = ent.EntityId;
                }
                else if (arg == "--this")
                {
                    var controlled = Context.Player?.Controller?.ControlledEntity?.Entity;
                    if (controlled == null)
                    {
                        Context.Respond($"You must have a controlled entity to use the --this argument");
                        return;
                    }

                    MyCubeGrid grid;
                    var        tmp = controlled;
                    do
                    {
                        grid = tmp as MyCubeGrid;
                        if (grid != null)
                        {
                            break;
                        }
                        tmp = tmp.Parent;
                    } while (tmp != null);

                    if (grid == null)
                    {
                        Context.Respond($"You must be controlling a grid to use the --this argument");
                        return;
                    }

                    entityMask = grid.EntityId;
                }
                else if (arg == "--gps")
                {
                    var controlled = Context.Player;
                    if (controlled == null)
                    {
                        Context.Respond($"GPS return can only be used by players");
                        return;
                    }

                    reportGPS = controlled.IdentityId;
                    CleanGPS(reportGPS.Value);
                }
                else if (arg.StartsWith("--mod="))
                {
                    var nam = arg.Substring("--mod=".Length);
                    foreach (var mod in MySession.Static.Mods)
                    {
                        var ctx = new MyModContext();
                        ctx.Init(mod);
                        if (ctx.ModId.Equals(nam, StringComparison.OrdinalIgnoreCase) || ctx.ModId.Equals(nam + ".sbm", StringComparison.OrdinalIgnoreCase) || ctx.ModName.Equals(nam, StringComparison.OrdinalIgnoreCase))
                        {
                            modFilter = ctx;
                            break;
                        }
                    }
                    if (nam.Equals("base", StringComparison.OrdinalIgnoreCase) || nam.Equals("keen", StringComparison.OrdinalIgnoreCase))
                    {
                        modFilter = MyModContext.BaseGame;
                    }

                    // ReSharper disable once InvertIf
                    if (modFilter == null)
                    {
                        Context.Respond($"Failed to find mod {nam}");
                        return;
                    }
                }
            }

            if (!ProfilerData.ChangeMask(playerMask, factionMask, entityMask, modFilter))
            {
                Context.Respond($"Failed to change profiling mask.  There can only be one.");
                return;
            }

            var req     = new ProfilerRequest(type, ticks);
            var context = Context;

            req.OnFinished += (printByPassCount, results) =>
            {
                for (var i = 0; i < Math.Min(top, results.Length); i++)
                {
                    var r             = results[i];
                    var formattedTime = FormatTime(r.MsPerTick);
                    var hits          = results[i].HitsPerTick;
                    var hitsUnit      = results[i].HitsUnit;
                    var formattedName = string.Format(r.Name ?? "unknown", i, formattedTime, hits, hitsUnit);
                    var formattedDesc = string.Format(r.Description ?? "", i, formattedTime, hits, hitsUnit);
                    if (reportGPS.HasValue || !r.Position.HasValue)
                    {
                        context.Respond(printByPassCount
                            ? $"{formattedName} {formattedDesc} took {hits:F1} {hitsUnit}"
                            : $"{formattedName} {formattedDesc} took {formattedTime} ({hits:F1} {hitsUnit})");
                        if (!reportGPS.HasValue || !r.Position.HasValue)
                        {
                            continue;
                        }
                        var gpsDisplay = printByPassCount ? $"{hits:F1} {hitsUnit} {formattedName}" : $"{formattedTime} {formattedName}";
                        var gpsDesc    = formattedDesc + $" {hits:F1} {hitsUnit}";
                        var gps        = new MyGps(new MyObjectBuilder_Gps.Entry
                        {
                            name        = gpsDisplay,
                            DisplayName = gpsDisplay,
                            coords      = r.Position.Value,
                            showOnHud   = true,
                            color       = VRageMath.Color.Purple,
                            description = gpsDesc,
                            entityId    = 0,
                            isFinal     = false
                        });
                        MyAPIGateway.Session?.GPS.AddGps(reportGPS.Value, gps);
                        var set = GpsForIdentity.GetOrAdd(reportGPS.Value, (x) => new HashSet <int>());
                        lock (set)
                            set.Add(gps.Hash);
                        continue;
                    }

                    var posData =
                        $"{r.Position.Value.X.ToString(ProfilerRequest.DistanceFormat)},{r.Position.Value.Y.ToString(ProfilerRequest.DistanceFormat)},{r.Position.Value.Z.ToString(ProfilerRequest.DistanceFormat)}";
                    context.Respond(
                        printByPassCount
                            ? $"{formattedName} {formattedDesc} took ({hits:F1} {hitsUnit})  @ {posData}"
                            : $"{formattedName} {formattedDesc} took {formattedTime} ({hits:F1} {hitsUnit})  @ {posData}");
                }

                {
                    var    totalUpdates = 0d;
                    var    totalTime    = 0d;
                    string hitsUnit     = null;
                    for (var i = Math.Min(top, results.Length) + 1; i < results.Length; i++)
                    {
                        var r = results[i];
                        totalUpdates += r.HitsPerTick;
                        totalTime    += r.MsPerTick;
                        hitsUnit      = r.HitsUnit;
                    }

                    if (totalUpdates > 0)
                    {
                        context.Respond(printByPassCount
                            ? $"Others took {totalUpdates:F1} {hitsUnit}"
                            : $"Others took {FormatTime(totalTime)} ({totalUpdates:F1} {hitsUnit})");
                    }
                }
            };
            var timeEstMs = ticks * MyEngineConstants.UPDATE_STEP_SIZE_IN_SECONDS * 1000f / (MyMultiplayer.Static?.ServerSimulationRatio ?? 1);

            context.Respond($"Profiling for {type} started, results in {ticks} ticks (about {FormatTime(timeEstMs)})");
            ProfilerData.Submit(req);
        }
コード例 #12
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];
                    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
                                    {
                                        var c = new MyModContext();
                                        c.Init(assembly.FullName, assembly.FullName);
                                        MyDefinitionErrors.Add(c, "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
                                {
                                    var c = new MyModContext();
                                    c.Init(assembly.FullName, assembly.FullName);
                                    MyDefinitionErrors.Add(c, "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);
                    }
                }
            }
        }
コード例 #13
0
        private void Compile(IEnumerable<string> scriptFiles, string assemblyName, bool zipped)
        {
            Assembly assembly = null;
            bool compiled = false;
            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)) , TErrorSeverity.Error);
                        MyDefinitionErrors.Add(c, 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(MyStringId.GetOrCompute(assemblyName), assembly);
            else
            {
                MyDefinitionErrors.Add(c, string.Format("Compilation of {0} failed:", assemblyName), TErrorSeverity.Error);
                MySandboxGame.Log.IncreaseIndent();
				foreach (var error in m_errors)
				{
					MyDefinitionErrors.Add(c, error.ToString(), TErrorSeverity.Error);
					Debug.Assert(false, error.ToString());
				}
                MySandboxGame.Log.DecreaseIndent();
                m_errors.Clear();
            }
            m_cachedFiles.Clear();
        }
コード例 #14
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();
                        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 ingamescript = MyScriptCompiler.Static.GetIngameScript(program, "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name, "sealed partial");
                    var messages     = new List <MyScriptCompiler.Message>();
                    var assembly     = MyScriptCompiler.Static.Compile(MyApiTarget.Ingame, null, ingamescript, messages, null).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.Severity > TErrorSeverity.Warning)
                            {
                                errors++;
                            }
                        }
                        if (errors > 0)
                        {
                            return(false);
                        }
                    }

                    if (assembly == null)
                    {
                        return(false);
                    }
                }
#endif
                return(true);
            }
            return(true);
        }
コード例 #15
0
ファイル: Uploader.cs プロジェクト: KiwiBear/SEWorkshopTool
        /// <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);
        }
コード例 #16
0
        // receiving messages
        private void LiveDebugging_ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData)
        {
            MyExternalDebugStructures.ACReloadInGameMsg msgReload;
            if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload))
            {
                try
                {
                    string acContentPath = msgReload.ACContentAddress;
                    string acAddress = msgReload.ACAddress;
                    string acName = msgReload.ACName;

                    MyObjectBuilder_Definitions allDefinitions; // = null;
                    // load animation controller definition from SBC file
                    if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) &&
                        allDefinitions.Definitions != null &&
                        allDefinitions.Definitions.Length > 0)
                    {
                        var firstDef = allDefinitions.Definitions[0];
                        MyModContext context = new MyModContext();
                        context.Init("AnimationControllerDefinition", acAddress, acContentPath);
                        MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition();
                        animationControllerDefinition.Init(firstDef, context);
                        MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName);

                        // post process and update in def. manager
                        MyAnimationControllerDefinition originalAnimationControllerDefinition =
                            MyDefinitionManagerBase.Static.GetDefinition<MyAnimationControllerDefinition>(
                                animSubtypeNameHash);

                        var postprocessor = MyDefinitionManagerBase.GetPostProcessor(typeof(MyObjectBuilder_AnimationControllerDefinition));
                        if (postprocessor != null)
                        {
                            MyDefinitionPostprocessor.Bundle originalBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context = MyModContext.BaseGame,
                                Definitions = new Dictionary<MyStringHash, MyDefinitionBase>
                                {
                                    {animSubtypeNameHash, originalAnimationControllerDefinition}
                                },
                                Set = new MyDefinitionSet()
                            };
                            originalBundle.Set.AddDefinition(originalAnimationControllerDefinition);

                            MyDefinitionPostprocessor.Bundle overridingBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context = context,
                                Definitions = new Dictionary<MyStringHash, MyDefinitionBase>
                                {
                                    {animSubtypeNameHash, animationControllerDefinition}
                                },
                                Set = new MyDefinitionSet()
                            };
                            overridingBundle.Set.AddDefinition(animationControllerDefinition);

                            // postprocess -> override existing definition in memory
                            postprocessor.AfterLoaded(ref overridingBundle);
                            postprocessor.OverrideBy(ref originalBundle, ref overridingBundle);
                        }

                        // swap animation controller for each entity
                        foreach (var component in m_skinnedEntityComponents)
                        {
                            if (component != null && component.SourceId.SubtypeName == acName)
                            {
                                component.Clear();
                                component.InitFromDefinition(originalAnimationControllerDefinition, forceReloadMwm: true); // reload from original def that was modified by postprocessor
                                if (component.ReloadBonesNeeded != null)
                                    component.ReloadBonesNeeded();
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                }
            }
        }
コード例 #17
0
        // receiving messages
        private void LiveDebugging_ReceivedMessageHandler(MyExternalDebugStructures.CommonMsgHeader messageHeader, IntPtr messageData)
        {
            MyExternalDebugStructures.ACReloadInGameMsg msgReload;
            if (MyExternalDebugStructures.ReadMessageFromPtr(ref messageHeader, messageData, out msgReload))
            {
                try
                {
                    string acContentPath = msgReload.ACContentAddress;
                    string acAddress     = msgReload.ACAddress;
                    string acName        = msgReload.ACName;

                    MyObjectBuilder_Definitions allDefinitions; // = null;
                    // load animation controller definition from SBC file
                    if (MyObjectBuilderSerializer.DeserializeXML(acAddress, out allDefinitions) &&
                        allDefinitions.Definitions != null &&
                        allDefinitions.Definitions.Length > 0)
                    {
                        var          firstDef = allDefinitions.Definitions[0];
                        MyModContext context  = new MyModContext();
                        context.Init("AnimationControllerDefinition", acAddress, acContentPath);
                        MyAnimationControllerDefinition animationControllerDefinition = new MyAnimationControllerDefinition();
                        animationControllerDefinition.Init(firstDef, context);
                        MyStringHash animSubtypeNameHash = MyStringHash.GetOrCompute(acName);

                        // post process and update in def. manager
                        MyAnimationControllerDefinition originalAnimationControllerDefinition =
                            MyDefinitionManagerBase.Static.GetDefinition <MyAnimationControllerDefinition>(
                                animSubtypeNameHash);

                        var postprocessor = MyDefinitionManagerBase.GetPostProcessor(typeof(MyObjectBuilder_AnimationControllerDefinition));
                        if (postprocessor != null)
                        {
                            MyDefinitionPostprocessor.Bundle originalBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context     = MyModContext.BaseGame,
                                Definitions = new Dictionary <MyStringHash, MyDefinitionBase>
                                {
                                    { animSubtypeNameHash, originalAnimationControllerDefinition }
                                },
                                Set = new MyDefinitionSet()
                            };
                            originalBundle.Set.AddDefinition(originalAnimationControllerDefinition);

                            MyDefinitionPostprocessor.Bundle overridingBundle = new MyDefinitionPostprocessor.Bundle
                            {
                                Context     = context,
                                Definitions = new Dictionary <MyStringHash, MyDefinitionBase>
                                {
                                    { animSubtypeNameHash, animationControllerDefinition }
                                },
                                Set = new MyDefinitionSet()
                            };
                            overridingBundle.Set.AddDefinition(animationControllerDefinition);

                            // postprocess -> override existing definition in memory
                            postprocessor.AfterLoaded(ref overridingBundle);
                            postprocessor.OverrideBy(ref originalBundle, ref overridingBundle);
                        }

                        // swap animation controller for each entity
                        foreach (var component in m_skinnedEntityComponents)
                        {
                            if (component != null && component.SourceId.SubtypeName == acName)
                            {
                                component.Clear();
                                component.InitFromDefinition(originalAnimationControllerDefinition, forceReloadMwm: true); // reload from original def that was modified by postprocessor
                                if (component.ReloadBonesNeeded != null)
                                {
                                    component.ReloadBonesNeeded();
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    MyLog.Default.WriteLine(e);
                }
            }
        }
コード例 #18
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...");
                        var mod = new MyModContext();
                        mod.Init(m_title, null, m_modPath);
                        _compileMethod.Invoke(_scriptManager, new object[]
                        {
                            m_modPath,
                            mod
                        });

                        // Process any errors
                        var errors = MyDefinitionErrors.GetErrors();
                        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)
                            {
                                System.Console.WriteLine(error.Message);
                            }

                            MyDefinitionErrors.Clear();     // Clear old ones, so next mod starts fresh

                            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"));
                    }
                }
                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 ingamescript = MyScriptCompiler.Static.GetIngameScript(program, "Program", typeof(Sandbox.ModAPI.Ingame.MyGridProgram).Name, "sealed partial");
                    var messages     = new List <MyScriptCompiler.Message>();
                    var assembly     = MyScriptCompiler.Static.Compile(MyApiTarget.Ingame, null, ingamescript, messages).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.Severity > TErrorSeverity.Warning)
                            {
                                errors++;
                            }
                        }
                        if (errors > 0)
                        {
                            return(false);
                        }
                    }

                    if (assembly == null)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            return(true);
        }