Exemplo n.º 1
0
 /// <summary>
 /// returns average value of given parameter from neighbouring patches
 /// 666 if none is defined    
 public float GetNeighbourAverage(int _x, int _z, PatchInfo parameter)
 {
     int count = 0;
     float sum = 0;
     for(int x = _x - patchSize; x <= _x + patchSize; x += patchSize)
     {
         for (int z = _z - patchSize; z <= _z + patchSize; z += patchSize)
         {
             float v = 666;
             switch (parameter)
             {
                 case PatchInfo.rMin:
                     v = rMin.GetValue(x, z);
                     break;
                 case PatchInfo.rMax:
                     v = rMax.GetValue(x, z);
                     break;
                 case PatchInfo.noise:
                     v = noise.GetValue(x, z);
                     break;
             }
             if(v != 666)
             {
                 sum += v;
                 count++;
             }
         }
     }
     if (count == 0)
         return 666;
     else
         return sum / count;
 }
    void AddSubMesh(PatchInfo mesh_info)
    {
        //把更新好的mesh全都合并成一个新的mesh,并赋值给原plane
        CombineInstance combine_instance = new CombineInstance();

        //combine_instance.mesh = mesh_info.Mesh;
        //combine_instance.transform = mesh_info.Transform.localToWorldMatrix;

        m_combine_instances.Add(combine_instance);
    }
Exemplo n.º 3
0
        public static bool TryGetPatchInfo(string actualSha1, out PatchInfo info)
        {
            info = null;

            info = (from i in kPatches
                    where i.Sha1 == actualSha1
                    select i).FirstOrDefault();

            return(info != null);
        }
Exemplo n.º 4
0
        public static PatchInfo ToPatchInfo(this MethodBase methodBase)
        {
            lock (PatchInfos)
            {
                if (PatchInfos.TryGetValue(methodBase, out var info))
                {
                    return(info);
                }

                return(PatchInfos[methodBase] = new PatchInfo());
            }
        }
Exemplo n.º 5
0
        /// <summary>Adds a transpiler</summary>
        /// <param name="patchInfo">The patch info</param>
        /// <param name="owner">The owner (Harmony ID)</param>
        /// <param name="info">The annotation info</param>
        ///
        internal static void AddTranspiler(PatchInfo patchInfo, string owner, HarmonyMethod info)
        {
            if (info == null || info.method == null)
            {
                return;
            }

            var priority = info.priority == -1 ? Priority.Normal : info.priority;
            var before   = info.before ?? new string[0];
            var after    = info.after ?? new string[0];

            patchInfo.AddTranspiler(info.method, owner, priority, before, after);
        }
 //Applies the patch.
 private static void ApplyPatch(PatchInfo patch)
 {
     try
     {
         PatchProcessor proc = new PatchProcessor(harmony, patch.patchClass, patch.target);
         proc.Patch();
         appliedPatches.Add(proc);
     }
     catch (Exception ex)
     {
         Debug.Log(string.Format("PostDbPatcher: Failed to apply patch for {0}, targetting {1}.{2}({3}): {4}", patch.patchClass.FullName, patch.target.declaringType, patch.target.methodName ?? ".ctor", ArgumentsToString(patch.target.argumentTypes), ex.ToString()));
     }
 }
    public async void Patching()
    {
        float counter = OnInitialize("Updating...");

        info = JsonConvert.DeserializeObject <PatchInfo>(File.ReadAllText(PatchPath + "/patch.txt"));
        int total = info.filesToAdd.Count + info.filesToDelete.Count + info.filesToReplace.Count;

        await ApplyAllPatches(counter, total);

        OnComplete("Update");
        string tmp;

        UpdateSelectedFolderInfo(path_OldStandAlone, out files_inOldStandAlone, out directory_inOldStandAlone, out tmp);
    }
Exemplo n.º 8
0
 void updatePatchList()
 {
     string[] foldList = Directory.GetDirectories(targetPath);
     for (int i = 0; i < foldList.Length; i++)
     {
         string    folderName = foldList[i];
         string    vername    = Path.GetFileName(folderName).Replace("_", ".");
         PatchInfo info       = new PatchInfo(vername);
         info.loadContent(folderName);
         if (info.isVaild)
         {
             patchList.Add(info);
         }
     }
 }
Exemplo n.º 9
0
        private async Task RoundtripTest(string OldDir, string NewDir, string TargetDir, string PatchDir, string ApplicationDir)
        {
            var patchInfo = new PatchInfo
            {
                OldPath   = OldDir,
                NewPath   = NewDir,
                PatchPath = PatchDir,
            };

            var builder = new RXPatchBuilder();
            await builder.CreatePatchAsync(patchInfo);

            await new RXPatcher().ApplyPatchFromWeb("file:///" + PatchDir, TargetDir, ApplicationDir, TestProgressHandlerFactory.Create(), new CancellationToken(), null);

            await DirectoryAssertions.IsSubsetOf(NewDir, TargetDir);
        }
    //Registers a patch. It will be applied after the game's Db is initialized. If the Db is already initialized, the patch will be applied immediately.
    public static void Register(Type patchClass, Type targetType, string targetMethodName, Type[] targetMethodParameters = null)
    {
        var target = new HarmonyMethod(targetType, targetMethodName, targetMethodParameters);
        //For some reason the constructor doesn't set these???
        //target.declaringType = targetType;
        //target.methodName = targetMethodName;
        //target.argumentTypes = targetMethodParameters;
        var patch = new PatchInfo(patchClass, target);

        if (delayedPatches != null) //Db not ready yet.
        {
            delayedPatches.Add(patch);
        }
        else //Db ready, apply immediately.
        {
            ApplyPatch(patch);
        }
    }
        private void WarnIfHasTranspiler(PatchInfo patchInfo, MelonLogger.Instance loggerInstance)
        {
            if (patchInfo.transpilers.Length <= 0)
            {
                return;
            }
            string txt = $"Harmony: Method {Original.FullDescription()} will only have its Unhollowed IL available to Transpilers, " +
                         "suggesting you either don't use any Transpilers when Patching this Method or ignore this Warning if modifying the Unhollowed IL is your goal.";

            if (loggerInstance != null)
            {
                loggerInstance.Warning(txt);
            }
            else
            {
                MelonLogger.Warning(txt);
            }
        }
Exemplo n.º 12
0
        static ExePatching()
        {
            // Xbox360:
#if false // #TODO
            var Xbox_v1 = new PatchInfo("0723A9FBAB23DE2B0AB80656174EEF0D2ADC2D98")
          //.Add(0x6D971F, 0xE9, 0x0A, 0x01, 0x00, 0x00);
                          kPatches.Add(Xbox_v1);
#endif

            // PC:
            var v1_11088_1_2 = new PatchInfo("2C1E144727CFF2AADDAE6BB71EE66B7820D3E163")
                               .Add(0x6D971F, 0xE9, 0x0A, 0x01, 0x00, 0x00);
            kPatches.Add(v1_11088_1_2);

            var v1_11279_1_2 = new PatchInfo("BF664000801CAC222514B7ACE88C17768B86CC30")
                               .Add(0x6DE03F, 0xE9, 0x0A, 0x01, 0x00, 0x00);
            kPatches.Add(v1_11279_1_2);
        }
