Esempio n. 1
0
    // Source: https://stackoverflow.com/questions/7413612/how-to-limit-the-execution-time-of-a-function-in-c-sharp
    // Used for debugging infinite loop errors
    //public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock)
    //{
    //    try
    //    {
    //        Task task = Task.Factory.StartNew(() => codeBlock());
    //        task.Wait(timeSpan);
    //        return task.IsCompleted;
    //    }
    //    catch (AggregateException ae)
    //    {
    //        throw ae.InnerExceptions[0];
    //    }
    //}

    void LoadGFFs()
    {
        Debug.Log("Loading GFFs");

        LoadingSystem manager = GameObject.Find("Loading System").GetComponent <LoadingSystem>();

        Dictionary <string, ClassDefinition> k1BaseDefs  = LoadBaseGameGFFs(Compatibility.KotOR);
        Dictionary <string, ClassDefinition> tslBaseDefs = LoadBaseGameGFFs(Compatibility.TSL);

        Dictionary <string, ClassDefinition> k1SaveDefs  = LoadSaveGFFs(Compatibility.KotOR);
        Dictionary <string, ClassDefinition> tslSaveDefs = LoadSaveGFFs(Compatibility.TSL);

        //Dictionary<string, ClassDefinition> k1SaveDefs = new Dictionary<string, ClassDefinition>();
        //Dictionary<string, ClassDefinition> tslSaveDefs = new Dictionary<string, ClassDefinition>();

        Dictionary <string, ClassDefinition> defs = CombineDefinitions(k1BaseDefs, tslBaseDefs, k1SaveDefs, tslSaveDefs);

        foreach (string str in defs.Keys)
        {
            Debug.Log("Created class " + str + " from TSL base game files");
        }

        // Generate and write code to disk
        foreach (string className in defs.Keys)
        {
            string code = preamble + defs[className].ToString();
            File.WriteAllText(OutputLocation + "\\" + className + ".cs", code);
        }
    }
