예제 #1
0
        private void CreateMesh(int width, int height, Vector2 origin)
        {
            int num    = Mathf.Clamp(height, 1, 480);
            int num2   = num / height;
            int width2 = Mathf.RoundToInt((float)Mathf.Clamp(width, 1, num2 * width));

            mesh            = MGHelper.CreateMeshWithOrigin(width2, num, origin);
            meshFilter.mesh = mesh;
        }
예제 #2
0
 public void Serialize(BinaryWriter br)
 {
     MGHelper.WriteVector3(br, targetPosition);
     MGHelper.WriteVector3(br, targetScale);
     br.Write(PrimaryName);
     br.Write(targetAlpha);
     br.Write((int)alignment);
     br.Write(shaderType);
 }
예제 #3
0
 public void SaveGame(int slotnum)
 {
     if (hasSnapshot)
     {
         byte[] array = CLZF2.Compress(snapshotData);
         MGHelper.KeyEncode(array);
         string str = (slotnum < 100) ? ("save" + slotnum.ToString("D3")) : ("qsave" + (slotnum - 100));
         File.WriteAllBytes(Path.Combine(MGHelper.GetSavePath(), str + ".dat"), array);
         saveManager.UpdateSaveSlot(slotnum);
         GameSystem.Instance.SceneController.WriteScreenshot(Path.Combine(MGHelper.GetSavePath(), str + ".png"));
     }
 }
예제 #4
0
        static string SaveFileToJSON(string path, int gameVersion)
        {
            byte[] array = File.ReadAllBytes(path);
            MGHelper.KeyEncode(array);
            byte[] buffer = CLZF2.Decompress(array);

            StringBuilder output = new StringBuilder();

            using (JsonTextWriter writer = new JsonTextWriter(new StringWriter(output))
            {
                Formatting = Formatting.Indented
            }) {
                writer.DateFormatHandling   = DateFormatHandling.IsoDateFormat;
                writer.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
                writer.WriteStartObject();
                using (MemoryStream input = new MemoryStream(buffer)) {
                    using (BinaryReader reader = new BinaryReader(input)) {
                        string magic = new string(reader.ReadChars(4));
                        if (magic != "MGSV")
                        {
                            throw new FileLoadException("Save file does not appear to be valid! Invalid header.");
                        }
                        int num = reader.ReadInt32();
                        if (num != 1)
                        {
                            throw new FileLoadException("Save file does not appear to be valid! Invalid version number.");
                        }
                        writer.WritePropertyName("Time");
                        writer.WriteValue(DateTime.FromBinary(reader.ReadInt64()));
                        foreach (var name in new string[] { "TextJP", "TextEN", "PrevTextJP", "PrevTextEN" })
                        {
                            writer.WriteNameValue(name, reader.ReadString());
                        }
                        writer.WriteNameValue("PrevAppendState", reader.ReadBoolean());
                        int stackSize = reader.ReadInt32();
                        writer.WritePropertyName("CallStack");
                        writer.WriteStartArray();
                        for (int i = 0; i < stackSize; i++)
                        {
                            StackEntryToJSON(writer, reader);
                        }
                        writer.WriteEndArray();
                        NamedObjectToJSON(StackEntryToJSON, writer, reader, "CurrentScript");
                        MemoryToJSON(writer, input);
                        CurrentAudioToJSON(writer, input);
                        SceneToJSON(writer, input, gameVersion);
                    }
                }
                writer.WriteEndObject();
            }

            return(output.ToString());
        }
예제 #5
0
        public static Sprite GetSprite(int[] binaryStates, Color colorOn, Color colorOff)
        {
            int integerStates = MGHelper.BinaryToInt(binaryStates);
            var key           = Tuple.Create(integerStates, colorOn, colorOff);

            textureDictionary.TryGetValue(key, out Sprite sprite);

            if (sprite != null)
            {
                return(sprite);
            }
            else
            {
                var barWidth = 4;
                var width    = binaryStates.Length * barWidth;
                var height   = 4;

                var t = new Texture2D(
                    width,
                    height,
                    TextureFormat.RGB565,
                    mipCount: 4,
                    linear: true)
                {
                    anisoLevel = 16,
                    filterMode = FilterMode.Bilinear
                };

                var colorArray = new Color[width * height];

                for (int iRow = 0; iRow < height; iRow++)
                {
                    for (int iCol = 0; iCol < width; iCol++)
                    {
                        int i      = iRow * width + iCol;
                        int iState = iCol / barWidth;
                        colorArray[i] = binaryStates[iState] == 0
                            ? colorOff
                            : colorOn;
                    }
                }

                t.SetPixels(colorArray);
                t.Apply(true);

                var rect = new Rect(0.0f, 0.0f, width, height);
                sprite = Sprite.Create(t, rect, rect.size / 2.0f, 100.0f, 1);
                textureDictionary.Add(key, sprite);

                return(sprite);
            }
        }
예제 #6
0
 public BurikoSaveManager()
 {
     saveList = new Dictionary <int, SaveEntry>();
     for (int i = 0; i < 100; i++)
     {
         string path = Path.Combine(MGHelper.GetSavePath(), string.Format("save{0}.dat", i.ToString("D3")));
         GetSaveData(i, path);
     }
     for (int j = 0; j < 3; j++)
     {
         string path2 = Path.Combine(MGHelper.GetSavePath(), string.Format("qsave{0}.dat", j.ToString("D1")));
         GetSaveData(j + 100, path2);
     }
 }