Exemplo n.º 13
0
        public void Serialize()
        {
            var method  = SymbolExtensions.GetMethodInfo(() => ExpectedJSON());
            var hMethod = new HarmonyMethod(method, Priority.High, new[] { "p1", null, "p2" }, new string[0], true);

            var patchInfo = new PatchInfo();

            patchInfo.AddPrefixes("prefixes", new[] { hMethod });
            patchInfo.AddPostfixes("postfixes", new[] { hMethod });
            patchInfo.AddTranspilers("transpilers", new[] { hMethod });
            patchInfo.AddFinalizers("finalizers", new[] { hMethod });

            PatchInfoSerialization.useBinaryFormatter = false;
            var result    = PatchInfoSerialization.Serialize(patchInfo);
            var resString = Encoding.UTF8.GetString(result, 0, result.Length);

            Assert.AreEqual(ExpectedJSON(), resString);
        }
Exemplo n.º 14
0
        private static void SortPatches(MethodBase original, PatchInfo patchInfo,
                                        out List <PatchContext> prefixes,
                                        out List <PatchContext> postfixes,
                                        out List <PatchContext> transpilers,
                                        out List <PatchContext> finalizers,
                                        out List <PatchContext> ilmanipulators)
        {
            Patch[] prefixesArr, postfixesArr, transpilersArr, finalizersArr, ilmanipulatorsArr;

            // Lock to ensure no more patches are added while we're sorting
            lock (patchInfo)
            {
                prefixesArr       = patchInfo.prefixes.ToArray();
                postfixesArr      = patchInfo.postfixes.ToArray();
                transpilersArr    = patchInfo.transpilers.ToArray();
                finalizersArr     = patchInfo.finalizers.ToArray();
                ilmanipulatorsArr = patchInfo.ilmanipulators.ToArray();
            }
Exemplo n.º 15
0
    //获取差异文件
    public ArrayList getDiffFiles(PatchInfo other)
    {
        ArrayList list = new ArrayList();

        foreach (KeyValuePair <string, UpdateFileInfo> info in other.fileList)
        {
            string         key     = info.Key;
            UpdateFileInfo newInfo = info.Value;
            UpdateFileInfo curInfo = null;
            fileList.TryGetValue(key, out curInfo);
            if (curInfo != null && curInfo.equal(newInfo))
            {
                continue;
            }
            list.Add(key);
        }
        return(list);
    }
Exemplo n.º 16
0
 private static bool ParseTextBank(string inputFileName)
 {
     try
     {
         string[] strPatches;
         using (StreamReader reader = new StreamReader(inputFileName))
         {
             if (!reader.ReadLine().Trim().Equals("[PATCHBANK]"))
             {
                 Console.WriteLine("The text bank header was not correct.");
                 throw new InvalidDataException("The input file is not a valid patch bank.");
             }
             comments   = ReadTag(reader, "comment").Trim();
             patchPath  = ReadTag(reader, "patchpath").Trim();
             assetPath  = ReadTag(reader, "assetpath").Trim();
             strPatches = ReadTag(reader, "patches").Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
         }
         for (int x = 0; x < strPatches.Length; x++)
         {
             string[] args = strPatches[x].Split(new char[] { '/' }, StringSplitOptions.None);
             short    bank;
             if (args[3][0] == 'i')
             {
                 bank = 0;
             }
             else if (args[3][0] == 'd')
             {
                 bank = PatchBank.DrumBank;
             }
             else
             {
                 bank = short.Parse(args[3]);
             }
             PatchInfo pInfo = new PatchInfo(args[0], new PatchInterval(bank, byte.Parse(args[1]), byte.Parse(args[2])));
             AddPatchInfo(pInfo);
         }
         return(true);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message);
     }
     return(false);
 }