Esempio n. 2
0
        private void Awake()
        {
            foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
            {
                KopernicusExpansionLoader kopELoaderAttr = null;

                foreach (var attr in Attribute.GetCustomAttributes(type))
                {
                    if (attr is KopernicusExpansionLoader)
                    {
                        kopELoaderAttr = (KopernicusExpansionLoader)attr;
                    }
                }

                if (kopELoaderAttr != null)
                {
                    LoaderSystemTypes.Add(type);
                    Utils.Log("Found LoadingSystem type " + type.Name);
                }
            }

            LoadingScreen screen = UnityEngine.Object.FindObjectOfType <LoadingScreen> ();

            if (screen == null)
            {
                Utils.LogError("LoadingScreen is null, abort!");
                return;
            }

            foreach (var type in LoaderSystemTypes)
            {
                //skip if this type is a dupe
                foreach (var loader in screen.loaders)
                {
                    if (type == loader.GetType())
                    {
                        continue;
                    }
                }

                //skip if  this type is not a LoadingSystem
                if (type.BaseType != typeof(LoadingSystem))
                {
                    continue;
                }

                try
                {
                    LoadingSystem newLoader = (LoadingSystem)LoaderObject.AddComponent(type);
                    screen.loaders.Add(newLoader);
                    Utils.Log("Added LoadingSystem type " + type.Name);
                }
                catch (Exception e)
                {
                    Utils.LogError("error encountered while attempting to add LoadingSystem type " + type.Name);
                    Debug.LogException(e);
                }
            }
        }
    // Start is called before the first frame update

    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else if (instance != null)
        {
            Destroy(gameObject);
        }

        DontDestroyOnLoad(this.gameObject);
    }
        /// <summary>
        /// Reloads all contract types from the config nodes.  Also re-runs ModuleManager if it is installed.
        /// </summary>
        private IEnumerator <YieldInstruction> ReloadContractTypes()
        {
            reloading  = true;
            reloadStep = ReloadStep.GAME_DATABASE;

            GameDatabase.Instance.Recompile = true;
            GameDatabase.Instance.StartLoad();

            // Wait for the reload
            while (!GameDatabase.Instance.IsReady())
            {
                yield return(new WaitForEndOfFrame());
            }

            // Attempt to find module manager and do their reload
            reloadStep = ReloadStep.MODULE_MANAGER;
            var allMM = from loadedAssemblies in AssemblyLoader.loadedAssemblies
                        let assembly = loadedAssemblies.assembly
                                       where assembly.GetName().Name.StartsWith("ModuleManager")
                                       orderby assembly.GetName().Version descending, loadedAssemblies.path ascending
            select loadedAssemblies;

            // Reload module manager
            if (allMM.Count() > 0)
            {
                Assembly mmAssembly = allMM.First().assembly;
                LoggingUtil.LogVerbose(this, "Reloading config using ModuleManager: " + mmAssembly.FullName);

                // Get the module manager object
                Type          mmPatchType   = mmAssembly.GetType("ModuleManager.MMPatchLoader");
                LoadingSystem mmPatchLoader = (LoadingSystem)FindObjectOfType(mmPatchType);

                // Do the module manager load
                mmPatchLoader.StartLoad();
                while (!mmPatchLoader.IsReady())
                {
                    yield return(new WaitForEndOfFrame());
                }
            }
        }
        /// <summary>
        ///     The core of the program that replaces the default LoadingScreen information with our customizations.
        /// </summary>
        private void ModifyLoadingScreens()
        {
            // We are going to rebuild the loaders and screens, so first grab the existing ones.

            // The logic is built to cope if mods and/or a future version change the screen types and/or ordering.  Originally
            // I thought this would be YAGNI but it turns out some mods add loaders and not screens so in fact it is very
            // needed, and the first implementation did not quite go far enough!

            // I don't know why anything would clear these, but just in case...
            if (LoadingScreen.Instance.loaders == null)
            {
                Log.Error("** WARNING - Loaders not defined.");
                LoadingScreen.Instance.loaders = new List <LoadingSystem>();
            }
            if (LoadingScreen.Instance.Screens == null)
            {
                Log.Error("** WARNING - Screens not defined.");
                LoadingScreen.Instance.Screens = new List <LoadingScreen.LoadingScreenState>();
            }

            var           gameDatabaseIndex  = -1;
            LoadingSystem gameDatabaseLoader = null;

            LoadingScreen.LoadingScreenState gameDatabaseScreen    = null;
            LoadingScreen.LoadingScreenState firstModifiableScreen = null;

            // It's possible something could have removed all loaders (in which case we'll just add ours later).
            if (LoadingScreen.Instance.loaders.Count > 0)
            {
                // The GameDatabase loader and its accompanying screen is the one that shows the SQUAD logo.  Normally it's 1st,
                // but we find it dynamically in case some mod behaved badly and moved it.
                // *** IMPORTANT NOTE ***
                // Under KSP forum rules, mods may not modify the in-games logos, so please don't submit anything that makes
                // changes to these.  All we are doing here is saving them so we can add them back later.
                gameDatabaseIndex = LoadingScreen.Instance.loaders.FindIndex(l => l is GameDatabase);
                if (gameDatabaseIndex >= 0)
                {
                    if (gameDatabaseIndex != 0)
                    {
                        Log.Warning("** WARNING - Game Database Loader is not where expected.");
                    }
                    gameDatabaseLoader = LoadingScreen.Instance.loaders[gameDatabaseIndex];
                    gameDatabaseScreen = LoadingScreen.Instance.Screens[gameDatabaseIndex];
                }
                else
                {
                    Log.Error("** WARNING - Game Database Loader is not present.");
                }

                // The "normal" loading screen after the logo is supposed to be second, but a mod could have inserted one.
                // So the first screen that isn't the logo is the one we can modify.
                // Note that we just assume this screen has the "original" tips and screens.  Could look for PartLoader to find
                // which index it is, but we don't need to be that strict.

                // Unless the *only* loader is the GameDatabase then there has to be a modifiable screen, and the only time it
                // can't be at index 0 is if the GameDatabase is (which is actually the norm).
                if (LoadingScreen.Instance.loaders.Count > 1 || gameDatabaseIndex < 0)
                {
                    var firstModifiableIndex = gameDatabaseIndex == 0 ? 1 : 0;
                    firstModifiableScreen = LoadingScreen.Instance.Screens[firstModifiableIndex];
                }
                if (firstModifiableScreen == null)
                {
                    Log.Warning("** WARNING - No existing modifiable loaders.");
                }
            }
            else
            {
                Log.Warning("** WARNING - No existing loaders found.");
            }

            var imageFilenames = this.GetImageFilenames();

            var customTips = this.LoadCustomTips();

            if (cfg._includeOriginalTips && firstModifiableScreen != null)
            {
                customTips.AddRange(firstModifiableScreen.tips);
            }
            var tips = customTips.ToArray();

            if (cfg._includeOriginalScreens && firstModifiableScreen != null)
            {
                for (var i = 0; i < firstModifiableScreen.screens.Length; i++)
                {
                    // Identify original by indexes, with a * in front so we know they can't be filenames.
                    imageFilenames.Add($"*{i}");
                }
            }

            if (cfg._forceSlideshowWithNoImageFiles || imageFilenames.Count > 0)
            {
                var       newScreens = new List <LoadingScreen.LoadingScreenState>(cfg._maxSlides + 1);
                Texture2D texture;
                string[]  ltips = new string[1];

                // Add logo screens here
                Log.Info("Adding logoscreens: " + cfg.logoScreens.Count);
                for (int i = 0; i < cfg.logoScreens.Count; i++)
                {
                    var s = cfg.logoScreens[i];
                    if (File.Exists(s))
                    {
                        ltips[0] = cfg.logoTips[i];

                        if (LoadImageFile(s, out texture))
                        {
                            AddScreen(newScreens, texture, ltips);
                        }
                    }
                }
                //int cnt = 0;
                while (newScreens.Count < cfg._maxSlides && imageFilenames.Count > 0)
                {
                    string filename;
#if true
                    int filenameIndex = this._random.Next(imageFilenames.Count);
                    filename = imageFilenames[filenameIndex];
                    imageFilenames.RemoveAt(filenameIndex);
#else
                    filename = imageFilenames[cnt++];
#endif


                    // A * in front of a filename denotes an original image (see above).
                    if (filename[0] == '*')
                    {
                        Log.Info("Using original image:  Index {0}", filename);
                        Debug.Assert(firstModifiableScreen != null);
                        // ReSharper doesn't recognize Unity's Assert() and I don't want to bother with external annotations...
                        // ReSharper disable once PossibleNullReferenceException
                        texture = (Texture2D)firstModifiableScreen.screens[int.Parse(filename.Substring(1))];
                    }
                    else
                    {
                        if (!LoadImageFile(filename, out texture))
                        {
                            continue;
                        }
                    }
                    texture.name = filename;
                    Log.Info("Adding image: " + filename);
                    AddScreen(newScreens, texture, tips);
                }

                // Existing loaders are saved to be added at the end.  See below for why.
                var existingLoaders = new List <LoadingSystem>(cfg._maxSlides + 1);
                // ReSharper disable once LoopCanBeConvertedToQuery
                for (var i = 0; i < LoadingScreen.Instance.loaders.Count; i++)
                {
                    if (i != gameDatabaseIndex)
                    {
                        existingLoaders.Add(LoadingScreen.Instance.loaders[i]);
                    }
                }
                var totalDummyLoaders = newScreens.Count - existingLoaders.Count;

                var newLoaders = new List <LoadingSystem>(cfg._maxSlides + 1);
                for (var i = 0; i < totalDummyLoaders; i++)
                {
                    newLoaders.Add(new DummyLoader());
                }

                // Add the logo stuff to the start.  Note if some mod had moved it, this will get undone.
                if (gameDatabaseLoader != null)
                {
                    newLoaders.Insert(0, gameDatabaseLoader);
                    newScreens.Insert(0, gameDatabaseScreen);
                }

                // Add existing loaders at the end.
                // The reason we put our loaders first is that, for some reason I haven't been able to figure out, they will
                // disrupt the progress bar partway through, but at least if they're at the end the progress bar will end up
                // going to 100% eventually.  If we just tacked them onto the end the progress bar would finish at like 20%,
                // which would look bad to the user.
                newLoaders.AddRange(existingLoaders);

                LoadingScreen.Instance.loaders = newLoaders;
                LoadingScreen.Instance.Screens = newScreens;

                // Raw counts for debugging.
                Log.Info("{0} loaders set{1}", newLoaders.Count,
                         gameDatabaseIndex >= 0 ? " (including GameDatabase)" : "");
                Log.Info("{0} raw screens set{1}", newScreens.Count,
                         gameDatabaseIndex >= 0 ? " (including logo)" : "");

                // Slide count.  The logo is not counted as a slide.
                slideCount = gameDatabaseIndex >= 0 ? newScreens.Count - 1 : newScreens.Count;
                Log.Info("{0} slides set", slideCount);
                if (slideCount < cfg._maxSlides)
                {
                    Log.Info("** WARNING:  Not enough images available ({0}) to meet requested number of slides ({1}).",
                             slideCount, cfg._maxSlides);
                }
#if DEBUG
                for (int i = 0; i < slideCount; i++)
                {
                    Log.Info("Texture # : " + i + ", name: " + newScreens[i].screens[0].name);
                }
#endif
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Reloads all contract types from the config nodes.  Also re-runs ModuleManager if it is installed.
        /// </summary>
        private IEnumerator <YieldInstruction> ReloadContractTypes()
        {
            reloading  = true;
            reloadStep = ReloadStep.GAME_DATABASE;

            GameDatabase.Instance.Recompile = true;
            GameDatabase.Instance.StartLoad();

            // Wait for the reload
            while (!GameDatabase.Instance.IsReady())
            {
                yield return(new WaitForEndOfFrame());
            }

            // Attempt to find module manager and do their reload
            reloadStep = ReloadStep.MODULE_MANAGER;
            var allMM = from loadedAssemblies in AssemblyLoader.loadedAssemblies
                        let assembly = loadedAssemblies.assembly
                                       where assembly.GetName().Name.StartsWith("ModuleManager")
                                       orderby assembly.GetName().Version descending, loadedAssemblies.path ascending
            select loadedAssemblies;

            // Reload module manager
            if (allMM.Count() > 0)
            {
                Assembly mmAssembly = allMM.First().assembly;
                LoggingUtil.LogVerbose(this, "Reloading config using ModuleManager: " + mmAssembly.FullName);

                // Get the module manager object
                Type          mmPatchType   = mmAssembly.GetType("ModuleManager.MMPatchLoader");
                LoadingSystem mmPatchLoader = (LoadingSystem)FindObjectOfType(mmPatchType);

                // Do the module manager load
                mmPatchLoader.StartLoad();
                while (!mmPatchLoader.IsReady())
                {
                    yield return(new WaitForEndOfFrame());
                }
            }

            // Clear contract configurator
            reloadStep = ReloadStep.CLEAR_CONFIG;
            yield return(new WaitForEndOfFrame());

            ClearContractConfig();

            // Load contract configurator
            reloadStep = ReloadStep.LOAD_CONFIG;
            IEnumerator <YieldInstruction> iterator = LoadContractConfig();

            while (iterator.MoveNext())
            {
                yield return(iterator.Current);
            }

            // Adjust contract types
            reloadStep = ReloadStep.ADJUST_TYPES;
            yield return(new WaitForEndOfFrame());

            AdjustContractTypes();

            // We're done!
            reloading = false;
            ScreenMessages.PostScreenMessage("Loaded " + successContracts + " out of " + totalContracts
                                             + " contracts successfully.", 5, ScreenMessageStyle.UPPER_CENTER);

            yield return(new WaitForEndOfFrame());

            DebugWindow.scrollPosition  = new Vector2();
            DebugWindow.scrollPosition2 = new Vector2();
        }
Esempio n. 7
0
        public Module(string name, AuroraData data, bool instantiateModule)
        {
            this.moduleName = name;
            this.data       = data;

            if (!instantiateModule)
            {
                return;
            }

            if (stateManager == null)
            {
                stateManager = GameObject.Find("State System").GetComponent <StateSystem>();
            }
            if (loader == null)
            {
                loader = GameObject.Find("Loading System").GetComponent <LoadingSystem>();
            }

            ifo = data.Get <AuroraIFO>("module", ResourceType.IFO);
            Debug.Log(ifo);
            string areaName = ifo.Mod_Entry_Area;

            are = data.Get <AuroraARE>(areaName, ResourceType.ARE);
            git = data.Get <AuroraGIT>(areaName, ResourceType.GIT);

            entryPosition = new Vector3(ifo.Mod_Entry_X, ifo.Mod_Entry_Z, ifo.Mod_Entry_Y);

            Dictionary <string, Vector3> layout = Resources.LoadLayout(areaName, data);

            Debug.Log("Layout has " + layout.Count + " rooms.");

            area = Area.Create(are);

            GameObject parent = new GameObject("Models");

            parent.transform.SetParent(area.transform);

            foreach (var value in layout)
            {
                loader.AddAction(() =>
                {
                    Debug.Log("Loading room " + value.Key);
                    string resref = value.Key.ToLower();

                    GameObject room = Resources.LoadModel(resref);

                    if (SetupSkybox(room))
                    {
                        return;
                    }

                    // Set up the Navmesh
                    SetLayerRecursive(room, LayerMask.NameToLayer("NavMeshStatic"));

                    // Set the room's position and parent
                    room.transform.position = value.Value;
                    room.transform.SetParent(parent.transform);
                });
            }

            LoadCreatures();
            LoadPlaceables();

            loader.AddAction(() => data.aiManager.BakeNavMesh());

            LoadDoors();
            LoadTriggers();
            LoadEncounters();
            LoadSounds();
            LoadStores();
            LoadWaypoints();
            LoadCameras();

            loader.AddAction(() =>
            {
                // Load the music
                //int musicId = git.AreaProperties.MusicDay;
                //string musicResource = Resources.Load2DA("ambientmusic")[musicId, "resource"];

                //ambientMusic = Resources.LoadAudio(musicResource);
            });
        }