예제 #7
0
        private static void HeuristicAdjustment(
            int genCount,
            int stepCount,
            float stepSize,
            int[] p,
            int[] indicesOfGenSortedByAlpha,
            float[] p_thr_max,
            float[] p_target_step_max)
        {
            int[] states;
            for (int iStep = 0; iStep < stepCount; iStep++)
            {
                states = MGHelper.IntToBinary(p[iStep], genCount);
                float p_thr_step_max     = SumGenPower(genCount, stepSize, p_thr_max, states);
                float p_target_remaining = p_target_step_max[iStep] - p_thr_step_max;

                if (p_target_remaining < 0.0f)
                {
                    for (int i = genCount - 1; i >= 0; i--)
                    {
                        int iGen = indicesOfGenSortedByAlpha[i];
                        if (states[iGen] == 1 && p_target_remaining + p_thr_max[iGen] * stepSize < 0.0f)
                        {
                            states[iGen]       = 0;
                            p_thr_step_max     = SumGenPower(genCount, stepSize, p_thr_max, states);
                            p_target_remaining = p_target_step_max[iStep] - p_thr_step_max;
                        }
                    }
                }
                else
                {
                    for (int i = 0; i < genCount; i++)
                    {
                        int iGen = indicesOfGenSortedByAlpha[i];
                        if (states[iGen] == 0)
                        {
                            if (p_target_remaining - p_thr_max[iGen] * stepSize > 0.0f)
                            {
                                states[iGen]       = 1;
                                p_thr_step_max     = SumGenPower(genCount, stepSize, p_thr_max, states);
                                p_target_remaining = p_target_step_max[iStep] - p_thr_step_max;
                            }
                        }
                    }
                }

                p[iStep] = MGHelper.BinaryToInt(states);
            }
        }
예제 #8
0
        private void CreateMesh(int width, int height, LayerAlignment alignment)
        {
            int   num  = Mathf.Clamp(height, 1, 480);
            float num2 = (float)num / (float)height;
            int   num3 = Mathf.RoundToInt(Mathf.Clamp((float)width, 1f, num2 * (float)width));

            if (num > num3)
            {
                num3 = Mathf.Clamp(width, 1, 640);
                num2 = (float)num3 / (float)width;
                num  = Mathf.RoundToInt(Mathf.Clamp((float)height, 1f, num2 * (float)height));
            }
            mesh            = MGHelper.CreateMesh(num3, num, alignment);
            meshFilter.mesh = mesh;
        }
예제 #9
0
        private void CreateMesh(int width, int height, Vector2 origin)
        {
            int num  = Mathf.Clamp(height, 1, 480);
            int num2 = num / height;
            int num3 = Mathf.RoundToInt((float)Mathf.Clamp(width, 1, num2 * width));

            if (num > num3)
            {
                num3 = Mathf.Clamp(width, 1, 640);
                num2 = num3 / width;
                num  = Mathf.RoundToInt((float)Mathf.Clamp(height, 1, num2 * height));
            }
            mesh            = MGHelper.CreateMeshWithOrigin(num3, num, origin);
            meshFilter.mesh = mesh;
        }
예제 #10
0
        public void DeleteSave(int slot)
        {
            string path  = Path.Combine(MGHelper.GetSavePath(), string.Format("save{0}.dat", slot.ToString("D3")));
            string path2 = Path.Combine(MGHelper.GetSavePath(), string.Format("save{0}.png", slot.ToString("D3")));

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            if (File.Exists(path2))
            {
                File.Delete(path2);
            }
            saveList.Remove(slot);
        }
예제 #11
0
 private void GetSaveData(int slot, string path)
 {
     if (File.Exists(path))
     {
         try
         {
             SaveEntry saveEntry = new SaveEntry
             {
                 Path = path
             };
             byte[] array = File.ReadAllBytes(path);
             MGHelper.KeyEncode(array);
             using (MemoryStream input = new MemoryStream(CLZF2.Decompress(array)))
             {
                 using (BinaryReader binaryReader = new BinaryReader(input))
                 {
                     if (new string(binaryReader.ReadChars(4)) != "MGSV")
                     {
                         throw new FileLoadException("Save file does not appear to be valid! Invalid header.");
                     }
                     if (binaryReader.ReadInt32() != 1)
                     {
                         throw new FileLoadException("Save file does not appear to be valid! Invalid version number.");
                     }
                     saveEntry.Time = DateTime.FromBinary(binaryReader.ReadInt64());
                     string input2  = binaryReader.ReadString();
                     string input3  = binaryReader.ReadString();
                     string pattern = "[<](size)[=][+](.+)[<][/](size)[>]";
                     input2           = Regex.Replace(input2, pattern, string.Empty);
                     input3           = (saveEntry.Text = Regex.Replace(input3, pattern, string.Empty));
                     saveEntry.TextJp = input2;
                 }
             }
             if (saveList.ContainsKey(slot))
             {
                 saveList.Remove(slot);
             }
             saveList.Add(slot, saveEntry);
         }
         catch (Exception ex)
         {
             Logger.LogWarning("Could not read from save file " + path + "\nException: " + ex);
             throw;
         }
     }
 }
 private void GetSaveData(int slot, string path)
 {
     if (File.Exists(path))
     {
         try
         {
             SaveEntry saveEntry = new SaveEntry();
             saveEntry.Path = path;
             SaveEntry saveEntry2 = saveEntry;
             byte[]    array      = File.ReadAllBytes(path);
             MGHelper.KeyEncode(array);
             byte[] buffer = CLZF2.Decompress(array);
             using (MemoryStream input = new MemoryStream(buffer))
             {
                 using (BinaryReader binaryReader = new BinaryReader(input))
                 {
                     string a = new string(binaryReader.ReadChars(4));
                     if (a != "MGSV")
                     {
                         throw new FileLoadException("Save file does not appear to be valid! Invalid header.");
                     }
                     int num = binaryReader.ReadInt32();
                     if (num != 1)
                     {
                         throw new FileLoadException("Save file does not appear to be valid! Invalid version number.");
                     }
                     saveEntry2.Time = DateTime.FromBinary(binaryReader.ReadInt64());
                     string textJp = binaryReader.ReadString();
                     string text   = saveEntry2.Text = binaryReader.ReadString();
                     saveEntry2.TextJp = textJp;
                 }
             }
             if (saveList.ContainsKey(slot))
             {
                 saveList.Remove(slot);
             }
             saveList.Add(slot, saveEntry2);
         }
         catch (Exception ex)
         {
             Logger.LogWarning("Could not read from save file " + path + "\nException: " + ex);
             throw;
             IL_013f :;
         }
     }
 }