Exemplo n.º 17
0
        void ProcessFiles(IEnumerable <string> files, CancellationToken token)
        {
            Dictionary <string, PatchInfo> patches = new Dictionary <string, PatchInfo>();

            foreach (string fullName in files)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                PatchInfo patch;
                string    directory = Path.GetDirectoryName(fullName);
                if (!patches.TryGetValue(directory, out patch))
                {
                    string[] patchFiles = Directory.GetFiles(directory, "*.patch");
                    if (patchFiles.Length > 0)
                    {
                        patch = PatchInfo.Read(patchFiles[0]);
                    }
                    else
                    {
                        patch = null;
                    }
                    patches.Add(directory, patch);
                }
                string imagePath = ImagePathBuilder.BuildPath(this.outputDir, fullName, this.rules, patch);
                if (!File.Exists(imagePath) && File.Exists(fullName))
                {
                    try {
                        string targetDirectory = Path.GetDirectoryName(imagePath);
                        if (!Directory.Exists(targetDirectory))
                        {
                            Directory.CreateDirectory(targetDirectory);
                        }
                        File.Copy(fullName, imagePath, false);
                    }
                    catch (Exception e) {
                        AppendLog("The file " + fullName + " has not copied.", e.Message, e.StackTrace);
                    }
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>根据Patch信息生成PatchInfo
        /// </summary>
        public PatchInfo PatchToInfo(Patch patch)
        {
            var patchInfo = new PatchInfo()
            {
                StoreType = StoreType.S3,
                Code      = patch.Code,
                Name      = patch.Name,
                State     = patch.State
            };

            if (patch.StoreType == (int)StoreType.S3)
            {
                var s3Patch    = (S3Patch)patch;
                var bucketDict = DictionaryEmit.ObjectToDictionary <BucketInfo>(s3Patch.Bucket);
                patchInfo.Expands.Add(bucketDict.ToList());
            }
            else if (patch.StoreType == (int)StoreType.FastDFS)
            {
                var fastDFSPatch = (FastDFSPatch)patch;
                foreach (var tracker in fastDFSPatch.Trackers)
                {
                    var trackerDict = DictionaryEmit.ObjectToDictionary <Tracker>(tracker);
                    patchInfo.Expands.Add(trackerDict.ToList());
                }
            }
            else
            {
                throw new ArgumentException("不是有效的Patch类型,无法转换成PatchInfo");
            }

            for (int i = 0; i < patchInfo.Expands.Count; i++)
            {
                for (int j = 0; j < patchInfo.Expands[i].Count; j++)
                {
                    var kv    = patchInfo.Expands[i][j];
                    var value = kv.Value.TrimEnd('\r').TrimEnd('\n');
                    patchInfo.Expands[i][j] = new KeyValuePair <string, string>(kv.Key, value);
                }
            }

            return(patchInfo);
        }
Exemplo n.º 19
0
        private void Button3_Click(object sender, EventArgs e)
        {
            string  file    = this.textBox3.Text;
            Patcher patcher = new Patcher(file);
            var     res     = patcher.Module.Resources.FindEmbeddedResource("app.resources").CreateReader();

            ResourceElement element  = res.ResourceElements.First(s => s.Name == resxName);
            MemoryStream    reStream = new MemoryStream();

            res.CreateReader().CopyTo(reStream);



            var rsA = Assembly.Load(reStream.ToArray());

            PatchInfo patchInfo = new PatchInfo()
            {
                Namespace = "TestLibrary",
                Class     = "TestAction",
                Method    = "Check",
            };

            // var methodDef = patcher.FindMethod(patchInfo);
            patcher.WriteReturnBody(patchInfo, true);
            AssemblyDef  assemblyDef  = patcher.Module.Assembly;
            MemoryStream memoryStream = new MemoryStream();

            patcher.Module.Write(memoryStream, new ModuleWriterOptions(patcher.Module)
            {
                MetadataOptions = { Flags = MetadataFlags.KeepOldMaxStack }
            });

            Assembly assembly = Assembly.Load(memoryStream.ToArray());

            Type       type       = assembly.GetType("TestLibrary.TestAction");
            MethodInfo method     = type.GetMethod("Check");
            var        ins        = Activator.CreateInstance(type);
            var        parameters = new object[] { this.textBox2.Text };
            bool       result     = (bool)method.Invoke(ins, parameters);

            MessageBox.Show(result.ToString());
        }
Exemplo n.º 20
0
        private static void SortPatches(MethodBase original, PatchInfo patchInfo, out List <MethodInfo> prefixes,
                                        out List <MethodInfo> postfixes, out List <MethodInfo> transpilers,
                                        out List <MethodInfo> finalizers)
        {
            Patch[] prefixesArr, postfixesArr, transpilersArr, finalizersArr;

            // Lock to ensure no more patches are added while we're sorting
            lock (patchInfo)
            {
                prefixesArr    = patchInfo.prefixes.ToArray();
                postfixesArr   = patchInfo.postfixes.ToArray();
                transpilersArr = patchInfo.transpilers.ToArray();
                finalizersArr  = patchInfo.finalizers.ToArray();
            }

            prefixes    = prefixesArr.Sort(original);
            postfixes   = postfixesArr.Sort(original);
            transpilers = transpilersArr.Sort(original);
            finalizers  = finalizersArr.Sort(original);
        }
Exemplo n.º 21
0
        private void ParseTextBank(string patchBank)
        {
            StreamReader reader = new StreamReader(patchBank);
            string       id     = reader.ReadLine().Trim().ToLower();

            if (!id.Equals("[patchbank]"))
            {
                throw new InvalidDataException("Invalid patch bank!");
            }
            comments  = ReadTag(reader, "comment").Trim();
            patchPath = ReadTag(reader, "patchpath").Trim();
            assetPath = ReadTag(reader, "assetpath").Trim();
            string[] strPatches = ReadTag(reader, "patches").Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
            reader.Close();
            for (int x = 0; x < strPatches.Length; x++)
            {
                string[] args = strPatches[x].Split(new char[] { '/' }, StringSplitOptions.None);
                short    bank;
                if (args[3][0] == 'i')
                {
                    bank = 0;
                }
                else if (args[3][0] == 'd')
                {
                    bank = PatchBank.DrumBank;
                }
                else
                {
                    bank = short.Parse(args[3]);
                }
                PatchInfo pInfo = new PatchInfo(args[0], new PatchInterval(bank, byte.Parse(args[1]), byte.Parse(args[2])));
                foreach (PatchInfo p in patches)
                {
                    if (pInfo.Ranges[0].WithinRange(p.Ranges[0]))
                    {
                        throw new Exception(string.Format("Invalid Bank. An overlap between ({0}) and ({1}) is not allowed.", p, pInfo));
                    }
                }
                patches.Add(pInfo);
            }
        }
Exemplo n.º 22
0
        /// <summary>根据PatchInfo转换成Patch
        /// </summary>
        public Patch InfoToPatch(PatchInfo info)
        {
            if (info.StoreType == StoreType.S3)
            {
                var s3Patch = new S3Patch()
                {
                    StoreType = (int)StoreType.S3,
                    Name      = info.Name,
                    Code      = info.Code,
                    State     = info.State
                };
                if (info.Expands.Any())
                {
                    var bucketDict = info.Expands[0].ToDictionary(x => x.Key, x => x.Value);
                    s3Patch.Bucket = DictionaryEmit.DictionaryToObject <BucketInfo>(bucketDict);
                }
                return(s3Patch);
            }
            else if (info.StoreType == StoreType.FastDFS)
            {
                var fastDFSPatch = new FastDFSPatch()
                {
                    StoreType = (int)StoreType.FastDFS,
                    Name      = info.Name,
                    Code      = info.Code,
                    State     = info.State
                };
                foreach (var item in info.Expands)
                {
                    var trackerDict = item.ToDictionary(x => x.Key, x => x.Value);
                    var tracker     = DictionaryEmit.DictionaryToObject <Tracker>(trackerDict);
                    fastDFSPatch.Trackers.Add(tracker);
                }

                return(fastDFSPatch);
            }
            else
            {
                throw new ArgumentException("不是有效的Patch类型,无法转换成Patch");
            }
        }
Exemplo n.º 23
0
    private void _print(int parentID, PatchInfo p)
    {
        if (parentID == 0)
        {
            p.print(Console.Out);

            /* only print the list if it wasn't a merge changeset.
             * merge changesets have tree-branches
             */
            if (p.treeBranches == null || p.treeBranches.Count == 0)
            {
                if (_printWhat != Printwhat.None)
                {
                    for (int i = 0; i < p.cs.Changes.Length; ++i)
                    {
                        switch (_printWhat)
                        {
                        case (Printwhat.NameOnly):
                        { Console.WriteLine("{0}", p.cs.Changes[i].Item.ServerItem); break; }

                        case (Printwhat.NameStatus):
                        {
                            Console.WriteLine("{0:20}{1}",
                                              p.cs.Changes[i].ChangeType, p.cs.Changes[i].Item.ServerItem);
                            break;
                        }
                        }
                    }
                    Console.WriteLine();
                }
            }
        }
        else
        {
            Console.WriteLine("Parent: {0}", parentID);
            Console.WriteLine("Changeset: {0}", p.cs.ChangesetId);
            Console.WriteLine();
        }
    }
Exemplo n.º 24
0
    static List <string> FindNeedUpdateFiles()
    {
        var           oldPatchList = GetOldPatchList();
        List <string> updateList   = new List <string>();

        foreach (var path in AppConst.AssetPaths)
        {
            string   fullPath = AppDataPath + path;
            string[] files    = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories);
            foreach (var file in files)
            {
                if (file.EndsWith(".meta"))
                {
                    continue;
                }
                var md5     = Util.md5file(file);
                var newfile = file.Replace('\\', '/');
                var newPath = newfile.Replace(AppDataPath + "/", "")
                              .Replace("StreamingAssets/", "")
                              .ToLower();

                PatchInfo patch = null;
                if (oldPatchList.TryGetValue(newPath, out patch))
                {
                    if (patch.md5 != md5)   //md5值不同添加更新列表
                    {
                        updateList.Add(newfile);
                    }
                }
                else
                {
                    updateList.Add(newfile);   //不存在直接添加更新列表
                }
            }
        }
        return(updateList);
    }
Exemplo n.º 25
0
        private static int LoadSfz(PatchInfo pInfo)
        {
            SfzReader sfz;

            using (FileStream fs = File.Open(patchPath + pInfo.Name, FileMode.Open, FileAccess.Read))
            {
                sfz = new SfzReader(fs, pInfo.Name);
            }
            PatchInfo[] pInfos  = new PatchInfo[sfz.Regions.Length];
            int         nameLen = sfz.Name.Length + 1 + sfz.Regions.Length.ToString().Length;

            if (nameLen > 20)
            {
                sfz.Name = sfz.Name.Remove(0, nameLen - 20);
            }
            for (int i = 0; i < pInfos.Length; i++)
            {
                pInfos[i]             = new PatchInfo(sfz.Name + "_" + i, new PatchInterval(-1, 0, 0));
                pInfos[i].Type        = "sfz ";
                pInfos[i].Description = new DescriptorList(sfz.Regions[i]);
            }
            DescriptorList multiDesc = new DescriptorList();

            multiDesc.CustomDescriptions = new CustomDescriptor[sfz.Regions.Length];
            for (int i = 0; i < multiDesc.CustomDescriptions.Length; i++)
            {
                SfzRegion r = sfz.Regions[i];
                multiDesc.CustomDescriptions[i] = new CustomDescriptor("mpat", pInfos[i].Name.Length + 14, new object[] { pInfos[i].Name, r.loChan, r.hiChan, r.loKey, r.hiKey, r.loVel, r.hiVel });
            }
            pInfo.Type        = "mult";
            pInfo.Description = multiDesc;
            multiPatches.Add(pInfo);
            patches.Remove(pInfo);
            patches.InsertRange(0, pInfos);
            return(pInfos.Length - 1);
        }
 private static int LoadPatch(PatchInfo pInfo)
 {
     using (StreamReader reader = new StreamReader(patchPath + pInfo.Name))
     {
         string str = reader.ReadLine();
         if (PatchBank.BankVersion != float.Parse(str.Substring(str.IndexOf("v") + 1)))
             throw new Exception("The patch " + pInfo.Name + " has an incorrect version.");
         pInfo.Type = reader.ReadLine().Trim().ToLower();
         pInfo.Description = new DescriptorList(reader);
     }
     if (pInfo.Type.Equals("multi"))
     {
         patches.Remove(pInfo);
         multiPatches.Add(pInfo);
         //load sub patches
         for (int i = 0; i < pInfo.Description.CustomDescriptions.Length; i++)
         {
             if (!pInfo.Description.CustomDescriptions[i].ID.Equals("mpat"))
                 throw new Exception("Invalid multi patch: " + pInfo.Name);
             string subPatchName = (string)pInfo.Description.CustomDescriptions[i].Objects[0];
             if (ContainsPatch(subPatchName, patches) == false)
             {
                 PatchInfo subPatch = new PatchInfo(subPatchName, new PatchInterval(-1, 0, 0));
                 patches.Add(subPatch);
             }
         }
         return -1;
     }
     return 0;
 }
Exemplo n.º 27
0
 /// <summary>
 /// returns maximal value of given parameter from neighbouring patches
 /// 666 if none is defined    
 public float GetNeighbourMax(int _x, int _z, PatchInfo parameter, int stepSize)
 {
     int count = 0;
     float max = -666;
     //Debug.Log(_x + "," + _z);
     for (int x = _x - stepSize; x <= _x + stepSize; x += stepSize)
     {
         for (int z = _z - stepSize; z <= _z + stepSize; z += stepSize)
         {
             float v = -666;
             switch (parameter)
             {
                 case PatchInfo.rMin:
                     v = rMin.GetValue(x, z);
                     break;
                 case PatchInfo.rMax:
                     v = rMax.GetValue(x, z);
                     break;
                 case PatchInfo.noise:
                     v = noise.GetValue(x, z);
                     break;
             }
             if (v > max)
             {
                 max = v;
                 count++;
             }
             //Debug.Log(x + "," + z + ": " + v);
         }
     }
     if (count == 0)
         return 666;
     else
         return max;
 }
Exemplo n.º 28
0
 public void MapRTToVertexColor(RenderTexture rt, PatchInfo mesh_info, in BakeDepthParam param, Mesh mesh, Color[] cols)
Exemplo n.º 29
0
        public void Update()
        {
            if (_currentState != UpdateState.None)
            {
                OnUpdateStateChanged(_currentState);
                return;
            }

            // Pour changer l'état le plus rapidement possible sans permettre de vérifier l'état avant qu'il ne change d'un autre flux
            _currentState = UpdateState.Started;

            // Démarrer l'exécution du code dans un thread à partir d'un pool de threads.
            ThreadPool.QueueUserWorkItem(async unused =>
            {
                // Informer les abonnés que la mise à jour a été lancée.
                OnUpdateStateChanged(UpdateState.Started);

                Task <string> task = Task.Factory.StartNew(() => _webClient.DownloadString(_serverPatchListFile));
                string patchlist   = await task;

                var patch = new PatchInfo(patchlist);

                // Obtenez le chemin d'accès au dossier dans lequel les données du client sont mises à jour (le dossier où se trouve le dispositif de mise à jour/le lanceur et les données à mettre à jour).
                string dataDirectory = Path.Combine(_rootDirectory);
                if (!Directory.Exists(dataDirectory))
                {
                    Directory.CreateDirectory(dataDirectory);
                }

                // Obtenir tous les fichiers mpq situés sur le disque local (y compris tous les sous-dossiers).
                string[] localFiles = Directory.GetFiles(dataDirectory, ".", SearchOption.AllDirectories);

                // Filtrer uniquement les fichiers locaux dont les noms coïncident avec les noms de fichiers dans le patch
                Dictionary <string, FileInfo> matchingFiles =
                    localFiles.Where(                                                     // Filtre où
                        f => patch.UpdateFiles.Any(                                       // le fichier local f correspond
                            pf => pf.FileName == Path.GetFileName(f) && !File.Exists(f))) // avec un fichier dans le patch nommé
                    .Select(mf => new FileInfo(mf))                                       // Projeter chaque élément de collection dans un nouveau type de données
                    .ToDictionary(info => info.Name);                                     // convertir la collection filtrée en dictionnaire avec la clé "nom de fichier"

                // Dernier pourcentage d'avancement de la mise à jour
                int lastPercentValue = 0;

                // Créer un dossier temporaire s'il n'existe pas. Dossier où nous allons télécharger les nouveaux fichiers de mise à jour
                if (!Directory.Exists(TempFolder))
                {
                    Directory.CreateDirectory(TempFolder);
                }

                // Créer une liste comparable de fichiers téléchargés avec des informations sur ce fichier
                // précédemment reçu du serveur (à partir d'une feuille de patch)
                var downloaded = new List <Tuple <string, UpdateFile> >(patch.UpdateFiles.Length);

                // créer un compteur variable du nombre d'octets téléchargés de tous les fichiers
                long downloadedBytesLength = 0L;
                // Télécharger tous les fichiers
                for (int i = 0; i < patch.UpdateFiles.Length; i++)
                {
                    UpdateFile updateFile = patch.UpdateFiles[i];

                    string tempFile = Path.Combine(TempFolder, updateFile.FileName);

                    if (matchingFiles.ContainsKey(updateFile.FileName))
                    {
                        FileInfo file        = matchingFiles[updateFile.FileName];
                        string localFileHash = HashHelper.GetMD5HashOfFile(file.FullName);
                        if (localFileHash == updateFile.Hash)
                        {
                            // on ajoute sa taille à la somme des octets téléchargés,
                            // que le pourcentage de progression du téléchargement est correctement pris en compte
                            downloadedBytesLength += updateFile.FileSize;
                            lastPercentValue       = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize);
                            continue; // quitter l'itération en cours du cycle et le cycle passe à l'étape suivante
                        }
                    }

                    long offset = 0L;
                    // Si le fichier existe (a été téléchargé plus tôt) et qu'il est entièrement téléchargé (le hachage correspond au hachage de la feuille de patch)
                    if (File.Exists(tempFile))
                    {
                        string hash = HashHelper.GetMD5HashOfFile(tempFile);
                        if (hash == updateFile.Hash) // vérifier les hashes.
                        {
                            // on ajoute sa taille à la somme des octets téléchargés,
                            // que le pourcentage de progression du téléchargement est correctement pris en compte
                            downloadedBytesLength += updateFile.FileSize;
                            downloaded.Add(Tuple.Create(tempFile, updateFile));
                            lastPercentValue = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize);
                            continue; // quitter l'itération en cours du cycle et le cycle passe au cycle suivant
                        }
                        /*-------------   pompant -------------------------*/
                        else
                        {
                            var fileInfo           = new FileInfo(tempFile);
                            offset                 = fileInfo.Length; // Combien d'octets ont été téléchargés. Combien vous devez déplacer lors du téléchargement.
                            downloadedBytesLength += fileInfo.Length; // les progrès seront désormais dûment pris en compte
                        }
                    }

                    Uri url = new Uri(UrlHelper.Combine(_serverFilesRoot, updateFile.FileName));
                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                    if (offset > 0L) // L signifie que les littéraux de type 0 sont longs ou Int64, ce qui est la même chose. Sans L, il y aura un type int.
                    {
                        request.AddRange(offset);
                    }
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        if (response.StatusCode != HttpStatusCode.OK)
                        {
                            string message = string.Format("POST failed. Received HTTP {0}", response.StatusCode);
                            MessageBox.Show(message);
                            //throw new ApplicationException(message); Don't crash
                        }

                        Stream source = response.GetResponseStream();
                        if (source != null)
                        {
                            // пытаемся создать папки, которые отсутствуют из пути
                            var address      = new Uri(Path.Combine(_rootDirectory + '/' + updateFile.FileName), UriKind.Absolute);
                            string directory = Path.GetDirectoryName(address.LocalPath);
                            Debug.Assert(directory != null);
                            if (!Directory.Exists(directory))
                            {
                                Directory.CreateDirectory(directory);
                            }

                            byte[] buffer = new byte[400]; //102400 байт = 100 Килобайт  (400)

                            if (!FileExists(_rootDirectory + "/" + "d3dcompiler_47.dll"))
                            {
                                using (FileStream fs = new FileStream(_rootDirectory + '/' + updateFile.FileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    fs.Position = offset;
                                    while (true)
                                    {
                                        //кол-во реально прочитанных байт (буфер может быть больше,
                                        //чем на последней итерации цикла "do while" реально прочитали)
                                        int readed = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
                                        if (readed == 0)
                                        {
                                            break;
                                        }

                                        await fs.WriteAsync(buffer, 0, readed).ConfigureAwait(false);
                                        downloadedBytesLength += readed;
                                        lastPercentValue       = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize, fs.Length);
                                    }
                                }
                            }
                            else if (updateFile.FileName != "d3dcompiler_47.dll")
                            {
                                using (FileStream fs = new FileStream(_rootDirectory + '/' + updateFile.FileName, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    fs.Position = offset;
                                    while (true)
                                    {
                                        //кол-во реально прочитанных байт (буфер может быть больше,
                                        //чем на последней итерации цикла "do while" реально прочитали)
                                        int readed = await source.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
                                        if (readed == 0)
                                        {
                                            break;
                                        }

                                        await fs.WriteAsync(buffer, 0, readed).ConfigureAwait(false);
                                        downloadedBytesLength += readed;
                                        lastPercentValue       = UpdateProgress(downloadedBytesLength, updateFile.FileName, patch.PatchLength, lastPercentValue, updateFile.FileSize, fs.Length);
                                    }
                                }
                            }

                            downloaded.Add(Tuple.Create(tempFile, updateFile));
                        }
                    }
                }

                /*
                 * foreach (Tuple<string, UpdateFile> tuple in downloaded) //<путь к временному файлу, соответствующее описание этому файлу>
                 * {
                 *  UpdateFile updateFile = tuple.Item2;
                 *  string tempFile = tuple.Item1;
                 *  string directory = string.Empty;
                 *
                 *  if (updateFile.FolderName == Path.Combine(AppDomain.CurrentDomain.BaseDirectory))
                 *  {   // ../Data
                 *      directory = Path.Combine(_rootDirectory);
                 *  }
                 *  if (!Directory.Exists(directory))
                 *  {
                 *      Directory.CreateDirectory(directory);
                 *  }
                 *
                 *  string file = Path.Combine(directory, updateFile.FileName);
                 *  if (File.Exists(file))
                 *  {
                 *      File.Delete(file);
                 *  }
                 *  File.Move(tempFile, file);
                 * }
                 */

                if (_pidFromServer != null)
                {
                    using (StreamWriter writer = File.CreateText(_localPidFile))
                    {
                        await writer.WriteAsync(_pidFromServer.ToString()).ConfigureAwait(false);
                        writer.Dispose();
                    }
                }

                OnUpdateStateChanged(UpdateState.Completed);
                OnUpdateStateChanged(UpdateState.None);
            });
        }
Exemplo n.º 30
0
        public static LayerDataPacket CreateLandPacket(List<PatchInfo> ps, byte type)
        {
            LayerDataPacket layer = new LayerDataPacket { LayerID = { Type = type } };

            TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader { Stride = STRIDE, PatchSize = Constants.TerrainPatchSize };

            byte[] outdata = new byte[1500];
            byte[] indata = BitConverter.GetBytes((ushort)header.Stride);
            if(!BitConverter.IsLittleEndian)
            {
                Array.Reverse(indata);
            }
            outdata[0] = indata[0];
            outdata[1] = indata[1];
            outdata[2] = (byte)header.PatchSize;
            outdata[3] = type;

            int outBitPos = 32;

            PatchInfo eop = new PatchInfo();
            eop.PackedData = new byte[] { END_OF_PATCHES };
            eop.BitLength = 8;
            ps.Add(eop);

            foreach(PatchInfo pi in ps)
            {
                int count = 0;
                int curBytePos = 0;
                int bitCount = pi.BitLength;
                /* this bit pack method has a slight variance allowing it to directly accept BitPacked data */
                while (bitCount > 0)
                {
                    count = bitCount;
                    if (count > 8)
                    {
                        count = 8;
                    }

                    byte srcBits = pi.PackedData[curBytePos];
                    while (count-- > 0)
                    {
                        byte curBitMask = (byte)(0x80 >> (outBitPos % 8));

                        if ((srcBits & 0x80) != 0)
                        {
                            outdata[outBitPos / 8] |= curBitMask;
                        }
                        else
                        {
                            outdata[outBitPos / 8] &= (byte)~curBitMask;
                        }

                        ++outBitPos;
                        srcBits <<= 1;
                    }
                    ++curBytePos;

                    if (bitCount > 8)
                    {
                        bitCount -= 8;
                    }
                    else
                    {
                        bitCount = 0;
                    }
                }
            }

            layer.LayerData.Data = new byte[(outBitPos + 7) / 8];
            Buffer.BlockCopy(outdata, 0, layer.LayerData.Data, 0, (outBitPos + 7) / 8);

            return layer;
        }