예제 #13
0
        public void SerializeScene(MemoryStream ms)
        {
            BinaryWriter binaryWriter = new BinaryWriter(ms);

            binaryWriter.Write(faceToUpperLayer);
            binaryWriter.Write(useFilm);
            binaryWriter.Write(useBlur);
            binaryWriter.Write(useHorizontalBlur);
            binaryWriter.Write(filmPower);
            binaryWriter.Write(filmType);
            binaryWriter.Write(filmStyle);
            MGHelper.WriteColor(binaryWriter, filmColor);
            if (activeScene == 0)
            {
                scene1.BackgroundLayer.Serialize(binaryWriter);
            }
            else
            {
                scene2.BackgroundLayer.Serialize(binaryWriter);
            }
            if (faceLayer.IsInUse)
            {
                binaryWriter.Write(value: true);
                faceLayer.Serialize(binaryWriter);
            }
            else
            {
                binaryWriter.Write(value: false);
            }
            for (int i = 0; i < 64; i++)
            {
                if (layers[i] == null)
                {
                    binaryWriter.Write(value: false);
                }
                else if (layers[i].FadingOut || !layers[i].IsInUse)
                {
                    binaryWriter.Write(value: false);
                }
                else
                {
                    binaryWriter.Write(value: true);
                    layers[i].Serialize(binaryWriter);
                }
            }
        }
예제 #14
0
        /// <summary>
        /// Executes a search on the provided microgrid data to generate
        /// optimal unit states for the formulated Unit Commitment Problem
        /// (UCP).
        /// </summary>
        /// <param name="input">Microgrid input data.</param>
        /// <param name="options">Defines the parameters for the PSO algorithm.</param>
        /// <param name="p_target">The local power demand at every moment of time.</param>
        /// <param name="progressCallback">Callback invoked every time the algorithm finishes a new iteration.</param>
        /// <returns>Binary integer array of unit states.</returns>
        public static async Task <int[, ]> UCPSearch(
            MGInput input,
            Options options,
            float[] p_target,
            OnNewSnapshotCallback progressCallback)
        {
            // Execute the PSO search.
#if !UNITY_WEBGL || (UNITY_WEBGL && UNITY_SSM_WEBGL_THREADING_CAPABLE)
            var t = new Task <int[]>(() =>
            {
                return(UCPExecutePSORuns(
                           input,
                           options,
                           p_target,
                           progressCallback));
            });

            t.Start();
            int[] u_thr_step_1d = await t;
#else
            int[] u_thr_step_1d = UCPExecutePSORuns(
                input,
                options,
                p_target,
                progressCallback);
#endif

            // Map the results from a 1D array to a 2D array where one
            // dimension is the generator states and the other dimension is
            // time, measured in time steps.
            int[,] u_thr_step_2d = MGHelper.Int1DToBin2D(
                u_thr_step_1d,
                options.stepCount,
                input.genCount);

            // Translate the time dimension from time steps to real time.
            float stepSize = input.tCount / options.stepCount;
            int[,] u_thr = MGHelper.TranslateTimeStep(
                u_thr_step_2d,
                stepSize,
                input.tCount,
                input.genCount);

            return(u_thr);
        }
예제 #15
0
 public void SaveGlobals()
 {
     byte[] inputBytes;
     using (MemoryStream memoryStream = new MemoryStream())
     {
         using (BsonWriter jsonWriter = new BsonWriter(memoryStream))
         {
             JsonSerializer jsonSerializer = new JsonSerializer();
             jsonSerializer.Serialize(jsonWriter, globalFlags);
             jsonSerializer.Serialize(jsonWriter, cgflags);
             jsonSerializer.Serialize(jsonWriter, readText);
             inputBytes = memoryStream.ToArray();
         }
     }
     byte[] array = CLZF2.Compress(inputBytes);
     MGHelper.KeyEncode(array);
     File.WriteAllBytes(Path.Combine(MGHelper.GetSavePath(), "global.dat"), array);
 }
예제 #16
0
        public void SetDataToCells(
            Image cellPrototype,
            int[,] binaryStates,
            Color colorOn,
            Color colorOff)
        {
            var rowCount = binaryStates.GetLength(1);

            EnsureImageCount(cellPrototype, rowCount);

            for (int iRow = 0; iRow < rowCount; iRow++)
            {
                cells[iRow].sprite = ScheduleTextureHelper.GetSprite(
                    MGHelper.GetCol(binaryStates, iRow),
                    colorOn,
                    colorOff);
            }
        }