Exemplo n.º 31
0
        public static LayerDataPacket CreateLandPacket(List <PatchInfo> ps, byte type)
        {
            LayerDataPacket layer = new LayerDataPacket {
                LayerID = { Type = type }
            };

            TerrainPatch.GroupHeader header = new TerrainPatch.GroupHeader {
                Stride = STRIDE, PatchSize = Constants.TerrainPatchSize
            };

            byte[] outdata = new byte[1500];
            byte[] indata  = BitConverter.GetBytes((ushort)header.Stride);
            if (!BitConverter.IsLittleEndian)
            {
                Array.Reverse(indata);
            }
            outdata[0] = indata[0];
            outdata[1] = indata[1];
            outdata[2] = (byte)header.PatchSize;
            outdata[3] = type;

            int outBitPos = 32;

            PatchInfo eop = new PatchInfo();

            eop.PackedData = new byte[] { END_OF_PATCHES };
            eop.BitLength  = 8;
            ps.Add(eop);

            foreach (PatchInfo pi in ps)
            {
                int count      = 0;
                int curBytePos = 0;
                int bitCount   = pi.BitLength;
                /* this bit pack method has a slight variance allowing it to directly accept BitPacked data */
                while (bitCount > 0)
                {
                    count = bitCount;
                    if (count > 8)
                    {
                        count = 8;
                    }

                    byte srcBits = pi.PackedData[curBytePos];
                    while (count-- > 0)
                    {
                        byte curBitMask = (byte)(0x80 >> (outBitPos % 8));

                        if ((srcBits & 0x80) != 0)
                        {
                            outdata[outBitPos / 8] |= curBitMask;
                        }
                        else
                        {
                            outdata[outBitPos / 8] &= (byte)~curBitMask;
                        }

                        ++outBitPos;
                        srcBits <<= 1;
                    }
                    ++curBytePos;

                    if (bitCount > 8)
                    {
                        bitCount -= 8;
                    }
                    else
                    {
                        bitCount = 0;
                    }
                }
            }

            layer.LayerData.Data = new byte[(outBitPos + 7) / 8];
            Buffer.BlockCopy(outdata, 0, layer.LayerData.Data, 0, (outBitPos + 7) / 8);

            return(layer);
        }
Exemplo n.º 32
0
 internal static void UpdatePatchInfo(MethodBase method, PatchInfo patchInfo)
 {
     state[method] = patchInfo;
 }
Exemplo n.º 33
0
        /// <summary>
        /// Builds a patch for the current platform
        /// </summary>
        public static void BuildPatch()
        {
            BuildTarget buildPlatform = EditorUserBuildSettings.activeBuildTarget;

            string playerPath       = Directory.GetCurrentDirectory().Replace('\\', '/') + "/obj/";
            string assetBundlesPath = Directory.GetCurrentDirectory().Replace('\\', '/') + "/obj/";
            string buildPath        = Directory.GetCurrentDirectory().Replace('\\', '/') + "/bin/";

            switch (buildPlatform)
            {
            case BuildTarget.StandaloneWindows:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            case BuildTarget.StandaloneWindows64:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            case BuildTarget.Android:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            case BuildTarget.WebGL:
                playerPath       += buildPlatform.ToString() + "/Player/";
                assetBundlesPath += buildPlatform.ToString() + "/AssetBundles/";
                buildPath        += buildPlatform.ToString() + "/Patch/";
                break;

            default:
                Debug.LogError("Mist of Time does not support " + buildPlatform.ToString() + " as a build target");
                return;
            }

            if (Directory.Exists(Path.GetDirectoryName(buildPath)))
            {
                Directory.Delete(Path.GetDirectoryName(buildPath), true);
            }

            Directory.CreateDirectory(Path.GetDirectoryName(buildPath));

            BuildPlayer();
            BuildAssetBundles();

            CopyDirectory(playerPath, buildPath, new string[] { });
            CopyDirectory(assetBundlesPath, buildPath, new string[] { ".manifest" });

            File.Move(buildPath + "AssetBundles", buildPath + "FTABLE.DAT");

            PatchInfo newPatchInfo = new PatchInfo();

            string[] buildDirectories = Directory.GetDirectories(buildPath, "*", SearchOption.AllDirectories);

            for (int i = 0; i < buildDirectories.Length; i++)
            {
                buildDirectories[i] = buildDirectories[i].Replace('\\', '/').Replace(buildPath, "");
                EditorUtility.DisplayProgressBar("Generating Patch Info", "Processing " + buildDirectories[i], ((float)i / buildDirectories.Length));
                newPatchInfo.PatchDirectories.Add(new PatchInfoDirectory(buildDirectories[i]));
            }

            EditorUtility.ClearProgressBar();

            string[] buildFiles = Directory.GetFiles(buildPath, "*", SearchOption.AllDirectories);

            for (int i = 0; i < buildFiles.Length; i++)
            {
                buildFiles[i] = buildFiles[i].Replace('\\', '/').Replace(buildPath, "");
                EditorUtility.DisplayProgressBar("Generating Patch Info", "Processing " + buildFiles[i], ((float)i / buildFiles.Length));

                using (FileStream stream = File.OpenRead(buildPath + buildFiles[i]))
                {
                    SHA256Managed sha      = new SHA256Managed();
                    byte[]        checksum = sha.ComputeHash(stream);
                    newPatchInfo.PatchFiles.Add(new PatchInfoFile(buildFiles[i], stream.Length, BitConverter.ToString(checksum).Replace("-", string.Empty)));
                }
            }

            EditorUtility.ClearProgressBar();

            newPatchInfo.Serialize(buildPath + "patch.txt");

            VersionInfo currentVersionInfo = (VersionInfo)AssetDatabase.LoadAssetAtPath("Assets/MOT/VersionInfo.asset", typeof(VersionInfo));

            File.WriteAllText(buildPath + "patch.ver", currentVersionInfo.PatchVersion);
        }
 private static bool ParseTextBank(string inputFileName)
 {
     try 
     {
         string[] strPatches;
         using (StreamReader reader = new StreamReader(inputFileName))
         {
             if(!reader.ReadLine().Trim().Equals("[PATCHBANK]"))
             {
                 Console.WriteLine("The text bank header was not correct.");
                 throw new InvalidDataException("The input file is not a valid patch bank.");
             }
             comments = ReadTag(reader, "comment").Trim();
             patchPath = ReadTag(reader, "patchpath").Trim();
             assetPath = ReadTag(reader, "assetpath").Trim();
             strPatches = ReadTag(reader, "patches").Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
         }
         for (int x = 0; x < strPatches.Length; x++)
         {
             string[] args = strPatches[x].Split(new char[] { '/' }, StringSplitOptions.None);
             short bank;
             if (args[3][0] == 'i')
                 bank = 0;
             else if (args[3][0] == 'd')
                 bank = PatchBank.DrumBank;
             else
                 bank = short.Parse(args[3]);
             PatchInfo pInfo = new PatchInfo(args[0], new PatchInterval(bank, byte.Parse(args[1]), byte.Parse(args[2])));
             AddPatchInfo(pInfo);
         }
         return true;
     } 
     catch (Exception ex) 
     {
         Debug.WriteLine(ex.Message);
     }
     return false;
 }
 private static void AddPatchInfo(PatchInfo pInfo)
 {
     foreach (PatchInfo p in patches)
     {
         int containIndex = -1;
         for(int x = 0; x < p.Ranges.Count; x++)
         {
             if(p.Ranges[x].WithinRange(pInfo.Ranges[0]))
             {
                 containIndex = x; 
                 break;
             }
         }
         if (pInfo.Name.Equals(p.Name))
         {
             if (containIndex >= 0) //the patch exists and its range is an overlap so we merge on the overlap
             {
                 p.Ranges[containIndex].Start = Math.Min(p.Ranges[containIndex].Start, pInfo.Ranges[0].Start);
                 p.Ranges[containIndex].End = Math.Max(p.Ranges[containIndex].End, pInfo.Ranges[0].End);
             }
             else//the patch already exists, but the ranges are different so we add its range the the existing one
                 p.Ranges.Add(pInfo.Ranges[0]);
             return;
         }
         else if (containIndex >= 0)
         {
             throw new Exception(string.Format("Patches {0} and {1} have overlapping assignments.", p.Name, pInfo.Name));
         }
     }
     patches.Add(pInfo);
 }
			[HandleProcessCorruptedStateExceptions, SecurityCritical]	// Req'd on .NET 4.0
			static bool PatchRuntime(IntPtr decryptAddr, PatchInfo info) {
				try {
					IntPtr baseAddr = new IntPtr(decryptAddr.ToInt64() - info.RvaDecryptMethod);
					if ((baseAddr.ToInt64() & 0xFFFF) != 0)
						return false;

					if (Marshal.ReadInt16(baseAddr) != 0x5A4D)
						return false;

					foreach (var patchData in info.PatchData) {
						var patchAddr = new IntPtr(baseAddr.ToInt64() + patchData.RVA);
						uint oldProtect;
						if (!VirtualProtect(patchAddr, patchData.Data.Length, PAGE_EXECUTE_READWRITE, out oldProtect))
							return false;
						Marshal.Copy(patchData.Data, 0, patchAddr, patchData.Data.Length);
						VirtualProtect(patchAddr, patchData.Data.Length, oldProtect, out oldProtect);
					}

					return true;
				}
				catch {
				}

				return false;
			}