예제 #17
0
        public void GetRowTest([Values(0, 1, 2, 3, 4)] int iRow)
        {
            //chpIndex,t
            var u1 = new int[, ]
            {
                { 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0 },
                { 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1 },
                { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                { 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 }
            };

            int[] actualRow = MGHelper.GetRow(u1, iRow);

            for (int j = 0; j < u1.GetLength(1); j++)
            {
                Assert.AreEqual(u1[iRow, j], actualRow[j]);
            }
        }
예제 #18
0
        public void GetColTest([Values(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)] int iCol)
        {
            //chpIndex,t
            var u1 = new int[, ]
            {
                { 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0 },
                { 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1 },
                { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                { 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 }
            };

            int[] actualCol = MGHelper.GetCol(u1, iCol);

            for (int i = 0; i < u1.GetLength(0); i++)
            {
                Assert.AreEqual(u1[i, iCol], actualCol[i]);
            }
        }
예제 #19
0
        public void GetUDTime_Up(
            [Values(60.0f, 60.0f, 60.0f, 60.0f, 60.0f)] float tIncr,
            [Values(0, 1, 2, 3, 4)] int iRow,
            [Values(11, 3, 0, 10, 5)] int iChp,
            [Values(4.0f, 2.0f, 0.0f, 0.0f, 5.0f)] float expectedCount)
        {
            //chpIndex,t
            var u1 = new int[, ]
            {
                { 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0 },
                { 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1 },
                { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
                { 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1 },
                { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0 }
            };

            var actual = MGHelper.GetUDTime(u1, iRow, iChp, tIncr, true);

            Assert.AreEqual(expectedCount * tIncr, actual);
        }
예제 #20
0
 public PacArchive(string filename)
 {
     Name = filename;
     path = Path.Combine(MGHelper.GetDataPath(), filename);
     try
     {
         using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
         {
             using (BinaryReader binaryReader = new BinaryReader(fileStream))
             {
                 string a = new string(binaryReader.ReadChars(4));
                 if (a != "MGPK")
                 {
                     throw new FileLoadException("File is not a valid pac file.");
                 }
                 int num = binaryReader.ReadInt32();
                 if (num != 1)
                 {
                     throw new FileLoadException("Cannot read from pac archive! Incorrect archive version.");
                 }
                 int num2 = binaryReader.ReadInt32();
                 for (int i = 0; i < num2; i++)
                 {
                     fileStream.Seek(12 + 48 * i, SeekOrigin.Begin);
                     string text = binaryReader.ReadString();
                     fileStream.Seek(12 + 48 * i + 32, SeekOrigin.Begin);
                     int       offset = binaryReader.ReadInt32();
                     int       size   = binaryReader.ReadInt32();
                     PacEntity value  = new PacEntity(text.ToLower(), offset, size);
                     EntityList.Add(text.ToLower(), value);
                 }
             }
         }
     }
     catch (Exception arg)
     {
         Logger.LogError($"Failed to open PacArchive {filename}!\nException: {arg}");
     }
 }
예제 #21
0
 private void Prepare(int width, int height, Shader shader, LayerAlignment align, bool retainMainTexture)
 {
     if (meshFilter == null)
     {
         meshFilter = base.gameObject.AddComponent <MeshFilter>();
     }
     if (meshRenderer == null)
     {
         meshRenderer = base.gameObject.AddComponent <MeshRenderer>();
     }
     mesh = MGHelper.CreateMesh(width, height, align);
     if (material != null)
     {
         if (!retainMainTexture)
         {
             Object.Destroy(primary);
         }
         Object.Destroy(material);
     }
     material              = new Material(shader);
     meshFilter.mesh       = mesh;
     meshRenderer.material = material;
 }
예제 #22
0
        private static float[][] Arr2DToJaggedArr(
            float[,] values,
            int length,
            int targetDimension)
        {
            float[][] _values = new float[length][];

            if (targetDimension == 0)
            {
                for (int i = 0; i < length; i++)
                {
                    _values[i] = MGHelper.GetRow(values, i);
                }
            }
            else if (targetDimension == 1)
            {
                for (int i = 0; i < length; i++)
                {
                    _values[i] = MGHelper.GetCol(values, i);
                }
            }

            return(_values);
        }
예제 #23
0
        public Texture2D LoadScreenshot(string filename)
        {
            string savePath = MGHelper.GetSavePath();
            string path     = Path.Combine(savePath, filename.ToLower());

            if (File.Exists(path))
            {
                try
                {
                    byte[] array  = File.ReadAllBytes(path);
                    byte[] array2 = new byte[4];
                    Buffer.BlockCopy(array, 16, array2, 0, 4);
                    int width = ReadLittleEndianInt32(array2);
                    Buffer.BlockCopy(array, 20, array2, 0, 4);
                    int       height    = ReadLittleEndianInt32(array2);
                    Texture2D texture2D = new Texture2D(width, height, TextureFormat.ARGB32, mipmap: false);
                    texture2D.LoadImage(array);
                    texture2D.filterMode = FilterMode.Bilinear;
                    texture2D.wrapMode   = TextureWrapMode.Clamp;
                    return(texture2D);

IL_008d:
                    Texture2D result;
                    return(result);
                }
                catch (Exception)
                {
                    return(LoadTexture("no_data"));

IL_00a5:
                    Texture2D result;
                    return(result);
                }
            }
            return(LoadTexture("no_data"));
        }
예제 #24
0
        private static PSOResult UCPExecutePSORun(
            int runIndex,
            MGInput mg,
            Options OptsPSO,
            int randomSeed,
            float[] p_target,
            float[] c_thr_max_1m,
            Dictionary <StateStep, float> cDict,
            OnNewSnapshotInnerCallback progressCallback = null)
        {
            var random    = new Random(randomSeed);
            int iterCount = OptsPSO.iterCount;
            int pCount    = OptsPSO.particleCount;
            int stepCount = OptsPSO.stepCount;
            int stepSize  = mg.tCount / stepCount;

            // The power demand that needs to be fulfilled at each time step.
            float[] p_target_step_max = new float[stepCount];

            // The min. downtime of each generator normalized to our time step.
            float[] dtime_norm = new float[mg.genCount];

            // The min. uptime of each generator normalized to our time step.
            float[] utime_norm = new float[mg.genCount];

            // Initialize min. downtime and uptime arrays.
            for (int iGen = 0; iGen < mg.genCount; iGen++)
            {
                dtime_norm[iGen] = mg.thr_min_dtime[iGen] / stepSize;
                utime_norm[iGen] = mg.thr_min_utime[iGen] / stepSize;
            }

            // Iterate through all time steps and initialize p_target_step_max.
            for (int iStep = 0; iStep < stepCount; iStep++)
            {
                // Start time of the current step.
                int t1 = iStep * stepSize;

                // End time of the current step.
                int t2 = (iStep + 1) * stepSize - 1;

                // Sum up the power demand for every real time unit across
                // our time step.
                for (int t = t1; t < t2; t++)
                {
                    p_target_step_max[iStep] +=
                        UnityEngine.Mathf.Max(
                            p_target_step_max[iStep],
                            p_target[t]);
                }
            }

            // Alpha - a criterion variable for how cost efficient a generator is.
            // Initialize an array to keep track of the alpha of every generator.
            float[] thr_alpha = MGHelper.ThermalGenerator.GetAlpha(
                mg.genCount, mg.p_thr_max, mg.thr_c_a, mg.thr_c_b, mg.thr_c_c);

            // Get an array of the indices of generators, sorted by their alpha.
            // In other words, if the 5th generator has the 2nd lowest alpha,
            // then thr_sorted_by_alpha[2] == 5.
            var thr_sorted_by_alpha = thr_alpha
                                      .Select(x => thr_alpha.OrderBy(alpha => alpha).ToList()
                                              .IndexOf(x)).ToArray();

            // Initialize an array for our particles.
            var p = InitParticles(pCount, mg.genCount, stepCount, random);

            // Initialize an array for keeping track of the global best at each time step.
            var gBest = new int[stepCount];

            // Variable for keeping track of the global best.
            float gBestFitness = float.MaxValue;

            // How many iterations have past since we've improved our global best.
            int iterSinceLastGBest = -1;

            // Go through all of our iterations, updating the particles each time.
            for (int iIter = 0; iIter < iterCount; iIter++)
            {
                iterSinceLastGBest++;

                // Percent of iterations completed.
                float completion = iIter / (float)iterCount;

                // Get the probability of inertia being applied to the
                // particle's velocity update.
                //
                // This probability decreases with each iteration, effectively
                // slowing down particles.
                float prob_inertia = UnityEngine.Mathf.Lerp(
                    1.0f, 0.35f, completion);

                // Get the probability of the particle's velocity being updated
                // to a random value.
                //
                // This probability increases with each iteration the swarm
                // goes through without finding a better global best.
                float prob_craziness = UnityEngine.Mathf.Lerp(
                    0.005f, 0.50f, iterSinceLastGBest / 100.0f);

                // Determines if the current iteration is an iteration where
                // it's possible to apply a heuristic adjustment to the swarm.
                //
                // This allows us to apply the adjustment only every n iterations.
                bool isHeuristicIter = iIter % 10 == 0;

                // Probability of a particle undergoing heuristic adjustment
                // when the iteration is a heuristic adjustment enabled
                // iteration.
                //
                // This allows us to control, on average, what percentage of
                // particles get affected by the heuristic adjustment.
                float prob_heuristic = 0.25f;

                // Step 1.
                // Iterate through all particles, evaluating their fitness
                // and establishing their personal best.
                for (int iP = 0; iP < pCount; iP++)
                {
                    float fitness = GetFitness(p[iP].pos, stepCount, cDict);

                    if (fitness < p[iP].fitnessBest)
                    {
                        p[iP].fitnessBest = fitness;
                        Array.Copy(p[iP].pos, p[iP].pBest, stepCount);
                    }
                }

                // Step 2.
                // Iterate through all particles, establishing the global best
                // in the swarm.
                for (int iP = 0; iP < pCount; iP++)
                {
                    if (p[iP].fitnessBest < gBestFitness)
                    {
                        gBestFitness = p[iP].fitnessBest;
                        Array.Copy(p[iP].pBest, gBest, stepCount);
                        iterSinceLastGBest = 0;
                    }
                }

                // Step 3.
                // Update the velocity and position of every particle.
                //
                // Optionally apply a heuristic adjustment aimed at speeding
                // the convergence of the swarm.
                //
                // Revert state switches of generators that would violate the
                // min/max uptime constraints of that generator. This is
                // necessary because the particles have no knowledge of those
                // constraionts. So we deal with that simply by undoing
                // illegal state switches.
                for (int iP = 0; iP < pCount; iP++)
                {
                    Binary.UpdateVel(
                        p[iP].pos,
                        p[iP].vel,
                        p[iP].pBest,
                        gBest,
                        prob_inertia,
                        prob_craziness,
                        mg.genCount,
                        random);

                    Binary.UpdatePos(p[iP].pos, p[iP].vel);

                    /*
                     * if (isHeuristicIter)
                     * {
                     *  if (random.NextDouble() < prob_heuristic)
                     *  {
                     *      HeuristicAdjustment(
                     *          mg.genCount,
                     *          stepCount,
                     *          stepSize,
                     *          p[iP].pos,
                     *          thr_sorted_by_alpha,
                     *          mg.p_thr_max,
                     *          p_target_step_max);
                     *  }
                     * }
                     */

                    MGHelper.FixMinTimeConstraints(
                        p[iP].pos, stepCount, mg.genCount, dtime_norm, utime_norm);
                }

                var snapshot = new IterationSnapshot(
                    iIter,
                    iterCount,
                    stepCount,
                    mg.genCount,
                    gBestFitness,
                    gBest,
                    p);

                progressCallback?.Invoke(runIndex, iIter, snapshot);
            }


            return(new PSOResult
            {
                bestPos = gBest,
                bestFitness = gBestFitness
            });
        }
예제 #25
0
        public void DeSerializeScene(MemoryStream ms)
        {
            BinaryReader binaryReader = new BinaryReader(ms);

            HideFilmEffector(0f, isBlocking: false);
            DrawScene("black", 0f);
            gameSystem.ExecuteActions();
            faceToUpperLayer  = binaryReader.ReadBoolean();
            useFilm           = binaryReader.ReadBoolean();
            useBlur           = binaryReader.ReadBoolean();
            useHorizontalBlur = binaryReader.ReadBoolean();
            filmPower         = binaryReader.ReadInt32();
            filmType          = binaryReader.ReadInt32();
            filmStyle         = binaryReader.ReadInt32();
            filmColor         = MGHelper.ReadColor(binaryReader);
            MGHelper.ReadVector3(binaryReader);
            MGHelper.ReadVector3(binaryReader);
            string backgroundfilename = binaryReader.ReadString();

            binaryReader.ReadSingle();
            binaryReader.ReadInt32();
            binaryReader.ReadInt32();
            DrawScene(backgroundfilename, 0.3f);
            if (binaryReader.ReadBoolean())
            {
                MGHelper.ReadVector3(binaryReader);
                MGHelper.ReadVector3(binaryReader);
                string texture = binaryReader.ReadString();
                binaryReader.ReadSingle();
                binaryReader.ReadInt32();
                binaryReader.ReadInt32();
                DrawFace(texture, 0f, isblocking: false);
            }
            for (int i = 0; i < 64; i++)
            {
                if (layers[i] != null && layers[i].IsInUse)
                {
                    layers[i].HideLayer();
                }
                if (binaryReader.ReadBoolean())
                {
                    Vector3 vector      = MGHelper.ReadVector3(binaryReader);
                    Vector3 scale       = MGHelper.ReadVector3(binaryReader);
                    string  textureName = binaryReader.ReadString();
                    float   alpha       = binaryReader.ReadSingle();
                    int     num         = binaryReader.ReadInt32();
                    int     type        = binaryReader.ReadInt32();
                    if (i != 50)
                    {
                        bool  isBustshot = num != 0;
                        Layer layer      = GetLayer(i);
                        UpdateLayerMask(layer, i);
                        layer.DrawLayer(textureName, (int)vector.x, (int)vector.y, 0, null, alpha, isBustshot, type, 0f, isBlocking: false);
                        layer.SetPriority(i);
                        layer.RestoreScaleAndPosition(scale, vector);
                    }
                }
            }
            if (useFilm)
            {
                CreateFilmEffector(filmType, filmColor, filmPower, filmStyle, 0f, isBlocking: false);
            }
            if (useHorizontalBlur)
            {
                CreateHorizontalGradation(filmPower, 0f, isBlocking: false);
            }
            SetFaceToUpperLayer(faceToUpperLayer);
            gameSystem.ExecuteActions();
        }
예제 #26
0
        private static int[] UCPExecutePSORuns(
            MGInput m,
            Options o,
            float[] p_target,
            OnNewSnapshotCallback progressCallback)
        {
            Random random = o.randomSeed.HasValue
                ? new Random(o.randomSeed.Value)
                : new Random();

            int runCount  = o.runCount;
            int iterCount = o.iterCount;
            int pCount    = o.particleCount;
            int stepCount = o.stepCount;
            int stepSize  = m.tCount / stepCount;

            int[] rBest        = new int[stepCount];
            float rBestFitness = float.MaxValue;
            float totalIter    = runCount * iterCount;
            var   threads      = new Thread[runCount];
            var   results      = new PSOResult[runCount];

            Dictionary <StateStep, float> cDict;

            cDict = MGHelper.ConstructCostDictionary(m, stepCount, stepSize, 400.0f, p_target);

            // Precompute an array that maps generator indices to the operating
            // costs for that generator if it ran at maximum power for a
            // timestep.
            float[] c_thr_max_1m = MGHelper.ThermalGenerator.GetCostAtMaxPower(
                m.genCount,
                m.p_thr_max,
                m.thr_c_a,
                m.thr_c_b,
                m.thr_c_c,
                stepSize);

            var lockObject     = new object();
            var iterLatest     = new int[runCount];
            var progressPerRun = new IterationSnapshot[runCount, iterCount];

            for (int iRun = 0; iRun < runCount; iRun++)
            {
                iterLatest[iRun] = -1;
            }

            void progressInner(
                int runIndex,
                int iterIndex,
                IterationSnapshot progressStruct)
            {
                lock (lockObject)
                {
                    iterLatest[runIndex] = iterLatest[runIndex] < iterIndex
                        ? iterIndex
                        : iterLatest[runIndex];

                    progressPerRun[runIndex, iterIndex] = progressStruct;

                    progressCallback?.Invoke(
                        runIndex,
                        iterIndex,
                        (int[])iterLatest.Clone(),
                        (IterationSnapshot[, ])progressPerRun.Clone());
                }
            }

#if !UNITY_WEBGL || (UNITY_WEBGL && UNITY_SSM_WEBGL_THREADING_CAPABLE)
            // Run the PSO multiple times in parallel.
            for (int iRun = 0; iRun < runCount; iRun++)
            {
                int _iRun = iRun;
                threads[_iRun] = new Thread(() =>
                {
                    var r          = random.Next();
                    results[_iRun] = UCPExecutePSORun(
                        _iRun, m, o, r, p_target, c_thr_max_1m, cDict, progressInner);
                });

                threads[_iRun].IsBackground = true;
                threads[_iRun].Start();
            }

            for (int iRun = 0; iRun < threads.Length; iRun++)
            {
                threads[iRun].Join();
            }
#else
            for (int iRun = 0; iRun < runCount; iRun++)
            {
                var r = random.Next();
                results[iRun] = UCPExecutePSORun(
                    iRun,
                    m,
                    o,
                    r,
                    p_target,
                    c_thr_max_1m,
                    cDict,
                    progressInner);
            }
#endif


            // Pick the best run.
            for (int iRun = 0; iRun < runCount; iRun++)
            {
                PSOResult result = results[iRun];
                if (result.bestFitness < rBestFitness)
                {
                    rBestFitness = result.bestFitness;
                    Array.Copy(result.bestPos, rBest, stepCount);
                }
            }

            return(rBest);
        }
예제 #27
0
        public void LoadGame(int slotnum)
        {
            SaveEntry saveInfoInSlot = saveManager.GetSaveInfoInSlot(slotnum);

            if (saveInfoInSlot != null)
            {
                GameSystem.Instance.TextController.ClearText();
                GameSystem.Instance.MainUIController.FadeOut(0f, isBlocking: true);
                byte[] array = File.ReadAllBytes(saveInfoInSlot.Path);
                MGHelper.KeyEncode(array);
                byte[] buffer = tempSnapshotData = (snapshotData = CLZF2.Decompress(array));
                hasSnapshot = true;
                GameSystem.Instance.ClearAllWaits();
                GameSystem.Instance.ClearActions();
                using (MemoryStream memoryStream = new MemoryStream(buffer))
                {
                    using (BinaryReader binaryReader = new BinaryReader(memoryStream))
                    {
                        if (new string(binaryReader.ReadChars(4)) != "MGSV")
                        {
                            throw new FileLoadException("Save file does not appear to be valid! Invalid header.");
                        }
                        if (binaryReader.ReadInt32() != 1)
                        {
                            throw new FileLoadException("Save file does not appear to be valid! Invalid version number.");
                        }
                        binaryReader.ReadInt64();
                        string text  = binaryReader.ReadString();
                        string text2 = binaryReader.ReadString();
                        string text3 = binaryReader.ReadString();
                        string text4 = binaryReader.ReadString();
                        bool   num   = binaryReader.ReadBoolean();
                        GameSystem.Instance.TextController.SetPrevText(text3, 0);
                        GameSystem.Instance.TextController.SetPrevText(text4, 1);
                        if (num)
                        {
                            if (GameSystem.Instance.UseEnglishText)
                            {
                                GameSystem.Instance.TextController.TypeTextImmediately(text4);
                                GameSystem.Instance.TextController.SetFullText(text3, 0);
                            }
                            else
                            {
                                GameSystem.Instance.TextController.TypeTextImmediately(text3);
                                GameSystem.Instance.TextController.SetFullText(text4, 1);
                            }
                            tempSnapshotText[0] = text3;
                            tempSnapshotText[1] = text4;
                            GameSystem.Instance.TextController.SetAppendState(append: true);
                        }
                        else
                        {
                            GameSystem.Instance.TextController.SetFullText(text, 0);
                            GameSystem.Instance.TextController.SetFullText(text2, 1);
                            tempSnapshotText[0] = text;
                            tempSnapshotText[1] = text2;
                            GameSystem.Instance.TextController.SetAppendState(append: false);
                        }
                        callStack.Clear();
                        int num2 = binaryReader.ReadInt32();
                        for (int i = 0; i < num2; i++)
                        {
                            string           key     = binaryReader.ReadString();
                            int              linenum = binaryReader.ReadInt32();
                            BurikoScriptFile script  = scriptFiles[key];
                            callStack.Push(new BurikoStackEntry(script, 0, linenum));
                        }
                        string key2     = binaryReader.ReadString();
                        int    linenum2 = binaryReader.ReadInt32();
                        currentScript = scriptFiles[key2];
                        if (!currentScript.IsInitialized)
                        {
                            currentScript.InitializeScript();
                        }
                        currentScript.JumpToLineNum(linenum2);
                        memoryManager.LoadMemory(memoryStream);
                        AudioController.Instance.DeSerializeCurrentAudio(memoryStream);
                        GameSystem.Instance.SceneController.DeSerializeScene(memoryStream);
                        GameSystem.Instance.ForceReturnNormalState();
                        GameSystem.Instance.CloseChoiceIfExists();
                        GameSystem.Instance.TextHistory.ClearHistory();
                        GameSystem.Instance.IsSkipping = false;
                        GameSystem.Instance.IsAuto     = false;
                        GameSystem.Instance.CanSkip    = true;
                        GameSystem.Instance.CanInput   = true;
                        GameSystem.Instance.CanSave    = true;
                        int flag = GetFlag("LTextFade");
                        GameSystem.Instance.TextController.SetTextFade(flag == 1);
                        if (BurikoMemory.Instance.GetGlobalFlag("GADVMode").IntValue() == 1 && BurikoMemory.Instance.GetGlobalFlag("GLinemodeSp").IntValue() == 2 && BurikoMemory.Instance.GetFlag("NVL_in_ADV").IntValue() == 0)
                        {
                            GameSystem.Instance.MainUIController.MODdisableNVLModeINADVMode();
                        }
                        if (BurikoMemory.Instance.GetGlobalFlag("GADVMode").IntValue() == 1 && BurikoMemory.Instance.GetGlobalFlag("GLinemodeSp").IntValue() == 0 && BurikoMemory.Instance.GetFlag("NVL_in_ADV").IntValue() == 1)
                        {
                            GameSystem.Instance.MainUIController.MODenableNVLModeINADVMode();
                        }
                    }
                }
            }
        }
예제 #28
0
        private static void SetToMG(
            Microgrid microgrid,
            GraphMicrogridLink link)
        {
            if (MGMisc.accessorLists.ContainsKey(link.mvar))
            {
                if (link.graphs.Count > 0)
                {
                    var values = GetYValues(link.graphs[0].RawCoords);
                    MGMisc.accessorLists[link.mvar].Set(microgrid, values);
                }
            }
            else if (MGMisc.accessor2DArray.ContainsKey(link.mvar))
            {
                float[,] values = MGMisc.accessor2DArray[link.mvar].Get(microgrid);

                int length = values.GetLength(link.targetDimension);

                if (length != link.graphs.Count)
                {
                    return;
                }

                if (link.targetDimension == 0)
                {
                    if (link.index >= 0)
                    {
                        var value = GetYValues(link.graphs[0].RawCoords);
                        MGHelper.SetRow(value, values, link.index);
                    }
                    else
                    {
                        for (int i = 0; i < length; i++)
                        {
                            var value = GetYValues(link.graphs[i].RawCoords);
                            MGHelper.SetRow(value, values, i);
                        }
                    }
                }
                else if (link.targetDimension == 1)
                {
                    if (link.index >= 0)
                    {
                        var value = GetYValues(link.graphs[0].RawCoords);
                        MGHelper.SetCol(value, values, link.index);
                    }
                    else
                    {
                        for (int i = 0; i < length; i++)
                        {
                            var value = GetYValues(link.graphs[i].RawCoords);
                            MGHelper.SetCol(value, values, i);
                        }
                    }
                }
                else if (link.targetDimension < 0)
                {
                    throw new ArgumentException("Trying to set to a " +
                                                "negative dimension.", nameof(link.targetDimension));
                }
                else
                {
                    throw new ArgumentException("Trying to set to an " +
                                                "unhandled dimension.", nameof(link.targetDimension));
                }

                MGMisc.accessor2DArray[link.mvar].Set(microgrid, values);
            }
        }
예제 #29
0
        public void LoadGlobals()
        {
            string path = Path.Combine(MGHelper.GetSavePath(), "global.dat");

            if (!File.Exists(path))
            {
                SetGlobalFlag("GUsePrompts", 1);
            }
            else
            {
                byte[] array = File.ReadAllBytes(path);
                MGHelper.KeyEncode(array);
                byte[] buffer = CLZF2.Decompress(array);
                try
                {
                    JsonSerializer jsonSerializer = new JsonSerializer();
                    using (MemoryStream stream = new MemoryStream(buffer))
                    {
                        BsonReader bsonReader = new BsonReader(stream);
                        bsonReader.CloseInput = false;
                        using (BsonReader reader = bsonReader)
                        {
                            globalFlags = jsonSerializer.Deserialize <Dictionary <int, int> >(reader);
                        }
                        bsonReader                      = new BsonReader(stream);
                        bsonReader.CloseInput           = false;
                        bsonReader.ReadRootValueAsArray = true;
                        using (BsonReader reader2 = bsonReader)
                        {
                            cgflags = jsonSerializer.Deserialize <List <string> >(reader2);
                        }
                        bsonReader            = new BsonReader(stream);
                        bsonReader.CloseInput = false;
                        using (BsonReader reader3 = bsonReader)
                        {
                            readText = jsonSerializer.Deserialize <Dictionary <string, List <int> > >(reader3);
                        }
                    }
                }
                catch (Exception arg)
                {
                    Debug.LogWarning("Failed to load global data! Exception: " + arg);
                    return;

                    IL_0128 :;
                }
                try
                {
                    GameSystem.Instance.TextController.TextSpeed     = GetGlobalFlag("GMessageSpeed").IntValue();
                    GameSystem.Instance.TextController.AutoSpeed     = GetGlobalFlag("GAutoSpeed").IntValue();
                    GameSystem.Instance.TextController.AutoPageSpeed = GetGlobalFlag("GAutoAdvSpeed").IntValue();
                    GameSystem.Instance.MessageWindowOpacity         = (float)GetGlobalFlag("GWindowOpacity").IntValue() / 100f;
                    GameSystem.Instance.UsePrompts                   = GetGlobalFlag("GUsePrompts").BoolValue();
                    GameSystem.Instance.SkipModeDelay                = GetGlobalFlag("GSlowSkip").BoolValue();
                    GameSystem.Instance.SkipUnreadMessages           = GetGlobalFlag("GSkipUnread").BoolValue();
                    GameSystem.Instance.ClickDuringAuto              = GetGlobalFlag("GClickDuringAuto").BoolValue();
                    GameSystem.Instance.RightClickMenu               = GetGlobalFlag("GRightClickMenu").BoolValue();
                    GameSystem.Instance.AudioController.VoiceVolume  = (float)GetGlobalFlag("GVoiceVolume").IntValue() / 100f;
                    GameSystem.Instance.AudioController.BGMVolume    = (float)GetGlobalFlag("GBGMVolume").IntValue() / 100f;
                    GameSystem.Instance.AudioController.SoundVolume  = (float)GetGlobalFlag("GSEVolume").IntValue() / 100f;
                    GameSystem.Instance.AudioController.SystemVolume = (float)GetGlobalFlag("GSEVolume").IntValue() / 100f;
                    GameSystem.Instance.StopVoiceOnClick             = GetGlobalFlag("GCutVoiceOnClick").BoolValue();
                    GameSystem.Instance.UseSystemSounds              = GetGlobalFlag("GUseSystemSound").BoolValue();
                    GameSystem.Instance.UseEnglishText               = GetGlobalFlag("GLanguage").BoolValue();
                    AssetManager.Instance.UseNewArt                  = GetGlobalFlag("GArtStyle").BoolValue();
                    GameSystem.Instance.AudioController.RefreshLayerVolumes();
                }
                catch (Exception message)
                {
                    Debug.LogWarning(message);
                }
            }
        }
예제 #30
0
 public void UpdateSaveSlot(int slot)
 {
     GetSaveData(path: (slot >= 100) ? Path.Combine(MGHelper.GetSavePath(), string.Format("qsave{0}.dat", (slot - 100).ToString("D1"))) : Path.Combine(MGHelper.GetSavePath(), string.Format("save{0}.dat", slot.ToString("D3"))), slot: slot);
 }