Exemplo n.º 37
0
 public static void Patch(string fileName, PatchInfo info, byte[] newWalue, byte fillValue, Stream outStr) {
   if (newWalue.Length > info.Size) throw new Exception("newWalue.Length > info.Size");
   if (newWalue.Length < info.Size) {
     byte[] nw = new byte[info.Size]; newWalue.CopyTo(nw, 0);
     for (int i = newWalue.Length; i < nw.Length; i++) nw[i] = fillValue;
     newWalue = nw;
   }
   using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) {
     ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
     crc.Reset();
     crc.Update(newWalue);
     int crcValue = (int)crc.Value;
     int actPos = 0;
     int len = (int)info.HeaderPatchPos;
     LowUtils.CopyStream(fs, 0, len, outStr); actPos += len;
     WriteLeInt(outStr, crcValue); actPos += 4;
     WriteLeInt(outStr, info.Size); actPos += 4;
     WriteLeInt(outStr, info.Size); actPos += 4;
     len = (int)info.DataPos - actPos;
     LowUtils.CopyStream(fs, actPos, len, outStr); actPos += len;
     outStr.Write(newWalue, 0, newWalue.Length); actPos += newWalue.Length;
     len = (int)fs.Length - actPos;
     LowUtils.CopyStream(fs, actPos, len, outStr); actPos += len;
   }
 }
Exemplo n.º 38
0
 public static void Patch(string fileName, PatchInfo info, byte[] newWalue) {
   if (newWalue.Length != info.Size) throw new Exception("newWalue.Length!=info.Size");
   using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) {
     ICSharpCode.SharpZipLib.Checksums.Crc32 crc = new ICSharpCode.SharpZipLib.Checksums.Crc32();
     crc.Reset();
     crc.Update(newWalue);
     int crcValue = (int)crc.Value;
     fs.Seek(info.HeaderPatchPos, SeekOrigin.Begin);
     WriteLeInt(fs, crcValue);
     WriteLeInt(fs, info.Size);
     WriteLeInt(fs, info.Size);
     fs.Seek(info.DataPos, SeekOrigin.Begin);
     fs.Write(newWalue, 0, newWalue.Length);
   }
 }
 private static int LoadSfz(PatchInfo pInfo)
 {
     SfzReader sfz;
     using (FileStream fs = File.Open(patchPath + pInfo.Name, FileMode.Open, FileAccess.Read))
     {
         sfz = new SfzReader(fs, pInfo.Name);
     }
     PatchInfo[] pInfos = new PatchInfo[sfz.Regions.Length];
     int nameLen = sfz.Name.Length + 1 + sfz.Regions.Length.ToString().Length;
     if (nameLen > 20)
     {
         sfz.Name = sfz.Name.Remove(0, nameLen - 20);
     }
     for (int i = 0; i < pInfos.Length; i++)
     {
         pInfos[i] = new PatchInfo(sfz.Name + "_" + i, new PatchInterval(-1, 0, 0));
         pInfos[i].Type = "sfz ";
         pInfos[i].Description = new DescriptorList(sfz.Regions[i]);
     }
     DescriptorList multiDesc = new DescriptorList();
     multiDesc.CustomDescriptions = new CustomDescriptor[sfz.Regions.Length];
     for (int i = 0; i < multiDesc.CustomDescriptions.Length; i++)
     {
         SfzRegion r = sfz.Regions[i];
         multiDesc.CustomDescriptions[i] = new CustomDescriptor("mpat", pInfos[i].Name.Length + 14, new object[] { pInfos[i].Name, r.loChan, r.hiChan, r.loKey, r.hiKey, r.loVel, r.hiVel });
     }
     pInfo.Type = "mult";
     pInfo.Description = multiDesc;
     multiPatches.Add(pInfo);
     patches.Remove(pInfo);
     patches.InsertRange(0, pInfos);
     return pInfos.Length - 1;
 }
Exemplo n.º 40
0
    /*********************************************************************************/
    /*                 PATCH jednoho souboru v ZIP                                   */
    /*********************************************************************************/

    //public void AddPatchableFileToZip(string fileName, byte[] fileBytes, string filePath) {
    //  PatchInfo res = AddPatchableFileToZip (fileBytes, filePath);
    //  new XElement("patch",
    //    new XElement("Size", res.Size.ToString()),
    //    new XElement("HeaderPatchPos", res.HeaderPatchPos.ToString()),
    //    new XElement("DataPos", res.DataPos.ToString()),
    //    new XElement("FileName", res.FileName)
    //    ).Save(fileName += ".patch");
    //}

    //public PatchInfo AddPatchableFileToZip(byte[] fileBytes, string filePath) {
    //  ZipEntry entry = new ZipEntry(filePath);
    //  PatchInfo res = new PatchInfo() {FileName = filePath};
    //  entry.DateTime = DateTime.UtcNow;
    //  entry.Size = res.Size = fileBytes.Length;
    //  entry.CompressionMethod = CompressionMethod.Stored;

    //  zip.PutNextEntry(entry);

    //  res.HeaderPatchPos = zip.headerPatchPos;
    //  //zip.patchEntryHeader = false;
    //  res.DataPos = zip.baseOutputStream.Position;
    //  zip.Write(fileBytes, 0, fileBytes.Length);
    //  return res;
    //}

    static PatchInfo infoFromXml(string fileName) {
      XElement el = XElement.Load(fileName + ".patch");
      PatchInfo res = new PatchInfo();
      res.Size = int.Parse(el.Element("Size").Value);
      res.HeaderPatchPos = int.Parse(el.Element("HeaderPatchPos").Value);
      res.DataPos = int.Parse(el.Element("DataPos").Value);
      res.FileName = el.Element("FileName").Value;
      return res;
    }
Exemplo n.º 41
0
 public void StartModify()
 {
     if (!updateHandle.Equals(PublishedFileUpdateHandle_t.Invalid))
     {
         throw new InvalidOperationException("Upload already started");
     }
     // Legacy Workshop item
     updateHandle = SteamRemoteStorage.CreatePublishedFileUpdateRequest(details.
                                                                        m_nPublishedFileId);
     if (updateHandle.Equals(PublishedFileUpdateHandle_t.Invalid))
     {
         OnModifyFailed?.Invoke();
     }
     else
     {
         PUtil.LogDebug("MODIFYING MOD: " + Mod.label.title);
         string desc = Description?.Trim(), title = Title?.Trim();
         if (!desc.IsNullOrWhiteSpace() && desc != details.m_rgchDescription)
         {
             PUtil.LogDebug("DESCRIPTION: " + desc);
             if (!SteamRemoteStorage.UpdatePublishedFileDescription(updateHandle, desc))
             {
                 PUtil.LogWarning("Failed to set item description!");
             }
         }
         if (!title.IsNullOrWhiteSpace() && title != details.m_rgchTitle)
         {
             PUtil.LogDebug("TITLE: " + title);
             if (!SteamRemoteStorage.UpdatePublishedFileTitle(updateHandle, title))
             {
                 PUtil.LogWarning("Failed to set item title!");
             }
         }
         if (!PatchInfo.IsNullOrWhiteSpace())
         {
             PUtil.LogDebug("PATCH INFO: " + PatchInfo);
             if (!SteamRemoteStorage.UpdatePublishedFileSetChangeDescription(
                     updateHandle, PatchInfo))
             {
                 PUtil.LogWarning("Failed to set change notes!");
             }
         }
         if (UpdateData && !DataPath.IsNullOrWhiteSpace())
         {
             byte[] zipData = ZipModFolder(DataPath);
             if (zipData != null)
             {
                 PUtil.LogDebug("DATA: " + DataPath + " => " + REMOTE_MOD_DATA);
                 if (!WriteToSteamStorage(zipData, REMOTE_MOD_DATA, OnDataUploaded))
                 {
                     OnModifyFailed?.Invoke();
                 }
             }
             else
             {
                 OnModifyFailed?.Invoke();
             }
         }
         else
         {
             StartPreviewUpload();
         }
     }
 }
Exemplo n.º 42
0
    /// <summary>
    /// returns value of given parameter of patch containing point [x,z]
    /// </summary>
    public float GetValue(int x, int z, PatchInfo parameter)
    {
        Vertex center = gm.GetPointOnGrid(new Vertex(x, z));
        switch (parameter)
        {
            case PatchInfo.rMin:
                return rMin.GetValue(center.x, center.z);
            case PatchInfo.rMax:
                return rMax.GetValue(center.x, center.z);
            case PatchInfo.noise:
                return noise.GetValue(center.x, center.z);
        }

        return 666;
    }